language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public Parser<RECORD> addParseTarget(final String setterMethodName, final SetterPolicy setterPolicy, final String fieldValue) throws NoSuchMethodException { Method method; try { method = recordClass.getMethod(setterMethodName, St...
java
private IQTree projectAwayUnnecessaryVariables(IQTree child, IQProperties currentIQProperties) { if (child.getRootNode() instanceof ConstructionNode) { ConstructionNode constructionNode = (ConstructionNode) child.getRootNode(); AscendingSubstitutionNormalization normalization = normaliz...
python
def download_file_powershell(url, target, headers={}): """ Download the file at url to target using Powershell (which will validate trust). Raise an exception if the command cannot complete. """ target = os.path.abspath(target) powershell_cmd = "$request = (new-object System.Net.WebClient);" ...
python
def dataframe_from_excel(path, sheetname=0, header=0, skiprows=None): # , parse_dates=False): """Thin wrapper for pandas.io.excel.read_excel() that accepts a file path and sheet index/name Arguments: path (str): file or folder to retrieve CSV files and `pandas.DataFrame`s from ext (str): file name...
java
public static boolean isFragment(Bundle bundle) { Dictionary<String, String> headers = bundle.getHeaders(); return headers.get(Constants.FRAGMENT_HOST) != null; }
java
@Override public <B> MaybeT<M, A> discardR(Applicative<B, MonadT<M, Maybe<?>, ?>> appB) { return MonadT.super.discardR(appB).coerce(); }
python
def get_day_of_week_description(self): """Generates a description for only the DAYOFWEEK portion of the expression Returns: The DAYOFWEEK description """ if self._expression_parts[5] == "*" and self._expression_parts[3] != "*": # DOM is specified and DOW is * s...
java
protected ActionExecute createActionExecute(ActionMapping actionMapping, Method executeMethod) { final Execute anno = getExecuteAnnotation(executeMethod); // exists, already checked final ExecuteOption executeOption = createExecuteOption(anno); return newActionExecute(actionMapping, executeMetho...
python
def fixcode(**kwargs): """ auto pep8 format all python file in ``source code`` and ``tests`` dir. """ # repository direcotry repo_dir = Path(__file__).parent.absolute() # source code directory source_dir = Path(repo_dir, package.__name__) if source_dir.exists(): print("Source c...
java
public PagedList<KeyItem> getKeysNext(final String nextPageLink) { ServiceResponse<Page<KeyItem>> response = getKeysNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<KeyItem>(response.body()) { @Override public Page<KeyItem> nextPage(String nextPageLin...
java
private void putDataPoint(int i, Entry<Long, Double> datapoint) { timestamps[i] = datapoint.getKey(); values[i] = datapoint.getValue(); }
python
def natural_sort(list, key=lambda s:s): """ Sort the list into natural alphanumeric order. """ def get_alphanum_key_func(key): convert = lambda text: int(text) if text.isdigit() else text return lambda s: [convert(c) for c in re.split('([0-9]+)', key(s))] sort_key = get_alphanum_key_...
python
def _create_epoch_data(self, streams: Optional[Iterable[str]]=None) -> EpochData: """Create empty epoch data double dict.""" if streams is None: streams = [self._train_stream_name] + self._extra_streams return OrderedDict([(stream_name, OrderedDict()) for stream_name in streams])
python
def delete(self, space_id): """ Deletes a space by ID. """ try: self.space_id = space_id return super(SpacesProxy, self).delete(space_id) finally: self.space_id = None
java
public static TerminalOp<Integer, Boolean> makeInt(IntPredicate predicate, MatchKind matchKind) { Objects.requireNonNull(predicate); Objects.requireNonNull(matchKind); class MatchSink extends BooleanTerminalSink<Integer> implements Sink.OfIn...
java
public List<Integer> findIntValues(JvmAnnotationTarget op, Class<? extends Annotation> annotationType) { final JvmAnnotationReference reference = this.lookup.findAnnotation(op, annotationType); if (reference != null) { return findIntValues(reference); } return null; }
java
public Jdbi build(Environment environment, PooledDataSourceFactory configuration, String name) { final ManagedDataSource dataSource = configuration.build(environment.metrics(), name); return build(environment, configuration, dataSource, name); }
python
def default_output_name(self, input_file): """ Derive a default output name from the ELF name. """ irom_segment = self.get_irom_segment() if irom_segment is not None: irom_offs = irom_segment.addr - ESP8266ROM.IROM_MAP_START else: irom_offs = 0 return "%s-...
java
private boolean willAttributeModifyModel(String attributeName, Object newValue) { Object currentValue = get(attributeName); return currentValue != null ? !currentValue.equals(newValue) : newValue != null; }
java
public ClientNetworkConfig addOutboundPortDefinition(String portDef) { if (outboundPortDefinitions == null) { outboundPortDefinitions = new HashSet<String>(); } outboundPortDefinitions.add(portDef); return this; }
java
public static ILigand[] order(ILigand[] ligands) { ILigand[] newLigands = new ILigand[ligands.length]; System.arraycopy(ligands, 0, newLigands, 0, ligands.length); Arrays.sort(newLigands, cipRule); return newLigands; }
python
def create(self, ignore=None): """Yield tuple with created index name and responses from a client.""" ignore = ignore or [] def _create(tree_or_filename, alias=None): """Create indices and aliases by walking DFS.""" # Iterate over aliases: for name, value in ...
python
def resolve(self): """Determine the final input value.""" if self.source: result = self.source[1][self.source[0]] if result: return result return self.default
java
public void jumpahead(int count) { if (count < 0) { throw new IllegalArgumentException(); } if (buf != null) { bufPos += count; if (bufPos > buf.length) { throw new IllegalArgumentException(); } if (bufPos == buf.length)...
python
def as_int(width, height): "Return an integer ratio tuple like (16, 9)." gcd = get_gcd(width, height) return int(width / gcd), int(height / gcd)
python
def forget_fact(term): """ Forgets a fact by removing it from the database """ logger.info('Removing fact %s', term) db.facts.remove({'term': term_regex(term)}) return random.choice(ACKS)
java
@Override public CallableStatement prepareCall(String sql) throws SQLException { return ProxyFactory.getProxyCallableStatement(this, trackStatement(delegate.prepareCall(sql))); }
java
public Observable<ServiceResponse<FoundFaces>> findFacesWithServiceResponseAsync(FindFacesOptionalParameter findFacesOptionalParameter) { if (this.client.baseUrl() == null) { throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot be null."); } fina...
java
private void getControllingProcessDirectory(long timestamp, String pid) { int count = 0; while (ivSubDirectory == null) { ivSubDirectory = makeLogDirectory(timestamp, pid); if (ivSubDirectory == null) { if (++count > FAILED_MAX_COUNT) { ivSubDirectory = makeLogDirectory(timestamp, pid,true); if(...
java
@Override public double validate(IMolecularFormula formula) throws CDKException { logger.info("Start validation of ", formula); double totalExactMass = MolecularFormulaManipulator.getTotalExactMass(formula); if (Math.abs(totalExactMass - mass) > tolerance) return 0.0; e...
python
def get_instance(self, payload): """ Build an instance of EventInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.event.EventInstance :rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance """ retur...
python
def _retry(self, state): ''' Starts a single try of the whole restart path. ''' state.attempt += 1 self.debug('Starting restart attempt: %d.', state.attempt) if self._cmp_strategy(RestartStrategy.buryme): self.debug('Agent %r is going to by buried according to...
python
def find_parent_id_for_component(self, component_id): """ Given the URL to a component, returns the parent component's URL. :param string component_id: The URL of the component. :return: A tuple containing: * The type of the parent record; valid values are ArchivesSpaceClien...
java
public static Type getOuter(final Type type) { if (type instanceof ParameterizedType) { // could contain outer generics return ((ParameterizedType) type).getOwnerType(); } return isInner(type) ? GenericsUtils.resolveClassIgnoringVariables(type).getEnclosin...
java
private void handleSerialApiGetInitDataResponse( SerialMessage incomingMessage) { logger.debug(String.format("Got MessageSerialApiGetInitData response.")); this.isConnected = true; int nodeBytes = incomingMessage.getMessagePayloadByte(2); if (nodeBytes != NODE_BYTES) { logger.error("Invalid number of n...
java
static void checkNotNull(Object o, String arg) { if (o == null) { throw new IllegalArgumentException(String.format("'%s' must not be null.", arg)); } }
python
def _parse_accounts(config): """ read accounts information from config :param config: valit alot config :type config: `configobj.ConfigObj` :returns: list of accounts """ accounts = [] if 'accounts' in config: for acc in config['accounts'].sec...
python
def uuid4(self): """Make an id in the format of UUID4, but keep in mind this could very well be pseudorandom, and if it is you'll not be truely random, and can regenerate same id if same seed""" return ''.join([hexchars[self.randint(0,15)] for x in range(0,8)]) + '-' +\ ''.join([hexchars[self.randint...
java
private void ensureLookahead(int lookahead) { for (int i = savedTokens.size() ; i < lookahead ; i ++) { savedTokens.add(tokenizer.readToken()); } }
java
public ChangesHolder getChanges(final Set<String> removedNodes, final Set<String> addedNodes) { if (handler != null) { Iterator<NodeData> addedStates = new Iterator<NodeData>() { private final Iterator<String> iter = addedNodes.iterator(); public boolean...
java
public static void validateNotEmptyAndNotEqual(Object t1, Object t2, String errorMsg) throws ValidateException { validateNotEmpty(t1, errorMsg); validateNotEqual(t1, t2, errorMsg); }
python
def update(self): ''' Update the income process, the assets grid, the permanent income grid, the medical shock distribution, and the terminal solution. Parameters ---------- none Returns ------- none ''' self.updateIncomeProcess()...
python
def as_dict(self): """json friendly dict representation of Kpoints""" d = {"comment": self.comment, "nkpoints": self.num_kpts, "generation_style": self.style.name, "kpoints": self.kpts, "usershift": self.kpts_shift, "kpts_weights": self.kpts_weights, "coord_type": ...
java
protected boolean isRestoreGoalPresent() { Plugin ekstaziPlugin = lookupPlugin(EKSTAZI_PLUGIN_KEY); if (ekstaziPlugin == null) { return false; } for (Object execution : ekstaziPlugin.getExecutions()) { for (Object goal : ((PluginExecution) execution).getGoals()) {...
python
def toTFExample(dtypes): """mapPartition function to convert a Spark RDD of Row into an RDD of serialized tf.train.Example bytestring. Note that tf.train.Example is a fairly flat structure with limited datatypes, e.g. tf.train.FloatList, tf.train.Int64List, and tf.train.BytesList, so most DataFrame types will be...
python
def equal(actual, expected): ''' Compare actual and expected using == >>> expect = Expector([]) >>> expect(1).to_not(equal, 2) (True, 'equal: expect 1 == 2') >>> expect(1).to(equal, 1) (True, 'equal: expect 1 == 1') ''' is_passing = (actual == expected) types_to_diff = (str, d...
java
public static void ensureMouseOver(Element element) { NativeEvent nativeEvent = Document.get().createMouseOverEvent( 0, 0, 0, 0, 0, false, false, false, false, 0, null); e...
java
public void saveModification(MaterialInstance materialInstance, Modification modification) { modification.setMaterialInstance(materialInstance); try { getHibernateTemplate().saveOrUpdate(modification); removeLatestCachedModification(materialInstance, modification); re...
java
@Override public final void fill(final Map<String, Object> pAddParam, final Object pEntity, final String pFieldName, final String pFieldStrValue) throws Exception { if (SeSeller.class != pEntity.getClass()) { throw new ExceptionWithCode(ExceptionWithCode .CONFIGURATION_MISTAKE, "It's wrong...
java
private void centerOnCurrentItem() { if(!mPieData.isEmpty()) { PieModel current = mPieData.get(getCurrentItem()); int targetAngle; if(mOpenClockwise) { targetAngle = (mIndicatorAngle - current.getStartAngle()) - ((current.getEndAngle() - current.getStartAngle...
java
protected void moskitoDoPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { super.doPost(req, res); }
python
def get_keystone_session(self, keystone_ip, username, password, api_version=False, admin_port=False, user_domain_name=None, domain_name=None, project_domain_name=None, project_name=None): """Return a keystone session object""...
java
public <I, V> void add(Option<I, V> option, V value) { getOrCreateValueContainer( option ).add( option.getOptionIdentifier(), value ); }
python
def is_installed(prog): """Return whether or not a given executable is installed on the machine.""" with open(os.devnull, 'w') as devnull: try: if os.name == 'nt': retcode = subprocess.call(['where', prog], stdout=devnull) else: retcode = subproces...
java
protected <E extends Event> void linkWave(final Node node, final javafx.event.EventType<E> eventType, final WaveType waveType, final WaveData<?>... waveData) { linkWave(node, eventType, waveType, null, waveData); }
java
public Bits readAhead(final int bytes) throws IOException { assert (0 < bytes); if (0 < bytes) { final byte[] buffer = new byte[bytes]; int bytesRead = this.inner.read(buffer); if (bytesRead > 0) { this.remainder = this.remainder.concatenate(new Bits(Arrays.copyOf(buffer, bytesRead)));...
python
def write_values(self, data, filepath=None, filename=None, indent=None, keys_to_write=None): """ Tries to write extra content to a JSON file. Creates filename.temp with updated content, removes the old file and finally renames the .temp to match the old file. This is in effort t...
python
def create(backbone: ModelFactory, input_block: typing.Optional[ModelFactory]=None, initial_std_dev=0.4, factorized_noise=True): """ Vel factory function """ if input_block is None: input_block = IdentityFactory() return NoisyQModelFactory( input_block=input_block, backbone=backb...
python
def _did_save(self, connection): """ Launched when save has been successfully executed """ self._new_password = None controller = NURESTSession.get_current_session().login_controller controller.password = None controller.api_key = self.api_key if connection.async: ...
python
def dump(args): """ %prog dump fastafile Convert FASTA sequences to list of K-mers. """ p = OptionParser(dump.__doc__) p.add_option("-K", default=23, type="int", help="K-mer size [default: %default]") p.set_outfile() opts, args = p.parse_args(args) if len(args) != ...
java
public void setTopContributors(java.util.Collection<Contributor> topContributors) { if (topContributors == null) { this.topContributors = null; return; } this.topContributors = new java.util.ArrayList<Contributor>(topContributors); }
java
public List<UUID> spawn(int nbAgents, Class<? extends Agent> agent, Object... params) { return this.spawnService.spawn(nbAgents, null, this.janusContext, null, agent, params); }
python
def bottom(self, features): """Transforms features to feed into body. Args: features: dict of str to Tensor. Typically it is the preprocessed data batch after Problem's preprocess_example(). Returns: transformed_features: dict of same key-value pairs as features. The value Tens...
java
@AroundInvoke public Object notSupported(final InvocationContext context) throws Exception { return runUnderUOWNoEnablement(UOWSynchronizationRegistry.UOW_TYPE_LOCAL_TRANSACTION, true, context, "NOT_SUPPORTED"); }
python
def metalayerize(user_func): """Wrap a function over a sequence of layers and an input into a layer.""" def returned(layers, *args, **kwargs): def begin_update(X, *args, **kwargs): return user_func(layers, X, *args, **kwargs) return FunctionLayer(begin_update, *args, **kwargs) ...
java
public void savePlayerInfo(GamePlayerInfo playerInfo, final SaveInfoHandler handler){ HMSAgentLog.i("savePlayerInfo:playerInfo=" + StrUtils.objDesc(playerInfo) + " handler=" + StrUtils.objDesc(handler)); this.playerInfo = playerInfo; this.handler = handler; this.retryTimes = MAX_RE...
java
@Override public Future<?> buildAsync(final Callable<?> builder, final HttpServletRequest req) { return getExecutors().getBuildExecutor().submit(new Callable<Object>() { public Object call() throws Exception { AbstractAggregatorImpl.this.currentRequest.set(req); Object result; try { result...
java
public static void start(String name, Version version, Class<?> classResource) { Engine.start(new EngineHeadless(name, version, classResource)); }
python
def deletable(self): """True if the MessageHandler can be deleted.""" return bool(lib.EnvIsDefmessageHandlerDeletable( self._env, self._cls, self._idx))
python
def geometryType(self): """ returns the feature's geometry type """ if self._geomType is None: if self.geometry is not None: self._geomType = self.geometry.type else: self._geomType = "Table" return self._geomType
python
def GetOutputPluginIndex( plugin_descriptors, plugin_id): """Gets an output plugin index for a plugin with a given id. Historically output plugins descriptors were stored in dicts-like structures with unique identifiers as keys. In REL_DB-based implementation, however, both plugin descriptors and their...
python
def p_expression_div(self, p): 'expression : expression DIVIDE expression' p[0] = Divide(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
java
public DescribeClientVpnEndpointsRequest withClientVpnEndpointIds(String... clientVpnEndpointIds) { if (this.clientVpnEndpointIds == null) { setClientVpnEndpointIds(new com.amazonaws.internal.SdkInternalList<String>(clientVpnEndpointIds.length)); } for (String ele : clientVpnEndpoint...
python
def _create_archive(self): '''This will create a tar.gz compressed archive of the scrubbed directory''' try: self.archive_path = os.path.join(self.report_dir, "%s.tar.gz" % self.session) self.logger.con_out('Creating SOSCleaner Archive - %s', self.archive_path) t = ta...
java
public static JMenuBar getAlignmentPanelMenu(JFrame frame, ActionListener actionListener, AFPChain afpChain, MultipleAlignment msa){ JMenuBar menu = new JMenuBar(); JMenu file= new JMenu("File"); file.getAccessibleContext().setAccessibleDescription("File Menu"); menu.add(file); ImageIcon saveicon = c...
python
def look(table, limit=0, vrepr=None, index_header=None, style=None, truncate=None, width=None): """ Format a portion of the table as text for inspection in an interactive session. E.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar'], ... ['a', 1], .....
java
static FormattingTuple format(final String messagePattern, Object argA, Object argB) { return arrayFormat(messagePattern, new Object[]{argA, argB}); }
java
public static WebDriver getFirefoxDriverWithJSSettings( final String userAgent, final boolean javascriptEnabled) { FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("general.useragent.override", userAgent); profile.setPreference("javascript.enabled", javascriptEnabled); WebDriver driver = ...
java
private String getLastWorkflowForUser() { CmsUser user = getCmsObject().getRequestContext().getCurrentUser(); return (String)user.getAdditionalInfo(PARAM_WORKFLOW_ID); }
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case BpsimPackage.DISTRIBUTION_PARAMETER__CURRENCY_UNIT: return getCurrencyUnit(); case BpsimPackage.DISTRIBUTION_PARAMETER__TIME_UNIT: return getTimeUnit(); } return super.eGet(featureID, resolve,...
java
private void addQueryParams(final Request request) { if (status != null) { request.addQueryParam("Status", status.toString()); } if (phoneNumber != null) { request.addQueryParam("PhoneNumber", phoneNumber.toString()); } if (incomingPhoneNumberSid != null...
python
def dynamics_from_bundle_bs(b, times, compute=None, return_roche_euler=False, **kwargs): """ Parse parameters in the bundle and call :func:`dynamics`. See :func:`dynamics` for more detailed information. NOTE: you must either provide compute (the label) OR all relevant options as kwargs (ltte) ...
java
public synchronized I_CmsResourceCollector addContentCollector(String className, String order) throws CmsConfigurationException { Class<?> classClazz; // init class for content collector try { classClazz = Class.forName(className); } catch (ClassNotFoundException e) { ...
java
public static ConfigParams readConfig(String correlationId, String path, ConfigParams parameters) throws ApplicationException { return new JsonConfigReader(path).readConfig(correlationId, parameters); }
java
private static URL getConfigUrl() throws ConfigurationException { String spec = System.getProperty(CONFIG_URL_PROPERTY_NAME); if (spec == null) { spec = DEFAULT_CONFIG_URL; } URL configUrl = null; try { configUrl = new URL(spec); conf...
java
public Waiter<GetDistributionRequest> distributionDeployed() { return new WaiterBuilder<GetDistributionRequest, GetDistributionResult>().withSdkFunction(new GetDistributionFunction(client)) .withAcceptors(new DistributionDeployed.IsDeployedMatcher()) .withDefaultPollingStrategy(...
java
private void addPostParams(final Request request) { if (type != null) { request.addPostParam("Type", type.toString()); } if (configurationUrl != null) { request.addPostParam("Configuration.Url", configurationUrl); } if (configurationMethod != null) { ...
python
def _get_specifications(specifications): """ Computes the list of strings corresponding to the given specifications :param specifications: A string, a class or a list of specifications :return: A list of strings :raise ValueError: Invalid specification found """ if not specifications or spe...
java
private void writeValue(Object value) throws JSONException { if (value instanceof Number) { String string = JSONObject.numberToString((Number) value); int integer = this.valuekeep.find(string); if (integer != none) { write(2, 2); write(integer,...
java
public static XlsWorkbook createWorkbook(OutputStream os, Workbook existing) throws IOException { try { if(existing != null) return new XlsWorkbook(jxl.Workbook.createWorkbook(os, (jxl.Workbook)existing.getWorkbook(), settings)); ...
python
def _handle_table_row(self): """Parse as style until end of the line, then continue.""" self._head += 2 if not self._can_recurse(): self._emit_text("|-") self._head -= 1 return self._push(contexts.TABLE_OPEN | contexts.TABLE_ROW_OPEN) padding ...
python
def iv(b, **kwargs): """Quick access to imview for interactive sessions """ import matplotlib.pyplot as plt import imview.imviewer as imview b = checkma(b) #if hasattr(kwargs,'imshow_kwargs'): # kwargs['imshow_kwargs']['interpolation'] = 'bicubic' #else: # kwargs['imshow_kwarg...
java
private void expandDirNodes(SpatialPrimitiveDistanceFunction<V> distFunction, DeLiCluNode node1, DeLiCluNode node2) { if(LOG.isDebuggingFinest()) { LOG.debugFinest("ExpandDirNodes: " + node1.getPageID() + " + " + node2.getPageID()); } int numEntries_1 = node1.getNumEntries(); int numEntries_2 = no...
python
def multi_normal(X, t): """ Multivariate normal sampler: Generates normal samples with mean m, precision matrix LL' Inputs: x : propose from Outputs: normal with mean m and precision LL' """ m, L = update_params(X, t) z = np.random.standard_normal(np.sh...
python
def hover(self): """ Hovers the element """ def do_hover(): """ Perform hover """ ActionChains(self.driver_wrapper.driver).move_to_element(self.element).perform() return self.execute_and_handle_webelement_exceptions(do_hover, 'hover...
python
def _process_yes_work(self, yes_work, no_catalogue, maybe_works, output_dir): """Returns statistics of how `yes_work` compares with the other works in `no_catalogue` and the "maybe" works. :param yes_work: name of work being processed :type yes_work: `str` ...
java
public boolean containsNone(UnicodeSet b) { // The specified set is a subset if some of its pairs overlap with some of this set's pairs. // This implementation accesses the lists directly for speed. int[] listB = b.list; boolean needA = true; boolean needB = true; int aPt...
python
def get_random_connection(self): """ Open new connection to random redis server. """ if self._available_connections: node_name = random.choice(list(self._available_connections.keys())) conn_list = self._available_connections[node_name] # check it in ca...
python
def _AlignUncompressedDataOffset(self, uncompressed_data_offset): """Aligns the compressed file with the uncompressed data offset. Args: uncompressed_data_offset (int): uncompressed data offset. Raises: IOError: if the ZIP file could not be opened. OSError: if the ZIP file could not be o...
python
def selectImports(pth, xtrapath=None): """ Return the dependencies of a binary that should be included. Return a list of pairs (name, fullpath) """ rv = [] if xtrapath is None: xtrapath = [os.path.dirname(pth)] else: assert isinstance(xtrapath, list) xtrapath = [os.p...