code
stringlengths
0
30.8k
source
stringclasses
6 values
language
stringclasses
9 values
__index_level_0__
int64
0
100k
async tokenize(options) { const card = _processCreditCardForTokenization(options) const paymentClaims = await this.getPaymentClaimsForTokenization(options) let res = await tokenize({ ...card, ...paymentClaims, }) return res.data }
function
javascript
300
func main() { ctrlAddress := "https://localhost:1280" caCerts, err := rest_util.GetControllerWellKnownCas(ctrlAddress) if err != nil { log.Fatal(err) } caPool := x509.NewCertPool() for _, ca := range caCerts { caPool.AddCert(ca) } ok, err := rest_util.VerifyController(ctrlAddress, caPool) if err != nil { log.Fatal(err) } if !ok { log.Fatal("controller failed CA validation") } client, err := rest_util.NewEdgeManagementClientWithUpdb("admin", "admin", ctrlAddress, caPool) if err != nil { log.Fatal(err) } params := &identity.ListIdentitiesParams{ Context: context.Background(), } resp, err := client.Identity.ListIdentities(params, nil) if err != nil { log.Fatal(err) } println("\n=== Identity List ===") for _, identityItem := range resp.GetPayload().Data { println(*identityItem.Name) } }
function
go
301
public static void main(String[] args) throws IOException { FhirContext ctx = FhirContext.forDstu2(); String serverBase = "http://fhir.healthintersections.com.au/open"; ClientInterface client = ctx.newRestfulClient(ClientInterface.class, serverBase); Identifier identifier = new Identifier().setSystem("urn:oid:1.2.36.146.595.217.0.1").setValue("12345"); List<Patient> patients = client.findPatientsForMrn(identifier); System.out.println("Found " + patients.size() + " patients"); Patient patient = patients.get(0); System.out.println("Patient Last Name: " + patient.getName().get(0).getFamily()); Reference managingRef = patient.getManagingOrganization(); Organization org = client.getOrganizationById(managingRef.getReferenceElement()); System.out.println(org.getName()); }
function
java
302
def exec_return(script, globals=None, locals=None, allow_statement=True): lines = script.split('\n') if ':=' in lines[-1]: lines[-1] = lines[-1].strip() if lines[-1][0] != '(': lines[-1] = '(' + lines[-1] + ')' script = '\n'.join(lines) stmts = list(ast.iter_child_nodes(ast.parse(script))) if not stmts: return None if isinstance(stmts[-1],ast.Assign): lineno = stmts[-1].lineno col_offset = stmts[-1].col_offset end_lineno = stmts[-1].end_lineno end_col_offset = stmts[-1].end_col_offset exp = ast.NamedExpr( target=stmts[-1].targets[0], value=stmts[-1].value) exp.lineno = lineno exp.col_offset = col_offset exp.end_lineno = end_lineno exp.end_col_offset = end_col_offset stmts[-1] = ast.Expr(exp) stmts[-1].lineno = lineno stmts[-1].col_offset = col_offset stmts[-1].end_lineno = end_lineno stmts[-1].end_col_offset = end_col_offset if isinstance(stmts[-1], ast.Expr): if len(stmts) > 1: exec(compile(ast.Module(body=stmts[:-1]), filename="<ast>", mode="exec"), globals, locals) return eval(compile(ast.Expression(body=stmts[-1].value), filename="<ast>", mode="eval"), globals, locals) else: if not allow_statement: raise SyntaxError(f"Last statement in {script} is not an expression: {ast.dump(stmts[-1])}") return exec(script, globals, locals)
function
python
303
public double userSetpoint() { if(controllMode == "manual") { RobotContainer.elevatorLift.elevatorControl(); run = false; }else if(controllMode == "setpoint") { switch (setpointID) { case 0: setpointValue = 120; break; case 1: setpointValue = 123000; break; case 2: setpointValue = 254000; break; } run = true; } return setpointValue; }
function
java
304
def _peeloff_pi(arg): for a in Add.make_args(arg): if a is pi: K = Integer(1) break elif a.is_Mul: K, p = a.as_two_terms() if p is pi and K.is_Rational: break else: return arg, Integer(0) m1 = (K % Rational(1, 2)) * pi m2 = K*pi - m1 return arg - m2, m2
function
python
305
public static class Init { /** * Create / Get ontology of feature pattern. * @return Ontology of feature pattern. */ public static Ontology fpOntology() { return FPO.fpOntology(GDNNS.FM.URI); } /** * Create / get a class that means a set of feature patterns. * @return A class that means a set of feature patterns. */ public static OntClass FeaturePatternSet() { return fpClazz("FeaturePatternSet"); } /** * Create / get a class that means a feature pattern. * @return A class that means a feature pattern. */ public static OntClass FeaturePattern() { return fpClazz("FeaturePattern"); } /** * Create / Get a class that means an element of a feature pattern. * @return A class that means an element of a feature pattern. */ public static OntClass PatternElement() { return fpClazz("PatternElement"); } /** * Create / Get a property that has a pattern number. * @return A property that has a pattern number. */ public static Property hasPatternNo() { Property p = fpProperty("hasPatternNo"); p.addProperty(RDF.type, OWL2.DatatypeProperty); p.addProperty(RDFS.subPropertyOf, OWL2.topDataProperty); return p; } /** * Create / Get a property that has a pattern name. * @return A property that has a pattern name. */ public static Property hasPatternName() { Property p = fpProperty("hasPatternName"); p.addProperty(RDF.type, OWL2.DatatypeProperty); p.addProperty(RDFS.subPropertyOf, OWL2.topDataProperty); return p; } /** * Create / Get a property that has element name ​​for the feature pattern. * @return A property that has element name ​​for the feature pattern. */ public static Property hasPatternElementName() { Property p = fpProperty("hasPatternElementName"); p.addProperty(RDF.type, OWL2.DatatypeProperty); p.addProperty(RDFS.subPropertyOf, OWL2.topDataProperty); return p; } /** * Create / Get a property that has element value ​​for the feature pattern. * @return A property that has element value ​​for the feature pattern. */ public static Property hasPatternElementValue() { Property p = fpProperty("hasPatternElementValue"); p.addProperty(RDF.type, OWL2.DatatypeProperty); p.addProperty(RDFS.subPropertyOf, OWL2.topDataProperty); return p; } /** * Create / Get a property that represents a relationship to the feature pattern generation settings. * @return A property that represents a relationship to the feature pattern generation settings. */ public static Property refSettingFile() { Property p = fpProperty("refSettingFile"); p.addProperty(RDF.type, OWL2.ObjectProperty); p.addProperty(RDFS.subPropertyOf, OWL2.topObjectProperty); return p; } /** * Create / Get a property that represents a relationship to the feature pattern. * @return A property that represents a relationship to the feature pattern. */ public static Property hasPattern() { Property p = fpProperty("hasPattern"); p.addProperty(RDF.type, OWL2.ObjectProperty); p.addProperty(RDFS.subPropertyOf, OWL2.topObjectProperty); return p; } /** * Create / Get a property that represents a relationship of nodes in a feature model. * @return A property that represents a relationship of nodes in a feature model. */ public static Property refNode() { Property p = fpProperty("refNode"); p.addProperty(RDF.type, OWL2.ObjectProperty); p.addProperty(RDFS.subPropertyOf, OWL2.topObjectProperty); return p; } /** * Create / Get a property that represents a relationship of elements in a feature pattern. * @return A property that represents a relationship of elements in a feature pattern. */ public static Property hasPatternElement() { Property p = fpProperty("hasPatternElement"); p.addProperty(RDF.type, OWL2.ObjectProperty); p.addProperty(RDFS.subPropertyOf, OWL2.topObjectProperty); return p; } }
class
java
306
DWORD CNodeCmd::DwGetLocalComputerName( CString & rstrComputerNameOut ) { DWORD sc; DWORD cchBufferSize = 256; CString strOutput; DWORD cchRequiredSize = cchBufferSize; do { sc = ERROR_SUCCESS; if ( GetComputerNameEx( ComputerNameDnsHostname , strOutput.GetBuffer( cchBufferSize ) , &cchRequiredSize ) == FALSE ) { sc = GetLastError(); if ( sc == ERROR_MORE_DATA ) { cchBufferSize = cchRequiredSize; } } strOutput.ReleaseBuffer(); } while( sc == ERROR_MORE_DATA ); if ( sc == ERROR_SUCCESS ) { rstrComputerNameOut = strOutput; } else { rstrComputerNameOut.Empty(); } return sc; }
function
c++
307
[Pure] public T PeekFirst() { TurboContract.Requires(this.Count > 0, conditionString: "this.Count > 0"); if (_circularList.Count == 0) throw new InvalidOperationException("Collection is empty"); return _circularList[0]; }
function
c#
308
public ListEntry[] loadSaveFile(File saveFile) { this.storage = Datastorage.parseFile(saveFile); ListEntry[] entry = new ListEntry[storage.getKeys().size()]; for(int i=0; i<entry.length; i++) { StorageKey key = storage.getKeys().get(i); Entry[] entrys = new Entry[key.getKeys().size()]; for(int j=0; j<entrys.length; j++) { entrys[j] = new Entry(entry[i], key.getKeys().get(j)); } entry[i] = new ListEntry(entrys, key.getName(), key); } lists = entry; return entry; }
function
java
309
class ColorRuler { constructor(items=[], colorScheme=interpolateRgbBasis(colors)) { this.colorScheme = colorScheme; this.colorMap = new Map(); // create a sequence of n=`items.length` amount of rational numbers between 0 and 1 // the `force` flag (second constructor argument) being true for this instantiation, means that the sequence won't be lazy upto the size of its default items // that means we can have n numbers to work with already, rather than having to generate them outside of the object itself this.numberGenerator = new LazyRulerNumbers(items.length, true); if (items.length > 0) { items.forEach((item, index) => this.addColor(item, this.numberGenerator.sequence[index])); } } addColor(item, scale) { if (scale >= 0 && scale <= 1) { this.colorMap.set(item, this.colorScheme(scale)); return this.colorMap.get(item); } } getColor(item) { // guarantee that a color exists for an item // first check if we have the color const hasColor = this.colorMap.has(item); // if we don't have the color we need to make it if (!hasColor) { // we make a color for an item, by assigning it a unique scale value, then adding a color in the usual way (using a color scheme interpolator) // we don't have to worry about if the color space is big enough - the number generator takes care of that for us // TODO: refactor this call for generator to look make it look more clean? this.colorMap[item] = this.addColor(item, this.numberGenerator.number().next().value.value); } return this.colorMap.get(item); } colors() { return Object.fromEntries(this.colorMap.entries()); } }
class
javascript
310
def _calculate_bar_factor( dem_path, factor_path, flow_accumulation_path, flow_direction_path, zero_absorption_source_path, loss_path, accumulation_path, out_bar_path): pygeoprocessing.new_raster_from_base( dem_path, zero_absorption_source_path, gdal.GDT_Float32, [_TARGET_NODATA], fill_value_list=[0.0]) flow_accumulation_nodata = pygeoprocessing.get_raster_info( flow_accumulation_path)['nodata'][0] natcap.invest.pygeoprocessing_0_3_3.routing.route_flux( flow_direction_path, dem_path, factor_path, zero_absorption_source_path, loss_path, accumulation_path, 'flux_only') def bar_op(base_accumulation, flow_accumulation): result = numpy.empty(base_accumulation.shape) valid_mask = ( (base_accumulation != _TARGET_NODATA) & (flow_accumulation != flow_accumulation_nodata)) result[:] = _TARGET_NODATA result[valid_mask] = ( base_accumulation[valid_mask] / flow_accumulation[valid_mask]) return result pygeoprocessing.raster_calculator( [(accumulation_path, 1), (flow_accumulation_path, 1)], bar_op, out_bar_path, gdal.GDT_Float32, _TARGET_NODATA)
function
python
311
public class FileSizeRotationPolicy implements FileRotationPolicy { private static final Logger LOG = LoggerFactory.getLogger(FileSizeRotationPolicy.class); public enum Units { KB((long)Math.pow(2, 10)), MB((long)Math.pow(2, 20)), GB((long)Math.pow(2, 30)), TB((long)Math.pow(2, 40)); private long byteCount; Units(long byteCount){ this.byteCount = byteCount; } public long getByteCount(){ return byteCount; } } private long maxBytes; private long lastOffset = 0; private long currentBytesWritten = 0; public FileSizeRotationPolicy(float count, Units units){ this.maxBytes = (long)(count * units.getByteCount()); } @Override public boolean mark(TridentTuple tuple, long offset) { return mark(offset); } @Override public boolean mark(long offset) { long diff = offset - this.lastOffset; this.currentBytesWritten += diff; this.lastOffset = offset; return this.currentBytesWritten >= this.maxBytes; } @Override public void reset() { this.currentBytesWritten = 0; this.lastOffset = 0; } @Override public void start() { } public long getMaxBytes() { return maxBytes; } }
class
java
312
fn handle_turn(&mut self, mut player: CurrentPlayer) -> (Player, Assets, CardSet<CardKind>) { loop { println!("{}", self.table); match player.read_action() { PlayerAction::Play(card) => card.play(&mut player, self), PlayerAction::Pass => break, PlayerAction::Rearrange => unimplemented!(), } } player.end_turn() }
function
rust
313
func (c *Client) openStream(ctx context.Context) error { retry := time.After(time.Nanosecond) tryAgain: for { select { case <-ctx.Done(): return ctx.Err() case <-retry: log.Info("Trying to establish new MCP stream") stream, err := c.client.StreamAggregatedResources(ctx) if err != nil { log.Errorf("Failed to create a new MCP stream: %v", err) retry = time.After(reestablishStreamDelay) continue tryAgain } log.Info("New MCP stream created") c.stream = stream for typeURL, state := range c.state { req := &mcp.MeshConfigRequest{ Client: c.clientInfo, TypeUrl: typeURL, } if err := c.stream.Send(req); err != nil { log.Errorf("Failed to send initial MCP request for %q: %v", typeURL, err) See RecvMsg and SendMsg grpc comments in Run() below for rationale. if err := c.stream.CloseSend(); err != nil { log.Errorf("Error closing MCP stream after initial send failure: %v", err) } for { if _, err := c.stream.Recv(); err != nil { if err == io.EOF { break } log.Errorf("Recv() error while waiting for MCP stream to close: %v", err) } } retry = time.After(reestablishStreamDelay) continue tryAgain } state.setVersion("") } return nil } } }
function
go
314
impl<'a> Add<&'a Matrix> for &'a Matrix { type Output = Matrix; fn add(self, other: Self) -> Matrix { assert_eq!(&self.dim, &other.dim); let mut result = vec![vec![0.0; self.dim.1]; self.dim.0]; for x in 0..self.dim.0 { for y in 0..self.dim.1 { result[x][y] = self.matrix[x][y] + other.matrix[x][y]; } } Matrix::new(result) } }
class
rust
315
def reverse(paths: Tuple[Path, ...], output: str = "lines"): workspace = Workspace.from_path() results: Set[str] = set(filter(None, (_reverse_path(workspace, path) for path in paths))) if output == "csv": theme.echo(",".join(results), err=False) sys.exit(0) for result in results: theme.echo(result, err=False) sys.exit(0)
function
python
316
int TreeItem_Height( TreeCtrl *tree, TreeItem item ) { int buttonHeight = 0; int useHeight; if (!TreeItem_ReallyVisible(tree, item)) return 0; if (item->header != NULL) { if (item->fixedHeight > 0) return item->fixedHeight; return Item_HeightOfStyles(tree, item); } useHeight = Item_HeightOfStyles(tree, item); if (TreeItem_HasButton(tree, item)) { buttonHeight = Tree_ButtonHeight(tree, item->state); } if (item->fixedHeight > 0) return MAX(item->fixedHeight, buttonHeight); if (tree->itemHeight > 0) return MAX(tree->itemHeight, buttonHeight); if (tree->minItemHeight > 0) useHeight = MAX(useHeight, tree->minItemHeight); return MAX(useHeight, buttonHeight); }
function
c
317
public static Map<String,Double> intPairCountsToPMI(Map<String,Integer> counts, IDFMap idf) { Map<String,Double> pmis = new HashMap(counts.size()); for( Map.Entry<String,Integer> entry : counts.entrySet() ) { String pairString = entry.getKey(); Integer count = entry.getValue(); int colon = pairString.indexOf(':'); int semicolon = pairString.indexOf(';'); String k1 = pairString.substring(0,colon); String k2 = pairString.substring(colon+1,semicolon); String w1 = WordEvent.stripWordFromPOSTag(k1); String w2 = WordEvent.stripWordFromPOSTag(k2); if( !w1.equals(k1) ) { w1 = CalculateIDF.createKey(w1, Integer.parseInt(WordEvent.stripPOSTagFromWord(k1))); w2 = CalculateIDF.createKey(w2, Integer.parseInt(WordEvent.stripPOSTagFromWord(k2))); } int count1 = idf.getFrequency(w1); int count2 = idf.getFrequency(w2); if( count1 > VERB_FREQ_CUTOFF && count2 > VERB_FREQ_CUTOFF ) { double denom = (double)count1 * (double)count2; double pmi = count.doubleValue() * (double)idf.totalCorpusCount() / denom; pmis.put(pairString, pmi); } else { System.out.println("Skipping " + w1 + " with " + w2); } } return pmis; }
function
java
318
private void mapPublishingData() { JSONArray eventData = new JSONArray(); try { for ( Entry<String, Long> chnEntry : getChannels().entrySet() ) { JSONObject eentry = new JSONObject(); eentry.put(MediaPoolEvent.PROP_CHANNELID, chnEntry.getKey()); eentry.put(MediaPoolEvent.PROP_RENDERINGSCHEME, chnEntry.getValue() ); eventData.put(eentry); } mediaPoolEvent.setPayloadArray(eventData); } catch (Exception e) { LOGGER.error("Error", e); } }
function
java
319
[Cmdlet("Set", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "RecoveryServicesAsrVaultContext", DefaultParameterSetName = ASRParameterSets.ARSVault, SupportsShouldProcess = true)] [Alias( "Set-ASRVaultContext", "Set-ASRVaultSettings", "Set-" + ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "RecoveryServicesAsrVaultSettings")] [OutputType(typeof(ASRVaultSettings))] public class SetAzureRmRecoveryServicesAsrVaultSettings : SiteRecoveryCmdletBase { [Parameter( ParameterSetName = ASRParameterSets.ARSVault, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public ARSVault Vault { get; set; } public override void ExecuteSiteRecoveryCmdlet() { base.ExecuteSiteRecoveryCmdlet(); if (this.ShouldProcess( this.Vault.Name, VerbsCommon.Set)) { this.SetARSVaultContext(this.Vault); } } private void SetARSVaultContext( ARSVault arsVault) { try { VaultExtendedInfoResource vaultExtendedInfo = null; try { vaultExtendedInfo = this.RecoveryServicesClient .GetVaultExtendedInfo(this.Vault.ResourceGroupName, this.Vault.Name); } catch (Exception ex) { Logger.Instance.WriteWarning(ex.Message); throw new Exception(Resources.TryDownloadingVaultFile); } ASRVaultCreds asrVaultCreds = new ASRVaultCreds(); asrVaultCreds.ResourceName = this.Vault.Name; asrVaultCreds.ResourceGroupName = this.Vault.ResourceGroupName; asrVaultCreds.ChannelIntegrityKey = vaultExtendedInfo.IntegrityKey; asrVaultCreds.ResourceNamespace = ARMResourceTypeConstants .RecoveryServicesResourceProviderNameSpace; asrVaultCreds.ARMResourceType = ARMResourceTypeConstants.RecoveryServicesVault; asrVaultCreds.PrivateEndpointStateForSiteRecovery = this.Vault.Properties.PrivateEndpointStateForSiteRecovery; Utilities.UpdateCurrentVaultContext(asrVaultCreds); this.RecoveryServicesClient.ValidateVaultSettings( asrVaultCreds.ResourceName, asrVaultCreds.ResourceGroupName); this.WriteObject(new ASRVaultSettings(asrVaultCreds)); } catch (InvalidOperationException e) { this.WriteDebug(e.Message); } } }
class
c#
320
def scans_average(self, rows, weighted=True, TAMS_hack=True): bpsw, Tsys, intgr = self.BPSW_average(rows, weighted=weighted, TAMS_hack=TAMS_hack) weight = intgr/Tsys**2 weight /= weight.sum(axis=0) wbpsw = weight*bpsw avewbpsw = wbpsw.sum(axis=0) sumintgr = intgr.sum(axis=0).reshape((2,)) aveTsys = (intgr*Tsys).sum(axis=0)/sumintgr meanTsys = aveTsys.mean(axis=1) return avewbpsw, meanTsys, sumintgr
function
python
321
public void Click(in SetSpeedLimitAction action, SetSpeedLimitTarget target, bool multiSegmentMode) { NetInfo netInfo = this.segmentId_.ToSegment().Info; Apply( segmentId: this.segmentId_, finalDir: NetInfo.Direction.Forward, netInfo: netInfo, action: action, target: target); Apply( segmentId: this.segmentId_, finalDir: NetInfo.Direction.Backward, netInfo: netInfo, action: action, target: target); if (multiSegmentMode) { this.ClickMultiSegment(action, target); } }
function
c#
322
public class NCListener implements BuildListener { private static final String APP_NAME = "Ant"; private static final String DEFAULT_GROWL_HOST = "localhost"; private static final String DEFAULT_GROWL_PASSWD = null; private static final int DEFAULT_GROWL_PORT = 23053; private static final String FINISHED_STICKY_NAME = "gbl.endsticky"; private boolean haveNotifier = true; public NCListener() { try { // Check for terminal-notifier Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("which terminal-notifier"); proc.waitFor(); int exitVal = proc.exitValue(); if(exitVal != 0) { haveNotifier = false; System.err.println("Can't find terminal-notifier. Please make sure it is installed and on your path."); } } catch(Exception ioe) { ioe.printStackTrace(); } } /** * Called when the build is started. * * @param event */ public void buildStarted(BuildEvent event) { sendMessage("Build starting...", "Build Started", "ant-started", 0, false); } /** * Called when the build is finished. * * @param event */ public void buildFinished(BuildEvent event) { Throwable t = event.getException(); String projectName = event.getProject().getName(); Hashtable props = event.getProject().getProperties(); boolean sticky = false; // Check if this message should be sticky or not if(props != null && props.containsKey(FINISHED_STICKY_NAME)) { sticky = Boolean.parseBoolean((String)props.get(FINISHED_STICKY_NAME)); } if (t != null) { sendMessage("Build failed: " + t.toString(), "Build failed", "ant-failed", 2, sticky); return; } sendMessage("Build finished for " + projectName, "Build finished", "ant-failed", 0, sticky); } // Other messages are currently ignored public void messageLogged(BuildEvent event) { } public void targetFinished(BuildEvent event) {} public void targetStarted(BuildEvent event) {} public void taskFinished(BuildEvent event) {} public void taskStarted(BuildEvent event) {} /** * Send a message to Notification Center. * * @param type The NotificationType * @param msg The message * @param title The title * @param priority The message priority * @param sticky If true, notification should be "sticky" */ protected void sendMessage(String msg, String title, String group, int priority, boolean sticky) { if(haveNotifier) { try { ProcessBuilder pb = new ProcessBuilder("terminal-notifier", "-message", msg, "-title", "\ud83d\udc1c", "-group", group, "-subtitle", title); pb.start(); } catch(Exception ioe) { ioe.printStackTrace(); } } } public static void main(String[] args) { NCListener ncl = new NCListener(); ncl.sendMessage("Testing Testing", "Test Title", "ant-test", 0, false); } }
class
java
323
GlGeometry BuildVignette( const float xFraction, const float yFraction ) { const float posx[] = { -1.001f, -1.0f + xFraction * 0.25f, -1.0f + xFraction, 1.0f - xFraction, 1.0f - xFraction * 0.25f, 1.001f }; const float posy[] = { -1.001f, -1.0f + yFraction * 0.25f, -1.0f + yFraction, 1.0f - yFraction, 1.0f - yFraction * 0.25f, 1.001f }; const int vertexCount = 6 * 6; VertexAttribs attribs; attribs.position.Resize( vertexCount ); attribs.uv0.Resize( vertexCount ); attribs.color.Resize( vertexCount ); for ( int y = 0; y < 6; y++ ) { for ( int x = 0; x < 6; x++ ) { const int index = y * 6 + x; attribs.position[index].x = posx[x]; attribs.position[index].y = posy[y]; attribs.position[index].z = 0.0f; attribs.uv0[index].x = 0.0f; attribs.uv0[index].y = 0.0f; const float c = ( y <= 1 || y >= 4 || x <= 1 || x >= 4 ) ? 0.0f : 1.0f; for ( int i = 0; i < 3; i++ ) { attribs.color[index][i] = c; } attribs.color[index][3] = 1.0f; } } Array< TriangleIndex > indices; indices.Resize( 24 * 6 ); int index = 0; for ( TriangleIndex x = 0; x < 5; x++ ) { for ( TriangleIndex y = 0; y < 5; y++ ) { if ( x == 2 && y == 2 ) { continue; } if ( x == y ) { indices[index + 0] = y * 6 + x; indices[index + 1] = (y + 1) * 6 + x + 1; indices[index + 2] = (y + 1) * 6 + x; indices[index + 3] = y * 6 + x; indices[index + 4] = y * 6 + x + 1; indices[index + 5] = (y + 1) * 6 + x + 1; } else { indices[index + 0] = y * 6 + x; indices[index + 1] = y * 6 + x + 1; indices[index + 2] = (y + 1) * 6 + x; indices[index + 3] = (y + 1) * 6 + x; indices[index + 4] = y * 6 + x + 1; indices[index + 5] = (y + 1) * 6 + x + 1; } index += 6; } } return GlGeometry( attribs, indices ); }
function
c++
324
private class QuantityFieldFilter extends DocumentFilter{ @Override public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException{ String resultText = generateFinalInsertText(fb, offset, text); if(bypassInsertOrReplace(resultText)){ super.insertString(fb, offset, text, attr); } } @Override public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr) throws BadLocationException{ String resultText = generateFinalReplaceText(fb, offset, length, text); if(bypassInsertOrReplace(resultText)){ super.replace(fb, offset, length, text, attr); } Document doc = fb.getDocument(); String fullText = doc.getText(0, doc.getLength()); //If the first character is a 0, and the text is longer than 1 character, //remove the 0 if(fullText.charAt(0) == '0' && fullText.length() > 1){ remove(fb, 0, 1); } } @Override public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException{ Document doc = fb.getDocument(); String fullText = doc.getText(0, doc.getLength()); String textAfterRemove = fullText.substring(0, offset) + fullText.substring((offset + length - 1), (fullText.length() - 1)); if(textAfterRemove.equals("")){ insertString(fb, 0, "0", null); super.remove(fb, offset + 1, length); } else{ super.remove(fb, offset, length); } } /** * Generate what the final text will be if the insert operation * is completed. * * @param fb the <tt>FilterBypass</tt> object to work around the filter. * @param offset the offset of the replacement text. * @param newText the replacement text. * @return the final text if the replace operation is completed. * @throws BadLocationException if text retrieved from the <tt>Document</tt> * doesn't exist at the specified location. */ private String generateFinalInsertText(DocumentFilter.FilterBypass fb, int offset, String newText) throws BadLocationException{ StringBuilder result = new StringBuilder(); Document doc = fb.getDocument(); String existingText = doc.getText(0, doc.getLength()); result.append(existingText.substring(0, offset)); result.append(newText); result.append(existingText.substring(offset)); return result.toString(); } /** * Generate what the final text will be if the replace operation * is completed. * * @param fb the <tt>FilterBypass</tt> object to work around the filter. * @param offset the offset of the replacement text. * @param length the length of the replacement text. * @param newText the replacement text. * @return the final text if the replace operation is completed. * @throws BadLocationException if text retrieved from the <tt>Document</tt> * doesn't exist at the specified location. */ private String generateFinalReplaceText(DocumentFilter.FilterBypass fb, int offset, int length, String newText) throws BadLocationException{ StringBuilder result = new StringBuilder(); Document doc = fb.getDocument(); String existingText = doc.getText(0, doc.getLength()); result.append(existingText.substring(0, offset)); result.append(newText); if((offset + length) < existingText.length()){ result.append(existingText.substring(offset + length)); } return result.toString(); } /** * Checks the inserted or replaced text to determine if it should bypass * the filter or not. * * @param fb the <tt>FilterBypass</tt> object. * @param text the text to check. * @return true if the text should bypass the filter. * @throws BadLocationException if text retrieved from the <tt>Document</tt> * doesn't exist at the specified location. */ private boolean bypassInsertOrReplace(String fullText) throws BadLocationException{ boolean result; if(! hasOnlyNumbers(fullText)){ //First test if the string only has numbers, and if it doesn't it //doesn't get added result = false; Toolkit.getDefaultToolkit().beep(); } else{ //If the string is just numbers, combine it with the existing text //and test to see if the full value is greater than the max int quantity = Integer.parseInt(fullText); //If it is greater than the max, the new text doesn't get added if(quantity > getShareLimit()){ result = false; Toolkit.getDefaultToolkit().beep(); } else{ //If it passes both tests, it gets added result = true; } } return result; } /** * Tests a <tt>String</tt> to see if it contains only valid * number values. This is accomplished by deliberately running * an unsafe <tt>Integer.parseInt(String)</tt> * operation in a try-catch block. If no exception occurs, this * method returns true that the <tt>String</tt> contains only * numbers. If an exception occurs, it is caught and squashed, * and this method returns false. * * @param string the <tt>String</tt> to be tested. * @return true if the <tt>String</tt> contains only numbers. */ private boolean hasOnlyNumbers(String string){ try{ Integer.parseInt(string); return true; } catch(NumberFormatException ex){ return false; } } }
class
java
325
[PublicAPI] [MoonSharpUserData] public class PinnedStructure<T> : IDisposable where T : struct { #region Properties private bool _isDisposed; public bool IsDisposed { [DebuggerStepThrough] get { return _isDisposed; } } private T _managedObject; public T ManagedObject { get { if (IsDisposed) { Log.Error ( "PinnedStructure::ManagedObject: " + "disposed" ); throw new ObjectDisposedException("PinnedStructure"); } return (T)_handle.Target; } set { Marshal.StructureToPtr ( value, _pointer, false ); } } private IntPtr _pointer; public IntPtr Pointer { [DebuggerStepThrough] get { if (IsDisposed) { Log.Error ( "PinnedStructure::Pointer: " + "disposed" ); throw new ObjectDisposedException("PinnedStructure"); } return _pointer; } } #endregion #region Construction public PinnedStructure() { _managedObject = new T(); _handle = GCHandle.Alloc ( _managedObject, GCHandleType.Pinned ); _pointer = _handle.AddrOfPinnedObject(); } ~PinnedStructure() { Dispose(); } #endregion #region Private members private GCHandle _handle; #endregion #region Public methods #endregion #region IDisposable members public void Dispose() { if (!IsDisposed) { _handle.Free(); _pointer = IntPtr.Zero; _isDisposed = true; } } #endregion }
class
c#
326
@OpenSearchIntegTestCase.SuiteScopeTestCase public class ShardReduceIT extends OpenSearchIntegTestCase { private IndexRequestBuilder indexDoc(String date, int value) throws Exception { return client().prepareIndex("idx", "type").setSource(jsonBuilder() .startObject() .field("value", value) .field("ip", "10.0.0." + value) .field("location", Geohash.stringEncode(5, 52, Geohash.PRECISION)) .field("date", date) .field("term-l", 1) .field("term-d", 1.5) .field("term-s", "term") .startObject("nested") .field("date", date) .endObject() .endObject()); } @Override public void setupSuiteScopeCluster() throws Exception { assertAcked(prepareCreate("idx") .addMapping("type", "nested", "type=nested", "ip", "type=ip", "location", "type=geo_point", "term-s", "type=keyword")); indexRandom(true, indexDoc("2014-01-01", 1), indexDoc("2014-01-02", 2), indexDoc("2014-01-04", 3)); ensureSearchable(); } public void testGlobal() throws Exception { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(global("global") .subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY) .minDocCount(0))) .get(); assertSearchResponse(response); Global global = response.getAggregations().get("global"); Histogram histo = global.getAggregations().get("histo"); assertThat(histo.getBuckets().size(), equalTo(4)); } public void testFilter() throws Exception { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(filter("filter", QueryBuilders.matchAllQuery()) .subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY) .minDocCount(0))) .get(); assertSearchResponse(response); Filter filter = response.getAggregations().get("filter"); Histogram histo = filter.getAggregations().get("histo"); assertThat(histo.getBuckets().size(), equalTo(4)); } public void testMissing() throws Exception { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(missing("missing").field("foobar") .subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY) .minDocCount(0))) .get(); assertSearchResponse(response); Missing missing = response.getAggregations().get("missing"); Histogram histo = missing.getAggregations().get("histo"); assertThat(histo.getBuckets().size(), equalTo(4)); } public void testGlobalWithFilterWithMissing() throws Exception { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(global("global") .subAggregation(filter("filter", QueryBuilders.matchAllQuery()) .subAggregation(missing("missing").field("foobar") .subAggregation(dateHistogram("histo").field("date") .dateHistogramInterval(DateHistogramInterval.DAY).minDocCount(0))))) .get(); assertSearchResponse(response); Global global = response.getAggregations().get("global"); Filter filter = global.getAggregations().get("filter"); Missing missing = filter.getAggregations().get("missing"); Histogram histo = missing.getAggregations().get("histo"); assertThat(histo.getBuckets().size(), equalTo(4)); } public void testNested() throws Exception { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(nested("nested", "nested") .subAggregation(dateHistogram("histo").field("nested.date").dateHistogramInterval(DateHistogramInterval.DAY) .minDocCount(0))) .get(); assertSearchResponse(response); Nested nested = response.getAggregations().get("nested"); Histogram histo = nested.getAggregations().get("histo"); assertThat(histo.getBuckets().size(), equalTo(4)); } public void testStringTerms() throws Exception { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(terms("terms").field("term-s") .collectMode(randomFrom(SubAggCollectionMode.values())) .subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY) .minDocCount(0))) .get(); assertSearchResponse(response); Terms terms = response.getAggregations().get("terms"); Histogram histo = terms.getBucketByKey("term").getAggregations().get("histo"); assertThat(histo.getBuckets().size(), equalTo(4)); } public void testLongTerms() throws Exception { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(terms("terms").field("term-l") .collectMode(randomFrom(SubAggCollectionMode.values())) .subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY) .minDocCount(0))) .get(); assertSearchResponse(response); Terms terms = response.getAggregations().get("terms"); Histogram histo = terms.getBucketByKey("1").getAggregations().get("histo"); assertThat(histo.getBuckets().size(), equalTo(4)); } public void testDoubleTerms() throws Exception { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(terms("terms").field("term-d") .collectMode(randomFrom(SubAggCollectionMode.values())) .subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY) .minDocCount(0))) .get(); assertSearchResponse(response); Terms terms = response.getAggregations().get("terms"); Histogram histo = terms.getBucketByKey("1.5").getAggregations().get("histo"); assertThat(histo.getBuckets().size(), equalTo(4)); } public void testRange() throws Exception { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(range("range").field("value").addRange("r1", 0, 10) .subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY) .minDocCount(0))) .get(); assertSearchResponse(response); Range range = response.getAggregations().get("range"); Histogram histo = range.getBuckets().get(0).getAggregations().get("histo"); assertThat(histo.getBuckets().size(), equalTo(4)); } public void testDateRange() throws Exception { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(dateRange("range").field("date").addRange("r1", "2014-01-01", "2014-01-10") .subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY) .minDocCount(0))) .get(); assertSearchResponse(response); Range range = response.getAggregations().get("range"); Histogram histo = range.getBuckets().get(0).getAggregations().get("histo"); assertThat(histo.getBuckets().size(), equalTo(4)); } public void testIpRange() throws Exception { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(ipRange("range").field("ip").addRange("r1", "10.0.0.1", "10.0.0.10") .subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY) .minDocCount(0))) .get(); assertSearchResponse(response); Range range = response.getAggregations().get("range"); Histogram histo = range.getBuckets().get(0).getAggregations().get("histo"); assertThat(histo.getBuckets().size(), equalTo(4)); } public void testHistogram() throws Exception { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(histogram("topHisto").field("value").interval(5) .subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY) .minDocCount(0))) .get(); assertSearchResponse(response); Histogram topHisto = response.getAggregations().get("topHisto"); Histogram histo = topHisto.getBuckets().get(0).getAggregations().get("histo"); assertThat(histo.getBuckets().size(), equalTo(4)); } public void testDateHistogram() throws Exception { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(dateHistogram("topHisto").field("date").dateHistogramInterval(DateHistogramInterval.MONTH) .subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY) .minDocCount(0))) .get(); assertSearchResponse(response); Histogram topHisto = response.getAggregations().get("topHisto"); Histogram histo = topHisto.getBuckets().iterator().next().getAggregations().get("histo"); assertThat(histo.getBuckets().size(), equalTo(4)); } public void testGeoHashGrid() throws Exception { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(geohashGrid("grid").field("location") .subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY) .minDocCount(0))) .get(); assertSearchResponse(response); GeoGrid grid = response.getAggregations().get("grid"); Histogram histo = grid.getBuckets().iterator().next().getAggregations().get("histo"); assertThat(histo.getBuckets().size(), equalTo(4)); } public void testGeoTileGrid() throws Exception { SearchResponse response = client().prepareSearch("idx") .setQuery(QueryBuilders.matchAllQuery()) .addAggregation(geotileGrid("grid").field("location") .subAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY) .minDocCount(0))) .get(); assertSearchResponse(response); GeoGrid grid = response.getAggregations().get("grid"); Histogram histo = grid.getBuckets().iterator().next().getAggregations().get("histo"); assertThat(histo.getBuckets().size(), equalTo(4)); } }
class
java
327
function todoUser() { this.scope("todo-app", { selector: ".users", idField: "identity" }); return () => ({ locales: ["en"], schema: { id: { type: "string" }, identity: { type: "string" }, color: { type: "string" }, locale: { type: "string", default: "en" } } }); }
function
javascript
328
public partial class MonomakhSaprChg : KaitaiStruct { public static MonomakhSaprChg FromFile(string fileName) { return new MonomakhSaprChg(new KaitaiStream(fileName)); } public MonomakhSaprChg(KaitaiStream p__io, KaitaiStruct p__parent = null, MonomakhSaprChg p__root = null) : base(p__io) { m_parent = p__parent; m_root = p__root ?? this; _read(); } private void _read() { _title = System.Text.Encoding.GetEncoding("ascii").GetString(m_io.ReadBytes(10)); _ent = new List<Block>(); { var i = 0; while (!m_io.IsEof) { _ent.Add(new Block(m_io, this, m_root)); i++; } } } public partial class Block : KaitaiStruct { public static Block FromFile(string fileName) { return new Block(new KaitaiStream(fileName)); } public Block(KaitaiStream p__io, MonomakhSaprChg p__parent = null, MonomakhSaprChg p__root = null) : base(p__io) { m_parent = p__parent; m_root = p__root; _read(); } private void _read() { _header = System.Text.Encoding.GetEncoding("ascii").GetString(m_io.ReadBytes(13)); _fileSize = m_io.ReadU8le(); _file = m_io.ReadBytes(FileSize); } private string _header; private ulong _fileSize; private byte[] _file; private MonomakhSaprChg m_root; private MonomakhSaprChg m_parent; public string Header { get { return _header; } } public ulong FileSize { get { return _fileSize; } } public byte[] File { get { return _file; } } public MonomakhSaprChg M_Root { get { return m_root; } } public MonomakhSaprChg M_Parent { get { return m_parent; } } } private string _title; private List<Block> _ent; private MonomakhSaprChg m_root; private KaitaiStruct m_parent; public string Title { get { return _title; } } public List<Block> Ent { get { return _ent; } } public MonomakhSaprChg M_Root { get { return m_root; } } public KaitaiStruct M_Parent { get { return m_parent; } } }
class
c#
329
private void AssembleResourceLoaderInitializers() { if (resourceLoaderInitializersActive) { return; } ArrayList resourceLoaderNames = runtimeServices.Configuration.GetVector(RuntimeConstants.RESOURCE_LOADER); for(int i = 0; i < resourceLoaderNames.Count; i++) { String loaderID = string.Format("{0}.{1}", resourceLoaderNames[i], RuntimeConstants.RESOURCE_LOADER); ExtendedProperties loaderConfiguration = runtimeServices.Configuration.Subset(loaderID); if (loaderConfiguration == null) { runtimeServices.Warn( string.Format("ResourceManager : No configuration information for resource loader named '{0}'. Skipping.", resourceLoaderNames[i])); continue; } loaderConfiguration.SetProperty(RESOURCE_LOADER_IDENTIFIER, resourceLoaderNames[i]); sourceInitializerList.Add(loaderConfiguration); } resourceLoaderInitializersActive = true; }
function
c#
330
func NewDecoder(json *bufio.Reader) (*Decoder, error) { if json.Size() < 8192 { json = bufio.NewReaderSize(json, 8192) } r := newRememberingReader(json) err := handleBOM(r) if err != nil { return nil, err } d := &Decoder{ json: r, maxDepth: 200, scratchPool: &sync.Pool{ New: func() interface{} { buf := make([]byte, 0, 256); return &buf }, }, } ch, err := d.readAfterWS() if err != nil { if err == io.EOF { return nil, err } return nil, newReadError(err) } switch ch { case '[': d.arrayStarted = true default: _ = d.json.UnreadByte() } return d, nil }
function
go
331
@RestController public class CapabilitiesController { private CapabilitiesService orcaCapabilities; private DeploymentMonitorCapabilities deploymentMonitorCapabilities; public CapabilitiesController( CapabilitiesService orcaCapabilities, Optional<DeploymentMonitorCapabilities> deploymentMonitorCapabilities) { this.deploymentMonitorCapabilities = deploymentMonitorCapabilities.orElse(null); this.orcaCapabilities = orcaCapabilities; } @GetMapping("/capabilities/deploymentMonitors") public List<DeploymentMonitorDefinition> getDeploymentMonitors() { if (deploymentMonitorCapabilities == null) { return Collections.emptyList(); } return deploymentMonitorCapabilities.getDeploymentMonitors(); } @GetMapping("/capabilities/expressions") public ExpressionCapabilityResult getExpressionCapabilities() { return orcaCapabilities.getExpressionCapabilities(); } }
class
java
332
static int pg_SSPI_startup(PGconn *conn, int use_negotiate) { SECURITY_STATUS r; TimeStamp expire; conn->sspictx = NULL; conn->sspicred = malloc(sizeof(CredHandle)); if (conn->sspicred == NULL) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("out of memory\n")); return STATUS_ERROR; } r = AcquireCredentialsHandle(NULL, use_negotiate ? "negotiate" : "kerberos", SECPKG_CRED_OUTBOUND, NULL, NULL, NULL, NULL, conn->sspicred, &expire); if (r != SEC_E_OK) { pg_SSPI_error(conn, libpq_gettext("could not acquire SSPI credentials"), r); free(conn->sspicred); conn->sspicred = NULL; return STATUS_ERROR; } if (!(conn->pghost && conn->pghost[0] != '\0')) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("host name must be specified\n")); return STATUS_ERROR; } conn->sspitarget = malloc(strlen(conn->krbsrvname) + strlen(conn->pghost) + 2); if (!conn->sspitarget) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("out of memory\n")); return STATUS_ERROR; } sprintf(conn->sspitarget, "%s/%s", conn->krbsrvname, conn->pghost); conn->usesspi = 1; return pg_SSPI_continue(conn); }
function
c
333
class SimpsonIntegral : public TrapezoidIntegral<Default> { public: SimpsonIntegral(Real accuracy, Size maxIterations) : TrapezoidIntegral<Default>(accuracy, maxIterations) {} protected: Real integrate(const boost::function<Real (Real)>& f, Real a, Real b) const { Size N = 1; Real I = (f(a)+f(b))*(b-a)/2.0, newI; Real adjI = I, newAdjI; Size i = 1; do { newI = Default::integrate(f,a,b,I,N); N *= 2; newAdjI = (4.0*newI-I)/3.0; if (std::fabs(adjI-newAdjI) <= absoluteAccuracy() && i > 5) return newAdjI; I = newI; adjI = newAdjI; i++; } while (i < maxEvaluations()); QL_FAIL("max number of iterations reached"); } }
class
c++
334
static struct io_plan *handle_txout_reply(struct io_conn *conn, struct daemon *daemon, const u8 *msg) { struct short_channel_id scid; u8 *outscript; struct amount_sat sat; bool was_unknown; if (!fromwire_gossip_get_txout_reply(msg, msg, &scid, &sat, &outscript)) master_badmsg(WIRE_GOSSIP_GET_TXOUT_REPLY, msg); was_unknown = false; for (size_t i = 0; i < tal_count(daemon->unknown_scids); i++) { if (short_channel_id_eq(&daemon->unknown_scids[i], &scid)) { was_unknown = true; tal_arr_remove(&daemon->unknown_scids, i); break; } } if (handle_pending_cannouncement(daemon->rstate, &scid, sat, outscript) && was_unknown) { gossip_missing(daemon); } maybe_send_own_node_announce(daemon); return daemon_conn_read_next(conn, daemon->master); }
function
c
335
public partial class GridSplitter : Control { internal const int GripperCustomCursorDefaultResource = -1; #if CSHTML5_NOT_SUPPORTED internal static readonly CoreCursor ColumnsSplitterCursor = new CoreCursor(CoreCursorType.SizeWestEast, 1); internal static readonly CoreCursor RowSplitterCursor = new CoreCursor(CoreCursorType.SizeNorthSouth, 1); internal CoreCursor PreviousCursor { get; set; } #else internal static readonly Cursor ColumnsSplitterCursor = Cursors.SizeWE; internal static readonly Cursor RowSplitterCursor = Cursors.SizeNS; internal Cursor PreviousCursor { get; set; } #endif private GridResizeDirection _resizeDirection; private GridResizeBehavior _resizeBehavior; private GripperHoverWrapper _hoverWrapper; #if !CSHTML5_NOT_SUPPORTED private Thumb _thumb; #endif private FrameworkElement TargetControl { get { if (ParentLevel == 0) { return this; } var parent = Parent; for (int i = 2; i < ParentLevel; i++) { var frameworkElement = parent as FrameworkElement; if (frameworkElement != null) { parent = frameworkElement.Parent; } } return parent as FrameworkElement; } } private Grid Resizable { get { if (TargetControl != null) return TargetControl.Parent as Grid; else return null; } } private ColumnDefinition CurrentColumn { get { if (Resizable == null) { return null; } var gridSplitterTargetedColumnIndex = GetTargetedColumn(); if ((gridSplitterTargetedColumnIndex >= 0) && (gridSplitterTargetedColumnIndex < Resizable.ColumnDefinitions.Count)) { return Resizable.ColumnDefinitions[gridSplitterTargetedColumnIndex]; } return null; } } private ColumnDefinition SiblingColumn { get { if (Resizable == null) { return null; } var gridSplitterSiblingColumnIndex = GetSiblingColumn(); if ((gridSplitterSiblingColumnIndex >= 0) && (gridSplitterSiblingColumnIndex < Resizable.ColumnDefinitions.Count)) { return Resizable.ColumnDefinitions[gridSplitterSiblingColumnIndex]; } return null; } } private RowDefinition CurrentRow { get { if (Resizable == null) { return null; } var gridSplitterTargetedRowIndex = GetTargetedRow(); if ((gridSplitterTargetedRowIndex >= 0) && (gridSplitterTargetedRowIndex < Resizable.RowDefinitions.Count)) { return Resizable.RowDefinitions[gridSplitterTargetedRowIndex]; } return null; } } private RowDefinition SiblingRow { get { if (Resizable == null) { return null; } var gridSplitterSiblingRowIndex = GetSiblingRow(); if ((gridSplitterSiblingRowIndex >= 0) && (gridSplitterSiblingRowIndex < Resizable.RowDefinitions.Count)) { return Resizable.RowDefinitions[gridSplitterSiblingRowIndex]; } return null; } } public GridSplitter() { #if CSHTML5_NOT_SUPPORTED DefaultStyleKey = typeof(GridSplitter); #else this.DefaultStyleKey = typeof(GridSplitter); this.Loaded += GridSplitter_Loaded; #endif } #if MIGRATION public override void OnApplyTemplate() #else protected override void OnApplyTemplate() #endif { base.OnApplyTemplate(); #if CSHTML5_NOT_SUPPORTED Loaded -= GridSplitter_Loaded; Loaded += GridSplitter_Loaded; #endif if (_hoverWrapper != null) { _hoverWrapper.UnhookEvents(); } #if CSHTML5_NOT_SUPPORTED ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY; #else if (_thumb != null) { _thumb.DragDelta -= Thumb_DragDelta; _thumb.DragStarted -= Thumb_DragStarted; _thumb.DragCompleted -= Thumb_DragCompleted; } _thumb = this.GetTemplateChild("PART_Thumb") as Thumb; We use it to compensate for the lack of the "Manipulation" events. if (_thumb != null) { _thumb.DragDelta += Thumb_DragDelta; _thumb.DragStarted += Thumb_DragStarted; _thumb.DragCompleted += Thumb_DragCompleted; } #endif } #if WORKINPROGRESS #region Not supported yet public static readonly DependencyProperty ShowsPreviewProperty = DependencyProperty.Register("ShowsPreview", typeof(bool), typeof(GridSplitter), null); public bool ShowsPreview { get { return (bool)this.GetValue(GridSplitter.ShowsPreviewProperty); } set { this.SetValue(GridSplitter.ShowsPreviewProperty, value); } } #endregion #endif }
class
c#
336
public class AdminOnlyFilter implements Filter { /** log4j category */ private static Logger log = Logger.getLogger(RegisteredOnlyFilter.class); private AuthorizeService authorizeService; public void init(FilterConfig config) { // Do nothing authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { Context context = null; // We need HTTP request objects HttpServletRequest hrequest = (HttpServletRequest) request; HttpServletResponse hresponse = (HttpServletResponse) response; try { // Obtain a context context = UIUtil.obtainContext(hrequest); // Continue if logged in or startAuthentication finds a user; // otherwise it will issue redirect so just return. if (context.getCurrentUser() != null || Authenticate.startAuthentication(context, hrequest, hresponse)) { // User is authenticated if (authorizeService.isAdmin(context)) { // User is an admin, allow request to proceed chain.doFilter(hrequest, hresponse); } else { // User is not an admin log.info(LogManager.getHeader(context, "admin_only", "")); JSPManager.showAuthorizeError(hrequest, hresponse, null); } } } catch (SQLException se) { log.warn(LogManager.getHeader(context, "database_error", se .toString()), se); JSPManager.showInternalError(hrequest, hresponse); } // Abort the context if it's still valid if ((context != null) && context.isValid()) { context.abort(); } } public void destroy() { // Nothing } }
class
java
337
private static Config loadConfig() { final String DEFAULT_CONF_FILE = "conf/application.conf"; String cmdConfigFile = System.getProperty("config.file", DEFAULT_CONF_FILE); File configFile = new File(cmdConfigFile); if (!configFile.isFile() || !configFile.canRead()) { if (StringUtils.equals(cmdConfigFile, DEFAULT_CONF_FILE)) { String msg = "Cannot read from config file [" + configFile.getAbsolutePath() + "]!"; LOGGER.error(msg); throw new RuntimeException(msg); } else { LOGGER.warn("Configuration file [" + configFile.getAbsolutePath() + "], is invalid or not readable, fallback to default!"); configFile = new File(DEFAULT_CONF_FILE); } } LOGGER.info("Loading configuration from [" + configFile + "]..."); if (!configFile.isFile() || !configFile.canRead()) { String msg = "Cannot read from config file [" + configFile.getAbsolutePath() + "]!"; LOGGER.error(msg); throw new RuntimeException(msg); } Config config = ConfigFactory.parseFile(configFile) .resolve(ConfigResolveOptions.defaults().setUseSystemEnvironment(true)); LOGGER.info("Application config: " + config); return config; }
function
java
338
private static T CreateObject<T>(ILocalRegistry localRegistry) { object obj = null; var iid = typeof(T).GUID; var ptr = IntPtr.Zero; NativeMethods.ThrowOnFailure( localRegistry.CreateInstance(typeof(VsTextBufferClass).GUID, null, ref iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out ptr)); try { obj = Marshal.GetObjectForIUnknown(ptr); } finally { Marshal.Release(ptr); } return (T)obj; }
function
c#
339
void Cy_SAR_SetLowLimit(SAR_Type *base, uint32_t lowLimit) { CY_ASSERT_L2(CY_SAR_RANGE_LIMIT(lowLimit)); uint32_t rangeThresReg; rangeThresReg = base->RANGE_THRES & ~SAR_RANGE_THRES_RANGE_LOW_Msk; rangeThresReg |= lowLimit & SAR_RANGE_THRES_RANGE_LOW_Msk; base->RANGE_THRES = rangeThresReg; }
function
c
340
@MappedSuperclass @ExposeClass public abstract class BaseModel { /** * Model ID. */ @Id @GeneratedValue @ExposeField(name = "id", template = "8") public Long id; /** * Date of the creation time of this model. */ @Column(name = "created_at") @ExposeField(name = "created_at") public Date createdAt; /** * Date of the last modification of this model. */ @Column(name = "updated_at") @ExposeField(name = "updated_at") public Date updatedAt; /** * Sets created and updated time on creation. */ @PrePersist protected void createdAt() { this.createdAt = this.updatedAt = new Date(); } /** * Sets last update time. */ @PreUpdate protected void updatedAt() { this.updatedAt = new Date(); } /** * Creates this model. */ public abstract void create(); /** * Updates this model. */ public abstract void update(); /** * Deletes this model. */ public abstract void delete(); /** * Returns true, if given Object obj is equal to this model. * * @param obj Object instance to check equality * @return True, of given Object obj is equal this */ @Override public boolean equals(Object obj) { return obj instanceof BaseModel && ((BaseModel)obj).id != null && ((BaseModel)obj).id.equals(this.id); } public List<String> getPropertyNames() { List<String> nameList = new ArrayList<>(); Field[] fields = this.getClass().getDeclaredFields(); for (Field f : fields) { if (f.getAnnotation(ExposeField.class) != null) { nameList.add(f.getAnnotation(ExposeField.class).name()); } } return nameList; } /** * Get one model of type T with a specific ID (null if it's not exists) * @param t Class of the models that should be returned * @param id ID of model, that should be returned * @param <T> Type of the model * @return One model of type T with ID id or null if no model with this id exists */ public static <T extends BaseModel> List<T> one(Class<T> t, long id) { if(id < 0 || !t.isAnnotationPresent(Entity.class)) return null; CriteriaBuilder cb = JPA.em().getCriteriaBuilder(); CriteriaQuery<T> cq = cb.createQuery(t); List<T> res = JPA.em().createQuery(cq.where(cb.equal(cq.from(t).get("id"), id))).getResultList(); if(res.size() == 0) return null; return res; } /** * Get the JPA-Path to the value of a property or the id, if it is a model as well (needed for filtering) * @param elem JPA-Path to the property * @param <T> Generic-Type of the Path * @return JPA-Path to the property or to the id of the model */ public static <T> Path<T> typeCheck(Path<T> elem) { return BaseModel.class.isAssignableFrom(elem.getJavaType()) ? elem.get("id") : elem; } // TODO: For access specific criteria there may not be a "or" relation, so is it better to introduce a new parameter? /** * Get a set of models of type T (e.g. posts, users). This models are paginated (offset, limit) and can be filtered * (map of keys and one or more values), ordered. All filter or order properties has previously checked to be * exposed. * @param t Class of Models to get from JPA * @param offset How many entries to skip * @param limit How many entries to response * @param criteria Filter criteria (pair of key and one or more values). This criteria should contain * access-specific criteria. * @param order Property to filter by * @param <T> Type of Models to get from JPA (Type of t) * @return A list of all matching entries */ public static <T> List<T> someWhere(Class<T> t, Integer offset, Integer limit, Map<String, String[]> criteria, String order) { if(!t.isAnnotationPresent(Entity.class)) // Break if requested model is not an JPA-Entry return null; if(order == null || order.isEmpty()) // If no order is given, default to order by id order = "id"; // Prepare the criteria query CriteriaBuilder cb = JPA.em().getCriteriaBuilder(); CriteriaQuery<T> cq = cb.createQuery(t); Root<T> root = cq.from(t); Predicate[] p = criteria.entrySet().stream() .filter(c -> c.getValue() != null) // Skip conditions with no values .map(c -> typeCheck(root.get(c.getKey())).as(String.class).in(c.getValue())) // Apply criteria (property value is in list of possible values) .toArray(Predicate[]::new); return JPA.em().createQuery(cq.where(cb.and(p)) .orderBy(cb.asc(root.get(order)))) .setFirstResult(offset) .setMaxResults(limit) .getResultList(); } }
class
java
341
func (pq *DefaultRunePublisher) PopDone() RuneSubscriber { if pq == nil || pq.Len() == 0 { return nil } if pq.Top().Done() { return pq.Pop() } return nil }
function
go
342
func findWhoToFollow(candidates []string, shortCndtID string, le *Election) (string, error) { idx := sort.SearchStrings(candidates, shortCndtID) if idx == 0 { return "", fmt.Errorf("%s %s Candidate is <%s>", "findWhoToFollow", leaderWhileDeterminingWhoToFollow, shortCndtID) } if idx == len(candidates) { return "", fmt.Errorf("%s Error finding candidate in child list. Candidate attempting match is (%s) - %v", "findWhoToFollow", shortCndtID, ElectionCompletedNotify) } if !strings.EqualFold(candidates[idx], shortCndtID) { return "", fmt.Errorf("%s Error finding candidate in child list. Candidate attempting match is (%v). "+ "Candidate located at position <%d> is <%s> - %v", "findWhoToFollow", shortCndtID, idx, candidates[idx], ElectionCompletedNotify) } nodeToWatchIdx := idx - 1 watchedNode := strings.Join([]string{le.ElectionResource, candidates[nodeToWatchIdx]}, "/") return watchedNode, nil }
function
go
343
def plot_combined_roc_curve(list_of_kargs, plot_title="title", save_plot = False, output_name = "output.png"): required_karg_set = set(["fpr_list", "tpr_list", "auc", "jscore", "j_threshold", "jindex", "line_label", "line_color"]) fig, ax = plt.subplots(1, figsize = (15,10)) sns.set(font='Arial', style = "white") sns.set_context("paper", font_scale = 2) sns.despine() for karg_dict in list_of_kargs: assert all(True if x in required_karg_set else False for x in karg_dict.keys()), "!!ERROR!! Mislabeled keys in kargs dictionary. Required kargs = {}. Correct for the mislabeled keyword arguments and try again.".format(", ".join(list(required_karg_set))) assert all(True if x in karg_dict.keys() else False for x in required_karg_set), "!!ERROR!! Missing keys in kargs dictionary. Required kargs = {}. Correct for the missing keyword arguments and try again.".format(", ".join(list(required_karg_set))) ax.plot(karg_dict["fpr_list"], karg_dict["tpr_list"], color = karg_dict["line_color"], linewidth = 1.5, label = "{} = {:.3f}, max J = {:.3f}".format(karg_dict["line_label"],karg_dict["auc"],karg_dict["jscore"])) ax.scatter(karg_dict["fpr_list"][karg_dict["jindex"]], karg_dict["tpr_list"][karg_dict["jindex"]], s = 100, color = karg_dict["line_color"] ) ax.plot([0, 1], [0, 1], 'k--') ax.set_title(plot_title, fontsize = 25) ax.set_xlabel('False positive rate', fontsize = 30) ax.set_ylabel('True positive rate', fontsize = 30) ax.legend(title = "ROC AUC, Yoden's J",loc="lower right",prop={'size': 20}) ax.tick_params(axis="x", labelsize=25) ax.tick_params(axis="y", labelsize=25) if save_plot: plt.savefig(output_name) plt.close() else: plt.show()
function
python
344
public static HashMap<Character, Double> charFrequency(String s, boolean countWhiteSpace) { if (!countWhiteSpace) { s = s.replaceAll("\\s+", ""); } HashMap<Character, Integer> charCountMap = charCount(s, countWhiteSpace); HashMap<Character, Double> charFrequencyMap = new HashMap<Character, Double>(); for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) { charFrequencyMap.put(entry.getKey(), entry.getValue() * 100.0 / s.length()); } return charFrequencyMap; }
function
java
345
func (s *Service) resolveFileContents( ctx context.Context, invocationContext *invocationContext, paths []string, patternsForContent []*luatypes.PathPattern, ) (_ map[string]string, err error) { ctx, _, endObservation := s.operations.resolveFileContents.With(ctx, &err, observation.Args{}) defer endObservation(1, observation.Args{}) relevantPaths, err := filterPathsByPatterns(paths, patternsForContent) if err != nil { return nil, err } pathspecs := make([]gitserver.Pathspec, 0, len(relevantPaths)) for _, p := range relevantPaths { pathspecs = append(pathspecs, gitserver.PathspecLiteral(p)) } opts := gitserver.ArchiveOptions{ Treeish: invocationContext.commit, Format: "zip", Pathspecs: pathspecs, } rc, err := invocationContext.gitService.Archive(ctx, invocationContext.repo, opts) if err != nil { return nil, err } data, err := io.ReadAll(rc) if err != nil { return nil, err } zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) if err != nil { return nil, nil } contentsByPath := make(map[string]string, len(zr.File)) for _, f := range zr.File { contents, err := readZipFile(f) if err != nil { return nil, err } contentsByPath[strings.TrimPrefix(f.Name, ":(literal)")] = contents } return contentsByPath, nil }
function
go
346
void usb_host_sendctrlsetup(usb_core_instance *pdev, uint8_t *buff, uint8_t hc_num) { pdev->host.hc[hc_num].is_epin = 0U; pdev->host.hc[hc_num].pid_type = PID_SETUP; pdev->host.hc[hc_num].xfer_buff = buff; pdev->host.hc[hc_num].xfer_len = 8; (void)host_driver_submitrequest(pdev, hc_num); }
function
c
347
public class ArraySegmentList<T> : IList<T>, IEnumerable<IList<T>>, IEnumerable<List<T>>, IEnumerable<ArraySegment<T>> { public readonly int SegmentCapacity = -1; List<List<T>> m_Segments = new List<List<T>>(); List<T> m_CurrentSegment = new List<T>(); public IEnumerable<ArraySegment<T>> Segments { get { return (this as IEnumerable<ArraySegment<T>>); } } public IEnumerable<List<T>> Lists { get { return (this as IEnumerable<List<T>>); } } public ArraySegmentList(int segmentCapacity = -1) { SegmentCapacity = segmentCapacity; } void EnsureCapacity(int amount = 1) { if (m_CurrentSegment.Count + amount > SegmentCapacity) { m_Segments.Add(new List<T>(m_CurrentSegment.ToArray())); m_CurrentSegment.Clear(); } } public T[] ToArray() { return ToArray(0, Count); } public T[] ToArray(int offset, int index) { T[] result = new T[Count - index]; CopyTo(result, index); return result; } public int IndexOf(T item) { return IndexOf(item, 0); } public int IndexOf(T item, int index = -1) { if (index < SegmentCapacity) index = m_CurrentSegment.IndexOf(item, System.Math.Max(0, index)); if (index != -1) return index; else index = 0; foreach (List<T> segment in m_Segments) { int localIndex = segment.IndexOf(item, index); if (localIndex != -1) return index + localIndex; else index += segment.Count; } return -1; } public void Insert(int index, T item) { List<T> found = FindSegmentForIndex(ref index); if (found != default(List<T>) && found.Count < SegmentCapacity) found.Insert(index, item); } public void RemoveAt(int index) { List<T> found = FindSegmentForIndex(ref index); found.RemoveAt(index); } List<T> FindSegmentForIndex(ref int index) { foreach (List<T> segment in m_Segments) { if (index >= SegmentCapacity) index -= segment.Count; else return segment; } return m_CurrentSegment; } public T this[int index] { get { List<T> found = FindSegmentForIndex(ref index); if (found != null) return found[System.Math.Min(found.Count - 1, index)]; else return default(T); } set { List<T> found = FindSegmentForIndex(ref index); if (found != null) found[index] = value; } } public void Add(T item) { EnsureCapacity(1); m_CurrentSegment.Add(item); } public void AddRange(IEnumerable<T> items, int start = 0, int count = -1) { if (count == -1) count = items.Count(); EnsureCapacity(count); } public void RemoveRange(int start, int count) { List<T> found = FindSegmentForIndex(ref start); if (found == null) return; while (--count > 0) found.RemoveAt(start); } public void Clear() { m_Segments.Clear(); m_CurrentSegment.Clear(); } public bool Contains(T item) { return m_CurrentSegment.Contains(item) || m_Segments.Any(s => s.Contains(item)); } public void CopyTo(T[] array, int arrayIndex) { foreach (List<T> segment in m_Segments) { segment.CopyTo(array, arrayIndex); arrayIndex += segment.Count; } m_CurrentSegment.CopyTo(array, arrayIndex); } public int Count { get { return m_CurrentSegment.Count + m_Segments.Sum(s => s.Count); } } public bool IsReadOnly { get { return false; } } public bool Remove(T item) { return Remove(item, false); } public bool Remove(T item, bool allSegments = false) { bool removed = false; if (allSegments) foreach (List<T> segment in m_Segments) removed = segment.Remove(item) || removed; return removed = m_CurrentSegment.Remove(item) || removed; } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return m_Segments.SelectMany(s => s.ToArray()).Concat(m_CurrentSegment.ToArray()).GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return m_Segments.Concat(m_CurrentSegment.Yield()).GetEnumerator(); } public IEnumerator<ArraySegment<T>> GetEnumerator() { IEnumerable<ArraySegment<T>> result = Enumerable.Empty<ArraySegment<T>>(); foreach (List<T> segment in m_Segments) result = result.Concat(new ArraySegment<T>(segment.ToArray(), 0, segment.Count).Yield()); result = result.Concat(new ArraySegment<T>(m_CurrentSegment.ToArray(), 0, m_CurrentSegment.Count).Yield()); return result.GetEnumerator(); } IEnumerator<IList<T>> IEnumerable<IList<T>>.GetEnumerator() { IEnumerable<IList<T>> result = Enumerable.Empty<IList<T>>(); foreach (IList<T> segment in m_Segments as IList<T>) result = result.Concat((segment as IList<T>).Yield()); (m_CurrentSegment as IList<T>).Yield(); return result.GetEnumerator(); } IEnumerator<List<T>> IEnumerable<List<T>>.GetEnumerator() { IEnumerable<List<T>> result = Enumerable.Empty<List<T>>(); foreach (List<T> segment in m_Segments) result = result.Concat(segment.Yield()); (m_CurrentSegment as List<T>).Yield(); return result.GetEnumerator(); } }
class
c#
348
def globe_plot(latitude, longitude, temperature, view=(100., 0.), flat=False, vmin=None, vmax=None, cmap='plasma', smooth_factor=1.0, save_fig=''): if flat: ax = plt.axes(projection=ccrs.PlateCarree()) else: ax = plt.axes(projection=ccrs.Orthographic(*view)) ax.coastlines() if smooth_factor == 1.0: mesh = ax.pcolormesh(longitude, latitude, temperature, transform=ccrs.PlateCarree(), cmap=cmap) else: interp_func = interp2d(longitude, latitude, temperature, kind='cubic') num_lons = int(smooth_factor * len(longitude)) lon_new = np.linspace(0, 360 - (360 / num_lons), num_lons) lat_new = np.linspace(latitude[0], latitude[-1], int(smooth_factor * len(latitude))) temp_new = interp_func(lon_new, -lat_new) mesh = ax.pcolormesh(lon_new, -lat_new, temp_new, transform=ccrs.PlateCarree(), cmap=cmap) if len(save_fig): plt.savefig(save_fig, format='png', dpi=300, bbox_inches='tight') plt.clf() plt.close() else: plt.show()
function
python
349
def _wrangle_vmr(df, rename): df.rename(rename, axis=1, inplace=True) df.loc[:, "LOA ft"] = (df.loc[:, "A"] + df.loc[:, "B"]) * M_TO_FT df.loc[:, "LOA ft"] = df.loc[:, "LOA ft"].round(0) df.loc[:, "Beam ft"] = (df.loc[:, "C"] + df.loc[:, "D"]) * M_TO_FT df.loc[:, "Beam ft"] = df.loc[:, "Beam ft"].round(0) df.loc[:, "Latitude"] = df.loc[:, "Latitude"].round(5) df.loc[:, "Longitude"] = df.loc[:, "Longitude"].round(5) df = _sanitize_vmr(df) df = df.loc[df.loc[:, "LOA ft"] < SUB_PANAMAX, :] df.loc[:, "Date/Time UTC"] = df.loc[:, "Date/Time UTC"].str.strip("UTC") df.loc[:, "Date/Time UTC"] = pd.to_datetime(df.loc[:, "Date/Time UTC"]) df = df.loc[:, (["Date/Time UTC", "Name", "MMSI", "LOA ft", "Latitude", "Longitude", "Course", "AIS Type", "Heading", "VSPD kn", "Beam ft"])] return df
function
python
350
private Term CopyAndReplaceForEquality(Term term, Dictionary<Term, Term> matchAndReplaceTerms) { if (matchAndReplaceTerms.TryGetValue(term, out var replacementTermId)) { return replacementTermId; } if (term.Arguments != null) { var newArguments = new Term[term.Arguments.Length]; bool foundMatch = false; for (int i = 0; i < newArguments.Length; i++) { var currentId = term.Arguments[i].Name.TermIdentifier.Value; var newTerm = CopyAndReplaceForEquality(term.Arguments[i], matchAndReplaceTerms); if (newTerm.Name.TermIdentifier.Value == currentId) { newArguments[i] = term.Arguments[i]; } else { newArguments[i] = newTerm; foundMatch = true; } } if (foundMatch) { return TermDatabase.Writer.CreateCopy(term, newArguments); } } return term; }
function
c#
351
@Autonomous(name="Autonomous - Light Sensor", group="MBot") public class MBotAutonomousUnstable extends LinearOpMode { /* Declare OpMode members. */ MBotHardwareControl robot = new MBotHardwareControl(); // Use a Pushbot's hardware private ElapsedTime runtime = new ElapsedTime(); static final double COUNTS_PER_MOTOR_REV = 1440 ; // eg: TETRIX Motor Encoder static final double DRIVE_GEAR_REDUCTION = 2.0 ; // This is < 1.0 if geared UP static final double WHEEL_DIAMETER_INCHES = 4.0 ; // For figuring circumference static final double COUNTS_PER_INCH = (COUNTS_PER_MOTOR_REV * DRIVE_GEAR_REDUCTION) / (WHEEL_DIAMETER_INCHES * 3.1415); static final double FORWARD_SPEED = 0.6; static final double TURN_SPEED = 0.5; @Override public void runOpMode() throws InterruptedException { /* * Initialize the drive system variables. * The init() method of the hardware class does all the work here */ robot.init(hardwareMap); // Send telemetry message to signify robot waiting; telemetry.addData("Status", "Ready to run"); // telemetry.update(); robot.getDrive().resetMotorEncoders(); idle(); robot.getDrive().runMotorsWithEncoders(); robot.awesomeMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); while (!isStarted()) { // Display the light level while we are waiting to start telemetry.addData("Light Level", robot.getTapeFinder().GetLightDetected()); telemetry.update(); idle(); } /* encoderDrive(FORWARD_SPEED, -5,-5,15); encoderDrive(TURN_SPEED, 8,-8,15); encoderDrive(FORWARD_SPEED, -12,-12,15); encoderDrive(TURN_SPEED, -8,8,15); RunUntilLine(); encoderDrive(TURN_SPEED, -8,8,15); encoderDrive(FORWARD_SPEED, -5,-5,15); */ encoderDrive(FORWARD_SPEED, 4*12,4*12,15); encoderDrive(TURN_SPEED,-8,8,15); encoderDrive(FORWARD_SPEED, 5*12, 5*12, 30); } /*public void drive(double time, boolean backwards) throws InterruptedException { double speed = backwards ? -FORWARD_SPEED : FORWARD_SPEED; robot.leftMotor.setPower(speed); robot.rightMotor.setPower(speed); runtime.reset(); while (opModeIsActive() && (runtime.seconds() < time)) { telemetry.addData("IsBackwards", backwards); telemetry.addData("LeftSpeed", speed); telemetry.addData("RightSpeed", speed); telemetry.addData("Time", time); telemetry.update(); idle(); } } public void turn(double time, boolean goRight) throws InterruptedException { double lSpeed = goRight ? -TURN_SPEED : TURN_SPEED; double rSpeed = goRight ? TURN_SPEED : -TURN_SPEED; robot.leftMotor.setPower(lSpeed); robot.leftMotor.setPower(rSpeed); runtime.reset(); while (opModeIsActive() && (runtime.seconds() < time)) { telemetry.addData("TurnDirection", goRight ? "Right" : "Left"); telemetry.addData("LeftSpeed", lSpeed); telemetry.addData("RightSpeed", rSpeed); telemetry.addData("Time", time); idle(); } }*/ public void encoderDrive(double speed, double leftInches, double rightInches, double timeoutS) throws InterruptedException { int newLeftTarget; int newRightTarget; // Ensure that the opmode is still active if (opModeIsActive()) { // Determine new target position, and pass to motor controller newLeftTarget = robot.getDrive().getLeftPosition() + (int)(leftInches * COUNTS_PER_INCH); newRightTarget = robot.getDrive().getRightPosition() + (int)(rightInches * COUNTS_PER_INCH); robot.getDrive().setLeftTarget(newLeftTarget); robot.getDrive().setRightTarget(newRightTarget); // Turn On RUN_TO_POSITION robot.getDrive().setRunToPosition(); // reset the timeout time and start motion. runtime.reset(); robot.getDrive().setMotorPower(Math.abs(speed)); // keep looping while we are still active, and there is time left, and both motors are running. while (opModeIsActive() && (runtime.seconds() < timeoutS) && (robot.getDrive().isLeftBusy() && robot.getDrive().isRightBusy())) { // Display it for the driver. telemetry.addData("Path1", "Running to %7d :%7d", newLeftTarget, newRightTarget); telemetry.addData("Path2", "Running at %7d :%7d", robot.getDrive().getLeftPosition(), robot.getDrive().getRightPosition()); telemetry.update(); // Allow time for other processes to run. idle(); } // Stop all motion; robot.getDrive().setMotorPower(0); // Turn off RUN_TO_POSITION robot.getDrive().resetMotorEncoders(); // sleep(250); // optional pause after each move } } public void RunUntilLine() throws InterruptedException { robot.getDrive().setMotorPower(FORWARD_SPEED); while (!(opModeIsActive() && !(robot.getTapeFinder().AtLine()))) { telemetry.addData("Light Level", robot.getTapeFinder().GetLightDetected()); telemetry.update(); idle(); } robot.getDrive().setMotorPower(0); } }
class
java
352
def load_character(name: str) -> Union[Character, None]: try: data = load_yaml() if data is None: print('No characters saved yet!') return None except Exception as e: print(f'An error occured when trying to load data!\n {type(e)}: {e}') return None try: char_data = data.get(name, None) if char_data is None: print(f'No character with the name {name} exist!') return None except Exception: print(f'Something went wrong!') _class = char_data.get('class', None) _treasure = char_data.get('treasure', None) if _class is None: print('The character doesn\'t have a class!') else: if _class == 'Knight': character = Knight(name, _treasure) elif _class == 'Wizard': character = Wizard(name, _treasure) elif _class == 'Thief': character = Thief(name, _treasure) else: print('The character is not a valid class!') return None return character return None
function
python
353
func (bot *Bot) guildCreate(s *discordgo.Session, event *discordgo.GuildCreate) { if event.Guild.Unavailable { return } log.Println("Joined " + event.Guild.Name + " (" + event.Guild.ID + ")" + " in " + event.Guild.Region) val, err := db.GetDataTuple(bot.DB, "M:"+event.Guild.OwnerID) if err != nil { if err == badger.ErrKeyNotFound || val == "" { if !utils.HaveIAskedMember(s, event.Guild.OwnerID) { err = utils.AskMember(s, event.Guild.OwnerID, fmt.Sprintf(bot.Messages["LANG"]["WelcomeAndLang"], bot.Prefix, bot.Prefix, bot.Prefix, bot.Prefix)) if err != nil { log.Println("Failed to send message to owner.") return } } _ = db.UpdateDataTuple(bot.DB, "M:"+event.Guild.OwnerID, "1") } } }
function
go
354
def parametric_fit(X_df, filters=DES_FILTERS): n_params = 5 full_params = np.zeros((len(X_df), len(filters) * n_params)) for idx, snid in enumerate(X_df.index): params = np.zeros((len(filters), n_params)) for id_filt, filt in enumerate(filters): time = X_df.loc[snid, 'mjd_%s' % filt] flux = X_df.loc[snid, 'fluxcal_%s' % filt] try: params[id_filt] = _fit_lightcurve(time, flux) except ValueError: continue full_params[idx] = params.ravel() return full_params
function
python
355
class LookSaySequenceTest { // Members LookSaySequence lss = new LookSaySequence(); /** * Test method for {@link com.smt.kata.math.LookSaySequence#translate(int)}. */ @Test void testTranslate11() throws Exception { assertEquals(21, lss.translate(11)); } /** * Test method for {@link com.smt.kata.math.LookSaySequence#translate(int)}. */ @Test void testTranslateOne() throws Exception { assertEquals(11, lss.translate(1)); } /** * Test method for {@link com.smt.kata.math.LookSaySequence#translate(int)}. */ @Test void testTranslate21() throws Exception { assertEquals(1211, lss.translate(21)); } /** * Test method for {@link com.smt.kata.math.LookSaySequence#translate(int)}. */ @Test void testTranslate111221() throws Exception { assertEquals(312211, lss.translate(111221)); } /** * Test method for {@link com.smt.kata.math.LookSaySequence#translate(int)}. */ @Test void testTranslateNegative() throws Exception { assertEquals(312211, lss.translate(-111221)); } /** * Test method for {@link com.smt.kata.math.LookSaySequence#translate(int)}. */ @Test void testTranslate1211() throws Exception { assertEquals(111221, lss.translate(1211)); } }
class
java
356
def _draw_history(self, dyn_obs: DynamicObstacle, call_stack: Tuple[str, ...], draw_params: ParamServer): time_begin = draw_params['time_begin'] history_base_color = draw_params.by_callstack(call_stack, ('vehicle_shape', 'occupancy', 'shape', 'rectangle', 'facecolor')) history_callstack = call_stack + ('history',) history_steps = draw_params.by_callstack(history_callstack, 'steps') history_fade_factor = draw_params.by_callstack(history_callstack, 'fade_factor') history_step_size = draw_params.by_callstack(history_callstack, 'step_size') history_base_color = rgb_to_hsv(to_rgb(history_base_color)) for history_idx in range(history_steps, 0, -1): time_step = time_begin - history_idx * history_step_size occ = dyn_obs.occupancy_at_time(time_step) if occ is not None: color_hsv_new = history_base_color.copy() color_hsv_new[2] = max(0, color_hsv_new[2] - history_fade_factor * history_idx) color_hex_new = to_hex(hsv_to_rgb(color_hsv_new)) draw_params[history_callstack + ('occupancy', 'shape', 'rectangle', 'facecolor')] = color_hex_new draw_params[history_callstack + ('occupancy', 'shape', 'circle', 'facecolor')] = color_hex_new draw_params[history_callstack + ('occupancy', 'shape', 'polygon', 'facecolor')] = color_hex_new occ.draw(self, draw_params, history_callstack)
function
python
357
def OrbitPlot(sim, figsize=None, lim=None, limz=None, Narc=100, unitlabel=None, color=False, periastron=False, trails=True, show_orbit=True, lw=1., slices=False, plotparticles=[]): try: import matplotlib.pyplot as plt from matplotlib import gridspec import numpy as np except: raise ImportError("Error importing matplotlib and/or numpy. Plotting functions not available. If running from within a jupyter notebook, try calling '%matplotlib inline' beforehand.") if unitlabel is not None: unitlabel = " " + unitlabel else: unitlabel = "" if slices: if figsize is None: figsize = (8,8) fig, ax = plt.subplots(2, 2, figsize=figsize) gs = gridspec.GridSpec(2, 2, width_ratios=[3., 2.], height_ratios=[2.,3.],wspace=0., hspace=0.) OrbitPlotOneSlice(sim, plt.subplot(gs[2]), lim=lim, Narc=Narc, color=color, periastron=periastron, trails=trails, show_orbit=show_orbit, lw=lw, axes="xy", plotparticles=plotparticles) OrbitPlotOneSlice(sim, plt.subplot(gs[3]), lim=lim, limz=limz, Narc=Narc, color=color, periastron=periastron, trails=trails, show_orbit=show_orbit, lw=lw, axes="zy", plotparticles=plotparticles) OrbitPlotOneSlice(sim, plt.subplot(gs[0]), lim=lim, limz=limz, Narc=Narc, color=color, periastron=periastron, trails=trails, show_orbit=show_orbit, lw=lw, axes="xz", plotparticles=plotparticles) plt.subplot(gs[2]).set_xlabel("x"+unitlabel) plt.subplot(gs[2]).set_ylabel("y"+unitlabel) plt.setp(plt.subplot(gs[0]).get_xticklabels(), visible=False) plt.subplot(gs[0]).set_ylabel("z"+unitlabel) plt.subplot(gs[3]).set_xlabel("z"+unitlabel) plt.setp(plt.subplot(gs[3]).get_yticklabels(), visible=False) else: if figsize is None: figsize = (5,5) fig, ax = plt.subplots(1, 1, figsize=figsize) ax.set_xlabel("x"+unitlabel) ax.set_ylabel("y"+unitlabel) OrbitPlotOneSlice(sim, ax, lim=lim, Narc=Narc, color=color, periastron=periastron, trails=trails, show_orbit=show_orbit, lw=lw, plotparticles=plotparticles) return fig
function
python
358
static fromNumber (value) { if (isNaN(value)) { return UINT64_ZERO } if (value < 0) { return UINT64_ZERO } if (value >= UINT64_TWO_PWR_64_DBL) { return UINT64_MAX } if (value < 0) { return UInt64.fromNumber(-value).neg() } return UInt64.fromBits((value % UINT64_TWO_PWR_32_DBL) | 0, (value / UINT64_TWO_PWR_32_DBL) | 0) }
function
javascript
359
def extract_comments_full(self): if not self.full_post_html: logger.error("Unable to get comments without full post HTML") return comments_area_selector = 'div.ufi' elem = self.full_post_html.find(comments_area_selector, first=True) if not elem: logger.error("No comments area found") return comments_selector = 'div[data-sigil="comment"]' if self.options.get("noscript"): comments_selector = "div._55wr" comments = list(elem.find(comments_selector)) if not comments: logger.warning("No comments found on page") return for comment in comments: result = self.extract_comment_with_replies(comment) if result: yield result more_selector = f"div#see_next_{self.post.get('post_id')} a" more = elem.find(more_selector, first=True) if not more: more_selector = f"div#see_prev_{self.post.get('post_id')} a" more = elem.find(more_selector, first=True) limit = 5000 if more and more.attrs.get("data-ajaxify-href"): parsed = parse_qs(urlparse(more.attrs.get("data-ajaxify-href")).query) count = int(parsed.get("count")[0]) if count < limit: limit = count comments_opt = self.options.get('comments') if type(comments_opt) in [int, float] and comments_opt < limit: limit = comments_opt logger.debug(f"Fetching up to {limit} comments") if self.options.get("progress"): pbar = tqdm(total=limit) visited_urls = [] request_url_callback = self.options.get('comment_request_url_callback') more_url = None if more: more_url = ( more.attrs.get("href") + "&m_entstream_source=video_home&player_suborigin=entry_point&player_format=permalink" ) if self.options.get("comment_start_url"): more_url = self.options.get("comment_start_url") while more_url and len(comments) <= limit: if request_url_callback: request_url_callback(utils.urljoin(FB_MOBILE_BASE_URL, more_url)) if more_url in visited_urls: logger.debug("cycle detected, break") break if self.options.get("progress"): pbar.update(30) else: logger.debug(f"Fetching {more_url}") try: response = self.request(more_url) except exceptions.TemporarilyBanned: raise except Exception as e: logger.error(e) break visited_urls.append(more_url) elem = response.html.find(comments_area_selector, first=True) if not elem: logger.warning("No comments found on page") break more_comments = elem.find(comments_selector) if not more_comments: logger.warning("No comments found on page") break for comment in more_comments: result = self.extract_comment_with_replies(comment) if result: yield result more = elem.find(more_selector, first=True) if more: more_url = ( more.attrs.get("href") + "&m_entstream_source=video_home&player_suborigin=entry_point&player_format=permalink" ) else: more_url = None
function
python
360
func Valid(sh SignedHead) error { now := time.Now().UTC().Unix() if now < sh.ValidFrom() { return ErrSignedHeadFuture } if now > sh.ValidTo() { return ErrSignedHeadExpired } return nil }
function
go
361
int arch_uprobe_post_xol(struct arch_uprobe *auprobe, struct pt_regs *regs) { struct uprobe_task *utask = current->utask; struct arch_uprobe_task *autask = &utask->autask; u32 insn = auprobe->ixol; int rc = 0; if (utask->state == UTASK_SSTEP_ACK) { regs->tnpc = relbranch_fixup(insn, utask, regs); regs->tpc = autask->saved_tnpc; rc = retpc_fixup(regs, insn, (unsigned long) utask->vaddr); } else { regs->tnpc = utask->vaddr+4; regs->tpc = autask->saved_tnpc+4; } return rc; }
function
c
362
final class Level extends Column { private final RolapStar.Column starColumn; private final boolean collapsed; private Level( final String name, final RolapSchema.PhysExpr expression, final int bitPosition, RolapStar.Column starColumn, boolean collapsed) { super(name, expression, starColumn.getDatatype(), bitPosition); this.starColumn = starColumn; this.collapsed = collapsed; AggStar.this.levelBitKey.set(bitPosition); } @Override public SqlStatement.Type getInternalType() { return starColumn.getInternalType(); } public boolean isCollapsed() { return collapsed; } }
class
java
363
public class CachingPredicateFactory extends TrivialPredicateFactory { /** Maximum size of all metadata caches (all maps are kept trimmed to this size). */ private static final int METADATA_MAP_MAXSIZE = 1024; /** Maximum size of all ID association caches (all maps are kept trimmed to this size). */ private static final int LONG_MAP_MAXSIZE = 1024*1024; /** LRU cache of the last metadata from the {@link Callables#CALLABLES} table. */ private final Long2ObjectLinkedOpenHashMap<JSONObject> callableGID2callableMetadata; /** LRU cache of the last metadata from the {@link Modules#MODULES} table. */ private final Long2ObjectLinkedOpenHashMap<JSONObject> moduleGID2moduleMetadata; /** LRU cache of the last metadata from the {@link PackageVersions#PACKAGE_VERSIONS} table. */ private final Long2ObjectLinkedOpenHashMap<JSONObject> packageVersionGID2packageVersionMetadata; /** * LRU cache of the map between {@linkplain Callables#CALLABLES GIDs} and * {@linkplain Modules#MODULES module database ids}. */ private final Long2LongLinkedOpenHashMap callableGID2moduleGID; /** * LRU cache of the map between {@linkplain Modules#MODULES module database ids} and * {@linkplains PackageVersions#PACKAGE_VERSIONS revision ids}. */ private final Long2LongLinkedOpenHashMap moduleGID2packageVersionGID; /** A factory for predicates that will be matched against a given database. * * @param dbContext the db context that will be used to match predicates. */ public CachingPredicateFactory(final DSLContext dbContext) { super(dbContext); this.callableGID2callableMetadata = new Long2ObjectLinkedOpenHashMap<>(); this.moduleGID2moduleMetadata = new Long2ObjectLinkedOpenHashMap<>(); this.packageVersionGID2packageVersionMetadata = new Long2ObjectLinkedOpenHashMap<>(); this.callableGID2moduleGID = new Long2LongLinkedOpenHashMap(); callableGID2moduleGID.defaultReturnValue(-1); this.moduleGID2packageVersionGID = new Long2LongLinkedOpenHashMap(); moduleGID2packageVersionGID.defaultReturnValue(-1); } /** Puts a given key/value pair in a map, and guarantees that the pair is in the first * position, ensuring also that the map size does not exceed a given maximum. * * @param map the map to be modified. * @param key the key. * @param value the value associated to the key. * @param maxSize the maximum size. */ private static <T> void putLRUMap(final Long2ObjectLinkedOpenHashMap<T> map, final long key, final T value, final int maxSize) { map.putAndMoveToFirst(key, value); if (map.size() > maxSize) map.removeLast(); } /** Puts a given key/value pair in a map, and guarantees that the pair is in the first * position, ensuring also that the map size does not exceed a given maximum. * * @param map the map to be modified. * @param key the key. * @param value the value associated to the key. * @param maxSize the maximum size. */ private static void putLRUMap(final Long2LongLinkedOpenHashMap map, final long key, final long value, final int maxSize) { map.putAndMoveToFirst(key, value); if (map.size() > maxSize) map.removeLastLong(); } /** Returns the metadata field of a given callable. * * @param callableGID the callable GID. * @return the metadata field associated to it. */ @Override protected JSONObject getCallableMetadata(final long callableGID) { JSONObject jsonMetadata = callableGID2callableMetadata.get(callableGID); if (jsonMetadata == null) { final SelectConditionStep<Record1<JSONB>> rs = dbContext.select(Callables.CALLABLES.METADATA).from(Callables.CALLABLES).where(Callables.CALLABLES.ID.eq(callableGID)); if (rs != null) { final Record1<JSONB> record = rs.fetchOne(); if (record != null) { jsonMetadata = new JSONObject(record.component1().data()); } } putLRUMap(callableGID2callableMetadata, callableGID, jsonMetadata, METADATA_MAP_MAXSIZE); } return jsonMetadata; } /** Returns the metadata field of the package version corresponding to a given callable. * * @param callableGID the callable GID. * @return the metadata field associated to the package version of the callable. */ @Override protected JSONObject getModuleMetadata(final long callableGID) { long moduleGID = callableGID2moduleGID.get(callableGID); JSONObject jsonMetadata = moduleGID >= 0? moduleGID2moduleMetadata.get(moduleGID) : null; if (jsonMetadata == null) { final Record2<JSONB, Long> queryResult = dbContext.select(Modules.MODULES.METADATA, Modules.MODULES.ID) .from(Callables.CALLABLES) .join(Modules.MODULES).on(Callables.CALLABLES.MODULE_ID.eq(Modules.MODULES.ID)) .where(Callables.CALLABLES.ID.eq(callableGID)).fetchOne(); moduleGID = queryResult.component2().longValue(); jsonMetadata = moduleGID >=0? new JSONObject(queryResult.component1().data()) : null; putLRUMap(callableGID2moduleGID, callableGID, moduleGID, LONG_MAP_MAXSIZE); putLRUMap(moduleGID2moduleMetadata, moduleGID, jsonMetadata, METADATA_MAP_MAXSIZE); } return jsonMetadata; } /** Returns the metadata field of the package version corresponding to a given callable. * * @param callableGID the callable id. * @return the metadata field associated to the package version of the callable. */ @Override protected JSONObject getPackageVersionMetadata(final long callableGID) { long moduleGID = callableGID2moduleGID.get(callableGID); long packageVersionGID = callableGID >= 0? moduleGID2packageVersionGID.get(moduleGID) : -1; JSONObject jsonMetadata = packageVersionGID >= 0? packageVersionGID2packageVersionMetadata.get(packageVersionGID) : null; if (jsonMetadata == null ) { final Record3<JSONB, Long, Long> queryResult = dbContext.select(PackageVersions.PACKAGE_VERSIONS.METADATA, PackageVersions.PACKAGE_VERSIONS.ID, Modules.MODULES.ID) .from(Callables.CALLABLES) .join(Modules.MODULES).on(Callables.CALLABLES.MODULE_ID.eq(Modules.MODULES.ID)) .join(PackageVersions.PACKAGE_VERSIONS).on(Modules.MODULES.PACKAGE_VERSION_ID.eq(PackageVersions.PACKAGE_VERSIONS.ID)) .where(Callables.CALLABLES.ID.eq(callableGID)).fetchOne(); packageVersionGID = queryResult.component2().longValue(); moduleGID = queryResult.component3().longValue(); jsonMetadata = packageVersionGID >= 0 && moduleGID >= 0? new JSONObject(queryResult.component1().data()) : null; putLRUMap(callableGID2moduleGID, callableGID, moduleGID, LONG_MAP_MAXSIZE); putLRUMap(moduleGID2packageVersionGID, moduleGID, packageVersionGID, LONG_MAP_MAXSIZE); putLRUMap(packageVersionGID2packageVersionMetadata, packageVersionGID, jsonMetadata, METADATA_MAP_MAXSIZE); } return jsonMetadata; } public static void main(final String[] args) { final var a = new JSONObject("{\"final\": false, \"access\": \"public\", \"superClasses\": [\"/it.unimi.dsi.webgraph/ImmutableGraph\", \"/java.lang/Object\"], \"superInterfaces\": [\"/it.unimi.dsi.lang/FlyweightPrototype\", \"/it.unimi.dsi.webgraph/CompressionFlags\"]}"); System.out.println(a.query("/superInterfaces")); } }
class
java
364
def special_characters(INPUT_FOLDER: Path) -> List[str]: assert INPUT_FOLDER.exists(), f"Path: {INPUT_FOLDER} does not exist" chars: Set[str] = set() for file in INPUT_FOLDER.iterdir(): with file.open("r") as f: text = f.read() chars = chars.union(set(text)) return list(filter(lambda char: True if ord(char) > 127 else False, chars))
function
python
365
async def chaincode_instantiate(self, requestor, channel_name, peers, args, cc_name, cc_version, cc_endorsement_policy=None, transient_map=None, collections_config=None, wait_for_event=False, wait_for_event_timeout=30): target_peers = [] for peer in peers: if isinstance(peer, Peer): target_peers.append(peer) elif isinstance(peer, str): peer = self.get_peer(peer) target_peers.append(peer) else: _logger.error('{} should be a peer name or a Peer instance'. format(peer)) if not target_peers: err_msg = "Failed to query block: no functional peer provided" _logger.error(err_msg) raise Exception(err_msg) tran_prop_req_dep = create_tx_prop_req( prop_type=CC_INSTANTIATE, cc_type=CC_TYPE_GOLANG, cc_name=cc_name, cc_version=cc_version, cc_endorsement_policy=cc_endorsement_policy, fcn='init', args=args, transient_map=transient_map, collections_config=collections_config ) tx_context_dep = create_tx_context( requestor, requestor.cryptoSuite, tran_prop_req_dep ) channel = self.get_channel(channel_name) responses, proposal, header = self.send_instantiate_proposal( tx_context_dep, target_peers, channel_name) res = await asyncio.gather(*responses) if not all([x.response.status == 200 for x in res]): return res[0].response.message tran_req = utils.build_tx_req((res, proposal, header)) tx_context = create_tx_context(requestor, requestor.cryptoSuite, TXProposalRequest()) responses = utils.send_transaction(self.orderers, tran_req, tx_context) async for v in responses: if not v.status == 200: return v.message res = decode_proposal_response_payload(res[0].payload) if wait_for_event: self.evt_tx_id = tx_context_dep.tx_id self.evts = {} event_stream = [] for target_peer in target_peers: channel_event_hub = channel.newChannelEventHub(target_peer, requestor) stream = channel_event_hub.connect() event_stream.append(stream) txid = channel_event_hub.registerTxEvent( self.evt_tx_id, unregister=True, disconnect=True, onEvent=self.txEvent) if txid not in self.evts: self.evts[txid] = {'channel_event_hubs': []} self.evts[txid]['channel_event_hubs'] += [channel_event_hub] try: await asyncio.wait_for(asyncio.gather(*event_stream, return_exceptions=True), timeout=wait_for_event_timeout) except asyncio.TimeoutError: for k, v in self.evts.items(): for channel_event_hub in v['channel_event_hubs']: channel_event_hub.unregisterTxEvent(k) raise TimeoutError('waitForEvent timed out') except Exception as e: raise e else: txEvents = self.evts[self.evt_tx_id]['txEvents'] statuses = [x['tx_status'] for x in txEvents] if not all([x == 'VALID' for x in statuses]): raise Exception(statuses) finally: for x in self.evts[self.evt_tx_id]['channel_event_hubs']: x.disconnect() ccd = ChaincodeData() payload = res['extension']['response']['payload'] ccd.ParseFromString(payload) policy = decode_signature_policy_envelope( ccd.policy.SerializeToString()) instantiation_policy = decode_signature_policy_envelope( ccd.instantiation_policy.SerializeToString()) chaincode = { 'name': ccd.name, 'version': ccd.version, 'escc': ccd.escc, 'vscc': ccd.vscc, 'policy': policy, 'data': { 'hash': ccd.data.hash, 'metadatahash': ccd.data.metadatahash, }, 'id': ccd.id, 'instantiation_policy': instantiation_policy, } return chaincode
function
python
366
def processData(existing_ids): new_data = [] new_ids = [] today = datetime.today() if PROCESS_HISTORY: startTime = MAX_AGE endTime = startTime + timedelta(days=31) while startTime < today: logging.info('Fetching data between {} and {}'.format(startTime, endTime)) new_data, new_ids = appendTimeFrame(existing_ids, startTime, endTime, new_data, new_ids) startTime = endTime endTime = startTime + timedelta(days=31) else: startTime = '' endTime = '' logging.info('Fetching data for last 30 days') new_data, new_ids = appendTimeFrame(existing_ids, startTime, endTime, new_data, new_ids) num_new = len(new_ids) if num_new: logging.info('Adding {} new records'.format(num_new)) cartosql.blockInsertRows(CARTO_TABLE, CARTO_SCHEMA.keys(), CARTO_SCHEMA.values(), new_data) return(num_new)
function
python
367
public static Task<Message> StartNewDialog(BotUser instance, TelegramBotClient client) { instance.Stage = Stage.ReceivingMenuItem; var sendingMenuTask = client.SendMenuAsync(instance); instance.CurrentPurchase = new Purchase { BotUser = instance, Basket = new List<BotUserLongBoard>(5), Guid = Guid.NewGuid() }; instance.Pending = null; return sendingMenuTask; }
function
c#
368
def advance_to_phase(self, phase: Phase): if phase.value >= 1000: logger.error(f'{self.game.game_prefix()}Tried to advance to Phase {phase}, but phase number is too high. ' f'Aborting phase advance') return if self.game.phase.value > phase.value: logger.error(f'{self.game.game_prefix()}Tried to advance to Phase {phase}, but game is already ' f'in phase {self.game.phase}, cannot go back in time. Aborting phase start.') return elif self.game.phase == phase: logger.warn( f'{self.game.game_prefix()}Tried to advance to Phase {phase}, but game is already in that phase.' f'Cannot start phase a second time.') return else: self.game.phase = phase self.cancel_all(phase == Phase.stopping) if self.task_dictionary[phase]: self.task_dictionary[phase].start()
function
python
369
func identicalMethods(a, b []*Method) bool { if len(a) != len(b) { return false } m := make(map[QualifiedName]*Method) for _, x := range a { assert(m[x.QualifiedName] == nil) m[x.QualifiedName] = x } for _, y := range b { if x := m[y.QualifiedName]; x == nil || !IsIdentical(x.Type, y.Type) { return false } } return true }
function
go
370
@Slf4j public class ShiroAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler { private final Set<String> requiredRoles; private final Set<String> requiredPermissions; public ShiroAuthenticationHandler(final String name, final ServicesManager servicesManager, final PrincipalFactory principalFactory, final Set<String> requiredRoles, final Set<String> requiredPermissions) { super(name, servicesManager, principalFactory, null); this.requiredRoles = requiredRoles; this.requiredPermissions = requiredPermissions; } @Override protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential transformedCredential, final String originalPassword) throws GeneralSecurityException { try { val token = new UsernamePasswordToken(transformedCredential.getUsername(), transformedCredential.getPassword()); if (transformedCredential instanceof RememberMeUsernamePasswordCredential) { token.setRememberMe(RememberMeUsernamePasswordCredential.class.cast(transformedCredential).isRememberMe()); } val currentUser = getCurrentExecutingSubject(); currentUser.login(token); checkSubjectRolesAndPermissions(currentUser); return createAuthenticatedSubjectResult(transformedCredential, currentUser); } catch (final UnknownAccountException uae) { throw new AccountNotFoundException(uae.getMessage()); } catch (final LockedAccountException | ExcessiveAttemptsException lae) { throw new AccountLockedException(lae.getMessage()); } catch (final ExpiredCredentialsException eae) { throw new CredentialExpiredException(eae.getMessage()); } catch (final DisabledAccountException eae) { throw new AccountDisabledException(eae.getMessage()); } catch (final AuthenticationException ice) { throw new FailedLoginException(ice.getMessage()); } } /** * Check subject roles and permissions. * * @param currentUser the current user * @throws FailedLoginException the failed login exception in case roles or permissions are absent */ protected void checkSubjectRolesAndPermissions(final Subject currentUser) throws FailedLoginException { if (this.requiredRoles != null) { for (val role : this.requiredRoles) { if (!currentUser.hasRole(role)) { throw new FailedLoginException("Required role " + role + " does not exist"); } } } if (this.requiredPermissions != null) { for (val perm : this.requiredPermissions) { if (!currentUser.isPermitted(perm)) { throw new FailedLoginException("Required permission " + perm + " cannot be located"); } } } } /** * Create authenticated subject result. * * @param credential the credential * @param currentUser the current user * @return the handler result */ protected AuthenticationHandlerExecutionResult createAuthenticatedSubjectResult(final Credential credential, final Subject currentUser) { val username = currentUser.getPrincipal().toString(); return createHandlerResult(credential, this.principalFactory.createPrincipal(username)); } /** * Gets current executing subject. * * @return the current executing subject */ protected Subject getCurrentExecutingSubject() { return SecurityUtils.getSubject(); } /** * Sets shiro configuration to the path of the resource * that points to the {@code shiro.ini} file. * * @param resource the resource */ @SneakyThrows public void loadShiroConfiguration(final Resource resource) { val shiroResource = ResourceUtils.prepareClasspathResourceIfNeeded(resource); if (shiroResource != null && shiroResource.exists()) { val location = shiroResource.getURI().toString(); LOGGER.debug("Loading Shiro configuration from [{}]", location); val factory = new IniSecurityManagerFactory(location); val securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); } else { LOGGER.debug("Shiro configuration is not defined"); } } }
class
java
371
def MeasureCommand(command, iterations, env, track_memory): with open(os.devnull, "wb") as dev_null: RemovePycs() CallAndCaptureOutput(command, env=env) an_s = "s" if iterations == 1: an_s = "" info("Running `%s` %d time%s", command, iterations, an_s) times = [] mem_usage = [] for _ in range(iterations): start_time = GetChildUserTime() subproc = subprocess.Popen(command, stdout=dev_null, stderr=subprocess.PIPE, env=env) if track_memory: future = MemoryUsageFuture(subproc.pid) _, stderr = subproc.communicate() if subproc.returncode != 0: raise RuntimeError("Benchmark died: " + stderr) if track_memory: mem_samples = future.GetMemoryUsage() end_time = GetChildUserTime() elapsed = end_time - start_time assert elapsed != 0 times.append(elapsed) if track_memory: mem_usage.extend(mem_samples) if not track_memory: mem_usage = None return RawData(times, mem_usage, inst_output=stderr)
function
python
372
func genBetaChengBC(aa, bb, a, b float64) float64 { var u1, u2, v, w, y, z float64 alpha := a + b beta := 1.0 / a delta := 1.0 + b - a k1 := delta * (0.0138889 + 0.0416667*a) / (b*beta - 0.777778) k2 := 0.25 + (0.5+0.25/delta)*a setVW := func() { v = beta * math.Log(u1/(1.0-u1)) if v <= 709.78 { w = b * math.Exp(v) if math.IsInf(w, 0) { w = math.MaxFloat64 } } else { w = math.MaxFloat64 } } for { u1, u2 = rand.Float64(), rand.Float64() if u1 < 0.5 { y = u1 * u2 z = u1 * y if 0.25*u2+z-y >= k1 { continue } } else { z = u1 * u1 * u2 if z <= 0.25 { setVW() break } if z >= k2 { continue } } setVW() if alpha*(math.Log(alpha/(a+w))+v)-1.3862944 >= math.Log(z) { break } } if aa == a { return a / (a + w) } return w / (a + w) }
function
go
373
async function startBot(token, player) { if (token) { const robot = new DraughtOTron(new LidraughtsApi(token), player); const username = (await robot.start()).data.username; return `<a href="https://lidraughts.org/@/${username}">${username}</a> on lidraughts.</h1><br/>`; } }
function
javascript
374
def select_from_aqi_table(average_value: float, current_aqi_table: tuple, increment: float) -> list: pair_of_values = [0, 0, 0, 0] i = 0 aqi_values_from_table = us_epa_table.get_table_values_for_aqi_epa() while average_value >= current_aqi_table[i]: i += 1 if i <= 1: pair_of_values[-2] = 0 pair_of_values[0] = 0 else: pair_of_values[-2] = current_aqi_table[i-1] + increment pair_of_values[0] = aqi_values_from_table[i-1] + 1 pair_of_values[-1] = current_aqi_table[i] pair_of_values[1] = aqi_values_from_table[i] aqi_index = (pair_of_values[1] - pair_of_values[0]) * (average_value-pair_of_values[-2]) / (pair_of_values[-1] - pair_of_values[-2]) + pair_of_values[0] return aqi_index
function
python
375
@ApiModel(value = "lookup-value", description = "pair of { field : value}") @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) @EqualsAndHashCode public final class JSONLookupValue { public static JSONLookupValue of(@NonNull final RepoIdAware key, final String caption) { return of(key.getRepoId(), caption); } public static JSONLookupValue of(final int key, final String caption) { final String keyStr = String.valueOf(key); final String description = null; final Map<String, Object> attributes = null; final Boolean active = null; final JSONLookupValueValidationInformation validationInformation = null; return new JSONLookupValue(keyStr, caption, description, attributes, active, validationInformation); } public static JSONLookupValue of( final String key, final String caption) { final String description = null; final Map<String, Object> attributes = null; final Boolean active = null; final JSONLookupValueValidationInformation validationInformation = null; return new JSONLookupValue(key, caption, description, attributes, active, validationInformation); } public static JSONLookupValue of( final String key, final String caption, @Nullable final String description) { final Map<String, Object> attributes = null; final Boolean active = null; return new JSONLookupValue(key, caption, description, attributes, active, null); } public static JSONLookupValue ofLookupValue(@NonNull final LookupValue lookupValue, @NonNull final String adLanguage) { final String id = lookupValue.getIdAsString(); final ITranslatableString displayNameTrl = lookupValue.getDisplayNameTrl(); final ITranslatableString descriptionTrl = lookupValue.getDescriptionTrl(); // final String adLanguage = Env.getAD_Language(Env.getCtx()); final String displayName = displayNameTrl.translate(adLanguage); final String description = descriptionTrl.translate(adLanguage); final JSONLookupValueValidationInformation validationInformation = JSONLookupValueValidationInformation.ofNullable( lookupValue.getValidationInformation(), adLanguage); // NOTE: for bandwidth optimization, we provide the flag only when it's false final Boolean active = !lookupValue.isActive() ? Boolean.FALSE : null; return new JSONLookupValue(id, displayName, description, lookupValue.getAttributes(), active, validationInformation); } public static JSONLookupValue ofNamePair(final NamePair namePair) { final Map<String, Object> attributes = null; final Boolean active = null; final JSONLookupValueValidationInformation validationInformation = null; return new JSONLookupValue(namePair.getID(), namePair.getName(), namePair.getDescription(), attributes, active, validationInformation); } public static IntegerLookupValue integerLookupValueFromJsonMap(@NonNull final Map<String, Object> map) { final Object keyObj = map.get(PROPERTY_Key); if (keyObj == null) { return null; } final String keyStr = keyObj.toString().trim(); if (keyStr.isEmpty()) { return null; } final int keyInt = Integer.parseInt(keyStr); final ITranslatableString displayName = extractCaption(map); final ITranslatableString description = extractDescription(map); final Boolean active = extractActive(map); final IntegerLookupValueBuilder builder = IntegerLookupValue.builder() .id(keyInt) .displayName(displayName) .description(description) .active(active); @SuppressWarnings("unchecked") final Map<String, Object> attributes = (Map<String, Object>)map.get(PROPERTY_Attributes); if (attributes != null && !attributes.isEmpty()) { builder.attributes(attributes); } return builder.build(); } public static StringLookupValue stringLookupValueFromJsonMap(@NonNull final Map<String, Object> map) { final Object keyObj = map.get(PROPERTY_Key); final String key = keyObj != null ? keyObj.toString() : null; final ITranslatableString displayName = extractCaption(map); final ITranslatableString description = extractDescription(map); final Boolean active = extractActive(map); final StringLookupValueBuilder builder = StringLookupValue.builder() .id(key) .displayName(displayName) .description(description) .active(active) .validationInformation(null); // TODO: Extract this from map for future usages @SuppressWarnings("unchecked") final Map<String, Object> attributes = (Map<String, Object>)map.get(PROPERTY_Attributes); if (attributes != null && !attributes.isEmpty()) { builder.attributes(attributes); } return builder.build(); } private static ITranslatableString extractCaption(@NonNull final Map<String, Object> map) { final Object captionObj = map.get(PROPERTY_Caption); final String caption = captionObj != null ? captionObj.toString() : ""; final ITranslatableString displayName = TranslatableStrings.anyLanguage(caption); return displayName; } private static ITranslatableString extractDescription(@NonNull final Map<String, Object> map) { final Object descriptionObj = map.get(PROPERTY_Description); final String descriptionStr = descriptionObj != null ? descriptionObj.toString() : ""; final ITranslatableString description = TranslatableStrings.anyLanguage(descriptionStr); return description; } private static Boolean extractActive(@NonNull final Map<String, Object> map) { return StringUtils.toBoolean(map.get(PROPERTY_Active), null); } public static JSONLookupValue unknown(final int id) { return of(id, "<" + id + ">"); } public static JSONLookupValue unknown(@Nullable final RepoIdAware id) { final int idAsInt = id != null ? id.getRepoId() : -1; return unknown(idAsInt); } // IMPORTANT: when changing this property name, pls also check/change de.metas.handlingunits.attribute.impl.AbstractAttributeValue.extractKey(Map<String, String>, I_M_Attribute) static final String PROPERTY_Key = "key"; @JsonProperty(PROPERTY_Key) @Getter private final String key; @JsonIgnore private transient Integer keyAsInt = null; // lazy private static final String PROPERTY_Caption = "caption"; @JsonProperty(PROPERTY_Caption) @Getter private final String caption; private static final String PROPERTY_Description = "description"; @JsonProperty(PROPERTY_Description) @JsonInclude(JsonInclude.Include.NON_EMPTY) @Getter private final String description; private static final String PROPERTY_Attributes = "attributes"; @JsonProperty(PROPERTY_Attributes) @JsonInclude(JsonInclude.Include.NON_EMPTY) @Getter private final Map<String, Object> attributes; private static final String PROPERTY_Active = "active"; @JsonProperty(PROPERTY_Active) @JsonInclude(JsonInclude.Include.NON_EMPTY) private final Boolean active; private static final String PROPERTY_ValidationInformation = "validationInformation"; @JsonProperty(PROPERTY_ValidationInformation) @JsonInclude(JsonInclude.Include.NON_EMPTY) @Getter private final JSONLookupValueValidationInformation validationInformation; @JsonCreator private JSONLookupValue( @JsonProperty(PROPERTY_Key) @NonNull final String key, @JsonProperty(PROPERTY_Caption) @NonNull final String caption, @JsonProperty(PROPERTY_Description) @Nullable final String description, @JsonProperty(PROPERTY_Attributes) final Map<String, Object> attributes, @JsonProperty(PROPERTY_Active) final Boolean active, @JsonProperty(PROPERTY_ValidationInformation) @Nullable final JSONLookupValueValidationInformation validationInformation) { this.key = key; this.caption = caption; this.description = description; this.attributes = attributes != null && !attributes.isEmpty() ? ImmutableMap.copyOf(attributes) : ImmutableMap.of(); this.active = active; this.validationInformation = validationInformation; } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("key", key) .add("caption", caption) .add("attributes", attributes) .add("active", active) .add("validationInformation", validationInformation) .toString(); } public int getKeyAsInt() { Integer keyAsInt = this.keyAsInt; if (keyAsInt == null) { keyAsInt = this.keyAsInt = Integer.parseInt(getKey()); } return keyAsInt; } public IntegerLookupValue toIntegerLookupValue() { return IntegerLookupValue.builder() .id(getKeyAsInt()) .displayName(TranslatableStrings.constant(getCaption())) .attributes(getAttributes()) .active(isActive()) .build(); } public StringLookupValue toStringLookupValue() { return StringLookupValue.builder() .id(getKey()) .displayName(TranslatableStrings.constant(getCaption())) .attributes(getAttributes()) .active(isActive()) .validationInformation(null) // NOTE: converting back from JSON is not supported nor needed atm .build(); } private boolean isActive() { return active == null || active.booleanValue(); } }
class
java
376
private ICollection<string> addSortedList(ICollection<string> vector, IDictionary<int, ICollection<string>> hash) { var sortedKeys = Util.SortKeysDesc(hash); for (int i = 0; i < sortedKeys.Length; i++) { var itens = hash[sortedKeys[i]].ToArray(); vector.AddRange(itens); } return vector; }
function
c#
377
func (w *WindowedMap) Put(uid UID, value interface{}) { if _, ok := w.uidMap[uid]; ok { w.Remove(uid) } item := &uidItem{uid, w.clock.Now().Add(w.lifetime), -1, value} heap.Push(&w.uidList, item) w.uidMap[uid] = item }
function
go
378
function addValues(frame, values, submit_parent) { var forms = document.getElementsByTagName('FORM')[frame], submit_parent = submit_parent || false, frm_storage = null; for (var key in values) { if (values[key] === null) { continue; } if (typeof forms !== 'undefined') { frm_storage = jQuery(forms).find('#' + key).get(0); } if (typeof frm_storage === 'undefined' || frm_storage === null) { frm_storage = document.getElementById(key); } if (jQuery(frm_storage).is('span')) { jQuery(frm_storage).html(values[key]); } else { jQuery(frm_storage).val(values[key]).change(); } } if (frm_storage !== null && submit_parent) { frm_storage.form.submit(); } }
function
javascript
379
public void ChangeEncoding(Encoding encoding) { logFileReader.ChangeEncoding(encoding); EncodingOptions.Encoding = encoding; if (guiStateArgs.CurrentEncoding.IsSingleByte != encoding.IsSingleByte || guiStateArgs.CurrentEncoding.GetPreamble().Length != encoding.GetPreamble().Length) { Reload(); } else { dataGridView.Refresh(); SendGuiStateUpdate(); } guiStateArgs.CurrentEncoding = logFileReader.CurrentEncoding; }
function
c#
380
private MethodInfo GetMethodInfoIfUsingSoftAssertExpectedAsserts(string className, string testName) { foreach (var assemblyName in AppDomain.CurrentDomain.GetAssemblies()) { try { var loadedAssembly = Assembly.Load(assemblyName.ToString()); var classType = loadedAssembly.GetType(className); if (classType != null) { var methods = GetMethods(classType, testName).ToList(); var hasSoftAssertExpectedAssertsAttribute = methods.Any(m => m.GetCustomAttributes<SoftAssertExpectedAssertsAttribute>(false).Any()); if (!hasSoftAssertExpectedAssertsAttribute) { return null; } else if (methods.Count == 1) { return methods[0]; } else if (methods.Count > 1) { this.TryToLog(MessageType.WARNING, $"There are mutliple methods with the name '{testName}'. This means MAQS will not respect the SoftAssertExpectedAsserts attribute for this test."); return null; } } } catch { } } throw new InvalidOperationException($"Unable to find assembly which contains the test named'{testName}' in the class '{className}'"); }
function
c#
381
public class SwapDemo { public static void main(String[] args) throws IOException { if (args.length != 4) { System.out.println("Usage:\njava ReplaceDemo <orig image> <swap image> <num columns to replace> <num rows to replace>"); return; } Picture origImg = new Picture( args[0]); String swapFilename = args[1]; int removeColumns = Integer.parseInt(args[2]); int removeRows = Integer.parseInt(args[3]); // Resize swap to be same size as original BufferedImage swapOrigImage = ImageIO.read( new File(swapFilename) ); swapOrigImage = ImageTest.resizeImageWithHint(origImg.width(), origImg.height(), swapOrigImage, BufferedImage.TYPE_INT_ARGB); Picture swapImg = new Picture(swapOrigImage); System.out.printf("image is %d columns by %d rows\n", origImg.width(), origImg.height()); //--------------------------------------------------------------------// // Seam Carving //--------------------------------------------------------------------// Picture seamPicture = processRecursive( origImg, swapImg, removeColumns, removeRows ); // Determine roughly the number of pixels that will be modified System.out.printf("new image size is %d columns by %d rows\n", seamPicture.width(), seamPicture.height()); String filename = args[0]; if( filename.endsWith(".png") ) filename = filename.replace(".png","_seam.png"); else filename = filename.replace(".jpg","_seam.png"); // NB: Save as PNG seamPicture.save( filename ); int seamPixels = (removeColumns*seamPicture.width()) + (removeRows*seamPicture.height()) - ( removeColumns + removeRows ); System.out.printf("Seam Random pixels %d\n", seamPixels ); //inputImg.show(); //seamPicture.show(); //--------------------------------------------------------------------// // Compare to random //--------------------------------------------------------------------// //int numPixels = (int)( 0.10 * inputImg.height() * inputImg.width() ); //int numPixels = seamPixels; //System.out.printf("Orig Random pixels %d\n", numPixels ); //Picture randPicture = origImg.replaceRandom( numPixels ); //filename = args[0]; //if( filename.endsWith(".png") ) filename = filename.replace(".png","_rand.png"); //else filename = filename.replace(".jpg","_rand.png"); // NB: PNG //randPicture.save( filename ); } public static Picture process( Picture origImg, Picture swapImg, int removeCols, int removeRows ) { SeamDoppelganger sc = new SeamDoppelganger(origImg); TreeMap<Integer,int[]> hseams = sc.findSmallestHorizontalSeams(); int hcount = 0; while( hcount < removeRows && !hseams.isEmpty() ) { int[] horizontalSeam = hseams.remove( hseams.firstKey() ); sc.swapHorizontalSeamRandom(horizontalSeam, swapImg); hcount++; } TreeMap<Integer,int[]> vseams = sc.findSmallestVerticalSeams(); int vcount = 0 ; while( vcount < removeCols && !vseams.isEmpty() ) { int[] verticalSeam = sc.findSmallestVerticalSeam(); sc.swapVerticalSeamRandom(verticalSeam, swapImg); vcount++; } return sc.picture(); } public static Picture processRecursive( Picture origImg, Picture swapImg, int removeCols, int removeRows ) { SeamDoppelganger sc = new SeamDoppelganger(origImg); for (int i = 0; i < removeRows; i++) { int[] horizontalSeam = sc.findSmallestHorizontalSeam(); sc.swapHorizontalSeamRandom(horizontalSeam, swapImg); } for (int i = 0; i < removeCols; i++) { int[] verticalSeam = sc.findSmallestVerticalSeam(); sc.swapVerticalSeamRandom(verticalSeam, swapImg); } return sc.picture(); } }
class
java
382
function resolveProviderChain(chain) { for (const item of chain) { if (stringUtils.isNonBlankString(item) && item !== 'undefined') { return item; } } return null; }
function
javascript
383
private static String[] splitString(String expr, String sep) { List<String> splitList = new ArrayList<>(); int sepIndex = -1; int exprLength = expr.length(); while (sepIndex < exprLength) { int nextIndex = getNextExpressionLastIndex(expr, sepIndex, sep) + 1; String argumentName = expr.substring(sepIndex + 1, nextIndex).trim(); splitList.add(argumentName); sepIndex = nextIndex; } return splitList.toArray(new String[0]); }
function
java
384
function deletePreviousPRComments(github, gitInfo) { return github.issues.getComments({ owner: gitInfo.repoOwner, repo: gitInfo.repoName, number: gitInfo.prNum, }) .then((issueCommentsData) => { const issueComments = issueCommentsData || []; const botIssues = issueComments.filter((issueComment) => { return (issueComment.user.login === 'WebFundBot'); }); return Promise.all( botIssues.map((botIssue) => { return github.issues.deleteComment({ id: botIssue.id, owner: gitInfo.repoOwner, repo: gitInfo.repoName, }); }) ); }) .then(() => console.log(chalk.green('✓'), 'Deleted previous bot comments')) .catch((err) => { console.log(chalk.red('✖'), 'Failed to delete previous bot comments'); console.error(err); }); }
function
javascript
385
public static Pair<Integer, Integer> normalizeAlleles(final List<byte[]> sequences, final List<IndexRange> bounds, final int maxShift, final boolean trim) { Utils.nonEmpty(sequences); Utils.validateArg(sequences.size() == bounds.size(), "Must have one initial allele range per sequence"); bounds.forEach(bound -> Utils.validateArg(maxShift <= bound.getStart(), "maxShift goes past the start of a sequence")); int startShift = 0; int endShift = 0; int minSize = bounds.stream().mapToInt(IndexRange::size).min().getAsInt(); while (trim && minSize > 0 && lastBaseOnRightIsSame(sequences, bounds)) { bounds.forEach(bound -> bound.shiftEndLeft(1)); minSize--; endShift++; } while (trim && minSize > 0 && firstBaseOnLeftIsSame(sequences, bounds)) { bounds.forEach(bound -> bound.shiftStart(1)); minSize--; startShift--; } while( startShift < maxShift && nextBaseOnLeftIsSame(sequences, bounds) && lastBaseOnRightIsSame(sequences, bounds)) { bounds.forEach(b -> b.shiftLeft(1)); startShift++; endShift++; } return ImmutablePair.of(startShift, endShift); }
function
java
386
def create_example_asset_administration_shell(concept_dictionary: model.ConceptDictionary) -> \ model.AssetAdministrationShell: view = model.View( id_short='ExampleView', contained_element={model.AASReference((model.Key(type_=model.KeyElements.SUBMODEL, local=False, value='https://acplt.org/Test_Submodel_Missing', id_type=model.KeyType.IRI),), model.Submodel)}) view_2 = model.View( id_short='ExampleView2') asset_administration_shell = model.AssetAdministrationShell( asset=model.AASReference((model.Key(type_=model.KeyElements.ASSET, local=False, value='https://acplt.org/Test_Asset_Missing', id_type=model.KeyType.IRI),), model.Asset), identification=model.Identifier(id_='https://acplt.org/Test_AssetAdministrationShell_Missing', id_type=model.IdentifierType.IRI), id_short='TestAssetAdministrationShell', category=None, description={'en-us': 'An Example Asset Administration Shell for the test application', 'de': 'Ein Beispiel-Verwaltungsschale für eine Test-Anwendung'}, parent=None, administration=model.AdministrativeInformation(version='0.9', revision='0'), security=None, submodel={model.AASReference((model.Key(type_=model.KeyElements.SUBMODEL, local=True, value='https://acplt.org/Test_Submodel_Missing', id_type=model.KeyType.IRI),), model.Submodel)}, concept_dictionary=[concept_dictionary], view=[view, view_2], derived_from=None) return asset_administration_shell
function
python
387
[Imported] [IgnoreNamespace] public abstract class Subscribable<T> : IDisposable { internal Subscribable() { } public void Dispose() { } public Subscribable<T> Extend(JsDictionary options) { return null; } public int GetSubscriptionsCount() { return 0; } public void NotifySubscribers(T value) { } for the Specified Event public void NotifySubscribers(T value, string eventName) { } public IDisposable Subscribe(Action<T> changeCallback) { return null; } public IDisposable Subscribe(Action<T> changeCallback, object callBackTarget) { return null; } public IDisposable Subscribe(Action<T> changeCallback, object callBackTarget, string eventName) { return null; } }
class
c#
388
void do_child(Session *s, const char *command) { extern char **environ; char **env; char *argv[10]; const char *shell, *shell0, *hostname = NULL; struct passwd *pw = s->pw; u_int i; destroy_sensitive_data(); if (options.use_login && command != NULL) options.use_login = 0; if (!options.use_login) { #ifdef HAVE_OSF_SIA session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty); if (!check_quietlogin(s, command)) do_motd(); #else do_nologin(pw); do_setusercontext(pw); #endif } shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell; #ifdef HAVE_LOGIN_CAP shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell); #endif env = do_setup_env(s, shell); if (options.use_login) hostname = get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping); if (packet_get_connection_in() == packet_get_connection_out()) close(packet_get_connection_in()); else { close(packet_get_connection_in()); close(packet_get_connection_out()); } channel_close_all(); endpwent(); for (i = 3; i < 64; i++) close(i); environ = env; #ifdef AFS if (k_hasafs()) { char cell[64]; if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0) krb_afslog(cell, 0); krb_afslog(0, 0); } #endif if (chdir(pw->pw_dir) < 0) { fprintf(stderr, "Could not chdir to home directory %s: %s\n", pw->pw_dir, strerror(errno)); #ifdef HAVE_LOGIN_CAP if (login_getcapbool(lc, "requirehome", 0)) exit(1); #endif } if (!options.use_login) do_rc_files(s, shell); signal(SIGPIPE, SIG_DFL); if (options.use_login) { launch_login(pw, hostname); } if ((shell0 = strrchr(shell, '/')) != NULL) shell0++; else shell0 = shell; if (!command) { char argv0[256]; argv0[0] = '-'; if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1) >= sizeof(argv0) - 1) { errno = EINVAL; perror(shell); exit(1); } argv[0] = argv0; argv[1] = NULL; execve(shell, argv, env); perror(shell); exit(1); } argv[0] = (char *) shell0; argv[1] = "-c"; argv[2] = (char *) command; argv[3] = NULL; execve(shell, argv, env); perror(shell); exit(1); }
function
c
389
public class AwsSignedBodyValue { public static final String EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; public static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; public static final String STREAMING_AWS4_HMAC_SHA256_PAYLOAD = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"; public static final String STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD = "STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD"; public static final String STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD_TRAILER = "STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD-TRAILER"; public static final String STREAMING_AWS4_HMAC_SHA256_EVENTS = "STREAMING-AWS4-HMAC-SHA256-EVENTS"; }
class
java
390
private boolean verifyDate(String number) { String dateString = number.substring(3, 11); DateFormat dateFormat = new SimpleDateFormat(GlobalConstants.DATE_FORMAT_STRING); try { Date date = dateFormat.parse(dateString); return date.compareTo(dateFormat.parse("20140101")) != -1; } catch (ParseException e) { return false; } }
function
java
391
public static Criterion buildInCriterion(String propertyName, List<?> values, int inStatementSizeLimit) { Criterion criterion = null; int listSize = values.size(); for (int i = 0; i < listSize; i += inStatementSizeLimit) { List<?> subList; if (listSize > i + inStatementSizeLimit) { subList = values.subList(i, (i + inStatementSizeLimit)); } else { subList = values.subList(i, listSize); } if (criterion != null) { criterion = Restrictions.or(criterion, Restrictions.in(propertyName, subList)); } else { criterion = Restrictions.in(propertyName, subList); } } return criterion; }
function
java
392
public static void extractTextUsingExtractorFactory() { try { String fileName = Common.mapSourceFilePath(DOC_FILE_PATH); ExtractorFactory factory = new ExtractorFactory(); try (TextExtractor extractor = factory.createTextExtractor(fileName)) { System.out.println(extractor != null ? extractor.extractAll() : "The document format is not supported"); } } catch (Exception exp) { System.out.println("Exception: " + exp.getMessage()); exp.printStackTrace(); } }
function
java
393
public Result initAndGet( Key key, Input input, BiFunction<Input, Result/*OldResult*/, Result> resourceFunction, Predicate<Result> cacheResourcePredicate, Predicate<Result> resourceExpiredPredicate ) { if (key == null || resourceFunction == null || cacheResourcePredicate == null) { throw new NullPointerException(); } SingleResourceInitializer<Input, Result> singleResourceIniter = resultMap.get(key); if (singleResourceIniter == null) { singleResourceIniter = new SingleResourceInitializer<>(); SingleResourceInitializer<Input, Result> oldValue = resultMap.putIfAbsent(key, singleResourceIniter); log.info("singleResourceIniter null, key={}, oldValueIsNull={}", key, (oldValue == null)); if (oldValue != null) { singleResourceIniter = oldValue; } } Result result = singleResourceIniter.initAndGet(input, resourceFunction, cacheResourcePredicate, resourceExpiredPredicate); if (!singleResourceIniter.isResourceCleaned()) { return result; } else { resultMap.remove(key, singleResourceIniter); return null; } }
function
java
394
private static class CreateSubscriptionAction extends PubSubAction<SubscriptionInfo> { @Override public void run(PubSub pubsub, SubscriptionInfo subscription) { pubsub.create(subscription); System.out.printf("Created subscription %s%n", subscription.name()); } @Override SubscriptionInfo parse(String... args) throws Exception { String message; if (args.length > 3) { message = "Too many arguments."; } else if (args.length < 2) { message = "Missing required topic or subscription name"; } else { SubscriptionInfo.Builder builder = SubscriptionInfo.builder(args[0], args[1]); if (args.length == 3) { builder.pushConfig(PushConfig.of(args[2])); } return builder.build(); } throw new IllegalArgumentException(message); } @Override public String params() { return "<topic> <subscription> <endpoint>?"; } }
class
java
395
def applyAugmentation(images): rotate_bounds = (0, 10) crop_bounds = (0, 0.15) tuple = (0.15, 6.0) scalex_bound = (1.0, 1.3) scaley_bound = (1.0, 1.3) sigma = (np.random.uniform(0.2, 2.5), np.random.uniform(0.2, 2.5)) gamma = (0.75, 1.1) scale_noise = (10, 30) hue_range = (-30, 50) output = images dice = np.random.randint(0, 10) / 10.0 if dice < 0: output = horizontal_flip(output) dice = np.random.randint(0, 10) / 10.0 if dice < 10: output = vertical_flip(output) ''' # crop dice = np.random.randint(0, 10) / 10.0 if dice < 0.3: output = crop(output, crop_bounds) dice = np.random.randint(0, 10) / 10.0 if dice > 0.9: output = scale(output, scalex_bound, scaley_bound) dice = np.random.randint(0, 10) / 10.0 if dice <=0.4: output = gaussian_blur(output, sigma) dice = np.random.randint(0, 10) / 10.0 if dice >0.5: output = contrast(output, gamma) ''' and saturation dice = np.random.randint(0, 10) / 10.0 if dice > 0.5: output = hue_and_saturation(output, hue_range) ''' dice = np.random.randint(0, 10) / 10.0 if dice > 0.7: output = gaussian_noise(output, scale_noise) ''' return convert_back_to_uint(output)
function
python
396
def visualize(self) -> None: nodes_links_str = "" if self.vis_type == "Tree" or self.vis_type == "BinaryTree" or self.vis_type == "AVLTree" or\ self.vis_type == "SinglyLinkedList" or self.vis_type == "DoublyLinkedList" or \ self.vis_type == "MultiList" or self.vis_type == "CircularSinglyLinkedList" or \ self.vis_type == "CircularDoublyLinkedList" or self.vis_type == "Array" or \ self.vis_type == "GraphAdjacencyList" or self.vis_type == "ColorGrid" or self.vis_type == "GraphAdjacencyMatrix" or \ self.vis_type == "largegraph" or self.vis_type == "KdTree" or self.vis_type == "SymbolCollection" or \ self.vis_type == "GameGrid" or self.vis_type == "BinarySearchTree" or self.vis_type == "LineChart" or \ self.vis_type == "Audio" or self.vis_type == "SymbolCollectionV2": nodes_links_str = self.ds_handle.get_data_structure_representation() ds = { "visual": self.vis_type, "title": self._title, "description": self._description, "coord_system_type": self._coord_system_type, "map_overlay": self._map_overlay, } if self.window is not None and len(self.window) == 4: ds['window'] = self.window ds.update(nodes_links_str) ds_json = json.dumps(ds) if self._json_flag: print(ds_json) response = self.connector.post("/assignments/" + self.get_assignment(), ds_json) if response == 200 and self._post_url_flag: print("\nCheck Your Visualization at the following link:\n\n" + self.connector.get_server_url() + "/assignments/" + str(self._assignment) + "/" + self._username + "\n\n") self._assignment_part = self._assignment_part + 1
function
python
397
public static List<T> ReadFixedLayoutClassList<T>(this BinaryReader br) { var count = br.ReadInt32(); var r = new List<T>(); for (var i = 0; i < count; ++i) r.Add(ReadFixedLayoutClass<T>(br)); return r; }
function
c#
398
public static <T> List<T> decode(final Object typeDescriptor, final List<ByteBuffer> encodedObjects, int start, int count, int threadCount, ExecutorService executor) throws GPUdbException { if (threadCount == 1 || count <= 1) { return decode(typeDescriptor, encodedObjects, start, count); } if (threadCount < 1) { throw new IllegalArgumentException("Thread count must be greater than zero."); } ArrayList<T> objects = new ArrayList<>(count); int partitionSize = count / threadCount; int partitionExtras = count % threadCount; ExecutorService executorService = executor != null ? executor : defaultThreadPool; List<Future<List<T>>> futures = new ArrayList<>(threadCount); for (int i = 0; i < threadCount; i++) { final int partitionStart = i * partitionSize + Math.min(i, partitionExtras); final int partitionEnd = (i + 1) * partitionSize + Math.min(i + 1, partitionExtras); if (partitionStart == partitionEnd) { break; } futures.add(executorService.submit(new Callable<List<T>>() { @Override public List<T> call() throws GPUdbException { return decode(typeDescriptor, encodedObjects, partitionStart, partitionEnd - partitionStart); } })); } for (Future<List<T>> future : futures) { try { objects.addAll(future.get()); } catch (ExecutionException ex) { if (ex.getCause() instanceof GPUdbException) { throw (GPUdbException)ex.getCause(); } else if (ex.getCause() instanceof RuntimeException) { throw (RuntimeException)ex.getCause(); } else { throw new GPUdbException(ex.getMessage(), ex); } } catch (InterruptedException ex) { throw new GPUdbException(ex.getMessage(), ex); } } return objects; }
function
java
399