code
stringlengths 46
37.2k
| language
stringclasses 9
values | AST_depth
int64 3
30
| alphanumeric_fraction
float64 0.2
0.91
| max_line_length
int64 13
399
| avg_line_length
float64 5.67
140
| num_lines
int64 7
299
| original_docstring
stringlengths 22
42.6k
| source
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
function stringToEthereumNetworkId(ethereumNetworkName)
{
let errPrefix = "(stringToEthereumNetworkId) ";
if (common_routines.isEmptyString(ethereumNetworkName))
throw new Error(errPrefix + "The Ethereum network name is empty.");
if (ethereumNetworkName == 'MAIN')
return EnumEthereumNetwork.MAIN;
if (ethereumNetworkName == 'MORDEN')
return EnumEthereumNetwork.MORDEN;
if (ethereumNetworkName == 'ROPSTEN')
return EnumEthereumNetwork.ROPSTEN;
if (ethereumNetworkName == 'RINKEBY')
return EnumEthereumNetwork.RINKEBY;
if (ethereumNetworkName == 'KOVAN')
return EnumEthereumNetwork.KOVAN;
if (ethereumNetworkName == 'GANACHE')
return EnumEthereumNetwork.GANACHE;
throw new Error(errPrefix + "Invalid Ethereum network name: " + ethereumNetworkName);
} | javascript | 9 | 0.781088 | 86 | 39.684211 | 19 | /**
* Convert an Ethereum network name to an Ethereum network ID enum.
*
* @param {string} ethereumNetworkName - The Ethereum network name to convert.
*
* @return {EnumEthereumNetwork} - Returns the enum that represents the given
* Ethereum network name.
*
*/ | function |
public static Color ColorFromHsl(double hue, double saturation, double brightness)
{
double normalizedHue = hue / 360;
double red, green, blue;
if (brightness == 0)
{
red = green = blue = 0;
}
else
{
if (saturation == 0)
{
red = green = blue = brightness;
}
else
{
double temp2;
if (brightness <= 0.5)
{
temp2 = brightness * (1.0 + saturation);
}
else
{
temp2 = brightness + saturation - (brightness * saturation);
}
double temp1 = (2.0 * brightness) - temp2;
double[] temp3 = { normalizedHue + (1.0 / 3.0), normalizedHue, normalizedHue - (1.0 / 3.0) };
double[] color = { 0, 0, 0 };
for (int i = 0; i < 3; i++)
{
if (temp3[i] < 0) temp3[i] += 1.0;
if (temp3[i] > 1) temp3[i] -= 1.0;
if (6.0 * temp3[i] < 1.0)
{
color[i] = temp1 + ((temp2 - temp1) * temp3[i] * 6.0);
}
else if (2.0 * temp3[i] < 1.0)
{
color[i] = temp2;
}
else if (3.0 * temp3[i] < 2.0)
{
color[i] = temp1 + ((temp2 - temp1) * ((2.0 / 3.0) - temp3[i]) * 6.0);
}
else
{
color[i] = temp1;
}
}
red = color[0];
green = color[1];
blue = color[2];
}
}
if (red > 1) red = 1;
if (red < 0) red = 0;
if (green > 1) green = 1;
if (green < 0) green = 0;
if (blue > 1) blue = 1;
if (blue < 0) blue = 0;
return Color.FromArgb((int)(255 * red), (int)(255 * green), (int)(255 * blue));
} | c# | 25 | 0.298614 | 113 | 37.419355 | 62 | /// <summary>
/// Converts a colour from HSL to RGB.
/// </summary>
/// <remarks>Adapted from the algoritm in Foley and Van-Dam</remarks>
/// <param name="hue">A double representing degrees ranging from 0 to 360 and is equal to the GetHue() on a Color structure.</param>
/// <param name="saturation">A double value ranging from 0 to 1, where 0 is gray and 1 is fully saturated with color.</param>
/// <param name="brightness">A double value ranging from 0 to 1, where 0 is black and 1 is white.</param>
/// <returns>A Color structure with the equivalent hue saturation and brightness</returns> | function |
func DecryptS(ptype string, val sql.NullString, data []byte, clear bool) (string, error) {
if !sdk.NeedPlaceholder(ptype) && val.Valid {
return val.String, nil
}
if len(data) == (nonceSize + macSize) {
return "", nil
}
if !clear {
return sdk.PasswordPlaceholder, nil
}
if val.Valid {
return val.String, nil
}
d, err := Decrypt(data)
if err != nil {
return "", err
}
return string(d), nil
} | go | 8 | 0.647202 | 90 | 20.684211 | 19 | // DecryptS wrap Decrypt and:
// - return Placeholder instead of value if not needed
// - cast returned value in string | function |
def start_session(username, **kwargs):
remember = kwargs.get("remember", True)
u = Users.load_user(username)
if u is None:
u = Users({"username":username, "password":random_str()})
if not u._auto_create():
if username in Users.RESERVED:
abort(400, "Username \"%s\" is reserved" % username)
else:
abort(500, "Failed to create user session")
login_user(u, remember=remember)
current_app.mongo.db.users.update_one({"username":u.username},{
"$set": {"last_login": time.time()}
}) | python | 15 | 0.530903 | 72 | 44.142857 | 14 |
after user is successfully authenticated, start user session
if user is not in local database, add them
| function |
@ApplicationPath("/rest")
@Path("/personaldata")
public class PersonalDataExtractor extends Application {
final static Logger logger = Logger.getLogger(PersonalDataExtractor.class);
/**
* This method extracts personal data and scores those personal data.
* Output data is formatted so that it can be consumed by D3 tree viewer library
*
* @param payload Text document from which personal data needs to be extracted
* @return Response Personal data and score output as JSON
*/
@POST
@Path("/forviewer")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getPersonalDataForViewer(InputStream payload) {
try {
if (payload == null) {
logger.error("Input data not available");
return Response.serverError().entity("Input data not available").build();
}
JSONObject payloadJSON = JSONObject.parse(payload);
if(logger.isInfoEnabled()){
logger.info("Input text provided by user");
logger.info(payloadJSON.toString());
}
PIIDataExtractor piiExtractor = new PIIDataExtractor();
JSONObject response = piiExtractor.getPersonalDataForViewer(payloadJSON);
if(logger.isInfoEnabled()){
logger.info("Output for D3 viewer format");
logger.info(response.toString());
}
return Response.ok(response, MediaType.APPLICATION_JSON)
.header("Access-Control-Allow-Origin", "*")
.build();
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
return Response.serverError().entity(e.getMessage()).build();
}
}
/**
* This method extracts personal data and scores those personal data.
* Output data is more generic, targetted to be consumed by other applications
*
* @param payload Text document from which personal data needs to be extracted
* @return Response Personal data and score output as JSON
*/
@POST
@Path("/forconsumer")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getPersonalDataForConsumer(InputStream payload) {
try {
if (payload == null) {
return Response.serverError().entity("Input data not available").build();
}
JSONObject payloadJSON = JSONObject.parse(payload);
if(logger.isInfoEnabled()){
logger.info("Input text provided by user");
logger.info(payloadJSON.toString());
}
PIIDataExtractor piiDataExtractor = new PIIDataExtractor();
JSONObject response = piiDataExtractor.getPersonalDataInGenericFormat(payloadJSON);
if(logger.isInfoEnabled()){
logger.info("Output for consumer format");
logger.info(response.toString());
}
return Response.ok(response, MediaType.APPLICATION_JSON)
.header("Access-Control-Allow-Origin", "*")
.build();
} catch (Exception e) {
logger.error("Error: " + e.getMessage());
e.printStackTrace();
return Response.serverError().entity(e.getMessage()).build();
}
}
} | java | 14 | 0.713258 | 86 | 30.73913 | 92 | /**
* Personal Data Extractor and scorer REST interface. It has two POST methods.
* "/forviewer" method's response is intended to be consumed by UI (D3), which
* requires a particular format of data. "/forconsumer" method's response is
* more generic and can be consumed by other applications which can then use the
* data for other purposes as needed by calling applications
*/ | class |
public abstract class Util
{
/**
* An instance of Util, containing the method implementations.
* <br><br>
* It is set during CraftGuide's {@literal @PreInit}.
*/
public static Util instance;
/**
* Causes CraftGuide to clear its list of recipes, and reload them with
* exactly the same process that was originally used to build the list.
*/
public abstract void reloadRecipes();
/**
* Converts the passed ItemStack's name and information into a List
* of Strings for display, similar to how GuiContainer does it.
* Additionally, contains logic to try an alternative if given a stack
* with a damage of -1 which produces an unusable name and information,
* if CraftGuide is set to always show item IDs it will insert the item's
* ID and damage value as the second line. If an exception is thrown
* at any time during the process, it will log it to CraftGuide.log and
* generate an error text to display that at least shows the item ID and
* damage.
* @param stack
* @return
*/
public abstract List<String> getItemStackText(ItemStack stack);
/**
* Gets a standard {@link ItemFilter} for any of the common types:
* <li>ItemStack
* <li>List of ItemStacks
* <li>String
*
* @param item
* @return
*/
public abstract ItemFilter getCommonFilter(Object item);
/**
* Gets a texture usable with {@link Renderer#renderRect}
* from a String identifier. At the moment, it only accepts the
* hardcoded values "ItemStack-Any", "ItemStack-Background", and
* "ItemStack-OreDict", but the eventual intention is to load the
* definitions from external text files, to allow for a far more
* advanced ability to re-skin the entire GUI than is normally
* possible from just swapping a texture file.
*
* @param identifier
* @return
*/
public abstract NamedTexture getTexture(String identifier);
/**
* Returns the number of partial ticks for this frame. I don't know
* quite what they do, but it's the third parameter to
* {@link net.minecraft.src.GuiScreen#drawScreen}, so I'm assuming
* that at least something needs it. Rather than pass it as an
* extra argument to every drawing method, it is stored at the
* start of rendering the GUI, and can be retrieved with this method.
* @return
*/
public abstract float getPartialTicks();
} | java | 6 | 0.719896 | 74 | 34.121212 | 66 | /**
* Contains a number of methods that implement common functionality
* that would otherwise need to be implemented by everyone who uses
* the API, or that relies on parts of CraftGuide not included in
* the API.
*/ | class |
private static class CompiledExpKey {
private final Exp exp;
private final boolean scalar;
private final ResultStyle resultStyle;
private int hashCode = Integer.MIN_VALUE;
private CompiledExpKey(
Exp exp,
boolean scalar,
ResultStyle resultStyle)
{
this.exp = exp;
this.scalar = scalar;
this.resultStyle = resultStyle;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof CompiledExpKey)) {
return false;
}
CompiledExpKey otherKey = (CompiledExpKey)other;
return this.scalar == otherKey.scalar
&& this.resultStyle == otherKey.resultStyle
&& this.exp.equals(otherKey.exp);
}
public int hashCode() {
if (hashCode != Integer.MIN_VALUE) {
return hashCode;
} else {
int hash = 0;
hash = Util.hash(hash, scalar);
hash = Util.hash(hash, resultStyle);
this.hashCode = Util.hash(hash, exp);
}
return this.hashCode;
}
} | java | 11 | 0.49574 | 62 | 30.512195 | 41 | /**
* Just a simple key of Exp/scalar/resultStyle, used for keeping
* compiled expressions. Previous to the introduction of this
* class, the key was a list constructed as Arrays.asList(exp, scalar,
* resultStyle) and having poorer performance on equals, hashCode,
* and construction.
*/ | class |
def check_depths(self):
counter, graph = 1, []
for rule in sorted(self.rules.keys()):
choices = self.rules[rule]['choices']
self.non_terminals[rule]['b_factor'] = self.rules[rule][
'no_choices']
for choice in choices:
graph.append([rule, choice['choice']])
while graph:
removeset = set()
for edge in graph:
if all([sy["type"] == "T" or
self.non_terminals[sy["symbol"]]['expanded']
for sy in edge[1]]):
removeset.add(edge[0])
for s in removeset:
self.non_terminals[s]['expanded'] = True
self.non_terminals[s]['min_steps'] = counter
graph = [e for e in graph if e[0] not in removeset]
counter += 1 | python | 16 | 0.475087 | 68 | 42.2 | 20 |
Run through a grammar and find out the minimum distance from each
NT to the nearest T. Useful for initialisation methods where we
need to know how far away we are from fully expanding a tree
relative to where we are in the tree and what the depth limit is.
:return: Nothing.
| function |
public boolean growSpores(World world, BlockPos pos, Random random) {
float sporeChance = 0.5F;
float sporeChancePicked = random.nextFloat();
if (sporeChancePicked <= sporeChance) {
world.setBlockState(pos, this.getDefaultState().with(LIT, true));
return true;
}
return false;
} | java | 11 | 0.618497 | 77 | 37.555556 | 9 | /**
* This method decides whether the blood kelp should have spores.
*
* @param world
* @param pos The position of the new block.
* @param random
*/ | function |
func (w *Map180) SVG(boundingBox string, width int, markers []Marker, insetBbox string) (buf bytes.Buffer, err error) {
var b bbox
if boundingBox == "" {
b, err = newBboxFromMarkers(markers)
if err != nil {
return
}
} else {
b, err = newBbox(boundingBox)
if err != nil {
return
}
}
m, err := b.newMap3857(width)
if err != nil {
return
}
buf.WriteString(`<?xml version="1.0"?>`)
buf.WriteString(fmt.Sprintf("<svg height=\"%d\" width=\"%d\" xmlns=\"http://www.w3.org/2000/svg\">",
m.height, m.width))
if b.title != "" {
buf.WriteString(`<title>Map of ` + b.title + `.</title>`)
} else {
buf.WriteString(`<title>Map of ` + boundingBox + `.</title>`)
}
var landLakes string
err = mapLayers.Get(dummyCtx, m.toKey(), groupcache.StringSink(&landLakes))
if err != nil {
return
}
buf.WriteString(landLakes)
if insetBbox != "" {
var inset bbox
inset, err = newBbox(insetBbox)
if err != nil {
return
}
var in map3857
in, err = inset.newMap3857(80)
if err != nil {
return
}
var insetMap string
err = mapLayers.Get(dummyCtx, in.toKey(), groupcache.StringSink(&insetMap))
if err != nil {
return
}
ibboxul := NewMarker(b.llx, b.ury, ``, ``, ``)
err = in.marker3857(&ibboxul)
if err != nil {
return
}
ibboxlr := NewMarker(b.urx, b.lly, ``, ``, ``)
err = in.marker3857(&ibboxlr)
if err != nil {
return
}
iw := int(ibboxlr.x - ibboxul.x)
if iw < 5 {
iw = 5
ibboxul.x = ibboxul.x - 2
}
ih := int(ibboxlr.y - ibboxul.y)
if ih < 5 {
ih = 5
ibboxul.y = ibboxul.y - 2
}
buf.WriteString(fmt.Sprintf("<g transform=\"translate(10,10)\"><rect x=\"-3\" y=\"-3\" width=\"%d\" height=\"%d\" rx=\"10\" ry=\"10\" fill=\"white\"/>",
in.width+6, in.height+6))
buf.WriteString(insetMap)
buf.WriteString(fmt.Sprintf("<rect x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" fill=\"red\" opacity=\"0.5\"/>",
int(ibboxul.x), int(ibboxul.y), iw, ih) + `</g>`)
}
err = m.drawMarkers(markers, &buf)
if err != nil {
return
}
var short bool
if m.width < 250 {
short = true
}
labelMarkers(markers, m.width-5, m.height-5, `end`, 12, short, &buf)
buf.WriteString("</svg>")
return
} | go | 14 | 0.592847 | 154 | 24.670588 | 85 | /*
SVG draws an SVG image showing a map of markers. The returned map uses EPSG3857.
Width is the SVG image width in pixels (height is calculated).
If boundingBox is the empty string then the map bounds are calculated from the markers.
See ValidBbox for boundingBox options.
*/ | function |
def read_rst_data(self,
win_idx,
datasets,
path_points,
bbox,
meta):
window = path_points[win_idx]
window_height, window_width = np.array([np.abs(bbox[win_idx][2] - bbox[win_idx][0]),
np.abs(bbox[win_idx][3] - bbox[win_idx][1])]).astype(np.int)
bnds = []
data = []
for ds in datasets:
bnd = from_bounds(window[0][1],
window[-1][0],
window[-1][1],
window[0][0],
transform=self.depth_rsts[ds].transform,
height=window_height,
width=window_width)
bnds.append(bnd)
read_data = self.depth_rsts[ds].read(1, window=bnd).astype(np.float32)
read_data[read_data == np.float32(self.depth_rsts[ds].meta['nodata'])] = np.nan
data.append(read_data)
del bnd
final_bnds = from_bounds(window[0][1],
window[-1][0],
window[-1][1],
window[0][0],
transform=meta['transform'],
height=window_height,
width=window_width)
return [final_bnds, bnds, data] | python | 15 | 0.386059 | 108 | 45.65625 | 32 |
Return data windows and final bounds of window
:param win_idx: int window index
:param datasets: list of int representing dataset inx
:param path_points: list of bbox for windows
:param bbox: list of ul/br coords of windows
:param meta: metadata for final dataset
:return: rasterio window object for final window, rasterio window of data window bounds,
data for each raster in window,
| function |
public UsbDeviceConnectionWrapper OpenDevice(UsbDevice Device, UsbInterface Interface, boolean ForceClaim) {
UsbDeviceConnection u = manager.openDevice(Device);
u.claimInterface(Interface, ForceClaim);
UsbDeviceConnectionWrapper uu = new UsbDeviceConnectionWrapper();
uu.connection = u;
uu.usbInterface = Interface;
return uu;
} | java | 7 | 0.800587 | 108 | 41.75 | 8 | /**
* Connects to the given device and claims exclusive access to the given interface.
*ForceClaim - Whether the system should disconnect kernel drivers if necessary.
*/ | function |
def to_image_list(tensors, size_divisible=0, shapes=None):
if isinstance(tensors, torch.Tensor) and size_divisible > 0:
assert False, "code path not tested with cuda graphs"
tensors = [tensors]
if isinstance(tensors, ImageList):
return tensors
elif isinstance(tensors, torch.Tensor):
assert False, "code path not tested with cuda graphs"
assert tensors.dim() == 4
image_sizes = [tensor.shape[-2:] for tensor in tensors]
return ImageList(tensors, image_sizes)
elif isinstance(tensors, (tuple, list)):
max_size = tuple(max(s) for s in zip(*[img.shape for img in tensors]))
if shapes is None:
if size_divisible > 0:
import math
stride = size_divisible
max_size = list(max_size)
max_size[1] = int(math.ceil(max_size[1] / stride) * stride)
max_size[2] = int(math.ceil(max_size[2] / stride) * stride)
max_size = tuple(max_size)
batch_shape = (len(tensors),) + max_size
batched_imgs = tensors[0].new(*batch_shape).zero_()
for img, pad_img in zip(tensors, batched_imgs):
pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)
else:
cost, H_best, W_best = None, None, None
C, H, W = max_size
for H_pad, W_pad in shapes:
if H <= H_pad and W <= W_pad:
if cost is None or H_pad*W_pad < cost:
cost, H_best, W_best = H_pad*W_pad, H_pad, W_pad
batch_shape = (len(tensors),C,H_best,W_best)
batched_imgs = tensors[0].new(*batch_shape).zero_()
for img, pad_img in zip(tensors, batched_imgs):
pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)
image_sizes = [im.shape[-2:] for im in tensors]
return ImageList(batched_imgs, image_sizes)
else:
raise TypeError("Unsupported type for to_image_list: {}".format(type(tensors))) | python | 19 | 0.555771 | 87 | 50.575 | 40 |
tensors can be an ImageList, a torch.Tensor or
an iterable of Tensors. It can't be a numpy array.
When tensors is an iterable of Tensors, it pads
the Tensors with zeros so that they have the same
shape
| function |
@Test
public void testSearchesWithConcepts() {
final TopicMapView topicMap = elementFactory.getFindPage().goToTopicMap();
topicMap.waitForMapLoaded();
final String selectedConcept = topicMap.clickNthClusterHeading(0);
elementFactory.getFindPage().waitUntilSavePossible();
saveService.saveCurrentAs("Conceptual Search", SearchType.QUERY);
final ConceptsPanel conceptsPanel = elementFactory.getConceptsPanel();
conceptsPanel.removableConceptForHeader(selectedConcept).removeAndWait();
assertThat(searchTabBar.currentTab(), is(modified()));
assertThat(conceptsPanel.selectedConceptHeaders(), empty());
saveService.resetCurrentQuery();
assertThat(searchTabBar.currentTab(), not(modified()));
final List<String> finalConceptHeaders = conceptsPanel.selectedConceptHeaders();
assertThat(finalConceptHeaders, hasSize(1));
assertThat(finalConceptHeaders, hasItem('"' + selectedConcept + '"'));
} | java | 10 | 0.724652 | 88 | 58.235294 | 17 | // Checks that the saved-ness of the search respects the selected concepts | function |
public static MimeType parse(final String mimeType) {
if (mimeType == null || "".equals(mimeType.trim())) {
throw new IllegalArgumentException("Mime Type can not be empty");
}
final Matcher mimeMatcher = MIME_REGEX.matcher(mimeType);
if (!mimeMatcher.matches()) {
throw new IllegalArgumentException(mimeType + " is not a valid Mime Type");
}
final boolean oneWildcard = mimeMatcher.group("wildcard") != null;
final String type = oneWildcard ? "*" : mimeMatcher.group("type");
final String subType = oneWildcard ? "*" : mimeMatcher.group("subtype");
Map<String, String> params = new HashMap<>();
if (mimeMatcher.group("subtype") != null) {
params = parseParams(mimeType);
}
return new MimeType(type, subType, params);
} | java | 10 | 0.612412 | 87 | 49.294118 | 17 | /**
* Parses a mime type string including media range and returns a MimeType
* object. For example, the media range 'application/*;q=0.5' would get
* parsed into: ('application', '*', {'q', '0.5'}).
*
* @param mimeType the mime type to parse
* @return a MimeType object
*/ | function |
def to_code(f, arg_value_hints=None, indentation=' '):
conversion_map = conversion.ConversionMap()
conversion.object_to_graph(f, conversion_map, arg_value_hints)
imports = '\n'.join(config.COMPILED_IMPORT_STATEMENTS)
code = '\n'.join(
compiler.ast_to_source(dep, indentation)
for dep in reversed(tuple(
six.itervalues(conversion_map.dependency_cache))))
return imports + '\n\n' + code | python | 15 | 0.693046 | 64 | 45.444444 | 9 | Return the equivalent of a function in TensorFlow code.
Args:
f: A Python function with arbitrary arguments and return values.
arg_value_hints: A dict mapping parameter names to objects that can hint
at the type of those parameters.
indentation: String, when to use for each level of indentation.
Returns:
String.
| function |
void
clean_ipv6_addr(int addr_family, char *addr)
{
#ifdef HAVE_IPV6
if (addr_family == AF_INET6)
{
char *pct = strchr(addr, '%');
if (pct)
*pct = '\0';
}
#endif
} | c | 11 | 0.483254 | 44 | 16.5 | 12 | /*
* clean_ipv6_addr --- remove any '%zone' part from an IPv6 address string
*
* XXX This should go away someday!
*
* This is a kluge needed because we don't yet support zones in stored inet
* values. Since the result of getnameinfo() might include a zone spec,
* call this to remove it anywhere we want to feed getnameinfo's output to
* network_in. Beats failing entirely.
*
* An alternative approach would be to let network_in ignore %-parts for
* itself, but that would mean we'd silently drop zone specs in user input,
* which seems not such a good idea.
*/ | function |
public class ComplexPiece {
/** The ID. */
private final int id;
/** The amount of pieces in the complex object. */
private final int pieceAmount;
/** The byte array of the data and checksum. */
private final byte[] data, checksum;
/** Instance of the protocol. */
private final IProtocol protocol;
/** Creates a byte array holding the data, id, and checksum of the complex object.
* @param id The ID.
* @param pieceAmount The amount of pieces in the complex object.
* @param data The piece of the object's byte array.
* @param protocol Instance of the protocol.
* @param checksum Object's checksum byte array.
*/
public ComplexPiece(int id, int pieceAmount, byte[] data, IProtocol protocol, byte[] checksum) {
this.id = id;
this.pieceAmount = pieceAmount;
this.protocol = protocol;
this.checksum = checksum;
this.data = getByteArray(data);
}
/** Sends the piece over TCP.
* @param tcpOut The TCP output stream.
*/
public void sendTcp(ObjectOutputStream tcpOut) {
try {
synchronized(tcpOut) {
tcpOut.write(data);
tcpOut.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/** Sends the piece over UDP.
* @param udpOut The UDP output stream.
* @param address The address to send it to.
* @param port The port to send it over.
*/
public void sendUdp(DatagramSocket udpOut, InetAddress address, int port) {
try {
DatagramPacket sendPacket = new DatagramPacket(data, data.length, address, port);
udpOut.send(sendPacket);
} catch (IOException e) {
e.printStackTrace();
}
}
/** Takes the id, converts it to four bytes and adds it in front of the bytes of data. It also makes the first index in the array
* equal to 99 because that is the key that will be used on the client/server side to determine whether or not it is part of a
* complex object.
* @param data The object's byte array.
* @return The combined array.
*/
private byte[] getByteArray(byte[] data) {
byte[] indexArray = new byte[4]; //holds the ID amount
copyArrayToArray(PacketUtils.intToByteArray(id), indexArray, 0); //Puts the ID into the array of 4 bytes
byte[] pieceAmountArray = new byte[4];
copyArrayToArray(PacketUtils.intToByteArray(pieceAmount), pieceAmountArray, 0); //Puts the amount of pieces into the array of 4 bytes
byte[] dataSizeArray = new byte[4];
copyArrayToArray(PacketUtils.intToByteArray(data.length), dataSizeArray, 0); //Puts the size of the data into the array of 4 bytes
byte[] ret = new byte[data.length + 1 + indexArray.length + pieceAmountArray.length + dataSizeArray.length]; //Added 1 to set the complex object ID in the front
ret[0] = 99; //1st Byte, Used to determine on the server/client side if the packet sent is part of a complex objects
copyArrayToArray(indexArray, ret, 1); //2nd byte
copyArrayToArray(pieceAmountArray, ret, 1 + indexArray.length);
copyArrayToArray(dataSizeArray, ret, 1 + indexArray.length + pieceAmountArray.length);
copyArrayToArray(data, ret, 1 + indexArray.length + pieceAmountArray.length + dataSizeArray.length);
ret = addArrays(ret, checksum);
return ret;
}
/** Takes the byte array of the object and id and puts the 10 bytes of the checksum in front of it.
* @param array The array to put the checksum in front of.
* @param checksumBytes The checksum value in bytes.
* @return The combined array.
*/
private byte[] addArrays(byte[] array, byte[] checksumBytes) {
byte[] concat = new byte[protocol.getConfig().PACKET_BUFFER_SIZE];
System.arraycopy(checksumBytes, 0, concat, 0, checksumBytes.length);
System.arraycopy(array, 0, concat, checksumBytes.length, array.length);
if (protocol.getEncryptionMethod() != null) {
concat = protocol.getEncryptionMethod().encrypt(concat);
}
return concat;
}
/** Takes an array and copies it to the destination array.
* @param src The array to copy from.
* @param dest The array to copy to.
* @param startIndex The index in the array of "dest" to start at.
*/
private void copyArrayToArray(byte[] src, byte[] dest, int startIndex) {
for (int i = 0; i < dest.length; i++) {
if (i < src.length)
dest[i + startIndex] = src[i];
else
break;
}
}
} | java | 14 | 0.685215 | 162 | 35.508621 | 116 | /**
* Networking Library
* ComplexPiece.java
* Purpose: A piece of a object's byte array that corresponds to a complex object. This piece's data is sent over a socket
* and recreated into an object later on.
*
* @author Jon R (Baseball435)
* @version 1.0 7/25/2014
*/ | class |
const SSCHAR* FindTextVariable (const SSCHAR* pString, const textreplace_t ReplaceInfo[]) {
int Index;
for (Index = 0; ReplaceInfo[Index].pVariable != NULL; ++Index) {
if (stricmp(ReplaceInfo[Index].pVariable, pString) == 0) return (ReplaceInfo[Index].pValue);
}
return (NULL);
} | c++ | 13 | 0.696246 | 96 | 41 | 7 | /*===========================================================================
*
* Function - const SSCHAR* FindTextVariable (pString, ReplaceInfo);
*
* Find a variable in an array of replacement information. Returns the
* matching record value (case insensitive) on success or NULL if not found.
*
*=========================================================================*/ | function |
Region *
Region::GetFirstAncestorOfNonExceptingFinallyParent()
{
Region * ancestor = this;
while (ancestor && ancestor->IsNonExceptingFinally())
{
ancestor = ancestor->GetParent();
}
Assert(ancestor && !ancestor->IsNonExceptingFinally());
if (ancestor && ancestor->GetType() != RegionTypeRoot && ancestor->GetParent()->IsNonExceptingFinally())
{
return ancestor->GetParent()->GetFirstAncestorOfNonExceptingFinally();
}
Assert(ancestor);
return ancestor ? (ancestor->GetType() == RegionTypeRoot ? ancestor : ancestor->GetParent()) : nullptr;
} | c++ | 10 | 0.683946 | 108 | 36.4375 | 16 | // Return the first ancestor of the region's parent which is not a non exception finally
// Skip all non exception finally regions in the region tree
// Return the parent of the first non-non-exception finally region | function |
protected void simplifyTransforms()
{
net.imglib2.concatenate.ConcatenateUtils.join( transforms );
for ( final ListIterator< Transform > i = transforms.listIterator(); i.hasNext(); )
{
final Transform t = i.next();
if ( Mixed.class.isInstance( t ) )
{
final Mixed mixed = ( Mixed ) t;
if ( isIdentity( mixed ) )
{
i.remove();
}
else if ( isTranslation( mixed ) )
{
final long[] translation = new long[ mixed.numTargetDimensions() ];
mixed.getTranslation( translation );
i.set( new TranslationTransform( translation ) );
}
else if ( isSlicing( mixed ) )
{
final int m = mixed.numTargetDimensions();
final long[] translation = new long[ m ];
final boolean[] zero = new boolean[ m ];
final int[] component = new int[ m ];
mixed.getTranslation( translation );
mixed.getComponentZero( zero );
mixed.getComponentMapping( component );
final SlicingTransform sl = new SlicingTransform( mixed.numSourceDimensions(), m );
sl.setTranslation( translation );
sl.setComponentZero( zero );
sl.setComponentMapping( component );
i.set( sl );
}
}
}
} | java | 17 | 0.634583 | 88 | 30.756757 | 37 | /**
* Simplify the {@link #transforms} list. First, concatenate neighboring
* transforms if possible. Then, for every {@link Mixed} transform:
* <ul>
* <li>remove it if it is the identity transforms.
* <li>replace it by a {@link TranslationTransform} if it is a pure
* translation.
* <li>replace it by a {@link SlicingTransform} if it is a pure slicing.
* </ul>
*/ | function |
private void startTask() {
try {
getClosestWater();
}catch (NullPointerException e) {
destination = new Point(world.getWidth(),world.getHeight());
}
if (currentTarget != null) {
destination = currentTarget.getLocation();
}
} | java | 12 | 0.672131 | 63 | 23.5 | 10 | /**
* Finds the closest water body and makes the alligator go towards it.
* Also finds any animal whilst going towards the water body, and makes
* the alligator go towards it first.
*/ | function |
public Bitmap GetBitmap(int mipmapLevel)
{
byte[] pic = GetPixels(mipmapLevel, out int w, out int h, colorEncoding == BlpColorEncoding.Argb8888 ? false : true);
Bitmap bmp = new Bitmap(w, h);
BitmapData bmpdata = bmp.LockBits(new System.Drawing.Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
Marshal.Copy(pic, 0, bmpdata.Scan0, pic.Length);
bmp.UnlockBits(bmpdata);
return bmp;
} | c# | 14 | 0.625251 | 142 | 54.555556 | 9 | /// <summary>
/// Converts the BLP to a System.Drawing.Bitmap
/// </summary>
/// <param name="mipmapLevel">The desired Mipmap-Level. If the given level is invalid, the smallest available level is choosen</param>
/// <returns>The Bitmap</returns> | function |
static void split_escape_and_log(char *tmpbuf, int len)
{
char *p = tmpbuf;
tmpbuf += len;
while (p < tmpbuf) {
char c;
char *q = G.parsebuf;
int pri = (LOG_USER | LOG_NOTICE);
if (*p == '<') {
pri = bb_strtou(p + 1, &p, 10);
if (*p == '>')
p++;
if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
pri = (LOG_USER | LOG_NOTICE);
}
while ((c = *p++)) {
if (c == '\n')
c = ' ';
if (!(c & ~0x1f) && c != '\t') {
*q++ = '^';
c += '@';
}
*q++ = c;
}
*q = '\0';
timestamp_and_log(pri, G.parsebuf, q - G.parsebuf);
}
} | c | 14 | 0.438721 | 55 | 19.142857 | 28 | /* tmpbuf[len] is a NUL byte (set by caller), but there can be other,
* embedded NULs. Split messages on each of these NULs, parse prio,
* escape control chars and log each locally. */ | function |
public class FrameFixedFieldTupleAppender implements IFrameTupleAppender, IFrameFieldAppender {
private FrameFixedFieldAppender fieldAppender;
private FrameTupleAppender tupleAppender;
private IFrame sharedFrame;
private IFrameAppender lastAppender;
public FrameFixedFieldTupleAppender(int numFields) {
tupleAppender = new FrameTupleAppender();
fieldAppender = new FrameFixedFieldAppender(numFields);
lastAppender = tupleAppender;
}
private void resetAppenderIfNecessary(IFrameAppender appender) throws HyracksDataException {
if (lastAppender != appender) {
if (lastAppender == fieldAppender) {
if (fieldAppender.hasLeftOverFields()) {
throw new HyracksDataException("The previous appended fields haven't been flushed yet.");
}
}
appender.reset(sharedFrame, false);
lastAppender = appender;
}
}
@Override
public boolean appendField(byte[] bytes, int offset, int length) throws HyracksDataException {
resetAppenderIfNecessary(fieldAppender);
return fieldAppender.appendField(bytes, offset, length);
}
@Override
public boolean appendField(IFrameTupleAccessor accessor, int tid, int fid) throws HyracksDataException {
resetAppenderIfNecessary(fieldAppender);
return fieldAppender.appendField(accessor, tid, fid);
}
@Override
public boolean append(IFrameTupleAccessor tupleAccessor, int tIndex) throws HyracksDataException {
resetAppenderIfNecessary(tupleAppender);
return tupleAppender.append(tupleAccessor, tIndex);
}
@Override
public boolean append(int[] fieldSlots, byte[] bytes, int offset, int length) throws HyracksDataException {
resetAppenderIfNecessary(tupleAppender);
return tupleAppender.append(fieldSlots, bytes, offset, length);
}
@Override
public boolean append(byte[] bytes, int offset, int length) throws HyracksDataException {
resetAppenderIfNecessary(tupleAppender);
return tupleAppender.append(bytes, offset, length);
}
@Override
public boolean appendSkipEmptyField(int[] fieldSlots, byte[] bytes, int offset, int length)
throws HyracksDataException {
resetAppenderIfNecessary(tupleAppender);
return tupleAppender.appendSkipEmptyField(fieldSlots, bytes, offset, length);
}
@Override
public boolean append(IFrameTupleAccessor tupleAccessor, int tStartOffset, int tEndOffset)
throws HyracksDataException {
resetAppenderIfNecessary(tupleAppender);
return tupleAppender.append(tupleAccessor, tStartOffset, tEndOffset);
}
@Override
public boolean appendConcat(IFrameTupleAccessor accessor0, int tIndex0, IFrameTupleAccessor accessor1, int tIndex1)
throws HyracksDataException {
resetAppenderIfNecessary(tupleAppender);
return tupleAppender.appendConcat(accessor0, tIndex0, accessor1, tIndex1);
}
@Override
public boolean appendConcat(IFrameTupleAccessor accessor0, int tIndex0, int[] fieldSlots1, byte[] bytes1,
int offset1, int dataLen1) throws HyracksDataException {
resetAppenderIfNecessary(tupleAppender);
return tupleAppender.appendConcat(accessor0, tIndex0, fieldSlots1, bytes1, offset1, dataLen1);
}
@Override
public boolean appendProjection(IFrameTupleAccessor accessor, int tIndex, int[] fields)
throws HyracksDataException {
resetAppenderIfNecessary(tupleAppender);
return tupleAppender.appendProjection(accessor, tIndex, fields);
}
@Override
public void reset(IFrame frame, boolean clear) throws HyracksDataException {
sharedFrame = frame;
tupleAppender.reset(sharedFrame, clear);
fieldAppender.reset(sharedFrame, clear);
}
@Override
public int getTupleCount() {
return lastAppender.getTupleCount();
}
@Override
public ByteBuffer getBuffer() {
return lastAppender.getBuffer();
}
@Override
public void flush(IFrameWriter outWriter, boolean clear) throws HyracksDataException {
lastAppender.flush(outWriter, clear);
}
} | java | 15 | 0.7106 | 119 | 37.080357 | 112 | /**
* This appender can appendTuple and appendField but at the expense of additional checks.
* Please use this Field/Tuple mixed appender only if you don't know the sequence of append functions.
* Try using {@link FrameFixedFieldAppender} if you only want to appendFields.
* and using {@link FrameTupleAppender} if you only want to appendTuples.
*/ | class |
func cleanAssetName(path, basePath, prependPath string) string {
var name string
path, basePath, prependPath = strings.TrimSpace(path), strings.TrimSpace(basePath), strings.TrimSpace(prependPath)
basePath, err := filepath.Abs(basePath)
if err != nil {
basePath = ""
}
apath, err := filepath.Abs(path)
if err == nil {
path = apath
}
if basePath == "" {
idx := strings.LastIndex(path, string(os.PathSeparator))
if idx != -1 {
idx = strings.LastIndex(path[:idx], string(os.PathSeparator))
}
name = path[idx+1:]
} else {
name = strings.Replace(path, basePath, "", 1)
if name[0] == os.PathSeparator {
name = name[1:]
}
}
if prependPath != "" {
if prependPath[0] == os.PathSeparator {
prependPath = prependPath[1:]
}
prependPath = EnsureTrailingSlash(prependPath)
}
r := prependPath + name[:len(name)-len(filepath.Ext(name))]
return strings.Replace(r, string(os.PathSeparator), "/", -1)
} | go | 14 | 0.667742 | 115 | 28.09375 | 32 | // cleanAssetName returns an asset name from the parent dirname and
// the file name without extension.
// The combination
// path=/tmp/css/default.css
// basePath=/tmp/
// prependPath=new/
// will return
// new/css/default | function |
function aggregate(sAlias) {
var oDetails = oAggregation.aggregate[sAlias],
sAggregate = oDetails.name || sAlias,
sGrandTotal = sAlias,
sWith = oDetails.with;
if (sWith) {
if ((sWith === "average" || sWith === "countdistinct")
&& (oDetails.grandTotal || oDetails.subtotals)) {
throw new Error("Cannot aggregate totals with '" + sWith + "'");
}
sAggregate += " with " + sWith + " as " + sAlias;
} else if (oDetails.name) {
sAggregate += " as " + sAlias;
}
if (!bFollowUp) {
if (oDetails.min) {
processMinOrMax(sAlias, "min");
}
if (oDetails.max) {
processMinOrMax(sAlias, "max");
}
}
if (oDetails.grandTotal) {
bHasGrandTotal = true;
if (!mQueryOptions.$skip) {
if (sWith) {
sGrandTotal += " with " + sWith + " as UI5grand__" + sAlias;
}
aConcatAggregate.push(sGrandTotal);
}
}
return sAggregate;
} | javascript | 15 | 0.559623 | 70 | 28 | 33 | /*
* Returns the corresponding part of the "aggregate" term for an aggregatable property,
* for example "AggregatableProperty with method as Alias". Processes min/max as a side
* effect.
*
* @param {string} sAlias - An aggregatable property name
* @returns {string} - Part of the "aggregate" term
* @throws {Error} If "average" or "countdistinct" are used together with subtotals or
* grand totals
*/ | function |
public static JMenu createMenu(String name, Action[] actions) {
final JMenu menu = new JMenu(name);
if (actions != null) {
for (final Action action : actions) {
menu.add(new JMenuItem(action));
}
}
return menu;
} | java | 12 | 0.561338 | 63 | 29 | 9 | /**
* Creates a JMenu
* @param name the name of the menu.
* @param actions an array of actions.
* @return the newly created JMenu with the corresponding items.
*/ | function |
def migrate_48(TRN):
TRN.add("SELECT "
"ag_login_id, "
"participant_name, "
"ag_consent_backup.participant_email, "
"is_juvenile, "
"parent_1_name, "
"parent_2_name, "
"deceased_parent, "
"date_signed, "
"assent_obtainer, "
"age_range, "
"date_revoked "
"FROM "
"ag.ag_consent_backup "
"LEFT JOIN "
"ag.consent_revoked_backup "
"USING (ag_login_id, participant_name)")
rows = TRN.execute()[-1]
for r in rows:
source_id = str(uuid.uuid4())
TRN.add("UPDATE "
"ag_login_surveys "
"SET "
"source_id = %s "
"WHERE "
"ag_login_id = %s AND "
"participant_name = %s",
(source_id,
r["ag_login_id"],
r["participant_name"]))
new_age_range = r["age_range"]
source_type = "human"
if r["age_range"] == "ANIMAL_SURVEY":
source_type = "animal"
new_age_range = None
new_deceased_parent = None
if r['deceased_parent'] is not None:
existing = r['deceased_parent'].lower()
if existing in ['yes', 'true']:
new_deceased_parent = True
elif existing in ['no', 'false']:
new_deceased_parent = False
else:
raise RuntimeError(
"ERROR: Cannot migrate source.deceased_parent: "
"Unknown input: " + str(existing))
TRN.add("INSERT INTO source("
"id, account_id, source_type, "
"source_name, participant_email, "
"is_juvenile, "
"parent_1_name, parent_2_name, "
"deceased_parent, "
"date_signed, date_revoked, "
"assent_obtainer, age_range) "
"VALUES ("
"%s, %s, %s, "
"%s, %s, "
"%s, "
"%s, %s, "
"%s, "
"%s, %s, "
"%s, %s)",
(source_id, r["ag_login_id"], source_type,
r["participant_name"], r["participant_email"],
r["is_juvenile"],
r["parent_1_name"], r["parent_2_name"],
new_deceased_parent,
r["date_signed"], r["date_revoked"],
r["assent_obtainer"], new_age_range)
)
TRN.add("SELECT barcode "
"FROM ag_kit_barcodes "
"LEFT JOIN source_barcodes_surveys USING (barcode) "
"LEFT JOIN ag_login_surveys USING (survey_id) "
"LEFT JOIN ag_kit USING (ag_kit_id) "
"WHERE "
"ag_kit.ag_login_id=%s AND "
"participant_name=%s "
"GROUP BY "
"barcode",
(r["ag_login_id"], r["participant_name"]))
associated_barcodes = TRN.execute()[-1]
for barcode_row in associated_barcodes:
TRN.add("UPDATE ag_kit_barcodes "
"SET source_id=%s "
"WHERE barcode=%s",
(source_id, barcode_row['barcode']))
TRN.add("SELECT ag_kit.ag_login_id, barcode, environment_sampled "
"FROM ag_kit_barcodes "
"LEFT JOIN source_barcodes_surveys "
"USING (barcode) "
"LEFT JOIN ag_login_surveys "
"USING (survey_id) "
"LEFT JOIN ag_consent_backup "
"USING (ag_login_id, participant_name) "
"LEFT JOIN ag_kit "
"USING (ag_kit_id) "
"WHERE "
"environment_sampled is not null AND "
"environment_sampled != '' AND "
"participant_name is null "
"ORDER BY (ag_kit.ag_login_id, environment_sampled, barcode)")
last_account_id = None
name_suffix = 1
env_rows = TRN.execute()[-1]
for r in env_rows:
if r['ag_login_id'] == last_account_id:
name_suffix = name_suffix + 1
else:
name_suffix = 1
last_account_id = r['ag_login_id']
source_id = str(uuid.uuid4())
source_type = "environmental"
TRN.add("INSERT INTO source("
"id, account_id, source_type, "
"source_name, participant_email, "
"is_juvenile, "
"parent_1_name, parent_2_name, "
"deceased_parent, "
"date_signed, date_revoked, "
"assent_obtainer, age_range, description) "
"VALUES ("
"%s, %s, %s, "
"%s, %s, "
"%s, "
"%s, %s, "
"%s, "
"%s, %s, "
"%s, %s, %s)",
(source_id, r["ag_login_id"], source_type,
"Environmental Sample-" + str(name_suffix).zfill(3), None,
None,
None, None,
None,
None, None,
None, None, r['environment_sampled'])
)
TRN.add("UPDATE ag_kit_barcodes "
"SET source_id=%s "
"WHERE barcode=%s",
(source_id, r['barcode'])) | python | 16 | 0.389987 | 79 | 41.06338 | 142 |
In order to support the REST api, we need participants to have unique
ids. This is a change from the previous keying in ag_consent
which worked off of a compound key (ag_login_id, participant_name).
As part of schema change 48, we are generating new unique IDs for all
sources, and migrating the consent information from ag_consent and
consent_revoked
This requires:
* Adding a new source table (Done in the 0048.sql)
* Mapping each ag_login_id, participant_name pair to a new unique id
* Migrating all data from the ag_consent table to source
* Migrating all data from the consent_revoked table to source
* Migrating ag_kit_barcodes.environment_sampled to source
:param TRN: The active transaction
:return:
| function |
protected void ThreePointCalibration(int frameNumber, Image8 camImage, out IppiPoint? poi)
{
poi = null;
if(_threePointPoints.Origin.x == -1)
{
var p = MoveAndDetect(_threePointFrame, camImage, new IppiPoint_32f(0.0f, 0.0f));
if (p.x != -1)
{
_threePointFrame = -1;
_threePointPoints.Origin = new IppiPoint(p.x, p.y);
_p0 = new IppiPoint(p.x, p.y);
poi = p;
_fgModel.Dispose();
_fgModel = new DynamicBackgroundModel(camImage, 5.0f / Properties.Settings.Default.FrameRate);
}
}
else if(_threePointPoints.XMove.x == -1)
{
var p = MoveAndDetect(_threePointFrame, camImage, new IppiPoint_32f(Properties.Settings.Default.MirrorXVAln, 0.0f));
if (p.x != -1)
{
_threePointFrame = -1;
_threePointPoints.XMove = new IppiPoint(p.x, p.y);
poi = p;
_fgModel.Dispose();
_fgModel = new DynamicBackgroundModel(camImage, 5.0f / Properties.Settings.Default.FrameRate);
}
}
else if(_threePointPoints.YMove.x == -1)
{
var p = MoveAndDetect(_threePointFrame, camImage, new IppiPoint_32f(0.0f, Properties.Settings.Default.MirrorYVAln));
if (p.x != -1)
{
_threePointFrame = -1;
_threePointPoints.YMove = new IppiPoint(p.x, p.y);
poi = p;
_fgModel.Dispose();
_fgModel = new DynamicBackgroundModel(camImage, 20.0f / Properties.Settings.Default.FrameRate);
}
}
else
{
double camera_height_x = CalculateHeight(_threePointPoints.XMove, MirrorAngle(Properties.Settings.Default.MirrorXVAln));
System.Diagnostics.Debug.WriteLine("Height according to x-mirror is: {0}", camera_height_x);
double camera_height_y = CalculateHeight(_threePointPoints.YMove, MirrorAngle(Properties.Settings.Default.MirrorYVAln));
System.Diagnostics.Debug.WriteLine("Height according to y-mirror is: {0}", camera_height_y);
_camera_height = (camera_height_x + camera_height_y) / 2.0;
double theta_x = CalculateCameraTheta(_threePointPoints.XMove, false);
System.Diagnostics.Debug.WriteLine("Theta according to x-mirror is: {0}", theta_x);
double theta_y = CalculateCameraTheta(_threePointPoints.YMove, true);
System.Diagnostics.Debug.WriteLine("Theta according to y-mirror is: {0}", theta_y);
_isYReflected = CheckReflection(theta_x, theta_y, out _camera_theta);
System.Diagnostics.Debug.WriteLine("Y reflection: {0}", _isYReflected);
System.Diagnostics.Debug.WriteLine("Final camera theta is: {0}", _camera_theta);
_experimentPhase = ExperimentPhases.InterpTable;
_interpParams = new InterpolationParams();
_interpParams.LookupTable = new BLIScanLookupTable(new IppiROI(10, 10, camImage.Width-20, camImage.Height-20), 4);
}
_threePointFrame++;
} | c# | 21 | 0.54739 | 136 | 56.166667 | 60 | /// <summary>
/// Runs the initial three point calibration to find approximate camera height and angle/reflection
/// </summary>
/// <param name="frameNumber">The current camera frame number</param>
/// <param name="camImage">The camera image</param>
/// <param name="poi">The detected beam centroid</param> | function |
private void addSingleton(TempCluster clus, DBIDRef id, double dist, boolean asCluster) {
if(asCluster) {
clus.addChild(makeCluster(id, dist, null));
}
else {
clus.add(id);
}
clus.depth = dist;
} | java | 10 | 0.578947 | 89 | 26.555556 | 9 | /**
* Add a singleton object, as point or cluster.
*
* @param clus Current cluster.
* @param id Object to add
* @param dist Distance
* @param asCluster Add as cluster (or only as id)
*/ | function |
def apply_aberration(model, mcoefs, pcoefs):
assert isinstance(model, HanserPSF), "Model must be a HanserPSF"
model = copy.copy(model)
if mcoefs is None and pcoefs is None:
logger.warning("No abberation applied")
return model
if mcoefs is None:
mcoefs = np.zeros_like(pcoefs)
if pcoefs is None:
pcoefs = np.zeros_like(mcoefs)
assert len(mcoefs) == len(pcoefs), "Coefficient lengths don't match"
model._gen_kr()
kr = model._kr
theta = model._phi
r = kr * model.wl / model.na
zerns = zernike(r, theta, np.arange(len(mcoefs)) + 1)
pupil_phase = (zerns * pcoefs[:, None, None]).sum(0)
pupil_mag = (zerns * mcoefs[:, None, None]).sum(0)
pupil_mag += abs(model._gen_pupil())
pupil_total = pupil_mag * np.exp(1j * pupil_phase)
model.apply_pupil(pupil_total)
return model | python | 12 | 0.631518 | 72 | 38.272727 | 22 | Apply a set of abberations to a model PSF.
Parameters
----------
model : HanserPSF
The model PSF to which to apply the aberrations
mcoefs : ndarray (n, )
The magnitude coefficiencts
pcoefs : ndarray (n, )
The phase coefficients
Note: this function assumes the mcoefs and pcoefs are Noll ordered
| function |
def list_images(self, location=None):
params = {}
if location is not None:
params['location'] = location.id
return self._to_base_images(
self.connection.request_api_1('base/imageWithDiskSpeed',
params=params)
.object) | python | 10 | 0.517241 | 68 | 39 | 8 |
return a list of available images
Currently only returns the default 'base OS images' provided by
DimensionData. Customer images (snapshots) are not yet supported.
@inherits: :class:`NodeDriver.list_images`
| function |
def check(self, identity, permission, *args, **kwargs):
try:
permission = self.permissions[permission]
except KeyError:
return False
else:
return permission.check(identity, *args, **kwargs) | python | 10 | 0.586345 | 62 | 34.714286 | 7 | Check if the identity has requested permission.
:param identity: Currently authenticated identity.
:param permission: Permission name.
:return: True if identity role has this permission.
| function |
@Override
public int compareTo(Object other) {
if (other == null) {
return -1;
}
FlowKey otherKey = (FlowKey)other;
return new CompareToBuilder()
.appendSuper(super.compareTo(other))
.append(getEncodedRunId(), otherKey.getEncodedRunId())
.toComparison();
} | java | 10 | 0.630719 | 62 | 26.909091 | 11 | /**
* Compares two FlowKey objects on the basis of
* their cluster, userName, appId and encodedRunId
*
* @param other
* @return 0 if this cluster, userName, appId and encodedRunId are equal to
* the other's cluster, userName, appId and encodedRunId,
* 1 if this cluster or userName or appId or encodedRunId are less than
* the other's cluster, userName, appId and encodedRunId,
* -1 if this cluster and userName and appId and encodedRunId are greater
* the other's cluster, userName, appId and encodedRunId,
*
*/ | function |
@Constraints(noNullInputs = true, notMutable = true, noDirectInsertion = true)
public static <T> void validateBean(@BoundInputVariable(initializer = true, atMostOnceWithSameParameters = true) T instance, Class<?> clazz)
throws FalsePositiveException, IllegalArgumentException{
Inputs.checkNull(instance, clazz);
for(Field f : getAllFieldsToInject(clazz)) {
f.setAccessible(true);
try {
Object obj = f.get(instance);
if(obj == null){
throw new FalsePositiveException("Missing dependency injection for field "+f.getName()+" in class "+clazz.getName());
}
} catch (IllegalAccessException e) {
logger.warn(e.toString());
}
}
Class<?> parent = clazz.getSuperclass();
if(parent != null && !parent.equals(Object.class)) {
validateBean(instance, parent);
}
} | java | 17 | 0.590437 | 144 | 47.15 | 20 | /**
* Check if all beans that need injection have been properly injected
*
* @param instance
* @param clazz
* @param <T>
* @throws FalsePositiveException
* @throws IllegalArgumentException
*/ | function |
class SetClass:
"""This class performs set operations on the data sets of two SetClass
objects.
Public Methods:
items()
display()
union()
intersection()
excluding()
isempty()
pretty_print()
"""
def __init__(self, arg=None, name=None):
""" Initialize private variable members.
Arguments:
arg -- the set of data (default None)
"""
if isinstance(arg, ListType):
self.members = self.dict_from_list(arg)
elif isinstance(arg, DictType):
self.members = arg
elif isinstance(arg, SetClass):
self.members = {}
self.members.update(arg.members)
else:
self.members = {}
self.my_name = name
def __getitem__(self, idx):
return self.members[idx]
def name(self):
"""Return the name of this set."""
return self.my_name
def isempty(self):
""" Return 1 if there are no members, 0 otherwise """
return len(self.members.keys()) == 0
def __len__(self):
return len(self.members)
def display(self):
""" Print out the entire members list."""
print self.members.values()
return
def pretty_print(self):
""" Print out the entire members list with each item per line."""
members = self.members.values()
members.sort()
for member in members:
print member
return
def items(self):
""" Returns a list of the items in this set."""
# This method can't be called 'members' because we have
# a variable called 'members'
return self.members.values()
def filter(self, func):
"""Returns a new set, filtered by a function. Like Python's
filter() function, but operates on sets instead of lists."""
return SetClass(filter(func, self.items()))
def union(self, other):
"""Return the union set of this object's members with the members
of another SetClass.
"""
res = {}
other_dict = self.get_dict(other)
res.update(self.members)
res.update(other_dict)
return SetClass(res)
def intersection(self, other):
"""Return the intersection set of this object's members with the
members of another SetClass. Returns a list.
"""
res = {}
other_dict = self.get_dict(other)
for x in self.members.keys():
if other_dict.has_key(x):
res[x] = self.members[x]
return SetClass(res)
def excluding(self, other):
"""Return the exclusion set of this object's members with the
members of another SetClass. Returns a list.
"""
res = {}
res.update(self.members)
other_dict = self.get_dict(other)
for x in other_dict.keys():
if res.has_key(x):
del res[x]
return SetClass(res)
def get_dict(self, object):
"""Given an object, either a SetClass, a dictionary, or a list,
get a dictionary from it. Raises TypeError if the object is
none of the 3 types listed above."""
if isinstance(object, SetClass):
dict = object.members
elif isinstance(object, ListType):
dict = self.dict_from_list(object)
elif isinstance(object, DictType):
dict = object
else:
raise TypeError("Requires a SetClass, dictionary, or list.")
return dict
def dict_from_list(self, list):
"""Returns a dictionary. Every item in 'list' is a key of
the dictionary. The value of each key is None."""
dict = {}
for item in list:
# If we can use the item directly in a hash, do so.
# If not, use the repr(). We could use the repr() all
# the time, but this would be wasteful ... if there's no
# reason to allocate a string, don't do so.
try:
dict[item] = item
except TypeError:
# Who knows? It's possible the repr() of some
# class returns another non-hashable type. Unlikely.
try:
dict[repr(item)] = item
except TypeError:
print "TypeError in pysets.py, dict_from_list()"
print "item=%s" % (item,)
return dict
def get_item_key(self, item):
"""Returns the key used to store this item, or None if
the item is not hash-able or is not in the set. """
try:
# Maybe the item can be used directly in a hash.
self.members[item]
return item
except TypeError:
# Or maybe the repr() of the item can be used in a hash.
try:
repr_item = repr(item)
self.members[repr_item]
return repr_item
except TypeError:
return None
except KeyError:
return None
def remove_item(self, item):
"""Removes an item from the set. Returns 1 on success,
or 0 if the item is not in the set."""
item_key = self.get_item_key(item)
if item_key == None:
return 0
else:
del self.members[item_key]
return 1
def add_item(self, item):
"""Add an item to the set. No-op if item is already in set.
No return value."""
# If we can use the item directly in a hash, do so.
# If not, use the repr(). We could use the repr() all
# the time, but this would be wasteful ... if there's no
# reason to allocate a string, don't do so.
try:
self.members[item] = item
except TypeError:
# Who knows? It's possible the repr() of some
# class returns another non-hashable type. Unlikely.
try:
self.members[repr(item)] = item
except TypeError:
print "TypeError in pysets.py, add()"
print "item=%s" % (item,)
def add_items(self, items):
"""Add multiple items to the set. No return value."""
for item in items:
self.add_item(item)
def contains_item(self, item):
"""Does the set contain the item? Returns 1 on true, 0 on false."""
item_key = self.get_item_key(item)
if item_key:
return 1
else:
return 0
def __repr__(self):
return repr(self.members.values()) | python | 17 | 0.542969 | 75 | 29.516129 | 217 | This class performs set operations on the data sets of two SetClass
objects.
Public Methods:
items()
display()
union()
intersection()
excluding()
isempty()
pretty_print()
| class |
bool isValidRequest(const SipMessage& sipMessage)
{
if ((sipMessage.hasHeader(TO)) &&
(sipMessage.hasHeader(FROM)) &&
(sipMessage.hasHeader(CSEQ)) &&
(sipMessage.hasHeader(CALL_ID)) &&
(sipMessage.hasHeader(MAX_FORWARDS)))
{
return true;
}
return false;
} | c++ | 12 | 0.646048 | 49 | 23.333333 | 12 | /// A valid SIP request formulated by a UAC MUST, at a minimum, contain
/// the following header fields : To, From, CSeq, Call - ID, Max - Forwards,
/// and Via; all of these header fields are mandatory in all SIP
/// requests.
| function |
public long xen_memory_calc()
{
long xen_mem = memory_overhead;
foreach (VM vm in Connection.ResolveAll(resident_VMs))
{
xen_mem += vm.memory_overhead;
if (vm.is_control_domain)
{
VM_metrics vmMetrics = vm.Connection.Resolve(vm.metrics);
if (vmMetrics != null)
xen_mem += vmMetrics.memory_actual;
}
}
return xen_mem;
} | c# | 16 | 0.444444 | 77 | 33.866667 | 15 | /// <summary>
/// The amount of memory used by Xen, including the control domain plus host and VM overheads.
/// Used to calculate this as total - free - tot_vm_mem, but that caused xen_mem to jump around
/// during VM startup/shutdown because some changes happen before others.
/// </summary> | function |
public class LockedModule extends CanvasComparable<LockedModule> implements Serializable{
private static final long serialVersionUID = 1L;
private long id;
private long context_id;
private String context_type;
private String name;
private String unlock_at;
private boolean require_sequential_progress;
private List<ModuleName> prerequisites = new ArrayList<>();
private List<ModuleCompletionRequirement> completion_requirements = new ArrayList<>();
///////////////////////////////////////////////////////////////////////////
// Getters and Setters
///////////////////////////////////////////////////////////////////////////
@Override
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getContextType() {
return context_type;
}
public void setContextType(String context_type) {
this.context_type = context_type;
}
public String getName() {
return name;
}
public void setName(String name){
this.name = name;
}
public boolean isRequireSequentialProgress() {
return require_sequential_progress;
}
public void setRequireSequentialProgress(boolean require_sequential_progress) {
this.require_sequential_progress = require_sequential_progress;
}
public List<ModuleName> getPrerequisites() {
return prerequisites;
}
public Date getUnlock_at() {
return APIHelpers.stringToDate(unlock_at);
}
public long getContext_id() {
return context_id;
}
public List<ModuleCompletionRequirement> getCompletionRequirements() {
return completion_requirements;
}
public void setCompletionRequirements(List<ModuleCompletionRequirement> completion_requirements) {
this.completion_requirements = completion_requirements;
}
//Module Name
private class ModuleName implements Serializable {
private static final long serialVersionUID = 1L;
private String getName() {
return name;
}
private void setName(String name) {
this.name = name;
}
private String name;
}
///////////////////////////////////////////////////////////////////////////
// Required Overrides
///////////////////////////////////////////////////////////////////////////
@Override
public Date getComparisonDate() {
return null;
}
@Override
public String getComparisonString() {
return getName();
}
///////////////////////////////////////////////////////////////////////////
// Unit Tests
///////////////////////////////////////////////////////////////////////////
public static boolean isLockedModuleValid(LockedModule lockedModule) {
if(lockedModule.getContext_id() <= 0) {
Log.d(TestHelpers.UNIT_TEST_TAG, "Invalid LockedModule id");
return false;
}
if(lockedModule.getName() == null) {
Log.d(TestHelpers.UNIT_TEST_TAG, "Invalid LockedModule name");
return false;
}
if(lockedModule.getUnlock_at() == null) {
Log.d(TestHelpers.UNIT_TEST_TAG, "Invalid LockedModule unlock date");
return false;
}
if(lockedModule.getPrerequisites() == null) {
Log.d(TestHelpers.UNIT_TEST_TAG, "Invalid LockedModule prerequisites");
return false;
}
for(int i = 0; i < lockedModule.getPrerequisites().size(); i++) {
if(lockedModule.getPrerequisites().get(i).getName() == null) {
Log.d(TestHelpers.UNIT_TEST_TAG, "Invalid LockedModule prereq name");
return false;
}
}
return true;
}
///////////////////////////////////////////////////////////////////////////
// Constructors
///////////////////////////////////////////////////////////////////////////
public LockedModule() {}
private LockedModule(Parcel in) {
in.readList(this.getPrerequisites(), ModuleName.class.getClassLoader());
this.unlock_at = in.readString();
this.name = in.readString();
this.context_id = in.readLong();
this.id = in.readLong();
this.context_type = in.readString();
this.require_sequential_progress = in.readByte() != 0;
in.readList(this.getCompletionRequirements(), ModuleCompletionRequirement.class.getClassLoader());
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeList(this.prerequisites);
dest.writeString(this.unlock_at);
dest.writeString(this.name);
dest.writeLong(this.context_id);
dest.writeLong(this.id);
dest.writeString(this.context_type);
dest.writeByte(this.require_sequential_progress ? (byte) 1 : (byte) 0);
dest.writeList(this.completion_requirements);
}
public static Creator<LockedModule> CREATOR = new Creator<LockedModule>() {
public LockedModule createFromParcel(Parcel source) {
return new LockedModule(source);
}
public LockedModule[] newArray(int size) {
return new LockedModule[size];
}
};
} | java | 14 | 0.556061 | 106 | 33.913907 | 151 | /**
* Created by Brady Larson on 9/6/13.
*
* Copyright (c) 2014 Instructure. All rights reserved.
*/ | class |
func (h *Filter) Process(_ *http.Request, wr *prompb.WriteRequest) error {
defer finalFiltering(wr)
tts := wr.Timeseries
if len(tts) == 0 {
return nil
}
clusterName, replicaName := haLabels(tts[0].Labels)
if err := validateClusterLabels(clusterName, replicaName); err != nil {
return err
}
minTUnix, maxTUnix := findDataTimeRange(tts)
minT := model.Time(minTUnix).Time()
maxT := model.Time(maxTUnix).Time()
allowInsert, leaseStart, err := h.service.CheckLease(minT, maxT, clusterName, replicaName)
if err != nil {
return fmt.Errorf("could not check ha lease: %#v", err)
}
if !minT.Before(leaseStart) {
if !allowInsert {
wr.Timeseries = wr.Timeseries[:0]
log.Debug("msg", "the samples aren't from the leader prom instance. skipping the insert", "replica", replicaName)
}
return nil
}
hasBackfill, err := h.filterBackfill(wr, minT, leaseStart, clusterName, replicaName)
if err != nil {
return fmt.Errorf("could not check backfill ha lease: %#v", err)
}
switch {
case !hasBackfill && allowInsert:
filterOutSampleRange(wr, minTUnix, toPromModelTime(leaseStart))
case hasBackfill && !allowInsert:
filterOutSampleRange(wr, toPromModelTime(leaseStart), maxTUnix+1)
case !hasBackfill && !allowInsert:
wr.Timeseries = wr.Timeseries[:0]
log.Debug("msg", "the samples aren't from the leader prom instance. skipping the insert", "replica", replicaName)
default:
}
return nil
} | go | 11 | 0.715797 | 116 | 34.475 | 40 | // FilterData validates and filters timeseries based on lease info from the service.
// When Prometheus & Promscale are running HA mode the below FilterData is used
// to validate leader replica samples & ha_locks in TimescaleDB. | function |
[Serializable]
public class SparseColumnMatrix : AbstractMatrix, ISparseColumnAccessMatrix,
IElementalAccessZeroColumnMatrix, IMatrixAccess
{
private readonly double[][] _data;
private readonly int[][] _rowIndex;
private readonly int[] _used;
private bool _isCompact;
public SparseColumnMatrix(int numRows, int numColumns, int[] nz) : base(numRows, numColumns)
{
_data = new double[numColumns][];
_rowIndex = new int[numColumns][];
for (int i = 0; i < numColumns; ++i)
{
_data[i] = new double[nz[i]];
_rowIndex[i] = new int[nz[i]];
}
_used = new int[numColumns];
}
public SparseColumnMatrix(int numRows, int numColumns, int nz) : base(numRows, numColumns)
{
_data = new double[numColumns][];
_rowIndex = new int[numColumns][];
for (int i = 0; i < numColumns; ++i)
{
_data[i] = new double[nz];
_rowIndex[i] = new int[nz];
}
_used = new int[numColumns];
}
public SparseColumnMatrix(int numRows, int numColumns) : this(numRows, numColumns, 0)
{
}
public SparseColumnMatrix(IMatrix A, int[] nz) : this(A.RowCount, A.ColumnCount, nz)
{
Blas.Default.Copy(A, this);
}
public SparseColumnMatrix(IMatrix A, int nz) : this(A.RowCount, A.ColumnCount, nz)
{
Blas.Default.Copy(A, this);
}
public SparseColumnMatrix(IMatrix A) : this(A, 0)
{
}
public virtual double[][] Data
{
get
{
Compact();
return _data;
}
}
public virtual IntDoubleVectorPair GetColumn(int i)
{
Compact(i);
return new IntDoubleVectorPair(_rowIndex[i], _data[i]);
}
public virtual void SetColumn(int i, IntDoubleVectorPair x)
{
_rowIndex[i] = x.Indices;
_data[i] = x.Data;
_used[i] = x.Data.Length;
_isCompact = false;
}
public virtual void ZeroColumns(int[] column, double diagonal)
{
foreach (int col in column)
{
if (col < row_count)
{
_data[col][0] = diagonal;
_rowIndex[col][0] = col;
_used[col] = 1;
}
else _used[col] = 0;
}
_isCompact = false;
}
public virtual void AddValue(int row, int column, double val)
{
int index = GetRowIndex(row, column);
_data[column][index] += val;
}
public virtual void SetValue(int row, int column, double val)
{
int index = GetRowIndex(row, column);
_data[column][index] = val;
}
public virtual double GetValue(int row, int column)
{
int ind = ArraySupport.BinarySearch(_rowIndex[column], row, 0, _used[column]);
if (ind != - 1) return _data[column][ind];
if (row < row_count && row >= 0) return 0.0;
throw new IndexOutOfRangeException("Row " + row + " Column " + column);
}
public virtual void AddValues(int[] row, int[] column, double[,] values)
{
for (int i = 0; i < column.Length; ++i)
{
for (int j = 0; j < row.Length; ++j)
{
int index = GetRowIndex(row[j], column[i]);
_data[column[i]][index] += values[j, i];
}
}
}
public virtual void SetValues(int[] row, int[] column, double[,] values)
{
for (int i = 0; i < column.Length; ++i)
{
for (int j = 0; j < row.Length; ++j)
{
int index = GetRowIndex(row[j], column[i]);
_data[column[i]][index] = values[j, i];
}
}
}
public virtual double[,] GetValues(int[] row, int[] column)
{
double[,] sub = new double[row.Length, column.Length];
for (int i = 0; i < row.Length; ++i)
for (int j = 0; j < column.Length; ++j)
sub[i, j] = GetValue(row[i], column[j]);
return sub;
}
public virtual void Compact()
{
if (!_isCompact)
{
for (int i = 0; i < column_count; ++i) Compact(i);
_isCompact = true;
}
}
private void Compact(int column)
{
if (_used[column] < _data[column].Length)
{
double[] newData = new double[_used[column]];
Array.Copy(_data[column], 0, newData, 0, _used[column]);
int[] newInd = new int[_used[column]];
Array.Copy(_rowIndex[column], 0, newInd, 0, _used[column]);
_data[column] = newData;
_rowIndex[column] = newInd;
}
}
private int GetRowIndex(int row, int col)
{
int[] curRow = _rowIndex[col];
double[] curDat = _data[col];
int ind = ArraySupport.BinarySearchGreater(curRow, row, 0, _used[col]);
if (ind < _used[col] && curRow[ind] == row)
return ind;
if (row < 0 || row >= row_count)
throw new IndexOutOfRangeException(" Row " + row + " Column " + col);
_used[col]++;
if (_used[col] > curDat.Length)
{
int newLength = 1;
if (curDat.Length != 0)
newLength = 2*curDat.Length;
int[] newRow = new int[newLength];
double[] newDat = new double[newLength];
Array.Copy(curRow, 0, newRow, 0, curDat.Length);
Array.Copy(curDat, 0, newDat, 0, curDat.Length);
_rowIndex[col] = newRow;
_data[col] = newDat;
curRow = newRow;
curDat = newDat;
}
for (int i = _used[col] - 1; i >= ind + 1; --i)
{
curRow[i] = curRow[i - 1];
curDat[i] = curDat[i - 1];
}
curRow[ind] = row;
curDat[ind] = 0.0;
_isCompact = false;
return ind;
}
} | c# | 19 | 0.591869 | 97 | 27.155556 | 180 | /// <summary> Sparse matrix stored as 2D ragged columns. For best performance during
/// assembly, ensure that enough memory is allocated at construction time,
/// as re-allocation may be time-consuming.
/// </summary> | class |
public class TestngListener implements ITestListener, IExecutionListener {
private static final Logger LOGGER = Logger.getLogger(TestngListener.class);
private final String hr = StringUtils.repeat("-", 100);
private enum RunResult {SUCCESS, FAILED, SKIPPED, TestFailedButWithinSuccessPercentage }
@Override
public void onTestStart(ITestResult result) {
LOGGER.info(hr);
LOGGER.info(
String.format("Testing going to start for: %s.%s(%s)", result.getTestClass().getName(),
result.getName(), Arrays.toString(result.getParameters())));
NDC.push(result.getName());
}
private void endOfTestHook(ITestResult result, RunResult outcome) {
LOGGER.info(
String.format("Testing going to end for: %s.%s(%s) ----- Status: %s", result.getTestClass().getName(),
result.getName(), Arrays.toString(result.getParameters()), outcome));
NDC.pop();
LOGGER.info(hr);
}
@Override
public void onTestSuccess(ITestResult result) {
endOfTestHook(result, RunResult.SUCCESS);
}
@Override
public void onTestFailure(ITestResult result) {
endOfTestHook(result, RunResult.FAILED);
LOGGER.info(ExceptionUtils.getStackTrace(result.getThrowable()));
LOGGER.info(hr);
}
@Override
public void onTestSkipped(ITestResult result) {
endOfTestHook(result, RunResult.SKIPPED);
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
endOfTestHook(result, RunResult.TestFailedButWithinSuccessPercentage);
}
@Override
public void onStart(ITestContext context) {
}
@Override
public void onFinish(ITestContext context) {
}
@Override
public void onExecutionStart() {
}
@Override
public void onExecutionFinish() {
}
} | java | 14 | 0.657427 | 118 | 29.365079 | 63 | /**
* Testng listener class. This is useful for things that are applicable to all the tests as well
* taking actions that depend on test results.
*/ | class |
func (i *fileLedgerIterator) Next() (*cb.Block, cb.Status) {
for {
if i.blockNumber < i.ledger.Height() {
block, err := i.ledger.blockStore.RetrieveBlockByNumber(i.blockNumber)
if err != nil {
return nil, cb.Status_SERVICE_UNAVAILABLE
}
i.blockNumber++
return block, cb.Status_SUCCESS
}
<-i.ledger.signal
}
} | go | 13 | 0.668657 | 73 | 24.846154 | 13 | // Next blocks until there is a new block available, or returns an error if the
// next block is no longer retrievable | function |
public void rsPlot(PlotFrame frame, Polynomial p, int index, double precision, double left, double right,
int subintervals) {
double delta = (Math.abs(right-left))/subintervals;
PolyPractice popeye = new PolyPractice();
for (double i = left; i <= right; i+=precision) {
frame.append(1, i, popeye.eval(p,i));
}
for (int i = 1; i <= subintervals; i++) {
slicePlot(frame, p, left+(i-1)*delta, left+i*delta);
}
} | java | 12 | 0.662791 | 105 | 38.181818 | 11 | /**
* This method graphs the input polynomial on the input PlotFrame.
* It also draws the regions used to calculate a particular Riemann sum.
* If RiemannSumRule extends Riemann and RSR is an object of type RiemannSumRule,
* then RSR.rsPlot should graph the input polynomial and draw the regions used to calculate the
* Riemann sum using the rule implemented in RiemannSumRule.
* @param frame is the PlotFrame on which the polynomial and the Riemann sum are drawn
* @param p is the polynomial whose Riemann sum is to be drawn
* @param index is the number associated to the collection of (x,y) coordinates that make up the dataset which,
* when plotted, is the graph of the polynomial
* @param precision is the difference between the x-coordinates of two adjacent
* points on the graph of the polynomial
* @param left is the left hand endpoint of the Riemann sum
* @param right is the right hand endpoint of the Riemann sum
* @param subintervals is the number of subintervals in the Riemann sum
*/ | function |
func (v *VolumeEntry) blockHostingSizeIsCorrect(used int) bool {
logger.Debug("volume [%v]: comparing %v == %v + %v + %v",
v.Info.Id, v.Info.Size,
used, v.Info.BlockInfo.FreeSize, v.Info.BlockInfo.ReservedSize)
unused := v.Info.BlockInfo.FreeSize + v.Info.BlockInfo.ReservedSize
if v.Info.Size != (used + unused) {
logger.Warning("detected volume [%v] has size %v != %v + %v + %v",
v.Info.Id, v.Info.Size,
used, v.Info.BlockInfo.FreeSize, v.Info.BlockInfo.ReservedSize)
return false
}
return true
} | go | 11 | 0.68472 | 68 | 38.846154 | 13 | // blockHostingSizeIsCorrect returns true if the total size of the volume
// is equal to the sum of the used, free and reserved block hosting size values.
// The used size must be provided and should be calculated based on the sizes
// of the block volumes. | function |
public static String utf8BytesToString(byte[] bytes, int start, int length) {
char[] chars = localBuffer.get();
if (chars == null || chars.length < length) {
chars = new char[length];
localBuffer.set(chars);
}
int outAt = 0;
for (int at = start; length > 0; /*at*/) {
int v0 = bytes[at] & 0xFF;
char out;
switch (v0 >> 4) {
case 0x00: case 0x01: case 0x02: case 0x03:
case 0x04: case 0x05: case 0x06: case 0x07: {
length--;
if (v0 == 0) {
return throwBadUtf8(v0, at);
}
out = (char) v0;
at++;
break;
}
case 0x0c: case 0x0d: {
length -= 2;
if (length < 0) {
return throwBadUtf8(v0, at);
}
int v1 = bytes[at + 1] & 0xFF;
if ((v1 & 0xc0) != 0x80) {
return throwBadUtf8(v1, at + 1);
}
int value = ((v0 & 0x1f) << 6) | (v1 & 0x3f);
if ((value != 0) && (value < 0x80)) {
/*
* This should have been represented with
* one-byte encoding.
*/
return throwBadUtf8(v1, at + 1);
}
out = (char) value;
at += 2;
break;
}
case 0x0e: {
length -= 3;
if (length < 0) {
return throwBadUtf8(v0, at);
}
int v1 = bytes[at + 1] & 0xFF;
if ((v1 & 0xc0) != 0x80) {
return throwBadUtf8(v1, at + 1);
}
int v2 = bytes[at + 2] & 0xFF;
if ((v2 & 0xc0) != 0x80) {
return throwBadUtf8(v2, at + 2);
}
int value = ((v0 & 0x0f) << 12) | ((v1 & 0x3f) << 6) |
(v2 & 0x3f);
if (value < 0x800) {
/*
* This should have been represented with one- or
* two-byte encoding.
*/
return throwBadUtf8(v2, at + 2);
}
out = (char) value;
at += 3;
break;
}
default: {
return throwBadUtf8(v0, at);
}
}
chars[outAt] = out;
outAt++;
}
return new String(chars, 0, outAt);
} | java | 17 | 0.315609 | 77 | 36.87013 | 77 | /**
* Converts an array of UTF-8 bytes into a string.
*
* @param bytes non-null; the bytes to convert
* @param start the start index of the utf8 string to convert
* @param length the length of the utf8 string to convert, not including any null-terminator that might be present
* @return non-null; the converted string
*/ | function |
def _service(method, request):
response = requests.post(API_URL, data=json.dumps({method: request}))
try:
response_dict = response.json()
except:
raise ServiceError('service did not return a valid response') from None
if "error" in response_dict:
raise ServiceError(response_dict['error'])
if method not in response_dict:
raise ServiceError('service did not return a valid response')
return response_dict | python | 12 | 0.681128 | 79 | 41 | 11 |
Send a request to the service API, raise exceptions for any
unexpected responses, and returned a parsed result.
| function |
public class AAShapePipe implements ShapeDrawPipe, ParallelogramPipe {
static RenderingEngine renderengine = RenderingEngine.getInstance();
CompositePipe outpipe;
public AAShapePipe(CompositePipe pipe) {
outpipe = pipe;
}
public void draw(SunGraphics2D sg, Shape s) {
BasicStroke bs;
if (sg.stroke instanceof BasicStroke) {
bs = (BasicStroke) sg.stroke;
} else {
s = sg.stroke.createStrokedShape(s);
bs = null;
}
renderPath(sg, s, bs);
}
public void fill(SunGraphics2D sg, Shape s) {
renderPath(sg, s, null);
}
private static Rectangle2D computeBBox(double ux1, double uy1, double ux2, double uy2) {
if ((ux2 -= ux1) < 0) {
ux1 += ux2;
ux2 = -ux2;
}
if ((uy2 -= uy1) < 0) {
uy1 += uy2;
uy2 = -uy2;
}
return new Rectangle2D.Double(ux1, uy1, ux2, uy2);
}
public void fillParallelogram(SunGraphics2D sg, double ux1, double uy1, double ux2, double uy2, double x, double y,
double dx1, double dy1, double dx2, double dy2) {
Region clip = sg.getCompClip();
int abox[] = new int[4];
AATileGenerator aatg = renderengine.getAATileGenerator(x, y, dx1, dy1, dx2, dy2, 0, 0, clip, abox);
if (aatg == null) {
// Nothing to render
return;
}
renderTiles(sg, computeBBox(ux1, uy1, ux2, uy2), aatg, abox);
}
public void drawParallelogram(SunGraphics2D sg, double ux1, double uy1, double ux2, double uy2, double x, double y,
double dx1, double dy1, double dx2, double dy2, double lw1, double lw2) {
Region clip = sg.getCompClip();
int abox[] = new int[4];
AATileGenerator aatg = renderengine.getAATileGenerator(x, y, dx1, dy1, dx2, dy2, lw1, lw2, clip, abox);
if (aatg == null) {
// Nothing to render
return;
}
// Note that bbox is of the original shape, not the wide path.
// This is appropriate for handing to Paint methods...
renderTiles(sg, computeBBox(ux1, uy1, ux2, uy2), aatg, abox);
}
private static byte[] theTile;
private synchronized static byte[] getAlphaTile(int len) {
byte[] t = theTile;
if (t == null || t.length < len) {
t = new byte[len];
} else {
theTile = null;
}
return t;
}
private synchronized static void dropAlphaTile(byte[] t) {
theTile = t;
}
public void renderPath(SunGraphics2D sg, Shape s, BasicStroke bs) {
boolean adjust = (bs != null && sg.strokeHint != SunHints.INTVAL_STROKE_PURE);
boolean thin = (sg.strokeState <= SunGraphics2D.STROKE_THINDASHED);
Region clip = sg.getCompClip();
int abox[] = new int[4];
AATileGenerator aatg = renderengine.getAATileGenerator(s, sg.transform, clip, bs, thin, adjust, abox);
if (aatg == null) {
// Nothing to render
return;
}
renderTiles(sg, s, aatg, abox);
}
public void renderTiles(SunGraphics2D sg, Shape s, AATileGenerator aatg, int abox[]) {
Object context = null;
byte alpha[] = null;
try {
context = outpipe
.startSequence(sg, s, new Rectangle(abox[0], abox[1], abox[2] - abox[0], abox[3] - abox[1]), abox);
int tw = aatg.getTileWidth();
int th = aatg.getTileHeight();
alpha = getAlphaTile(tw * th);
byte[] atile;
for (int y = abox[1]; y < abox[3]; y += th) {
for (int x = abox[0]; x < abox[2]; x += tw) {
int w = Math.min(tw, abox[2] - x);
int h = Math.min(th, abox[3] - y);
int a = aatg.getTypicalAlpha();
if (a == 0x00 || outpipe.needTile(context, x, y, w, h) == false) {
aatg.nextTile();
outpipe.skipTile(context, x, y);
continue;
}
if (a == 0xff) {
atile = null;
aatg.nextTile();
} else {
atile = alpha;
aatg.getAlpha(alpha, 0, tw);
}
outpipe.renderPathTile(context, atile, 0, tw, x, y, w, h);
}
}
} finally {
aatg.dispose();
if (context != null) {
outpipe.endSequence(context);
}
if (alpha != null) {
dropAlphaTile(alpha);
}
}
}
} | java | 17 | 0.510764 | 119 | 32.13986 | 143 | /**
* This class is used to convert raw geometry into 8-bit alpha tiles
* using an AATileGenerator for application by the next stage of
* the pipeline.
* This class sets up the Generator and computes the alpha tiles
* and then passes them on to a CompositePipe object for painting.
*/ | class |
def create_cluster_role_binding(self, name: str, subjects: List[ObjectMeta], role_ref_name: str):
self.execute_kubernetes_client(
self._create_cluster_role_binding,
metadata={
"name": name,
},
role_ref_name=role_ref_name,
subjects=subjects,
) | python | 10 | 0.547904 | 97 | 36.222222 | 9 | Creates a cluster role binding
Parameters
----------
name
cluster role binding name
subjects
subjects that the permissions defined in the cluster role with the given
name are granted to
role_ref_name
cluster role defining permissions granted to the given subjects
| function |
char *
asc_tolower(const char *buff, size_t nbytes)
{
char *result;
char *p;
if (!buff)
return NULL;
result = pnstrdup(buff, nbytes);
for (p = result; *p; p++)
*p = pg_ascii_tolower((unsigned char) *p);
return result;
} | c | 11 | 0.617021 | 44 | 18.666667 | 12 | /*
* ASCII-only lower function
*
* We pass the number of bytes so we can pass varlena and char*
* to this function. The result is a palloc'd, null-terminated string.
*/ | function |
int PlatformCore::GetDisplayCount()
{
MonitorSet monitors;
monitors.MonitorCount = 0;
EnumDisplayMonitors(NULL, NULL, MonitorEnumProc, (LPARAM)&monitors);
int primary = 0;
MONITORINFOEX info;
for (int m=0; m < monitors.MonitorCount; m++)
{
info.cbSize = sizeof(MONITORINFOEX);
GetMonitorInfo(monitors.Monitors[m], &info);
if (info.dwFlags & MONITORINFOF_PRIMARY)
primary++;
}
if (primary > 1)
return 1;
else
return monitors.MonitorCount;
} | c++ | 10 | 0.601083 | 72 | 28.210526 | 19 | // Returns the number of active screens for extended displays and 1 for mirrored display | function |
def customjson(jsonid, json_data, account, active, export):
if jsonid is None:
print("First argument must be the custom_json id")
if json_data is None:
print("Second argument must be the json_data, can be a string or a file name.")
data = import_custom_json(jsonid, json_data)
if data is None:
return
stm = shared_blockchain_instance()
if stm.rpc is not None:
stm.rpc.rpcconnect()
if not account:
account = stm.config["default_account"]
if not unlock_wallet(stm):
return
acc = Account(account, blockchain_instance=stm)
if active:
tx = stm.custom_json(jsonid, data, required_auths=[account])
else:
tx = stm.custom_json(jsonid, data, required_posting_auths=[account])
export_trx(tx, export)
tx = json.dumps(tx, indent=4)
print(tx) | python | 12 | 0.642689 | 87 | 35.913043 | 23 | Broadcasts a custom json
First parameter is the cusom json id, the second field is a json file or a json key value combination
e.g. beempy customjson -a holger80 dw-heist username holger80 amount 100
| function |
public class SMIMESigned
extends CMSSignedData {
static {
final MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("application/pkcs7-signature;; x-java-content-handler=org.spongycastle.mail.smime.handlers.pkcs7_signature");
mc.addMailcap("multipart/signed;; x-java-content-handler=org.spongycastle.mail.smime.handlers.multipart_signed");
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
CommandMap.setDefaultCommandMap(mc);
return null;
}
});
}
Object message;
MimeBodyPart content;
/**
* base constructor using a defaultContentTransferEncoding of 7bit
*
* @throws MessagingException on an error extracting the signature or
* otherwise processing the message.
* @throws CMSException if some other problem occurs.
*/
public SMIMESigned(
MimeMultipart message)
throws MessagingException, CMSException {
super(new CMSProcessableBodyPartInbound(message.getBodyPart(0)), getInputStream(message.getBodyPart(1)));
this.message = message;
this.content = (MimeBodyPart) message.getBodyPart(0);
}
private static InputStream getInputStream(
Part bodyPart)
throws MessagingException {
try {
if (bodyPart.isMimeType("multipart/signed")) {
throw new MessagingException("attempt to create signed data object from multipart content - use MimeMultipart constructor.");
}
return bodyPart.getInputStream();
} catch (IOException e) {
throw new MessagingException("can't extract input stream: " + e);
}
}
} | java | 15 | 0.638752 | 141 | 34.843137 | 51 | /**
* general class for handling a pkcs7-signature message.
* <p>
* A simple example of usage - note, in the example below the validity of
* the certificate isn't verified, just the fact that one of the certs
* matches the given signer...
* <p>
* <pre>
* CertStore certs = s.getCertificates("Collection", "BC25519");
* SignerInformationStore signers = s.getSignerInfos();
* Collection c = signers.getSigners();
* Iterator it = c.iterator();
*
* while (it.hasNext())
* {
* SignerInformation signer = (SignerInformation)it.next();
* Collection certCollection = certs.getCertificates(signer.getSID());
*
* Iterator certIt = certCollection.iterator();
* X509Certificate cert = (X509Certificate)certIt.next();
*
* if (signer.verify(cert.getPublicKey()))
* {
* verified++;
* }
* }
* </pre>
* <p>
* Note: if you are using this class with AS2 or some other protocol
* that does not use 7bit as the default content transfer encoding you
* will need to use the constructor that allows you to specify the default
* content transfer encoding, such as "binary".
* </p>
*/ | class |
class FuncVerifier {
public:
LogicalResult failure() { return mlir::failure(); }
LogicalResult failure(const Twine &message, Operation &value) {
return value.emitError(message);
}
LogicalResult failure(const Twine &message, Function &fn) {
return fn.emitError(message);
}
LogicalResult failure(const Twine &message, Block &bb) {
if (!bb.empty())
return failure(message, bb.front());
return failure(message, fn);
}
Dialect *getDialectForAttribute(const NamedAttribute &attr) {
assert(attr.first.strref().contains('.') && "expected dialect attribute");
auto dialectNamePair = attr.first.strref().split('.');
return fn.getContext()->getRegisteredDialect(dialectNamePair.first);
}
template <typename ErrorContext>
LogicalResult verifyAttribute(Attribute attr, ErrorContext &ctx) {
if (!attr.isOrContainsFunction())
return success();
if (auto fnAttr = attr.dyn_cast<FunctionAttr>()) {
if (!fnAttr.getValue())
return failure("attribute refers to deallocated function!", ctx);
if (fnAttr.getValue()->getModule() != fn.getModule())
return failure("attribute refers to function '" +
Twine(fnAttr.getValue()->getName()) +
"' defined in another module!",
ctx);
return success();
}
for (auto elt : attr.cast<ArrayAttr>().getValue())
if (failed(verifyAttribute(elt, ctx)))
return failure();
return success();
}
LogicalResult verify();
LogicalResult verifyBlock(Block &block, bool isTopLevel);
LogicalResult verifyOperation(Operation &op);
LogicalResult verifyDominance(Block &block);
LogicalResult verifyOpDominance(Operation &op);
explicit FuncVerifier(Function &fn)
: fn(fn), identifierRegex("^[a-zA-Z_][a-zA-Z_0-9\\.\\$]*$") {}
private:
Function &fn;
DominanceInfo *domInfo = nullptr;
llvm::Regex identifierRegex;
llvm::StringMap<bool> dialectAllowsUnknownOps;
} | c++ | 20 | 0.663815 | 78 | 37.980392 | 51 | /// This class encapsulates all the state used to verify a function body. It is
/// a pervasive truth that this file treats "true" as an error that needs to be
/// recovered from, and "false" as success.
/// | class |
final class UtilizationObjective extends AbstractObjective
implements WorkloadDependentObjective
{
/**
* The name of the class.
*/
static final String name = "utilization";
/**
* Short run detection.
*/
private List zoneList = new LinkedList();
/**
* Format for printing utilization.
*/
private static final DecimalFormat uf = new DecimalFormat("0.00");
/**
* Solver used to calculate delta, i.e. gap, between target and
* actual utilization values.
*/
private Solver gapSolver;
/**
* Determine whether an objective is satisfied. If the
* objective is still satisfied, return false; otherwise
* return true.
*
* The assessment of control is made by the monitoring class
* using the supplied Expression and resource.
*
* @param conf The configuration to be examined
* @param solver The solving interface used to get utilization
* information
* @param elem The element to which the objective belongs
*
* @throws PoolsException if there is an error examining the
* pool configuration
* @throws StaleMonitorException if there is an error accessing
* the element's ResourceMonitor
*/
public boolean examine(Configuration conf, Solver solver,
Element elem) throws PoolsException, StaleMonitorException
{
KVOpExpression kve = (KVOpExpression) getExpression();
ResourceMonitor mon;
/*
* If there is no resource monitor, then we cannot
* make an assessment of the objective's achievability.
* Log a message to make clear that this objective is
* not being assessed and then indicate that
* the objective has been achieved.
*/
try {
mon = solver.getMonitor().get((Resource)elem);
} catch (StaleMonitorException sme) {
Poold.MON_LOG.log(Severity.INFO,
elem.toString() +
" utilization objective not measured " +
toString() + " as there are no available " +
"statistics.");
return (false);
}
gapSolver = solver;
double val = solver.getMonitor().getUtilization((Resource)elem);
StatisticList sl = (StatisticList) mon.get("utilization");
int zone = sl.getZone(kve, val);
if (zoneList.size() == 9) {
zoneList.remove(0);
}
zoneList.add(new Integer(sl.getZoneMean(val)));
/*
* Evaluate whether or not this objective is under
* control.
*/
if ((zone & StatisticOperations.ZONEZ) ==
StatisticOperations.ZONEZ) {
/*
* If the objective is GT or LT, then don't
* return true as long as the objective is
* satisfied.
*/
if (kve.getOp() == KVOpExpression.LT &&
(zone & StatisticOperations.ZONET) ==
StatisticOperations.ZONELT)
return (false);
if (kve.getOp() == KVOpExpression.GT &&
(zone & StatisticOperations.ZONET) ==
StatisticOperations.ZONEGT)
return (false);
Poold.MON_LOG.log(Severity.INFO,
elem.toString() +
" utilization objective not satisfied " +
toString() + " with utilization " + uf.format(val) +
" (control zone bounds exceeded)");
return (true);
}
/*
* Check if our statistics need to be recalculated.
*/
checkShort(mon, elem, val);
return (false);
}
/**
* Calculates the value of a configuration in terms of this
* objective.
*
* Every set must be classified with a control zone when this
* function is called. The move can be assessed in terms of
* the control violation type. zone violations which are minor
* are offered a lower contribution than more significant
* violations.
*
* @param conf Configuration to be scored.
* @param move Move to be scored.
* @param elem The element to which the objective applies
* @throws Exception If an there is an error in execution.
*/
public double calculate(Configuration conf, Move move, Element elem)
throws PoolsException
{
KVOpExpression kve = (KVOpExpression) getExpression();
double ret;
/*
* If the move is from the examined element, then
* check to see if the recipient has any
* objectives. If not, score the move poorly since we
* should never want to transfer resources to a
* recipient with no objectives. If there are
* objectives, then return the delta between target
* performance and actual performance for this
* element.
*
* If the move is to the examined element, then check
* to see if the donor has any objectives. If not,
* score the move highly, since we want to favour
* those resources with objectives. If there are
* objectives, return the delta between actual and
* target performance.
*
* If the element is neither the recipient or the
* donor of this proposed move, then score the move
* neutrally as 0.
*/
try {
double val, gap;
StatisticList sl;
if (elem.equals(move.getFrom())) {
val = gapSolver.getMonitor().
getUtilization(move.getFrom());
sl = (StatisticList) gapSolver.getMonitor().
get(move.getFrom()).get("utilization");
gap = sl.getGap(kve, val) / 100;
if (gapSolver.getObjectives(move.getTo()) ==
null) {
/*
* Moving to a resource with
* no objectives should always
* be viewed unfavourably. The
* degree of favourability is
* thus bound between 0 and
* -1. If the source gap is
* negative, then subtract it
* from -1 to get the
* score. If positive,
* just return -1.
*/
if (gap < 0) {
ret = -1 - gap;
} else {
ret = -1;
}
} else {
ret = 0 - gap;
}
} else if (elem.equals(move.getTo())) {
val = gapSolver.getMonitor().
getUtilization(move.getTo());
sl = (StatisticList) gapSolver.getMonitor().
get(move.getTo()).get("utilization");
gap = sl.getGap(kve, val) / 100;
if (gapSolver.getObjectives(move.getFrom()) ==
null) {
/*
* Moving from a resource with
* no objectives should always
* be viewed favourably. The
* degree of favourability is
* thus bound between 0 and
* 1. If the destination gap
* is negative, then add to 1
* to get the score. If
* positive, just return 1.
*/
if (gap < 0) {
ret = 0 - gap;
} else {
ret = 1;
}
} else {
ret = 0 + gap;
}
} else {
ret = 0;
}
} catch (StaleMonitorException sme) {
/*
* We should always find a monitor,
* but if we can't then just assume
* this is a neutral move and return
* 0.
*/
ret = 0;
}
Poold.MON_LOG.log(Severity.DEBUG, "ret: " + ret);
return (ret);
}
/**
* Check whether or not a set's statistics are still useful
* for making decision..
*
* Each set is controlled in terms of the zones of control
* based in terms of standard deviations from a mean. If the
* utilization of the set is not fluctuating normally around a
* mean, these checks will cause the accumulated statistics to
* be discarded and control suspended until a new sufficient
* set of data is accumulated.
*
* @param mon Resource monitor to examine.
* @param elem Element to which the resource monitor belongs.
* @param val Latest monitored value.
*/
private void checkShort(ResourceMonitor mon, Element elem, double val)
{
boolean checkOne = true;
int checkOnePos = 0;
boolean doCheckOne = false;
Iterator itZones = zoneList.iterator();
while (itZones.hasNext()) {
int zone = ((Integer) itZones.next()).intValue();
if (doCheckOne) {
if (checkOne) {
if ((zone & StatisticOperations.ZONET)
!= checkOnePos) {
checkOne = false;
}
}
} else {
if (zoneList.size() >= 9) {
checkOnePos = zone &
StatisticOperations.ZONET;
doCheckOne = true;
}
}
}
if (zoneList.size() >= 9 && checkOne) {
Poold.MON_LOG.log(Severity.INFO,
elem.toString() +
" utilization objective statistics reinitialized " +
toString() + " with utilization " + uf.format(val) +
" (nine points on same side of mean)");
mon.resetData("utilization");
zoneList.clear();
}
}
} | java | 18 | 0.645533 | 71 | 27.789286 | 280 | /**
* A resource set utilization based objective which will assess moves
* in terms of their (likely) impact on the future performance of a
* resource set with respect to it's specified utilization objective.
*
* The utilization objective must be specified in terms of a
* KVOpExpression, see the class definition for information about the
* form of these expressions. The objective can be examined in terms
* of it's compliance with the aid of a monitoring object. The actual
* assessment of compliance is indicated by the associated monitoring
* object, with this class simply acting as a co-ordinator of the
* relevant information.
*/ | class |
public void SetExpandAll(bool expanded)
{
foreach (var control in ResizeContainerControls)
{
control?.ToggleExpandAction(expanded);
}
} | c# | 10 | 0.536946 | 60 | 28.142857 | 7 | /// <summary>
/// Sets the expand state of all the message boxes within the control to a specified value.
/// </summary>
/// <param name="expanded">if set to <c>true</c> all the message boxes within the control are expanded.</param> | function |
private String retrieveDnsLabel(LookupContext ctx) throws LookupException
{
ctx.setPrefix(ctx.getType() + Constants.NAME);
ctx.setRrType(Type.PTR);
Record[] records = lookup(ctx);
String dnsLabel = null;
if (records != null) {
for (Record record : records) {
if (record instanceof PTRRecord) {
dnsLabel = PointerRecord.build((PTRRecord) record).getDnsLabel();
}
}
}
if (dnsLabel == null) {
throw ExceptionsUtil.build(StatusCode.RESOLUTION_NAME_ERROR,
FormattingUtil.unableToRetrieveLabel(ctx.getDomainName().fqdnWithPrefix(ctx.getPrefix())),
errorsTrace.get());
} else {
return dnsLabel;
}
} | java | 15 | 0.505051 | 114 | 41.47619 | 21 | /**
* Retrieve the DNS domain label for the browsing domain and specified Service Type.
*
* @param ctx A <code>LookupContext</code> defining this lookup parameters
* @return A <code>String</code> containing the DNS domain label
* @throws LookupException In case of unsuccessful DNS lookup; the <code>StatusCode</code>
* is returned as part of this error.
*/ | function |
def source_releasability(request):
if request.method == 'POST' and request.is_ajax():
type_ = request.POST.get('type', None)
id_ = request.POST.get('id', None)
name = request.POST.get('name', None)
note = request.POST.get('note', None)
action = request.POST.get('action', None)
date = request.POST.get('date', datetime.datetime.now())
if not isinstance(date, datetime.datetime):
date = parse(date, fuzzy=True)
user = str(request.user.username)
if not type_ or not id_ or not name or not action:
error = "Modifying releasability requires a type, id, source, and action"
return render_to_response("error.html",
{"error" : error },
RequestContext(request))
if action == "add":
result = add_releasability(type_, id_, name, user)
elif action == "add_instance":
result = add_releasability_instance(type_, id_, name, user,
note=note)
elif action == "remove":
result = remove_releasability(type_, id_, name, user)
elif action == "remove_instance":
result = remove_releasability_instance(type_, id_, name, date, user)
else:
error = "Unknown releasability action: %s" % action
return render_to_response("error.html",
{"error" : error },
RequestContext(request))
if result['success']:
subscription = {
'type': type_,
'id': id_
}
html = render_to_string('releasability_header_widget.html',
{'releasability': result['obj'],
'subscription': subscription},
RequestContext(request))
response = {'success': result['success'],
'html': html}
else:
response = {'success': result['success'],
'error': result['message']}
return HttpResponse(json.dumps(response),
content_type="application/json")
else:
error = "Expected AJAX POST!"
return render_to_response("error.html",
{"error" : error },
RequestContext(request)) | python | 15 | 0.483858 | 85 | 48.215686 | 51 |
Modify a top-level object's releasability. Should be an AJAX POST.
:param request: Django request.
:type request: :class:`django.http.HttpRequest`
:returns: :class:`django.http.HttpResponse`
| function |
private Button createActionButton(String actionLabel) {
Button button = new Button(getActivity());
button.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable
.action_button_background));
button.setText(actionLabel);
CalligraphyUtils.applyFontToTextView(getActivity(), button, ConfigurationManager
.getInstance(getActivity()).getTypefacePath(ConfigurationConstants.REGULAR_FONT));
LinearLayout.LayoutParams params =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
int margin = (int) getResources().getDimension(R.dimen.error_button_side_margin);
params.setMargins(margin, 0, margin, 0);
button.setLayoutParams(params);
button.setTextColor(ContextCompat
.getColorStateList(getActivity(), R.color
.action_button_text_color_selector));
button.setFocusable(true);
button.setFocusableInTouchMode(true);
button.setNextFocusDownId(button.getId());
button.setNextFocusUpId(button.getId());
button.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable
.action_button_background));
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.doButtonClick(ErrorDialogFragment.this,
ErrorUtils.getErrorButtonType(
ErrorDialogFragment.this.getActivity(),
(((TextView) v).getText()).toString()),
(ErrorUtils.ERROR_CATEGORY) getArguments().get
(ARG_ERROR_CATEGORY));
}
});
return button;
} | java | 20 | 0.572493 | 98 | 56.571429 | 35 | /**
* Creates the action button.
*
* @param actionLabel The text to be displayed on the action button.
* @return The instantiated button.
*/ | function |
def compute(self, nof_coefficients, ncap=None, permute=None, residual=False, get_trafo=False):
if ncap is None:
ncap = self.discretized_bath.max_nof_coefficients
if ncap < nof_coefficients:
print('Accuracy parameter set too low. Must be >= nof_coefficients. Automatically set ncap=nof_coefficients')
ncap = nof_coefficients
if nof_coefficients > self.discretized_bath.max_nof_coefficients:
print('Number of coefficients to calculate must smaller or equal the size of the discretized bath!')
raise AssertionError
if self.discretized_bath.max_nof_coefficients < ncap:
print('Error: Buffer of discretized bath not sufficient. Must fit at least ncap = ' + str(ncap) +
'elements')
raise AssertionError
if nof_coefficients > self.max_nof_coefficients:
print('Error: Selected number of coefficients too high! Must increase max_nof_coefficients')
raise AssertionError
assert nof_coefficients <= ncap
self.sorting.select(permute)
cutoff = self._get_cutoff(nof_coefficients)
try:
self._update_tridiag(ncap)
except EOFCoefficients as err:
print('Limit for the calculation of gamma/xi coefficients reached. Using fixed max. accuracy of '
'ncap = ' + str(err.nof_calc_coeff))
self._update_tridiag(err.nof_calc_coeff)
alpha, beta, info = self.tridiag.get_tridiagonal(cutoff=cutoff, residual=residual,
get_trafo=get_trafo)
info['ncap'] = ncap
if self.type == 'full':
self._c0, self.omega_buf[:nof_coefficients], self.t_buf[:nof_coefficients - 1] = \
beta[0], alpha[1:], beta[1:]
elif self.type == 'bath':
self._c0, self.omega_buf[:nof_coefficients], self.t_buf[:nof_coefficients - 1] = \
np.sqrt(self.discretized_bath.eta_0), alpha, beta
else:
print('Unrecognized tridiagonalisation type')
raise AssertionError
self.nof_calculated_coefficients = nof_coefficients
return info | python | 13 | 0.612568 | 121 | 55.74359 | 39 |
Central method, which computes the chain coefficients via tridigonalization from the discretized bath
coefficients. Stores the result in the internal buffers of the object, accessible via
c0, omega and t. Uses a fixed accuracy parameter/number of discretized coefficients ncap for the
computation.
:param nof_coefficients: Number of chain coefficients to be calculated
:param ncap: Accuracy/Number of star coefficients to be used (must not be more than the discretized bath
passed upon construction can support)
:param permute: If the star coefficients should be permuted before the tridiagonalization (essentially
sorting them, see utils.sorting.sort_star_coefficients for an explanation of the
possible parameters). This may help increase numerical stability for Lanczos tridiagonalization
specifically
:param residual: If set True computes the residual for the tridiagonalization.
This may use extra memory!
:param get_trafo: Returns the corresponding transformation matrix
:return: info dict with entries: 'ncap': ncap used for the tridiagonalization.
'res': Residual of the tridiagonalization
'trafo': Transformation matrix if selected
| function |
private byte[] unzip(final byte[] bytes, final int imgWidth,
final int imgHeight) throws DataFormatException {
final byte[] data = new byte[imgWidth * imgHeight * 8];
int count = 0;
final Inflater inflater = new Inflater();
inflater.setInput(bytes);
count = inflater.inflate(data);
inflater.end();
final byte[] uncompressedData = new byte[count];
System.arraycopy(data, 0, uncompressedData, 0, count);
return uncompressedData;
} | java | 9 | 0.627907 | 63 | 42.083333 | 12 | /**
* Uncompress the image using the ZIP format.
* @param bytes the compressed image data.
* @param imgWidth the width of the image in pixels.
* @param imgHeight the height of the image in pixels.
* @return the uncompressed image.
* @throws DataFormatException if the compressed image is not in the ZIP
* format or cannot be uncompressed.
*/ | function |
def _validate_translation_suggestion_counts(cls, item):
supported_language_codes = [
language_code['id'] for language_code in
constants.SUPPORTED_AUDIO_LANGUAGES
]
all_translation_suggestion_models_in_review = (
suggestion_models.GeneralSuggestionModel.get_all()
.filter(suggestion_models.GeneralSuggestionModel.status == (
suggestion_models.STATUS_IN_REVIEW))
.filter(
suggestion_models.GeneralSuggestionModel.suggestion_type == (
feconf.SUGGESTION_TYPE_TRANSLATE_CONTENT))
)
for language_code in supported_language_codes:
expected_translation_suggestion_count = (
all_translation_suggestion_models_in_review.filter(
suggestion_models.GeneralSuggestionModel.language_code == (
language_code))
.count()
)
if language_code in item.translation_suggestion_counts_by_lang_code:
model_translation_suggestion_count = (
item.translation_suggestion_counts_by_lang_code[
language_code]
)
if model_translation_suggestion_count != (
expected_translation_suggestion_count):
cls._add_error(
'translation suggestion %s' % (
base_model_validators.ERROR_CATEGORY_COUNT_CHECK),
'Entity id %s: Translation suggestion count for '
'language code %s: %s does not match the expected '
'translation suggestion count for language code %s: '
'%s' % (
item.id, language_code,
model_translation_suggestion_count, language_code,
expected_translation_suggestion_count)
)
elif expected_translation_suggestion_count != 0:
cls._add_error(
'translation suggestion count %s' % (
base_model_validators.ERROR_CATEGORY_FIELD_CHECK),
'Entity id %s: The translation suggestion count for '
'language code %s is %s, expected model '
'CommunityContributionStatsModel to have the language code '
'%s in its translation suggestion counts but it doesn\'t '
'exist.' % (
item.id, language_code,
expected_translation_suggestion_count, language_code)
) | python | 15 | 0.526706 | 80 | 52.94 | 50 | For each language code, validate that the translation suggestion
count matches the number of translation suggestions in the datastore
that are currently in review.
Args:
item: datastore_services.Model. CommunityContributionStatsModel to
validate.
| function |
public class HTTPResponseHandler {
private RequestObject request;
private HashMap<String, Handler> map;
private PrintWriter writer;
private Handler handler;
private String headers = "";
private String page = "";
private Logger logger;
/**
* Constructor that initializes the below parameters
* @param requestLine
* @param parameters
* @param map
*/
public HTTPResponseHandler(PrintWriter writer,RequestObject request, HashMap<String, Handler> map, String log) throws IOException {
this.request = request;
this.map = map;
this.writer = writer;
logger = Logger.getLogger("MyLog");
FileHandler fh;
try {
// This block configure the logger with handler and formatter
fh = new FileHandler(log);
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.info(logger.getName());
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* respond method that parses the request and write the header and page
*/
public void respond() {
String httpMethod = request.getMethod();
HTMLStorage storage = new HTMLStorage();
String path = request.getPath();
HashMap<String, String> paramList = request.getParameters();
String page = "";
if (httpMethod == null || path == null || httpMethod.length() < 1 || path.length() < 1) {
page = storage.failedPage(HTTPConstants.BAD_REQUEST);
headers = HTTPConstants.BAD_REQUEST + HTTPConstants.CONNECTION_CLOSE + storage.contentLength(page.length());;
}
else {
if (!(httpMethod.equals("GET") || httpMethod.equals("POST"))) {
page = storage.failedPage(HTTPConstants.NOT_ALLOWED);
headers = HTTPConstants.NOT_ALLOWED + HTTPConstants.CONNECTION_CLOSE + storage.contentLength(page.length());
}
else {
for (String key : map.keySet()) {
if (path.equals(key)) {
handler = map.get(key);
handler.handle(writer, request);
page = handler.getPage();
headers = HTTPConstants.OK_HEADER + HTTPConstants.CONNECTION_CLOSE + storage.contentLength(page.length());
break;
}
}
if (headers.equals("")) {
page = storage.failedPage(HTTPConstants.NOT_FOUND);
headers = HTTPConstants.NOT_FOUND + HTTPConstants.CONNECTION_CLOSE + storage.contentLength(page.length());
}
}
}
logger.info("Response: \n" + headers + page);
writer.write(headers);
writer.write(page);
writer.flush();
}
/**
* returns the header
* @return header
*/
public String getHeader() {
return headers;
}
} | java | 20 | 0.657101 | 132 | 28.934783 | 92 | /**
* A class that reads the parsed request lines and returns appropriate message to the client
* @author Tae Hyon Lee
*
*/ | class |
@WebService(endpointInterface = PluginConstants.CERTIFICATE_ENROLLMENT_SERVICE_ENDPOINT,
targetNamespace = PluginConstants.DEVICE_ENROLLMENT_SERVICE_TARGET_NAMESPACE)
@Addressing(enabled = true, required = true)
@BindingType(value = SOAPBinding.SOAP12HTTP_BINDING)
public class CertificateEnrollmentServiceImpl implements CertificateEnrollmentService {
private static Log log = LogFactory.getLog(
org.wso2.carbon.device.mgt.mobile.windows.api.services.wstep.impl.CertificateEnrollmentServiceImpl.class);
private X509Certificate rootCACertificate;
private String pollingFrequency;
private String provisioningURL;
private String domain;
@Resource
private WebServiceContext context;
/**
* This method implements MS-WSTEP for Certificate Enrollment Service.
*
* @param tokenType - Device Enrolment Token type is received via device
* @param requestType - WS-Trust request type
* @param binarySecurityToken - CSR from device
* @param additionalContext - Device type and OS version is received
* @param response - Response will include wap-provisioning xml
* @WindowsDeviceEnrolmentException -
*/
@Override
public void requestSecurityToken(String tokenType, String requestType, String binarySecurityToken,
AdditionalContext additionalContext,
Holder<RequestSecurityTokenResponse> response) throws
WindowsDeviceEnrolmentException {
String headerBinarySecurityToken = null;
String headerTo = null;
String encodedWap;
List<Header> headers = getHeaders();
for (Header headerElement : headers) {
String nodeName = headerElement.getName().getLocalPart();
if (PluginConstants.SECURITY.equals(nodeName)) {
Element element = (Element) headerElement.getObject();
headerBinarySecurityToken = element.getFirstChild().getNextSibling().getFirstChild().getTextContent();
}
if (PluginConstants.TO.equals(nodeName)) {
Element toElement = (Element) headerElement.getObject();
headerTo = toElement.getFirstChild().getTextContent();
}
}
String[] splitEmail = headerTo.split("(/ENROLLMENTSERVER)");
String email = splitEmail[PluginConstants.CertificateEnrolment.EMAIL_SEGMENT];
String[] splitDomain = email.split("(EnterpriseEnrollment.)");
domain = splitDomain[PluginConstants.CertificateEnrolment.DOMAIN_SEGMENT];
provisioningURL = PluginConstants.CertificateEnrolment.ENROLL_SUBDOMAIN + domain +
PluginConstants.CertificateEnrolment.SYNCML_PROVISIONING_SERVICE_URL;
List<ConfigurationEntry> tenantConfigurations;
try {
if ((tenantConfigurations = WindowsAPIUtils.getTenantConfigurationData()) != null) {
for (ConfigurationEntry configurationEntry : tenantConfigurations) {
if ((PluginConstants.TenantConfigProperties.NOTIFIER_FREQUENCY.equals(
configurationEntry.getName()))) {
pollingFrequency = configurationEntry.getValue().toString();
} else {
pollingFrequency = PluginConstants.TenantConfigProperties.DEFAULT_FREQUENCY;
}
}
} else {
pollingFrequency = PluginConstants.TenantConfigProperties.DEFAULT_FREQUENCY;
String msg = "Tenant configurations are not initialized yet.";
log.error(msg);
}
ServletContext ctx = (ServletContext) context.getMessageContext().
get(MessageContext.SERVLET_CONTEXT);
File wapProvisioningFile = (File) ctx.getAttribute(PluginConstants.CONTEXT_WAP_PROVISIONING_FILE);
if (log.isDebugEnabled()) {
log.debug("Received CSR from Device:" + binarySecurityToken);
}
String wapProvisioningFilePath = wapProvisioningFile.getPath();
RequestSecurityTokenResponse requestSecurityTokenResponse = new RequestSecurityTokenResponse();
requestSecurityTokenResponse.setTokenType(PluginConstants.CertificateEnrolment.TOKEN_TYPE);
encodedWap = prepareWapProvisioningXML(binarySecurityToken, wapProvisioningFilePath,
headerBinarySecurityToken);
RequestedSecurityToken requestedSecurityToken = new RequestedSecurityToken();
BinarySecurityToken binarySecToken = new BinarySecurityToken();
binarySecToken.setValueType(PluginConstants.CertificateEnrolment.VALUE_TYPE);
binarySecToken.setEncodingType(PluginConstants.CertificateEnrolment.ENCODING_TYPE);
binarySecToken.setToken(encodedWap);
requestedSecurityToken.setBinarySecurityToken(binarySecToken);
requestSecurityTokenResponse.setRequestedSecurityToken(requestedSecurityToken);
requestSecurityTokenResponse.setRequestID(PluginConstants.CertificateEnrolment.REQUEST_ID);
response.value = requestSecurityTokenResponse;
} catch (CertificateGenerationException e) {
String msg = "Problem occurred while generating certificate.";
log.error(msg, e);
throw new WindowsDeviceEnrolmentException(msg, e);
} catch (WAPProvisioningException e) {
String msg = "Problem occurred while generating wap-provisioning file.";
log.error(msg, e);
throw new WindowsDeviceEnrolmentException(msg, e);
} catch (DeviceManagementException e) {
String msg = "Error occurred while getting tenant configurations.";
log.error(msg);
throw new WindowsDeviceEnrolmentException(msg, e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Method used to Convert the Document object into a String.
*
* @param document - Wap provisioning XML document
* @return - String representation of wap provisioning XML document
* @throws TransformerException
*/
private String convertDocumentToString(Document document) throws TransformerException {
DOMSource DOMSource = new DOMSource(document);
StringWriter stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(DOMSource, streamResult);
return stringWriter.toString();
}
/**
* This method prepares the wap-provisioning file by including relevant certificates etc.
*
* @param binarySecurityToken - CSR from device
* @param wapProvisioningFilePath - File path of wap-provisioning file
* @return - base64 encoded final wap-provisioning file as a String
* @throws CertificateGenerationException
* @throws org.wso2.carbon.device.mgt.mobile.windows.api.common.exceptions.WAPProvisioningException
*/
private String prepareWapProvisioningXML(String binarySecurityToken, String wapProvisioningFilePath,
String headerBst) throws CertificateGenerationException,
WAPProvisioningException,
WindowsDeviceEnrolmentException {
String rootCertEncodedString;
String signedCertEncodedString;
X509Certificate signedCertificate;
String provisioningXmlString;
CertificateManagementServiceImpl certMgtServiceImpl = CertificateManagementServiceImpl.getInstance();
Base64 base64Encoder = new Base64();
try {
rootCACertificate = (X509Certificate) certMgtServiceImpl.getCACertificate();
rootCertEncodedString = base64Encoder.encodeAsString(rootCACertificate.getEncoded());
signedCertificate = certMgtServiceImpl.getSignedCertificateFromCSR(binarySecurityToken);
signedCertEncodedString = base64Encoder.encodeAsString(signedCertificate.getEncoded());
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
domFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document document = builder.parse(wapProvisioningFilePath);
NodeList wapParm = document.getElementsByTagName(PluginConstants.CertificateEnrolment.PARM);
Node caCertificatePosition = wapParm.item(PluginConstants.CertificateEnrolment.CA_CERTIFICATE_POSITION);
//Adding SHA1 CA certificate finger print to wap-provisioning xml.
caCertificatePosition.getParentNode().getAttributes().getNamedItem(PluginConstants.
CertificateEnrolment.TYPE).setTextContent(String.valueOf(
DigestUtils.sha1Hex(rootCACertificate.getEncoded())).toUpperCase());
//Adding encoded CA certificate to wap-provisioning file after removing new line
// characters.
NamedNodeMap rootCertAttributes = caCertificatePosition.getAttributes();
Node rootCertNode =
rootCertAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
rootCertEncodedString = rootCertEncodedString.replaceAll("\n", "");
rootCertNode.setTextContent(rootCertEncodedString);
if (log.isDebugEnabled()) {
log.debug("Root certificate: " + rootCertEncodedString);
}
Node signedCertificatePosition = wapParm.item(PluginConstants.CertificateEnrolment.
SIGNED_CERTIFICATE_POSITION);
//Adding SHA1 signed certificate finger print to wap-provisioning xml.
signedCertificatePosition.getParentNode().getAttributes().getNamedItem(PluginConstants.
CertificateEnrolment.TYPE).setTextContent(String.valueOf(
DigestUtils.sha1Hex(signedCertificate.getEncoded())).toUpperCase());
//Adding encoded signed certificate to wap-provisioning file after removing new line
// characters.
NamedNodeMap clientCertAttributes = signedCertificatePosition.getAttributes();
Node clientEncodedNode =
clientCertAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
signedCertEncodedString = signedCertEncodedString.replaceAll("\n", "");
clientEncodedNode.setTextContent(signedCertEncodedString);
if (log.isDebugEnabled()) {
log.debug("Signed certificate: " + signedCertEncodedString);
}
//Adding domainName to wap-provisioning xml.
Node domainPosition = wapParm.item(PluginConstants.CertificateEnrolment.DOMAIN_POSITION);
NamedNodeMap domainAttribute = domainPosition.getAttributes();
Node domainNode = domainAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
domainNode.setTextContent(domain);
//Adding Next provisioning service URL to wap-provisioning xml.
Node syncmlServicePosition = wapParm.item(PluginConstants.CertificateEnrolment.
SYNCML_PROVISIONING_ADDR_POSITION);
NamedNodeMap syncmlServiceAttribute = syncmlServicePosition.getAttributes();
Node syncmlServiceNode = syncmlServiceAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
syncmlServiceNode.setTextContent(provisioningURL);
// Adding user name auth token to wap-provisioning xml.
Node userNameAuthPosition = wapParm.item(PluginConstants.CertificateEnrolment.APPAUTH_USERNAME_POSITION);
NamedNodeMap appServerAttribute = userNameAuthPosition.getAttributes();
Node authNameNode = appServerAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
MobileCacheEntry cacheEntry = DeviceUtil.getTokenEntry(headerBst);
String userName = cacheEntry.getUsername();
authNameNode.setTextContent(cacheEntry.getUsername());
DeviceUtil.removeTokenEntry(headerBst);
String password = DeviceUtil.generateRandomToken();
Node passwordAuthPosition = wapParm.item(PluginConstants.CertificateEnrolment.APPAUTH_PASSWORD_POSITION);
NamedNodeMap appSrvPasswordAttribute = passwordAuthPosition.getAttributes();
Node authPasswordNode = appSrvPasswordAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
authPasswordNode.setTextContent(password);
String requestSecurityTokenResponse = SyncmlCredentialUtil.generateRST(userName, password);
DeviceUtil.persistChallengeToken(requestSecurityTokenResponse, null, userName);
// Get device polling frequency from the tenant Configurations.
Node numberOfFirstRetries = wapParm.item(PluginConstants.CertificateEnrolment.POLLING_FREQUENCY_POSITION);
NamedNodeMap pollingAttributes = numberOfFirstRetries.getAttributes();
Node pollValue = pollingAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
pollValue.setTextContent(pollingFrequency);
provisioningXmlString = convertDocumentToString(document);
} catch (ParserConfigurationException e) {
throw new WAPProvisioningException("Problem occurred while creating configuration request", e);
} catch (CertificateEncodingException e) {
throw new WindowsDeviceEnrolmentException("Error occurred while encoding certificates.", e);
} catch (SAXException e) {
throw new WAPProvisioningException("Error occurred while parsing wap-provisioning.xml file.", e);
} catch (TransformerException e) {
throw new WAPProvisioningException("Error occurred while transforming wap-provisioning.xml file.", e);
} catch (IOException e) {
throw new WAPProvisioningException("Error occurred while getting wap-provisioning.xml file.", e);
} catch (SyncmlMessageFormatException e) {
throw new WindowsDeviceEnrolmentException("Error occurred while generating password hash value.", e);
} catch (KeystoreException e) {
throw new CertificateGenerationException("CA certificate cannot be generated.", e);
}
return base64Encoder.encodeAsString(provisioningXmlString.getBytes());
}
/**
* This method get the soap request header contents.
*
* @return List of SOAP headers.
*/
private List<Header> getHeaders() {
MessageContext messageContext = context.getMessageContext();
if (messageContext == null || !(messageContext instanceof WrappedMessageContext)) {
return null;
}
Message message = ((WrappedMessageContext) messageContext).getWrappedMessage();
return CastUtils.cast((List<?>) message.get(Header.HEADER_LIST));
}
} | java | 19 | 0.685394 | 118 | 56.702602 | 269 | /**
* Implementation class of CertificateEnrollmentService interface. This class implements MS-WSTEP
* protocol.
*/ | class |
def test(job):
import sys
import os
RESULT_OK = 'OK : %s'
RESULT_FAILED = 'FAILED : %s'
RESULT_ERROR = 'ERROR : %s %%s' % job.service.name
model = job.service.model
model.data.result = RESULT_OK % job.service.name
failures = []
expected_actors = ['cockpittesting', 'datacenter', 'sshkey']
expected_files_per_actor = ['actions.py', 'actor.json', 'schema.capnp']
actor_missing_msg = 'Actor folder [%s] does not exist'
actor_file_missing_msg = 'File [%s] for actor [%s] is missing'
service_file_missing_msg = 'Service file [%s] is missing'
expected_services = {'datacenter!ovh_germany1':{
'files': ['data.json', 'schema.capnp', 'service.json']},
'datacenter!ovh_germany3': {'cockpittesting!cockpitv2': {'files': ['data.json',
'schema.capnp',
'service.json']},
'files': ['data.json', 'schema.capnp', 'service.json']},
'sshkey!main': {'files': ['data.json', 'schema.capnp', 'service.json']}}
cwd = os.getcwd()
repos = []
repo_name = 'sample_repo1'
repo_path = j.sal.fs.joinPaths(j.dirs.CODEDIR, 'github/jumpscale/ays9/tests/%s' % repo_name)
repos.append(repo_name)
def check_service_dir(base_path, service):
for service_name, service_info in service.items():
if service_name != 'files':
path = j.sal.fs.joinPaths(base_path, service_name)
check_service_dir(path, service_info)
else:
for service_file in service['files']:
if not j.sal.fs.exists(j.sal.fs.joinPaths(base_path, service_file)):
failures.append(service_file_missing_msg % j.sal.fs.joinPaths(base_path, service_file))
try:
ays_client = j.clients.atyourservice.get().api.ays
blueprints = map(lambda item: item['name'], ays_client.listBlueprints(repo_name, query_params={'archived': False}).json())
for blueprint in blueprints:
ays_client.executeBlueprint(data={}, blueprint=blueprint, repository=repo_name)
for actor in expected_actors:
if not j.sal.fs.exists(j.sal.fs.joinPaths(repo_path, 'actors', actor)):
failures.append(actor_missing_msg % actor)
else:
for actor_file in expected_files_per_actor:
if not j.sal.fs.exists(j.sal.fs.joinPaths(repo_path, 'actors', actor, actor_file)):
failures.append(actor_file_missing_msg % (actor_file, actor))
for service_name, service_info in expected_services.items():
path = j.sal.fs.joinPaths(repo_path, 'services', service_name)
check_service_dir(path, service_info)
if failures:
model.data.result = RESULT_FAILED % '\n'.join(failures)
except:
model.data.result = RESULT_ERROR % str(sys.exc_info()[:2])
finally:
job.service.save()
j.sal.fs.changeDir(cwd)
for repo in repos:
ays_client.destroyRepository(data={}, repository=repo) | python | 22 | 0.599016 | 130 | 50.711864 | 59 |
Test the created directory structure is corrected after ays blueprint on a test repo
| function |
static int check_sac_nvhdr(const int nvhdr)
{
int lswap = FALSE;
if (nvhdr != SAC_HEADER_MAJOR_VERSION) {
byte_swap((char*) &nvhdr, SAC_DATA_SIZEOF);
if (nvhdr == SAC_HEADER_MAJOR_VERSION)
lswap = TRUE;
else
lswap = -1;
}
return lswap;
} | c | 11 | 0.54485 | 51 | 24.166667 | 12 | /*
* check_sac_nvhdr
*
* Description: Determine the byte order of the SAC file
*
* IN:
* const int nvhdr : nvhdr from header
*
* Return:
* FALSE no byte order swap is needed
* TRUE byte order swap is needed
* -1 not in sac format ( nvhdr != SAC_HEADER_MAJOR_VERSION )
*
*/ | function |
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.chbHexa = new System.Windows.Forms.CheckBox();
this.txbSendData = new System.Windows.Forms.TextBox();
this.btnSend = new System.Windows.Forms.Button();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.txbTick = new System.Windows.Forms.TextBox();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.SuspendLayout();
chbHexa
this.chbHexa.AutoSize = true;
this.chbHexa.Location = new System.Drawing.Point(4, 5);
this.chbHexa.Name = "chbHexa";
this.chbHexa.Size = new System.Drawing.Size(15, 14);
this.chbHexa.TabIndex = 0;
this.toolTip1.SetToolTip(this.chbHexa, "체크: HEXA, 언체크: TEXT");
this.chbHexa.UseVisualStyleBackColor = true;
txbSendData
this.txbSendData.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txbSendData.Location = new System.Drawing.Point(20, 1);
this.txbSendData.Name = "txbSendData";
this.txbSendData.Size = new System.Drawing.Size(305, 21);
this.txbSendData.TabIndex = 2;
this.txbSendData.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtSendData_KeyPress);
btnSend
this.btnSend.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnSend.Location = new System.Drawing.Point(329, 2);
this.btnSend.Name = "btnSend";
this.btnSend.Size = new System.Drawing.Size(24, 19);
this.btnSend.TabIndex = 3;
this.btnSend.Text = "S";
this.btnSend.UseVisualStyleBackColor = true;
this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
txbTick
this.txbTick.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.txbTick.Location = new System.Drawing.Point(352, 1);
this.txbTick.Name = "txbTick";
this.txbTick.Size = new System.Drawing.Size(55, 21);
this.txbTick.TabIndex = 4;
this.txbTick.Text = "1000";
timer1
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
CtrlTxData
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.txbTick);
this.Controls.Add(this.btnSend);
this.Controls.Add(this.txbSendData);
this.Controls.Add(this.chbHexa);
this.Name = "CtrlTxData";
this.Size = new System.Drawing.Size(410, 23);
this.ResumeLayout(false);
this.PerformLayout();
} | c# | 19 | 0.618689 | 156 | 55.964286 | 56 | /// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary> | function |
func (maintenanceWindow *MaintenanceWindow) AssignPropertiesToMaintenanceWindow(destination *v1alpha1api20210501storage.MaintenanceWindow) error {
propertyBag := genruntime.NewPropertyBag()
destination.CustomWindow = genruntime.ClonePointerToString(maintenanceWindow.CustomWindow)
destination.DayOfWeek = genruntime.ClonePointerToInt(maintenanceWindow.DayOfWeek)
destination.StartHour = genruntime.ClonePointerToInt(maintenanceWindow.StartHour)
destination.StartMinute = genruntime.ClonePointerToInt(maintenanceWindow.StartMinute)
if len(propertyBag) > 0 {
destination.PropertyBag = propertyBag
} else {
destination.PropertyBag = nil
}
return nil
} | go | 8 | 0.847201 | 146 | 49.923077 | 13 | // AssignPropertiesToMaintenanceWindow populates the provided destination MaintenanceWindow from our MaintenanceWindow | function |
public final class PPDrawingTextListing {
public static void main(String[] args) throws Exception {
if(args.length < 1) {
System.err.println("Need to give a filename");
System.exit(1);
}
HSLFSlideShow ss = new HSLFSlideShow(args[0]);
// Find PPDrawings at any second level position
Record[] records = ss.getRecords();
for(int i=0; i<records.length; i++) {
Record[] children = records[i].getChildRecords();
if(children != null && children.length != 0) {
for(int j=0; j<children.length; j++) {
if(children[j] instanceof PPDrawing) {
System.out.println("Found PPDrawing at " + j + " in top level record " + i + " (" + records[i].getRecordType() + ")" );
// Look for EscherTextboxWrapper's
PPDrawing ppd = (PPDrawing)children[j];
EscherTextboxWrapper[] wrappers = ppd.getTextboxWrappers();
System.out.println(" Has " + wrappers.length + " textbox wrappers within");
// Loop over the wrappers, showing what they contain
for(int k=0; k<wrappers.length; k++) {
EscherTextboxWrapper tbw = wrappers[k];
System.out.println(" " + k + " has " + tbw.getChildRecords().length + " PPT atoms within");
// Loop over the records, printing the text
Record[] pptatoms = tbw.getChildRecords();
for(int l=0; l<pptatoms.length; l++) {
String text = null;
if(pptatoms[l] instanceof TextBytesAtom) {
TextBytesAtom tba = (TextBytesAtom)pptatoms[l];
text = tba.getText();
}
if(pptatoms[l] instanceof TextCharsAtom) {
TextCharsAtom tca = (TextCharsAtom)pptatoms[l];
text = tca.getText();
}
if(text != null) {
text = text.replace('\r','\n');
System.out.println(" ''" + text + "''");
}
}
}
}
}
}
}
}
} | java | 25 | 0.593903 | 125 | 33.679245 | 53 | /**
* Uses record level code to locate PPDrawing entries.
* Having found them, it sees if they have DDF Textbox records, and if so,
* searches those for text. Prints out any text it finds
*/ | class |
public class ChangeProf extends ConcretePrereqObject
{
/**
* A reference to the source WeaponProf that this ChangeProf impacts
* (effectively changes the TYPE)
*/
private final CDOMReference<WeaponProf> source;
/**
* The resulting Group into which the source WeaponProf is effectively
* placed for the PlayerCharacter that possesses this ChangeProf.
*/
private final CDOMGroupRef<WeaponProf> result;
/**
* Constructs a new ChangeProf with the given reference to a source
* WeaponProf and given resulting Group into which the source WeaponProf is
* effectively placed for a PlayerCharacter that possesses this ChangeProfF.
*
* @param sourceProf
* A reference to the source WeaponProf that this ChangeProf
* impacts
* @param resultType
* The resulting Group into which the source WeaponProf is
* effectively placed for the PlayerCharacter that possesses this
* ChangeProf.
*/
public ChangeProf(CDOMReference<WeaponProf> sourceProf,
CDOMGroupRef<WeaponProf> resultType)
{
if (sourceProf == null)
{
throw new IllegalArgumentException(
"Source Prof for ChangeProf cannot be null");
}
if (resultType == null)
{
throw new IllegalArgumentException(
"Resulting Prof Type for ChangeProf cannot be null");
}
source = sourceProf;
result = resultType;
}
/**
* Returns a reference to the source WeaponProf for this ChangeProf
*
* @return A reference to the source WeaponProf for this ChangeProf
*/
public CDOMReference<WeaponProf> getSource()
{
return source;
}
/**
* Returns a reference to the Group into which the source WeaponProf is
* effectively placed for the PlayerCharacter that possesses this
* ChangeProf.
*
* @return A reference to the Group into which the source WeaponProf is
* effectively placed.
*/
public CDOMGroupRef<WeaponProf> getResult()
{
return result;
}
/**
* Returns a consistent-with-equals hashCode for this ChangeProf
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
return 31 * source.hashCode() + result.hashCode();
}
/**
* Returns true if the given object is a ChangeProf with identical source
* and target Group
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj)
{
if (obj == this)
{
return true;
}
if (!(obj instanceof ChangeProf))
{
return false;
}
ChangeProf other = (ChangeProf) obj;
return source.equals(other.source) && result.equals(other.result);
}
@Override
public String toString()
{
return getClass() + "[" + source + " -> " + result + "]";
}
} | java | 13 | 0.666071 | 77 | 24.40566 | 106 | /**
* Represents a change to a type of WeaponProficiency for a PlayerCharacter. The
* change impacts a given WeaponProf primitive and effectively places that
* WeaponProf into a separate TYPE.
*/ | class |
class SettingItem:
"""Creates a setting item
:param default: default value for the setting item
:type default: Any
:param limits: lower and upper bounds of item
:type limits: Union[(Any, Any), None]
:param sub_type: type of the contents of iterable items
:type sub_type: type object
:param fixed_size: size of iterable item
:type fixed_size: int
"""
def __init__(self, default, limits=None, sub_type=None, fixed_size=False):
self.default = default
self.type = type(default)
self.sub_type = sub_type
self.size = 0
with suppress(TypeError):
self.size = len(default)
self.fixed_size = fixed_size
self.limits = limits | python | 11 | 0.630854 | 78 | 33.619048 | 21 | Creates a setting item
:param default: default value for the setting item
:type default: Any
:param limits: lower and upper bounds of item
:type limits: Union[(Any, Any), None]
:param sub_type: type of the contents of iterable items
:type sub_type: type object
:param fixed_size: size of iterable item
:type fixed_size: int
| class |
async _selectAccount({accountId, callback}) {
this.app.logger.info(`${this}select account ${accountId}`)
let account = this.app.state.settings.webrtc.account
if (accountId) {
const res = await this.app.api.client.put('api/plugin/user/selected_account/', {id: accountId})
if (res.status === 400) {
const message = `${this.app.$t('unexpected error')}!`
this.app.notify({
icon: 'github',
link: {
url: 'https://github.com/vialer/vialer-js/issues',
text: `${this.app.$t('more info')}...`,
},
message, type: 'warning', timeout: 0})
return
}
account.selected = this._formatAccount(res.data)
account.using = this._formatAccount(res.data)
} else {
account.using = this.app.state.settings.webrtc.account.fallback
}
account.status = null
await this.app.setState({
settings: {
webrtc: {
account,
enabled: accountId ? true : false,
},
},
}, {persist: true})
callback({account: account.selected})
} | javascript | 18 | 0.478528 | 107 | 39.78125 | 32 | /**
* Handles changing the account and signals when the new account info
* is loaded, by responding with the *complete* account credentials in
* the callback.
* @param options - options to pass.
* @param options.accountId - Id of an account from options to set.
* @param options.callback - Callback to the original emitting event.
*/ | function |
pub fn verify_share(
&self,
candidate_share: CandidateShare<G>,
ciphertext: Ciphertext<G>,
index: usize,
proof: &LogEqualityProof<G>,
) -> Result<DecryptionShare<G>, VerificationError> {
let key_share = self.participant_keys[index].as_element();
let dh_element = candidate_share.dh_element();
let mut transcript = Transcript::new(b"elgamal_decryption_share");
self.commit(&mut transcript);
transcript.append_u64(b"i", index as u64);
proof.verify(
&PublicKey::from_element(ciphertext.random_element),
(key_share, dh_element),
&mut transcript,
)?;
Ok(DecryptionShare::new(dh_element))
} | rust | 11 | 0.599727 | 74 | 37.578947 | 19 | /// Verifies a candidate decryption share for `ciphertext` provided by a participant
/// with the specified `index`.
///
/// # Errors
///
/// Returns an error if the `proof` does not verify. | function |
static int poll_for_response(OSSL_CMP_CTX *ctx, int sleep, int rid,
OSSL_CMP_MSG **rep, int *checkAfter)
{
OSSL_CMP_MSG *preq = NULL;
OSSL_CMP_MSG *prep = NULL;
ossl_cmp_info(ctx,
"received 'waiting' PKIStatus, starting to poll for response");
*rep = NULL;
for (;;) {
if ((preq = ossl_cmp_pollReq_new(ctx, rid)) == NULL)
goto err;
if (!send_receive_check(ctx, preq, &prep, OSSL_CMP_PKIBODY_POLLREP))
goto err;
if (OSSL_CMP_MSG_get_bodytype(prep) == OSSL_CMP_PKIBODY_POLLREP) {
OSSL_CMP_POLLREPCONTENT *prc = prep->body->value.pollRep;
OSSL_CMP_POLLREP *pollRep = NULL;
int64_t check_after;
char str[OSSL_CMP_PKISI_BUFLEN];
int len;
if (sk_OSSL_CMP_POLLREP_num(prc) > 1) {
ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_RESPONSES_NOT_SUPPORTED);
goto err;
}
pollRep = ossl_cmp_pollrepcontent_get0_pollrep(prc, rid);
if (pollRep == NULL)
goto err;
if (!ASN1_INTEGER_get_int64(&check_after, pollRep->checkAfter)) {
ERR_raise(ERR_LIB_CMP, CMP_R_BAD_CHECKAFTER_IN_POLLREP);
goto err;
}
if (check_after < 0 || (uint64_t)check_after
> (sleep ? ULONG_MAX / 1000 : INT_MAX)) {
ERR_raise(ERR_LIB_CMP, CMP_R_CHECKAFTER_OUT_OF_RANGE);
if (BIO_snprintf(str, OSSL_CMP_PKISI_BUFLEN, "value = %jd",
check_after) >= 0)
ERR_add_error_data(1, str);
goto err;
}
if (pollRep->reason == NULL
|| (len = BIO_snprintf(str, OSSL_CMP_PKISI_BUFLEN,
" with reason = '")) < 0) {
*str = '\0';
} else {
char *text = ossl_sk_ASN1_UTF8STRING2text(pollRep->reason, ", ",
sizeof(str) - len - 2);
if (text == NULL
|| BIO_snprintf(str + len, sizeof(str) - len,
"%s'", text) < 0)
*str = '\0';
OPENSSL_free(text);
}
ossl_cmp_log2(INFO, ctx,
"received polling response%s; checkAfter = %ld seconds",
str, check_after);
if (ctx->total_timeout > 0) {
const int exp = 5;
int64_t time_left = (int64_t)(ctx->end_time - exp - time(NULL));
if (time_left <= 0) {
ERR_raise(ERR_LIB_CMP, CMP_R_TOTAL_TIMEOUT);
goto err;
}
if (time_left < check_after)
check_after = time_left;
}
OSSL_CMP_MSG_free(preq);
preq = NULL;
OSSL_CMP_MSG_free(prep);
prep = NULL;
if (sleep) {
ossl_sleep((unsigned long)(1000 * check_after));
} else {
if (checkAfter != NULL)
*checkAfter = (int)check_after;
return -1;
}
} else {
ossl_cmp_info(ctx, "received ip/cp/kup after polling");
break;
}
}
if (prep == NULL)
goto err;
OSSL_CMP_MSG_free(preq);
*rep = prep;
return 1;
err:
OSSL_CMP_MSG_free(preq);
OSSL_CMP_MSG_free(prep);
return 0;
} | c | 19 | 0.441193 | 82 | 38.877778 | 90 | /*-
* When a 'waiting' PKIStatus has been received, this function is used to
* poll, which should yield a pollRep or finally a CertRepMessage in ip/cp/kup.
* On receiving a pollRep, which includes a checkAfter value, it return this
* value if sleep == 0, else it sleeps as long as indicated and retries.
*
* A transaction timeout is enabled if ctx->total_timeout is > 0.
* In this case polling will continue until the timeout is reached and then
* polling is done a last time even if this is before the "checkAfter" time.
*
* Returns -1 on receiving pollRep if sleep == 0, setting the checkAfter value.
* Returns 1 on success and provides the received PKIMESSAGE in *rep.
* In this case the caller is responsible for freeing *rep.
* Returns 0 on error (which includes the case that timeout has been reached).
*/ | function |
public void update(GameContainer gc, int delta) {
if (!Settings.is("score_effects")) {
return;
}
HashSet<TextParticle> dead = new HashSet<>();
for (TextParticle scoreParticle : particles) {
if (scoreParticle.update(gc, delta)) {
dead.add(scoreParticle);
}
}
particles.removeAll(dead);
} | java | 10 | 0.535897 | 54 | 31.583333 | 12 | /**
* Update the effects unless disabled in settings.
*
* @param gc game container
* @param delta delta time
*/ | function |
@SuppressWarnings("unchecked")
public static void startTelemetry() {
if (CONFIG_REFRESH_LISTENER != null) {
return;
}
final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
ImmutableList.Builder<ConfigModule> modulesBuilder = ImmutableList.builder();
ServiceLoader.load(ConfigModule.class).forEach(modulesBuilder::add);
ImmutableList<ConfigModule> modules = modulesBuilder.build();
if (modules.isEmpty()) {
logger.warn("Unable to discover any modules for telemetry config. Will not refresh config.");
return;
}
mapper.registerModules(modules);
final ObjectReader reader = mapper.readerFor(TelemetryConfigurator.class);
Provider<CompleteRefreshConfig<InnerTelemetryConf>> configurationProvider =
new Provider<CompleteRefreshConfig<InnerTelemetryConf>>() {
private final ExceptionWatcher exceptionWatcher =
new ExceptionWatcher((ex) -> logger.warn("Failure reading telemetry configuration. Leaving telemetry as is.", ex));
@Override
public CompleteRefreshConfig<InnerTelemetryConf> get() {
URL resource = null;
CompleteRefreshConfig<InnerTelemetryConf> ret = null;
try {
String configFilePath = System.getProperty(CONFIG_FILE_PROPERTY);
if (configFilePath!=null && !configFilePath.isEmpty()) {
File file = new File(configFilePath);
if (file.exists()) {
resource = file.toURI().toURL();
}
}
if (resource == null) {
resource = Resources.getResource(CONFIG_FILE);
}
final TelemetryConfigurator fromConfig = reader.readValue(resource);
final InnerTelemetryConf telemConf = new InnerTelemetryConf(fromConfig.getMetricsConfigs(), fromConfig.getTracerConfig());
ret = new CompleteRefreshConfig<>(fromConfig.getRefreshConfig(), telemConf);
exceptionWatcher.reset();
} catch (IllegalArgumentException | IOException ex) {
exceptionWatcher.notify(ex);
}
return ret;
}
};
CONFIG_REFRESH_LISTENER = new InnerTelemetryConfigListener(TracerFacade.INSTANCE);
CONFIG_REFRESHER = new AutoRefreshConfigurator<>(configurationProvider, CONFIG_REFRESH_LISTENER);
} | java | 20 | 0.670386 | 134 | 48.595745 | 47 | /**
* Reads the telemetry config file and sets itself up to listen for changes.
* If telemetry is already available, the most up to date telemetry dependencies (e.g. tracer)
* will be added to the registry.
*/ | function |
def process_image(self, img):
if self.size is None or self.size[0] != img.shape[0] or self.size[1] != img.shape[1]:
h, w = img.shape[:2]
self.size = (h, w)
self.bin = np.empty((h, w, 1), dtype=np.uint8)
self.hsv = np.empty((h, w, 3), dtype=np.uint8)
self.hue = np.empty((h, w, 1), dtype=np.uint8)
self.sat = np.empty((h, w, 1), dtype=np.uint8)
self.val = np.empty((h, w, 1), dtype=np.uint8)
self.zeros = np.zeros((h, w, 1), dtype=np.bool)
if w <= 320:
k = 2
offset = (0,0)
self.kHoleClosingIterations = 1
self.kMinWidth = 2
self.kThickness = 1
self.kTgtThickness = 1
self.kPolyAccuracy = 10.0
elif w <= 480:
k = 2
offset = (0,0)
self.kHoleClosingIterations = 2
self.kMinWidth = 5
self.kThickness = 1
self.kTgtThickness = 2
self.kPolyAccuracy = 15.0
else:
k = 3
offset = (1,1)
self.kHoleClosingIterations = 6
self.kMinWidth = 10
self.kThickness = 1
self.kTgtThickness = 2
self.kPolyAccuracy = 20.0
self.morphKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (k,k), anchor=offset)
logging.info("New image size: %sx%s, morph size set to %s, %s iterations", w,h,k, self.kHoleClosingIterations)
ih, iw = self.size
centerOfImageY = ih/2.0
cv2.cvtColor(img, self.colorspace, self.hsv)
cv2.split(self.hsv, [self.hue, self.sat, self.val])
cv2.threshold(self.hue, self.thresh_hue_p, 255, type=cv2.THRESH_BINARY, dst=self.bin)
cv2.threshold(self.hue, self.thresh_hue_n, 255, type=cv2.THRESH_BINARY_INV, dst=self.hue)
cv2.bitwise_and(self.hue, self.bin, self.hue)
if self.show_hue:
img[np.dstack((self.zeros, self.hue != 0, self.zeros))] = 255
cv2.threshold(self.sat, self.thresh_sat_p, 255, type=cv2.THRESH_BINARY, dst=self.bin)
cv2.threshold(self.sat, self.thresh_sat_n, 255, type=cv2.THRESH_BINARY_INV, dst=self.sat)
cv2.bitwise_and(self.sat, self.bin, self.sat)
if self.show_sat:
img[np.dstack((self.sat != 0, self.zeros, self.zeros))] = 255
cv2.threshold(self.val, self.thresh_val_p, 255, type=cv2.THRESH_BINARY, dst=self.bin)
cv2.threshold(self.val, self.thresh_val_n, 255, type=cv2.THRESH_BINARY_INV, dst=self.val)
cv2.bitwise_and(self.val, self.bin, self.val)
if self.show_val:
img[np.dstack((self.zeros, self.zeros, self.val != 0))] = 255
cv2.bitwise_and(self.hue, self.sat, self.bin)
cv2.bitwise_and(self.bin, self.val, self.bin)
cv2.morphologyEx(self.bin, cv2.MORPH_CLOSE, self.morphKernel, dst=self.bin, iterations=self.kHoleClosingIterations)
if self.show_bin:
cv2.imshow('bin', self.bin)
if self.show_bin_overlay:
img[np.dstack((self.bin, self.bin, self.bin)) != 0] = 255
return img, self.bin | python | 13 | 0.550062 | 123 | 50.380952 | 63 |
Processes an image and thresholds it. Returns the original
image, and a binary version of the image indicating the area
that was filtered
:returns: img, bin
| function |
public static List<NurbsCurve> BezierInterpolation(List<Vector3> pts)
{
if (pts.Count == 0)
{
throw new Exception("Collection of points is empty.");
}
List<NurbsCurve> beziers = new List<NurbsCurve>();
(List<Vector3> ptsA, List<Vector3> ptsB) ctrlPts = SolveBezierCtrlPts(pts);
for (int i = 0; i < pts.Count - 1; i++)
{
beziers.Add(new NurbsCurve(new List<Vector3> { pts[i], ctrlPts.ptsA[i], ctrlPts.ptsB[i], pts[i + 1] },
3));
}
return beziers;
} | c# | 19 | 0.499197 | 118 | 40.6 | 15 | /// <summary>
/// Creates a set of interpolated cubic beziers through a set of points.
/// </summary>
/// <param name="pts">Set of points to interpolate.</param>
/// <returns>A set of cubic beziers.</returns> | function |
def vote(self, mission: list[int], leader: int) -> bool:
self.selections.append((leader, mission))
if self.spy:
return len([p for p in mission if p in self.spies]) > 0
total = sum(self._estimate(p) for p in mission if p != self)
alternate = sum(
self._estimate(p) for p in self.players if p != self and p not in mission
)
return bool(total <= alternate) | python | 13 | 0.583529 | 85 | 46.333333 | 9 |
The method is called on an agent to inform them of the outcome
of a vote, and which agent voted for or against the mission.
Args:
mission (list[int]):
A list of unique agents to be sent on a mission.
leader (int):
The index of the player who proposed the mission
between 0 and number_of_players.
Returns:
bool:
True if the vote is for the mission, and
False if the vote is against the mission.
| function |
def _create_modulename(cdef_sources, source, sys_version):
key = '\x00'.join([sys_version[:3], source] + cdef_sources)
key = key.encode('utf-8')
k1 = hex(binascii.crc32(key[0::2]) & 0xffffffff)
k1 = k1.lstrip('0x').rstrip('L')
k2 = hex(binascii.crc32(key[1::2]) & 0xffffffff)
k2 = k2.lstrip('0').rstrip('L')
return '_Cryptography_cffi_{0}{1}'.format(k1, k2) | python | 12 | 0.615584 | 63 | 47.25 | 8 |
cffi creates a modulename internally that incorporates the cffi version.
This will cause cryptography's wheels to break when the version of cffi
the user has does not match what was used when building the wheel. To
resolve this we build our own modulename that uses most of the same code
from cffi but elides the version key.
| function |
public class ReplayTestTemplate extends ReplayTestingEnvironment { //Every replay test should extend ReplayTestingEnvironment
/*
* To test the replay while it is executing, it is necessary to create threads which will run the replays.
*/
private Thread replayThread = new Thread() {
@Override
public void run() {
try {
//This is the title of the replay to be played. It is generally the name of the folder in the 'recordings' directory.
String replayTitle = "REPLAY_TITLE";
//This executes the game opening the replay desired for testing. It is always 'TEST_CLASS_NAME.super.openReplay(replayTitle)' .
ReplayTestTemplate.super.openReplay(replayTitle);
} catch (Exception e) {
e.printStackTrace();
}
}
};
@After
public void closeReplay() throws Exception {
//these last two lines are important to correctly shutdown the game after the tests are done.
super.getHost().shutdown();
replayThread.join();
}
@Ignore("This is just a template and should be ignored by Jenkins.")
@Test
public void testTemplate() {
replayThread.start(); //always start the thread before the test, so the replay can execute.
try {
/*
This 'while' is useful because when it is over it means everything in the replay was loaded, which means it
is possible to test the replay's initial state, such as the player character's initial position.
*/
while (RecordAndReplayStatus.getCurrentStatus() != RecordAndReplayStatus.REPLAYING) {
Thread.sleep(1000); //this sleep is optional and is used only to improve the game performance.
}
//the checks of initial states should be written here, between the 'while' statements.
//The code inside this 'while' will execute while the replay is playing.
while (RecordAndReplayStatus.getCurrentStatus() != RecordAndReplayStatus.REPLAY_FINISHED) {
//Tests can be written here to check something in the middle of a replay.
/*
Example of test: The test in the comment below gets the event system and checks if the RecordedEvent of
number 1000 was already processed. If it was, it tests something. This is useful to test, for example,
if a block disappeared after its destruction, if the player location changed after a certain movement
event was sent.
*/
/*
EventSystemReplayImpl eventSystem = (EventSystemReplayImpl) CoreRegistry.get(EventSystem.class);
if (eventSystem.getLastRecordedEventPosition() >= 1000) {
//test something
}
*/
//this sleep is optional and is used only to improve the game performance.
Thread.sleep(1000);
}
//tests can be written here to test something at the end of a replay.
} catch (Exception e) {
e.printStackTrace();
}
}
} | java | 15 | 0.615624 | 143 | 44.914286 | 70 | /**
* This is a template with comments to aid in the creation of a replay test.
* For more information about Replay Tests, see https://github.com/MovingBlocks/Terasology/wiki/Replay-Tests
*/ | class |
handleVisibleChange_(cacheItem) {
const layer = cacheItem.layer;
const visible = layer.getVisible();
const googleTileLayer = cacheItem.googleTileLayer;
const googleMapsLayers = this.gmap.overlayMapTypes;
const layerIndex = googleMapsLayers.getArray().indexOf(googleTileLayer);
if (visible) {
if (layerIndex == -1) {
googleMapsLayers.push(googleTileLayer);
}
this.activateCacheItem_(cacheItem);
} else {
if (layerIndex != -1) {
googleMapsLayers.removeAt(layerIndex);
}
this.deactivateCacheItem_(cacheItem);
}
} | javascript | 10 | 0.668908 | 76 | 32.111111 | 18 | /**
* Deal with the google tile layer when we enable or disable the OL3 tile layer
* @param {module:olgm/herald/TileSource~LayerCache} cacheItem cacheItem for the
* watched layer
* @private
*/ | function |
def delinear_weights(components, method):
if not hasattr(math.ease, method):
raise ValueError("Blend method '{}' is not supported.".format(method))
tween = getattr(math.ease, method)
data = defaultdict(list)
for component in components:
data[component.split(".")[0]].append(component)
with Progress(len(data)) as progress:
for node, components in data.items():
skin_cluster = skin.get_cluster(node)
skin_cluster_obj = api.conversion.get_object(skin_cluster)
skin_cluster_fn = OpenMayaAnim.MFnSkinCluster(skin_cluster_obj)
cmds.select(components)
selection = OpenMaya.MGlobal.getActiveSelectionList()
node_dag, node_components = selection.getComponent(0)
weights_old, num = skin_cluster_fn.getWeights(node_dag, node_components)
weights_new = OpenMaya.MDoubleArray()
influences = OpenMaya.MIntArray(range(num))
for weights in conversion.as_chunks(weights_old, num):
weights = conversion.normalize(weights)
weights = [tween(w) for w in weights]
weights = conversion.normalize(weights)
for weight in weights:
weights_new.append(weight)
skin.set_weights(
skin_cluster_fn,
dag=node_dag,
components=node_components,
influences=influences,
weights_old=weights_old,
weights_new=weights_new
)
progress.next() | python | 14 | 0.594937 | 84 | 46.909091 | 33 |
Loop over all of the provided components and see if these components
are deformed by a skin cluster. If this is the case, the weights will be
de-linearized by the function provided. This function is found in the
tweening module.
:param list[str] components:
:param str method:
:raise ValueError: When blend method is not supported.
| function |
def find_direction(self, bundle):
reset = 0
if type(self.volume.IoR) is float:
self.IoR = self.volume.IoR
else:
self.IoR = self.volume.IoR.__call__(bundle.wave_len)
vect = sph2cart(bundle.theta, bundle.phi)
vect = rm.rot(self.tilt, vect, self.n)
[self.refracted_vect, index, indexmatch] = self.check_interface(
bundle, vect)
self.rho = lc.reflectivity(vect, self.refracted_vect)
[theta, phi, bundle_reflect_stay,
bundle_reflect_lost, bundle_refract_lost] = (
lc.refraction_or_reflection(self.rho, vect,
self.tilt, self.refracted_vect,
indexmatch, self.n))
if bundle_reflect_stay == 1:
index = self.index
if bundle_reflect_lost == 1:
self.bundles_reflected += 1
reset = 1
if bundle_refract_lost == 1:
self.bundles_refracted += 1
self.wave_len_log.append(bundle.wave_len)
reset = 1
return [theta, phi, reset, index] | python | 12 | 0.512425 | 73 | 43.923077 | 26 | Determine trajectory of a bundle as it leaves a boundary. For an
OpaqueBoundary, a bundle can be reflected specularly or diffusely.
Parameters
----------
bundle : object
Houses bundle characteristics, this is used here to pull bundle
direction.
Returns
-------
theta : float
Polar incidence angle (classically defined as just the incidence
angle) in global coordinates. This is a spherical coordinate.
phi : float
Azimuthal incidence angle in global coordinates. This is a
spherical coordinate.
reset : int
Reset is set to zero to ensure that a bundle won't be lost
index : int
Reports the index of the volume a bundle will enter next. This
could be the same volume if a bundle is reflected at a boundary,
this could be a different volume if a bundle is transmitted.
Notes
-----
It seems like reset and index are redundant and could be removed.
More inputs could be placed into this function to be more descriptive.
| function |
def run(uri: str, **kwargs) -> str:
from . import run_local_task, RunFailed, DownloadFailed, Terminated
from .. import parse_tasks, values_from_json
downloader_ctx = _downloader(uri)
assert downloader_ctx
try:
with downloader_ctx(uri) as (downloader_wdl, downloader_inputs):
task = parse_tasks(downloader_wdl, version="1.0")[0]
task.typecheck()
inputs = values_from_json(downloader_inputs, task.available_inputs)
subdir, outputs = run_local_task(task, inputs, **kwargs)
return outputs["file"].value
except RunFailed as exn:
if isinstance(exn.__cause__, Terminated):
raise exn.__cause__ from None
raise DownloadFailed(uri) from exn.__cause__
except:
raise DownloadFailed(uri) | python | 14 | 0.62963 | 81 | 44.055556 | 18 |
Download the URI and return the local filename.
kwargs are passed through to ``run_local_task``, so ``run_dir`` and ``logger_prefix`` may be
useful in particular.
| function |
class Input$1 extends WebComponent {
static get metadata() {
return metadata$d;
}
static get renderer() {
return InputLitRenderer;
}
static get calculateTemplateContext() {
return InputTemplateContext.calculate;
}
constructor(state) {
super(state);
this.iconPressHandler = this.iconPress.bind(this);
// Indicates if there is selected suggestionItem.
this.hasSuggestionItemSelected = false;
// Indicates if there is focused suggestionItem.
// Used to ignore the Input 'focusedOut' and this preventing firing 'change' event.
this.hasSuggestionItemFocused = false;
// A temporary value of the Input, stored between 'focusedOut' events.
// Used to register and fire 'change' event,
// Note: the property 'value' is updated upon each user input and can`t be used.
this.tempValue = "";
// Represents the value before user moves selection between the suggestion items.
// Used to register and fire 'liveChange' event upon [SPACE] [ENTER].
// Note: the property 'value' is updated selection move and can`t be used.
this.valueBeforeItemSelection;
// Indicates if the Input lost the focus.
this.lostFocus = false;
this.firstRendering = true;
}
onBeforeRendering() {
this.initIcon();
if (this.showSuggestion) {
this.enableSuggestions();
}
}
onAfterRendering() {
if (!this.firstRendering && this.InputSuggestion) {
this.InputSuggestion.updateSuggestionList(this.suggestionItems || []);
}
this.handleFocusOut();
this.firstRendering = false;
}
onsapup(event) {
if (this.InputSuggestion && this.InputSuggestion.isSuggestionListOpened()) {
event.preventDefault();
this.InputSuggestion.handleSuggestioItemsNavigation(false /* forward */);
}
}
onsapdown(event) {
if (this.InputSuggestion && this.InputSuggestion.isSuggestionListOpened()) {
event.preventDefault();
this.InputSuggestion.handleSuggestioItemsNavigation(true /* forward */);
}
}
onsapright(event) {
this.onsapdown(event);
}
onsapleft(event) {
this.onsapup(event);
}
onsapspace(event) {
if (this.InputSuggestion && this.InputSuggestion.isSuggestionItemOnTarget()) {
event.preventDefault();
this.InputSuggestion.onSuggestionItemSelected(null, true /* keyboardUsed */);
}
}
onsapenter() {
if (this.InputSuggestion && this.InputSuggestion.isSuggestionItemOnTarget()) {
this.InputSuggestion.onSuggestionItemSelected(null, true /* keyboardUsed */);
return;
}
this.onChange("submit");
}
onfocusin() {
this._focused = true; // invalidating property
this.lostFocus = false;
this.hasSuggestionItemFocused = false;
}
onfocusout() {
this._focused = false; // invalidating property
this.lostFocus = true;
}
oninput() {
this.onChange("input");
this.hasSuggestionItemSelected = false;
if (this.InputSuggestion) {
this.InputSuggestion.selectedSuggestionItemIndex = null;
}
}
onChange(eventType) {
if (this.disabled || this.readonly) {
return;
}
const inputValue = this.getInputValue();
const valueChanged = this.tempValue !== inputValue;
const isSubmit = eventType === "submit";
this.value = inputValue;
if (eventType === 'input') {
this.fireEvent("liveChange", { value: inputValue });
return;
}
if ((isSubmit || eventType === "focusOut") && valueChanged) {
this.fireEvent("change", { value: inputValue });
this.tempValue = inputValue;
}
if (isSubmit) {
this.fireEvent("submit", { value: inputValue });
}
}
handleFocusOut() {
if (this.lostFocus && !this.hasSuggestionItemFocused) {
this.onChange("focusOut");
}
}
initIcon() {
if (this.icon) {
this.icon.removeEventListener("press", this.iconPressHandler);
this.icon.addEventListener("press", this.iconPressHandler);
this.icon._customClasses = ['sapMInputBaseIcon', 'sapMInputBaseIconPressed'];
}
}
iconPress() {
this.fireEvent('iconPress');
}
getInputValue() {
const inputDOM = this.getDomRef();
if (inputDOM) {
return this.getInputDOMRef().value;
}
return "";
}
getInputDOMRef() {
return this.getDomRef().querySelector(`#${this.getInputId()}`);
}
getLabelableElementId() {
return this.getInputId();
}
getInputId() {
return this._id + "-inner";
}
/* ================================= */
/* InputSuggestion handling */
/* ================================= */
enableSuggestions() {
if (this.InputSuggestion) {
return;
}
try {
this.InputSuggestion = Input$1.getInputSuggestion();
this.InputSuggestion.enableSuggestionsFor(this);
} catch(err) {
throw new Error(`You have to import @openui5/sap.ui.webcomponents.main/src/sap/ui/webcomponents/main/InputSuggestion module to use input suggestions:: ${err}`);
}
}
onSuggestionItemFocus() {
this.hasSuggestionItemFocused = true;
}
onSuggestionItemSelected(item, keyboardUsed) {
const itemText = item._nodeText;
const fireLiveChange = keyboardUsed ? this.valueBeforeItemSelection !== itemText : this.value !== itemText;
this.hasSuggestionItemSelected = true;
this.fireEvent('suggestionItemSelect', { item: item });
if (fireLiveChange) {
this.fireEvent('liveChange', { value: itemText });
this.value = itemText;
this.valueBeforeItemSelection = itemText;
}
}
onSuggestionItemPreview(previewText) {
this.valueBeforeItemSelection = this.value;
this.value = previewText;
}
} | javascript | 13 | 0.692667 | 163 | 23.253394 | 221 | /**
* @class
* A class to represent an <code>Input</code>.
*
* <h3>Overview</h3>
*
* Allows the user to enter and edit text or numeric values in one line.
* You can enable showSuggestion option to easily enter a valid value.
* The suggestions are stored in two aggregations <code>suggestionItems</code>.
*
* <h3>Guidelines</h3>
*
* <ul>
* <li> Always provide a meaningful label for any input field </li>
* <li> Limit the length of the input field. This will visually emphasize the constraints for the field. </li>
* <li> Do not use the <code>placeholder</code> property as a label.</li>
* </ul>
*
* <h3>Usage</h3>
*
* <b>When to use:</b>
* Use the control for short inputs like emails, phones, passwords, fields for assisted value selection.
*
* <b>When not to use:</b>
* Don't use the control for long texts, dates, designated search fields, fields for multiple selection.
*
* @constructor
* @author SAP SE
* @alias sap.ui.webcomponents.main.Input
* @public
*/ | class |
public class Line extends DocumentElement {
private Position startPoint;
private Position endPoint;
private double lineWidth = 0.5;
/**
* Creates a new instance of {@link Line} using the specified properties.
*
* @param areaID
* <p>
* The identifier of the area definition this line is associated
* with.
* </p>
* <p>
* <b>Note:</b> This element requires a valid area identifier
* although it will be rendered on page level.
* </p>
* @param startPoint
* The start point of the line to render.
* @param endPoint
* The end point of the line to render.
* @throws NullPointerException
* Is thrown if the given start point, end point or area
* identifier is <code>null</code>.
* @throws IllegalArgumentException
* Is thrown if the given area identifier is an empty string.
*/
public Line(String areaID, Position startPoint, Position endPoint) throws NullPointerException {
super(areaID);
if (startPoint == null)
throw new NullPointerException("The startPoint may not be null.");
if (endPoint == null)
throw new NullPointerException("The endPoint may not be null.");
this.startPoint = startPoint;
this.endPoint = endPoint;
}
/**
* Creates a new instance of {@link Line} using the specified properties.
*
* @param areaID
* <p>
* The identifier of the area definition this line is associated
* with.
* </p>
* <p>
* <b>Note:</b> This element requires a valid area identifier
* although it will be rendered on page level.
* </p>
* @param startPoint
* The start point of the line to render.
* @param endPoint
* The end point of the line to render.
* @param lineWidth
* The width of the line.
*/
public Line(String areaID, Position startPoint, Position endPoint, double lineWidth) {
this(areaID, startPoint, endPoint);
this.lineWidth = lineWidth;
}
/**
* Creates a new instance of {@link Line} using the specified properties.
*
* @param areaID
* <p>
* The identifier of the area definition this line is associated
* with.
* </p>
* <p>
* <b>Note:</b> This element requires a valid area identifier
* although it will be rendered on page level.
* </p>
* @param startPoint
* The start point of the line to render.
* @param endPoint
* The end point of the line to render.
* @param lineWidth
* The width of the line.
* @param isRepeating
* <code>true</code> if the line should be rendered on every
* document page. Otherwise <code>false</code>.
*/
public Line(String areaID, Position startPoint, Position endPoint, double lineWidth, boolean isRepeating) {
this(areaID, startPoint, endPoint, lineWidth);
setIsRepeating(isRepeating);
}
/**
* Returns the start point of this line.
*
* @return The start point of this line.
*/
public Position getStartPoint() {
return startPoint;
}
/**
* Returns the end point of this line.
*
* @return The end point of this line.
*/
public Position getEndPoint() {
return endPoint;
}
/**
* Returns the width of this line.
*
* @return The width of this line.
*/
public double getLineWidth() {
return lineWidth;
}
@Override
protected boolean needsStyleID() {
return false;
}
/**
* Sets the start point of this line.
*
* @param startPoint
* The start point to set.
* @throws NullPointerException
* Is thrown if the given start point is <code>null</code>.
*/
public void setStartPoint(Position startPoint) throws NullPointerException {
if (startPoint == null)
throw new NullPointerException("The startPoint may not be null.");
this.startPoint = startPoint;
}
/**
* Sets the end point of this line.
*
* @param endPoint
* The end point to set.
* @throws NullPointerException
* Is thrown if the given end point is <code>null</code>.
*/
public void setEndPoint(Position endPoint) throws NullPointerException {
if (endPoint == null)
throw new NullPointerException("The endPoint may not be null.");
this.endPoint = endPoint;
}
/**
* Sets the width of this line.
*
* @param lineWidth
* The width to set.
* @throws IllegalArgumentException
* Is thrown if the given width is negative.
*/
public void setLineWidth(double lineWidth) throws IllegalArgumentException {
if (lineWidth < 0)
throw new IllegalArgumentException("The lineWidth may not be negative.");
this.lineWidth = lineWidth;
}
@Override
protected String getXSIType() {
return "Line";
}
@Override
protected String getAdditionalAttributes() {
return null;
}
@Override
protected String getXmlContent() {
StringBuilder sb = new StringBuilder();
sb.append(String.format(Locale.US, "%s\n%s\n<LineWidth>%.2f</LineWidth>\n<LineColor />",
startPoint.toXML("StartPoint"), endPoint.toXML("EndPoint"), lineWidth));
return sb.toString();
}
@Override
protected DocumentElement onCopy() {
Line l = new Line(getAreaID(), startPoint, endPoint, lineWidth);
return l;
}
} | java | 13 | 0.628782 | 108 | 27.531579 | 190 | /**
* <p>
* Represents a line that will be rendered inside a document.
* </p>
* <p>
* <b>Note:</b> The line will be positioned absolute within the document and
* does not take up space inside the specified area.
* </p>
*
* @author Marcel Singer
*
*/ | class |
def new_release_available(self):
try:
current_release = self.src_doc.get("download", {}).get("release")
except:
current_release = False
if not current_release or int(self.release) > int(current_release):
self.logger.info("New release '%s' found" % self.release)
return True
else:
self.logger.debug("No new release found")
return False | python | 12 | 0.568493 | 77 | 38.909091 | 11 | Determine if newest release needs to be downloaded | function |
public static SettlersFolderInfo checkSettlersFolder(String settlersFolder) {
if (settlersFolder == null || settlersFolder.isEmpty()) {
return new SettlersFolderInfo();
}
File settlersBaseFolderFile = new File(settlersFolder);
return checkSettlersFolder(settlersBaseFolderFile);
} | java | 8 | 0.791096 | 77 | 40.857143 | 7 | /**
* Checks a potential Settlers III installation folder and extracts the gfx and snd folders.
*
* @param settlersFolder
* Folder of Settlers III installation
* @return Instance of {@link SettlersFolderInfo}.
*/ | function |
public class EnvironmentMap {
List<Line>[] vertical;
List<Line>[] horizontal;
int sizeX;
int sizeY;
/**
* Returns an unmodifiable list of all vertical lines with X-coordinate at i.
* @param i X-coordinate of walls in the list
* @return an unmodifiable list of all vertical lines with X-coordinate at i.
*/
public List<Line> getVerticalLines(int i) {
return Collections.unmodifiableList(vertical[i]);
}
/**
* Returns an unmodifiable list of all horizontal lines with Y-coordinate at i.
* @param i Y-coordinate of walls in the list
* @return an unmodifiable list of all horizontal lines with Y-coordinate at i.
*/
public List<Line> getHorizontalLines(int i) {
return Collections.unmodifiableList(horizontal[i]);
}
/**
* Returns a width of the map as it was specified in a scenario file.
* @return width of the map as it was specified in a scenario file.
*/
public int getSizeX() {
return sizeX;
}
/**
* Returns a height of the map as it was specified in a scenario file.
* @return height of the map as it was specified in a scenario file.
*/
public int getSizeY() {
return sizeY;
}
@SuppressWarnings("unchecked")
EnvironmentMap(int sizeX, int sizeY) {
this.sizeX = sizeX;
this.sizeY = sizeY;
vertical = new ArrayList[sizeX+1];
for (int i = 0; i <= sizeX; i++) {
vertical[i] = new ArrayList();
}
horizontal = new ArrayList[sizeY+1];
for (int i = 0; i <= sizeY; i++) {
horizontal[i] = new ArrayList();
}
}
} | java | 11 | 0.605844 | 83 | 28.438596 | 57 | /**
* Representation of the map of physical obstacles in the environment. Map is represented as a list of horizontal and
* vertical line segments. Those segments can have only integer coordinates because the map is given by a bitmap image
* with discrete pixels. A robot can never cross any of those lines as they represent physical walls.
*
* @author Danylo Khalyeyev
*/ | class |
public class TemplatingDataflowPipelineRunner extends PipelineRunner<DataflowPipelineJob> {
private static final Logger LOG = LoggerFactory.getLogger(TemplatingDataflowPipelineRunner.class);
private final DataflowPipelineRunner dataflowPipelineRunner;
private final PipelineOptions options;
protected TemplatingDataflowPipelineRunner(DataflowPipelineRunner internalRunner,
PipelineOptions options) {
this.dataflowPipelineRunner = internalRunner;
this.options = options;
}
private static class TemplateHooks extends DataflowPipelineRunnerHooks {
@Override
public boolean shouldActuallyRunJob() {
return false;
}
@Override
public boolean failOnJobFileWriteFailure() {
return true;
}
}
/** Constructs a runner from the provided options. */
public static TemplatingDataflowPipelineRunner fromOptions(PipelineOptions options) {
DataflowPipelineDebugOptions dataflowOptions =
PipelineOptionsValidator.validate(DataflowPipelineDebugOptions.class, options);
DataflowPipelineRunner dataflowPipelineRunner =
DataflowPipelineRunner.fromOptions(dataflowOptions);
checkArgument(!Strings.isNullOrEmpty(dataflowOptions.getDataflowJobFile()),
"--dataflowJobFile must be present to create a template.");
return new TemplatingDataflowPipelineRunner(dataflowPipelineRunner, options);
}
private static class TemplateJob extends DataflowPipelineJob {
private static final String ERROR =
"The result of template creation should not be used.";
TemplateJob() {
super(null, null, null, null);
}
@Override
public String getJobId() {
throw new UnsupportedOperationException(ERROR);
}
@Override
public String getProjectId() {
throw new UnsupportedOperationException(ERROR);
}
@Override
public DataflowPipelineJob getReplacedByJob() {
throw new UnsupportedOperationException(ERROR);
}
@Override
public Dataflow getDataflowClient() {
throw new UnsupportedOperationException(ERROR);
}
@Override
public State waitToFinish(
long timeToWait,
TimeUnit timeUnit,
MonitoringUtil.JobMessagesHandler messageHandler) {
throw new UnsupportedOperationException(ERROR);
}
@Override
public void cancel() {
throw new UnsupportedOperationException(ERROR);
}
@Override
public State getState() {
throw new UnsupportedOperationException(ERROR);
}
}
@Override
public DataflowPipelineJob run(Pipeline p) {
dataflowPipelineRunner.setHooks(new TemplateHooks());
final DataflowPipelineJob job = dataflowPipelineRunner.run(p);
LOG.info("Template successfully created.");
return new TemplateJob();
}
@Override
public <OutputT extends POutput, InputT extends PInput> OutputT apply(
PTransform<InputT, OutputT> transform, InputT input) {
// We delegate graph building to the inner runner.
return dataflowPipelineRunner.apply(transform, input);
}
@Override
public String toString() {
return "TemplatingDataflowPipelineRunner";
}
/** Register the {@link TemplatingDataflowPipelineRunner}. */
@AutoService(PipelineRunnerRegistrar.class)
public static class Runner implements PipelineRunnerRegistrar {
@Override
public Iterable<Class<? extends PipelineRunner<?>>> getPipelineRunners() {
return ImmutableList
.<Class<? extends PipelineRunner<?>>>of(TemplatingDataflowPipelineRunner.class);
}
}
} | java | 16 | 0.736902 | 100 | 30.256637 | 113 | /**
* A {@link PipelineRunner} that's like {@link DataflowPipelineRunner} but only stores a template of
* a job.
*
* <p>Requires that {@link getDataflowJobFile} is set.
*/ | class |
public abstract class ApiPathMixin
{
#region Properties
public abstract ApiPathMixinKind ApiKind { get; }
#endregion
#region Factory Methods
public static ApiPathMixin CreatePropertyPathMixin(string apiName)
{
Contract.Requires(apiName.SafeHasContent());
return new ApiPropertyPathMixin(apiName);
}
public static ApiPathMixin CreateCollectionItemPathMixin(int apiIndex)
{
Contract.Requires(apiIndex >= 0);
return new ApiCollectionItemPathMixin(apiIndex);
}
#endregion
#region Predicate Methods
public bool IsCollectionItem()
{
return this.ApiKind == ApiPathMixinKind.CollectionItem;
}
public bool IsNull()
{
return this.ApiKind == ApiPathMixinKind.Null;
}
public bool IsProperty()
{
return this.ApiKind == ApiPathMixinKind.Property;
}
#endregion
#region Fields
public static readonly ApiPathMixin Null = new ApiNullPathMixin();
#endregion
} | c# | 11 | 0.60424 | 78 | 31.371429 | 35 | /// <summary>
/// Represents a "mixin" that encapsulates the parent/child "path" relationship of the associated child API node to a parent API node.
/// The following are the 3 child/parent path relationships:
/// <list type="bullet">
/// <item><description>Null path relationship.</description></item>
/// <item><description>Property path relationship - child node is a property of the parent node.</description></item>
/// <item><description>Collection item path relationship - child node is an indexed collection item of the parent node.</description></item>
/// </list>
/// </summary> | class |
private static string Encode(string data)
{
if (string.IsNullOrEmpty(data))
{
return string.Empty;
}
return System.Net.WebUtility.UrlEncode(data).Replace("%20", "+");
} | c# | 11 | 0.5 | 77 | 30.125 | 8 | /// <summary>
/// Encodes the specified data for <see cref="mediaContentType"/>.
/// </summary>
/// <param name="data">The data to encode.</param>
/// <returns>Encoded data string.</returns> | function |
func (opts formatOptions) FormatValue(v reflect.Value, m visitedPointers) (out textNode) {
if !v.IsValid() {
return nil
}
t := v.Type()
if !opts.AvoidStringer && v.CanInterface() {
if (t.Kind() != reflect.Ptr && t.Kind() != reflect.Interface) || !v.IsNil() {
switch v := v.Interface().(type) {
case error:
return textLine("e" + formatString(v.Error()))
case fmt.Stringer:
return textLine("s" + formatString(v.String()))
}
}
}
var skipType bool
defer func() {
if !skipType {
out = opts.FormatType(t, out)
}
}()
var ptr string
switch t.Kind() {
case reflect.Bool:
return textLine(fmt.Sprint(v.Bool()))
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return textLine(fmt.Sprint(v.Int()))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
if t.PkgPath() == "" || t.Kind() == reflect.Uintptr {
return textLine(formatHex(v.Uint()))
}
return textLine(fmt.Sprint(v.Uint()))
case reflect.Float32, reflect.Float64:
return textLine(fmt.Sprint(v.Float()))
case reflect.Complex64, reflect.Complex128:
return textLine(fmt.Sprint(v.Complex()))
case reflect.String:
return textLine(formatString(v.String()))
case reflect.UnsafePointer, reflect.Chan, reflect.Func:
return textLine(formatPointer(v))
case reflect.Struct:
var list textList
for i := 0; i < v.NumField(); i++ {
vv := v.Field(i)
if value.IsZero(vv) {
continue
}
s := opts.WithTypeMode(autoType).FormatValue(vv, m)
list = append(list, textRecord{Key: t.Field(i).Name, Value: s})
}
return textWrap{"{", list, "}"}
case reflect.Slice:
if v.IsNil() {
return textNil
}
if opts.PrintAddresses {
ptr = formatPointer(v)
}
fallthrough
case reflect.Array:
var list textList
for i := 0; i < v.Len(); i++ {
vi := v.Index(i)
if vi.CanAddr() {
p := vi.Addr()
if m.Visit(p) {
var out textNode
out = textLine(formatPointer(p))
out = opts.WithTypeMode(emitType).FormatType(p.Type(), out)
out = textWrap{"*", out, ""}
list = append(list, textRecord{Value: out})
continue
}
}
s := opts.WithTypeMode(elideType).FormatValue(vi, m)
list = append(list, textRecord{Value: s})
}
return textWrap{ptr + "{", list, "}"}
case reflect.Map:
if v.IsNil() {
return textNil
}
if m.Visit(v) {
return textLine(formatPointer(v))
}
var list textList
for _, k := range value.SortKeys(v.MapKeys()) {
sk := formatMapKey(k)
sv := opts.WithTypeMode(elideType).FormatValue(v.MapIndex(k), m)
list = append(list, textRecord{Key: sk, Value: sv})
}
if opts.PrintAddresses {
ptr = formatPointer(v)
}
return textWrap{ptr + "{", list, "}"}
case reflect.Ptr:
if v.IsNil() {
return textNil
}
if m.Visit(v) || opts.ShallowPointers {
return textLine(formatPointer(v))
}
if opts.PrintAddresses {
ptr = formatPointer(v)
}
skipType = true
return textWrap{"&" + ptr, opts.FormatValue(v.Elem(), m), ""}
case reflect.Interface:
if v.IsNil() {
return textNil
}
skipType = true
return opts.WithTypeMode(emitType).FormatValue(v.Elem(), m)
default:
panic(fmt.Sprintf("%v kind not handled", v.Kind()))
}
} | go | 19 | 0.644162 | 99 | 26.606838 | 117 | // FormatValue prints the reflect.Value, taking extra care to avoid descending
// into pointers already in m. As pointers are visited, m is also updated. | function |
public ExprTree parseExpression(String buffer, boolean full) throws IOException {
stringLexerSource.setNewSource(buffer);
ExprTreeHolder mutableExpr = objectPool.mutableExprPool.get();
if (lexer.initialize(stringLexerSource)) {
parseExpression(mutableExpr, full);
}
return mutableExpr.getInnerTree();
} | java | 8 | 0.698324 | 81 | 43.875 | 8 | /**
* Parse an expression
*
* @param buffer
* Buffer containing the string representation of the expression.
* @param full
* If this parameter is true, the parse is considered to succeed
* only if the expression was parsed successfully and no other
* tokens are left.
* @return pointer to the expression object if successful, or null otherwise
*/ | function |
func (f *Fpdf) SetLineCapStyle(styleStr string) {
var capStyle int
switch styleStr {
case "round":
capStyle = 1
case "square":
capStyle = 2
default:
capStyle = 0
}
f.capStyle = capStyle
if f.page > 0 {
f.outf("%d J", f.capStyle)
}
} | go | 9 | 0.64257 | 49 | 15.666667 | 15 | // SetLineCapStyle defines the line cap style. styleStr should be "butt",
// "round" or "square". A square style projects from the end of the line. The
// method can be called before the first page is created. The value is
// retained from page to page. | function |
int32
select_common_typmod(ParseState *pstate, List *exprs, Oid common_type)
{
ListCell *lc;
bool first = true;
int32 result = -1;
foreach(lc, exprs)
{
Node *expr = (Node *) lfirst(lc);
if (exprType(expr) != common_type)
return -1;
else if (first)
{
result = exprTypmod(expr);
first = false;
}
else
{
if (result != exprTypmod(expr))
return -1;
}
}
return result;
} | c | 14 | 0.602439 | 70 | 16.125 | 24 | /*
* select_common_typmod()
* Determine the common typmod of a list of input expressions.
*
* common_type is the selected common type of the expressions, typically
* computed using select_common_type().
*/ | function |
public boolean isFirstTimeParamIsOlder(JyotishyaTime oldTime,JyotishyaTime recentTime){
boolean isFirstParamIsOlder=true;
if(recentTime.getGalige()<oldTime.getGalige()){
isFirstParamIsOlder=false;
}else if(recentTime.getGalige()==oldTime.getGalige()){
if(recentTime.getVigalige()<oldTime.getVigalige()){
isFirstParamIsOlder=false;
}
}
return isFirstParamIsOlder;
} | java | 11 | 0.773779 | 87 | 34.454545 | 11 | /**Checks whether first parameter is relatively older than second.
* @param oldTime Relatively old time
* @param recentTime Relatively recent time.
* @return True if first parameter is relatively older than second. False if
* they don't mean their names.
*/ | function |
def depth_estimation_result_from_batch_and_lists(batch: FrameBatch, segms: List[np.ndarray],
depths: List[np.ndarray]):
assert len(batch.frames) == len(segms)
assert len(batch.frames) == len(depths)
results = []
for i in range(len(batch.frames)):
results.append(DepthEstimationResult(batch.frames[i], segms[i], depths[i]))
return results | python | 12 | 0.590698 | 92 | 52.875 | 8 |
Factory method for returning a list of depth estimation result for the batch
Arguments:
batch (FrameBatch): frame batch for which the predictions belong to
segms (List[numpy.ndarray]): List of segmentation output per frame in batch
depths (List[numpy.ndarray]): List of depth estimation per frame in batch
Returns:
List[DepthEstimationResult]
| function |