language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static <T> T waitUntil(ExpectedCondition<T> expectedCondition, WebDriver driver, long timeOutInSeconds) { logger.debug("BEGIN wait (timeout=" + timeOutInSeconds + "s) for " + expectedCondition); T object = new WebDriverWait(driver, timeOutInSeconds) .until(expectedCondition); logger.debug("EN...
java
public static void bindSystemStreamsToSLF4J(Logger sysOutLogger, Logger sysErrLogger) { SecurityUtil.sysOutLogger = sysOutLogger; SecurityUtil.sysErrLogger = sysErrLogger; bindSystemStreamsToSLF4J(); }
java
public void marshall(CreateTaskSetRequest createTaskSetRequest, ProtocolMarshaller protocolMarshaller) { if (createTaskSetRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createTaskSetReques...
python
def iterate_over_file(self, fasta_path): """ Generator that yields identifiers paired with sequences. """ with self._open(fasta_path) as f: for line in f: line = line.rstrip() if len(line) == 0: continue # ...
python
def get_system_uptime_input_rbridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_system_uptime = ET.Element("get_system_uptime") config = get_system_uptime input = ET.SubElement(get_system_uptime, "input") rbridge_id = ET.SubEle...
java
public long getWorkspaceIndexSize(String repositoryName, String workspaceName) throws QuotaManagerException { RepositoryQuotaManager rqm = getRepositoryQuotaManager(repositoryName); return rqm.getWorkspaceIndexSize(workspaceName); }
python
def create_order(self, kitchen, recipe_name, variation_name, node_name=None): """ Full graph '/v2/order/create/<string:kitchenname>/<string:recipename>/<string:variationname>', methods=['PUT'] Single node '/v2/order/create/onenode/<string:kitchenname>/<string:recipen...
java
@Override public void write(byte[] buffer, int offset, int len) { // avoid int overflow if (offset < 0 || offset > buffer.length || len < 0 || len > buffer.length - offset) throw new IndexOutOfBoundsException(); if (len == 0) return; /* Expand if necessa...
java
private void setMessagingEngineUuid(SIBUuid8 uuid) { if (tc.isEntryEnabled()) SibTr.entry(tc, "setMessagingEngineUuid", new Object[] { uuid }); messagingEngineUuid = uuid; if (tc.isEntryEnabled()) SibTr.exit(tc, "setMessagingEngineUuid"); }
python
def xflatten(iterable, transform, check=is_iterable): """Apply a transform to iterable before flattening at each level.""" for value in transform(iterable): if check(value): for flat in xflatten(value, transform, check): yield flat else: yield value
java
public String getFirstSentence(String paragraph) { if (paragraph == null || paragraph.length() == 0) { return ""; } BreakIterator sentenceBreaks = BreakIterator.getSentenceInstance(); sentenceBreaks.setText(paragraph); int start = sentenceBreaks.first(); int...
python
def serialize(obj): """JSON serializer that accepts datetime & date""" from datetime import datetime, date, time if isinstance(obj, date) and not isinstance(obj, datetime): obj = datetime.combine(obj, time.min) if isinstance(obj, datetime): return obj.isoformat()
python
def from_frequencies(cls, frequencies, concat=None): """ Build Huffman code table from given symbol frequencies :param frequencies: symbol to frequency mapping :param concat: function to concatenate symbols """ concat = concat or _guess_concat(next(iter(frequencies))) ...
python
def _NormalizePath(path): """Removes surrounding whitespace, leading separator and normalize.""" # TODO(emrekultursay): Calling os.path.normpath "may change the meaning of a # path that contains symbolic links" (e.g., "A/foo/../B" != "A/B" if foo is a # symlink). This might cause trouble when matching against l...
java
public static boolean getBooleanValue(Object newValue, boolean defaultValue) { if (newValue != null) { if (newValue instanceof String) { return Boolean.parseBoolean((String) newValue); } else if (newValue instanceof Boolean) return (Boolean) newValue; ...
java
private Map findLoaders() { Map loaders = getContainer().getComponentDescriptorMap(ProviderLoader.class.getName()); if (loaders == null) { throw new Error("No provider loaders found"); } Set keys = loaders.keySet(); Map found = null; ProviderLoader defaultLoa...
java
public static Expression filter(String field, String operator, Val<Expression>[] args, EbeanExprInvoker invoker) { if (args.length > 0) { SpiExpressionFactory queryEf = (SpiExpressionFactory) invoker.getServer().getExpressionFactory(); ExpressionFactory filterEf = queryEf.createExpressio...
java
public static void setLogWriter(java.io.PrintWriter out) { SecurityManager sec = System.getSecurityManager(); if (sec != null) { sec.checkPermission(SET_LOG_PERMISSION); } logStream = null; logWriter = out; }
java
public void setCenterProperties(DoubleProperty x, DoubleProperty y, DoubleProperty z) { this.cxProperty = x; this.cyProperty = y; this.czProperty = z; }
python
def show_progress(self): """ whether to show the progress of heavy calculations on this object. """ from pyemma import config # no value yet, obtain from config if not hasattr(self, "_show_progress"): val = config.show_progress_bars self._show_progress = val ...
python
def regions(): """ Get all available regions for the SDB service. :rtype: list :return: A list of :class:`boto.sdb.regioninfo.RegionInfo` instances """ return [SDBRegionInfo(name='us-east-1', endpoint='sdb.amazonaws.com'), SDBRegionInfo(name='eu-west-1', ...
python
def raise_for_old_graph(graph): """Raise an ImportVersionWarning if the BEL graph was produced by a legacy version of PyBEL. :raises ImportVersionWarning: If the BEL graph was produced by a legacy version of PyBEL """ graph_version = tokenize_version(graph.pybel_version) if graph_version < PYBEL_MI...
java
@Override public RebootInstancesResult rebootInstances(RebootInstancesRequest request) { request = beforeClientExecution(request); return executeRebootInstances(request); }
python
def iter_items(iterable): """ Iterate through all items (key-value pairs) within an iterable dictionary-like object. If the object has a `keys` method, this is used along with `__getitem__` to yield each pair in turn. If no `keys` method exists, each iterable element is assumed to be a 2-tuple of ke...
python
def _check_len(a, b): """ Raises an exception if the two values do not have the same length. This is useful for validating preconditions. :a: the first value :b: the second value :raises ValueError: if the sizes do not match """ if len(a) != len(b): msg = "Length must be {}. Got...
python
def resolve_data_path(self, data=None, filename=None): """Resolve data path for use with the executor. :param data: Data object instance :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given data file in programs executed usin...
java
public static TaskAttemptID downgrade(org.apache.hadoop.mapreduce.TaskAttemptID old) { if (old instanceof TaskAttemptID) { return (TaskAttemptID) old; } else { return new TaskAttemptID(TaskID.downgrade(old.getTaskID()), old.getId()); } }
python
def deep_update(original, new_dict, new_keys_allowed, whitelist): """Updates original dict with values from new_dict recursively. If new key is introduced in new_dict, then if new_keys_allowed is not True, an error will be thrown. Further, for sub-dicts, if the key is in the whitelist, then new subkeys ...
python
def bottleneck_block_v1(cnn, depth, depth_bottleneck, stride): """Bottleneck block with identity short-cut for ResNet v1. Args: cnn: the network to append bottleneck blocks. depth: the number of output filters for this bottleneck block. depth_bottleneck: the number of bottleneck filters for this bloc...
python
def add(self, other): """ Add an Interval to the IntervalSet by taking the union of the given Interval object with the existing Interval objects in self. This has no effect if the Interval is already represented. :param other: an Interval to add to this IntervalSet. """ ...
python
def _submit(self): '''submit the issue to github. When we get here we should have: {'user_prompt_issue': 'I want to do the thing.', 'user_prompt_repo': 'vsoch/hello-world', 'user_prompt_title': 'Error with this thing', 'record_asciinema': '/tmp/helpme...
java
private ASN1EncodableVector buildUnauthenticatedAttributes(byte[] timeStampToken) throws IOException { if (timeStampToken == null) return null; // @todo: move this together with the rest of the defintions String ID_TIME_STAMP_TOKEN = "1.2.840.113549.1.9.16.2.14"; // RFC 3161 id-aa-...
python
async def states(self, country: str) -> list: """Return a list of supported states in a country.""" data = await self._request( 'get', 'states', params={'country': country}) return [d['state'] for d in data['data']]
java
private int lineBeginningFor(int pos) { if (sourceChars == null) { return -1; } if (pos <= 0) { return 0; } char[] buf = sourceChars; if (pos >= buf.length) { pos = buf.length - 1; } while (--pos >= 0) { char...
java
@NotNull public DoubleStream mapToDouble(@NotNull final ToDoubleFunction<? super T> mapper) { return new DoubleStream(params, new ObjMapToDouble<T>(iterator, mapper)); }
java
@Override public void discardOutput() throws IllegalStateException, IOException{ // validate state if (isClosed()) throw new IllegalStateException("Serial connection is not open; cannot 'discardOutput()'."); // flush data to serial port immediately com.pi4j.jni.Seria...
java
protected String getTextAt(final MBasicTable table, final int row, final int column) { String text = table.getTextAt(row, column); // suppression de tags éventuellements présents (par ex. avec un MultiLineTableCellRenderer) if (text != null && text.startsWith("<html>")) { text = text.replaceFirst("<html>",...
python
def get_searches(self, quick=False, saved=True): '''Get searches listing. :param quick bool: Include quick searches (default False) :param quick saved: Include saved searches (default True) :returns: :py:class:`planet.api.models.Searches` :raises planet.api.exceptions.APIExcepti...
java
public static <B extends Buffer> Input<B> fromSource( ManagedBuffer<B> buffer, boolean endOfRecord) { return new Input<>(buffer, endOfRecord); }
python
def username_password_authn(environ, start_response, reference, key, redirect_uri): """ Display the login form """ logger.info("The login page") headers = [] resp = Response(mako_template="login.mako", template_lookup=LOOKUP, headers=headers) ...
java
private boolean fillReadBuffer() throws IOException { // TODO: Add reading from error stream of external process. Otherwise the InputFormat might get deadlocked! // stream was completely processed if(noMoreStreamInput) { if(this.readBufferReadPos == this.readBufferFillPos) { this.noMoreRecordBuffers = t...
python
def sync(ui, repo, **opts): """synchronize with remote repository Incorporates recent changes from the remote repository into the local repository. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) if not opts["local"]: # If there are incoming CLs, pull -u will do the update. # If there...
python
def _verify_password(self, raw_password, hashed_password): """ Verifies that a plaintext password matches the hashed version of that password using the stored passlib password context """ PraetorianError.require_condition( self.pwd_ctx is not None, "Praeto...
java
@Deprecated public void addCapabilityRequirements(OperationContext context, ModelNode attributeValue) { addCapabilityRequirements(context, null, attributeValue); }
java
public String addAddressToTarget(String address) { if (address != null) { MessageDetailTarget messageDetailTarget = (MessageDetailTarget)this.getMainRecord(); String site = messageDetailTarget.getProperty(TrxMessageHeader.DESTINATION_PARAM); site = this.getSiteFro...
python
def fax(self): """ Access the Fax Twilio Domain :returns: Fax Twilio Domain :rtype: twilio.rest.fax.Fax """ if self._fax is None: from twilio.rest.fax import Fax self._fax = Fax(self) return self._fax
java
int readReferenceOrNull (Input input, Class type, boolean mayBeNull) { if (type.isPrimitive()) type = getWrapperClass(type); boolean referencesSupported = referenceResolver.useReferences(type); int id; if (mayBeNull) { id = input.readVarInt(true); if (id == NULL) { if (TRACE || (DEBUG && depth ...
python
def get_win_color(color): """Convert a named color definition to Windows console color foreground, background and style numbers.""" foreground = background = style = None control = '' if ";" in color: control, color = color.split(";", 1) if control == bold: style = colora...
java
public Groundy addStringArrayList(String key, ArrayList<String> value) { mArgs.putStringArrayList(key, value); return this; }
java
@VisibleForTesting public static void prepareBookKeeperEnv(final String availablePath, ZooKeeper zooKeeper) throws IOException { final CountDownLatch availablePathLatch = new CountDownLatch(1); StringCallback cb = new StringCallback() { @Override public void processResult(int rc, String pat...
python
def parse_name_myher(record): """Parse NAME structure assuming MYHERITAGE dialect. In MYHERITAGE dialect married name (if present) is saved as _MARNM sub-record. Maiden name is stored in SURN record. Few examples: No maiden name: 1 NAME John /Smith/ 2 GIVN John 2 SURN Smith ...
python
def add_hotkey(hotkey, callback, args=(), suppress=False, timeout=1, trigger_on_release=False): """ Invokes a callback every time a hotkey is pressed. The hotkey must be in the format `ctrl+shift+a, s`. This would trigger when the user holds ctrl, shift and "a" at once, releases, and then presses "s". T...
python
def process_common_disease_file(self, raw, unpadded_doids, limit=None): """ Make disaese-phenotype associations. Some identifiers need clean up: * DOIDs are listed as DOID-DOID: --> DOID: * DOIDs may be unnecessarily zero-padded. these are remapped to their non-padded equ...
java
public byte getByte(int index) { checkIndexLength(index, SizeOf.SIZE_OF_BYTE); return unsafe.getByte(base, address + index); }
java
protected void doBye(SipServletRequest request) throws ServletException, IOException { if(logger.isInfoEnabled()) { logger.info("SimpleProxyServlet: Got BYE request:\n" + request); } SipServletResponse sipServletResponse = request.createResponse(200); sipServletResponse.send(); SipApplicationSess...
java
public Rule parseRule(String id, String rule, boolean silent, PipelineClassloader ruleClassLoader) throws ParseException { final ParseContext parseContext = new ParseContext(silent); final SyntaxErrorListener errorListener = new SyntaxErrorListener(parseContext); final RuleLangLexer lexer = new...
python
def _run_cmplx(fn, image): """Run a complex function on a non-complex image. The image needs to be complex, or have an even number of bands. The input can be int, the output is always float or double. """ original_format = image.format if image.format != 'complex' and image.format != 'dpcomple...
python
def _build_hash_magic(self, subtitle_id): """Build the other half of the encryption key hash I have no idea what is going on here @param int subtitle_id @return str """ media_magic = self.HASH_MAGIC_CONST ^ subtitle_id hash_magic = media_magic ^ media_magic >> ...
python
def hierarchical(df, cluster_cols=True, cluster_rows=False, n_col_clusters=False, n_row_clusters=False, row_labels=True, col_labels=True, fcol=None, z_score=0, method='ward', cmap=cm.PuOr_r, return_clusters=False, rdistance_fn=distance.pdist, cdistance_fn=distance.pdist ): """ Hierarchical clustering of samples...
java
@Override public CommerceWishList findByGroupId_Last(long groupId, OrderByComparator<CommerceWishList> orderByComparator) throws NoSuchWishListException { CommerceWishList commerceWishList = fetchByGroupId_Last(groupId, orderByComparator); if (commerceWishList != null) { return commerceWishList; } ...
java
public void setProxypassword(String proxypassword) throws ApplicationException { try { smtp.getProxyData().setPassword(proxypassword); } catch (Exception e) { throw new ApplicationException("attribute [proxypassword] of the tag [mail] is invalid", e.getMessage()); } }
java
public void setDir(java.lang.String dir) { getStateHelper().put(PropertyKeys.dir, dir); handleAttribute("dir", dir); }
java
public ModifyInstanceCreditSpecificationResult withSuccessfulInstanceCreditSpecifications( SuccessfulInstanceCreditSpecificationItem... successfulInstanceCreditSpecifications) { if (this.successfulInstanceCreditSpecifications == null) { setSuccessfulInstanceCreditSpecifications(new com.a...
java
public final void readChildren(ObjectInputStream in) throws IOException, ClassNotFoundException { int childCount = in.readInt(); for (int i = 0; i < childCount; i++) { internalAdd(in.readObject(), false); } }
python
def _get_librato(ret=None): ''' Return a Librato connection object. ''' _options = _get_options(ret) conn = librato.connect( _options.get('email'), _options.get('api_token'), sanitizer=librato.sanitize_metric_name, hostname=_options.get('api_url')) log.info("Conn...
python
def get(self, now): """ Get a bucket key to compact. If none are available, returns None. This uses a Lua script to ensure that the bucket key is popped off the sorted set in an atomic fashion. :param now: The current time, as a float. Used to ensure the b...
python
def start(self, measurementId): """ Posts to the target to tell it a named measurement is starting. :param measurementId: """ self.sendURL = self.rootURL + measurementId + '/' + self.deviceName self.startResponseCode = self._doPut(self.sendURL)
java
@Transactional(readOnly=true) public List<Permission> loadRolesAndPermissions() throws Exception { return _persistence.getResults(_qRoleAuthorizations, null); }
java
public static Request newDeleteObjectRequest(Session session, String id, Callback callback) { return new Request(session, id, null, HttpMethod.DELETE, callback); }
java
public boolean addAll(Collection<? extends E> c) { Iterator<? extends E> cIterator = c.iterator(); while(cIterator.hasNext()) { this.add(cIterator.next()); } return true; }
java
@VisibleForTesting Config updateNumContainersIfNeeded(Config initialConfig, TopologyAPI.Topology initialTopology, PackingPlan packingPlan) { int configNumStreamManagers = TopologyUtils.getNumContainers(initialTopology); int packingNumS...
python
def set_option(self, key, subkey, value): """Sets the value of an option. :param str key: First identifier of the option. :param str subkey: Second identifier of the option. :param value: New value for the option (type varies). :raise: :NotRegisteredError: If ``key`...
java
public boolean isInnerNode() { boolean inner = true; if ( (_leftChild == null) || (_rightChild == null) ) inner = false; return inner; }
java
@Override public EClass getIfcGeometricRepresentationItem() { if (ifcGeometricRepresentationItemEClass == null) { ifcGeometricRepresentationItemEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(304); } return ifcGeometricRepresentationItemEClass; ...
python
def toJSONFilters(actions): """Generate a JSON-to-JSON filter from stdin to stdout The filter: * reads a JSON-formatted pandoc document from stdin * transforms it by walking the tree and performing the actions * returns a new JSON-formatted pandoc document to stdout The argument `actions` is ...
java
public static void warn(String format, Object... arguments) { warn(LogFactory.indirectGet(), format, arguments); }
java
public FTPUploadRequest addFileToUpload(String filePath) throws FileNotFoundException { UploadFile file = new UploadFile(filePath); file.setProperty(FTPUploadTask.PARAM_REMOTE_PATH, new File(filePath).getName()); params.files.add(file); return this; }
python
def predict(self, *args, **kwargs): """ Predict given DataFrame using the given model. Actual prediction steps will not be executed till an operational step is called. :param list[DataFrame] args: input DataFrames to be predicted :param kwargs: named input DataFrames or predicti...
python
def main(args_list=None): """ Script which loads variants and annotates them with overlapping genes and predicted coding effects. Example usage: varcode --vcf mutect.vcf \ --vcf strelka.vcf \ --maf tcga_brca.maf \ --variant chr1 498584 C G \ ...
java
private Object convertTabularDataDirectly(TabularData pTd, Stack<String> pExtraArgs, ObjectToJsonConverter pConverter) throws AttributeNotFoundException { if (!pExtraArgs.empty()) { throw new IllegalArgumentException("Cannot use a path for converting tabular data with complex keys (" + ...
java
@Override public CreateProtectionResult createProtection(CreateProtectionRequest request) { request = beforeClientExecution(request); return executeCreateProtection(request); }
python
def format_link_json(self): """Convert a Link object to json format.""" link_json = {} link_json['trace_id'] = self.trace_id link_json['span_id'] = self.span_id link_json['type'] = self.type if self.attributes is not None: link_json['attributes'] = self.attri...
python
def _get_mean_and_median(hist: Hist) -> Tuple[float, float]: """ Retrieve the mean and median from a ROOT histogram. Note: These values are not so trivial to calculate without ROOT, as they are the bin values weighted by the bin content. Args: hist: Histogram from which the values ...
java
public IGPSObject parse(final String line) throws ParseException { try { final JSONObject json = new JSONObject(line); return this.parse(json); } catch (final JSONException e) { throw new ParseException("Parsing failed", e); } }
python
def update_notes(self, xml_file, new=False): """Update information about the sleep scoring. Parameters ---------- xml_file : str file of the new or existing .xml file new : bool if the xml_file should be a new file or an existing one """ i...
python
def mget(self, body, index=None, doc_type=None, **query_params): """ Get multiple document from the same index and doc_type (optionally) by ids `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html>` :param body: list of docs with or without the index and ...
java
protected void openPublish() { HashMap<String, String> params = Maps.newHashMap(); params.put(CmsPublishOptions.PARAM_CONTAINERPAGE, "" + CmsCoreProvider.get().getStructureId()); params.put(CmsPublishOptions.PARAM_START_WITH_CURRENT_PAGE, ""); params.put(CmsPublishOptions.PARAM_DETAIL, ...
python
def remove_from_products(self, products=None, all_products=False): """ Remove user group from some product license configuration groups (PLCs), or all of them. :param products: list of product names the user group should be removed from :param all_products: a boolean meaning remove from ...
python
def annotate_segments(self, Z): """ Report the copy number and start-end segment """ # We need a way to go from compressed idices to original indices P = Z.copy() P[~np.isfinite(P)] = -1 _, mapping = np.unique(np.cumsum(P >= 0), return_index=True) dZ = Z.compress...
java
public String getAttribute(final String name) { for(AttributeInfo item : attributes) { if(item.name.equals(name)) { return item.value; } } return null; }
java
public Query addInsidePolygon(float latitude, float longitude) { if (insidePolygon == null) { insidePolygon = "insidePolygon=" + latitude + "," + longitude; } else if (insidePolygon.length() > 14) { insidePolygon += "," + latitude + "," + longitude; } return this; }
java
public synchronized boolean log(WsByteBuffer data) { if (null == data) { // return failure return false; } // if we've stopped then there is no worker to hand this to; however, the // caller does not expect to have to release buffers handed to the // logge...
java
private LNGIntVector generateBlockingClause(final LNGBooleanVector modelFromSolver, final LNGIntVector relevantVars) { final LNGIntVector blockingClause; if (relevantVars != null) { blockingClause = new LNGIntVector(relevantVars.size()); for (int i = 0; i < relevantVars.size(); i++) { final ...
python
def status(ctx, services, show_all): """Show status of installed service(s).""" logger.debug("running command %s (%s)", ctx.command.name, ctx.params, extra={"command": ctx.command.name, "params": ctx.params}) home = ctx.obj["HOME"] services_path = os.path.join(home, SERVICES) def ...
java
public static void unregisterMXBean(CacheProxy<?, ?> cache, MBeanType type) { ObjectName objectName = getObjectName(cache, type); unregister(objectName); }
java
void initEditor( CmsEditorContext context, CmsContentDefinition contentDefinition, I_CmsInlineFormParent formParent, boolean inline, String mainLocale) { m_context = context; m_locale = contentDefinition.getLocale(); m_entityId = contentDefinitio...
java
public void start() { //only start the thread if the interval is sane if(refreshInterval > 0) { refreshUsed = new Thread(new DURefreshThread(), "refreshUsed-"+dirPath); refreshUsed.setDaemon(true); refreshUsed.start(); } }
python
def delete_if_exists(self, **kwargs): """ Deletes an object if it exists in database according to given query parameters and returns True otherwise does nothing and returns False. Args: **kwargs: query parameters Returns(bool): True or False """ ...
python
def _find_sink_scc(self): """ Set self._sink_scc_labels, which is a list containing the labels of the strongly connected components. """ condensation_lil = self._condensation_lil() # A sink SCC is a SCC such that none of its members is strongly # connected to no...
java
public static void main(String[] args) throws Exception { BinaryProblem problem = new OneMax(1024) ; MutationOperator<BinarySolution> mutationOperator = new BitFlipMutation(1.0 / problem.getNumberOfBits(0)) ; int improvementRounds = 10000 ; Comparator<BinarySolution> comparator = new Dominanc...