language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def AddAnalogShortIdMsecRecordNoStatus(site_service, tag, time_value, msec, value): """ This function will add an analog value to the specified eDNA service and tag, without an associated point status. :param site_service: The site.service where data will be pushe...
java
public EClass getProjectDeleted() { if (projectDeletedEClass == null) { projectDeletedEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(LogPackage.eNS_URI).getEClassifiers() .get(17); } return projectDeletedEClass; }
python
def parse_midi_event(self, fp): """Parse a MIDI event. Return a dictionary and the number of bytes read. """ chunk_size = 0 try: ec = self.bytes_to_int(fp.read(1)) chunk_size += 1 self.bytes_read += 1 except: raise IOError(...
python
def get_script_iterator(package_name, verbose = False): """ Args: package_name: name of package Returns: the script_iterators of the package as a dictionary """ packs = hf.explore_package(package_name + '.core') print(packs) script_iterator = {} ...
python
def match_one(template, image, options=None): """ Match template and find exactly one match in the Image using specified features. :param template: Template Image :param image: Search Image :param options: Options include - features: List of options for each feature :return: (Box, Score...
java
public AwsSecurityFindingFilters withType(StringFilter... type) { if (this.type == null) { setType(new java.util.ArrayList<StringFilter>(type.length)); } for (StringFilter ele : type) { this.type.add(ele); } return this; }
python
def do_py(self, arg): """ :: Usage: py py COMMAND Arguments: COMMAND the command to be executed Description: The command without a parameter will be executed and the interactive pyth...
java
@FromString public static Weeks parseWeeks(String periodStr) { if (periodStr == null) { return Weeks.ZERO; } Period p = PARSER.parsePeriod(periodStr); return Weeks.weeks(p.getWeeks()); }
java
public ServiceCall<Classifiers> listClassifiers(ListClassifiersOptions listClassifiersOptions) { String[] pathSegments = { "v3/classifiers" }; RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments)); builder.query("version", versionDate); Map<String, Str...
java
void setTypeConvertersInOrder(Collection<TypeConverter> typeConverters) { LockableList<TypeConverter> newList = new LockableList<>(); newList.addAll(typeConverters); newList.lock(); typeConvertersInOrder = newList; // update list of converters to allow mentioning type converter ...
java
public List<ColumnResult<SqlResultSetMapping<T>>> getAllColumnResult() { List<ColumnResult<SqlResultSetMapping<T>>> list = new ArrayList<ColumnResult<SqlResultSetMapping<T>>>(); List<Node> nodeList = childNode.get("column-result"); for(Node node: nodeList) { ColumnResult<SqlResultSet...
python
def _setup_language_variables(self, lang: str): # pylint: disable=no-self-use """Check for language availability and presence of tagger files. :param lang: The language argument given to the class. :type lang: str :rtype : dict """ assert lang in TAGGERS.keys(), \ ...
java
public void registerDeferredService(BundleContext bundleContext, Class<?> providedService, Dictionary dict) { Object obj = serviceReg.get(); if (obj instanceof ServiceRegistration<?>) { // already registered - nothing to do here return; } if (obj instanceof CountD...
python
def save_cookies(self, ignore_discard=True, ignore_expires=True): """Save cookies to the file :attr:`.API.cookies_filename`""" if not isinstance(self.cookies, cookielib.FileCookieJar): m = 'Cookies must be a cookielib.FileCookieJar object to be saved.' raise APIError(m) s...
java
public void end(Xid xid, int flags) throws XAException { if (pad) xid = convertXid(xid); xaResource.end(xid, flags); }
python
def _get_field_values(item, fldnames, rpt_fmt=None, itemid2name=None): """Return fieldnames and values of either a namedtuple or GOEnrichmentRecord.""" if hasattr(item, "_fldsdefprt"): # Is a GOEnrichmentRecord return item.get_field_values(fldnames, rpt_fmt, itemid2name) if hasattr(i...
java
@BindingAdapter("bind:tv_typeface") public static void setCustomTypeface(TypefaceEditText editText, String type) { editText.mCurrentTypeface = TypefaceType.getTypeface(type != null ? type : ""); Typeface typeface = getFont(editText.getContext(), editText.mCurrentTypeface.getAssetFileName()); ...
java
public Matrix4f orthoSymmetricLH(float width, float height, float zNear, float zFar) { return orthoSymmetricLH(width, height, zNear, zFar, false, thisOrNew()); }
python
def reboot_autopilot(self, hold_in_bootloader=False): '''reboot the autopilot''' if self.mavlink10(): if hold_in_bootloader: param1 = 3 else: param1 = 1 self.mav.command_long_send(self.target_system, self.target_component, ...
python
def timeline_home(self, max_id=None, min_id=None, since_id=None, limit=None): """ Fetch the logged-in users home timeline (i.e. followed users and self). Returns a list of `toot dicts`_. """ return self.timeline('home', max_id=max_id, min_id=min_id, ...
python
def bellman_ford(G, seeds, maxiter=None): """Bellman-Ford iteration. Parameters ---------- G : sparse matrix Returns ------- distances : array nearest_seed : array References ---------- CLR """ G = asgraph(G) N = G.shape[0] if maxiter is not None and maxi...
python
def main(): """Main entry point for CLI commands.""" options = docopt(__doc__, version=__version__) if options['segment']: segment( options['<file>'], options['--output'], options['--target-duration'], options['--mpegts'], )
python
def extract_from_stream(stream, detections, pad=5.0, length=30.0): """ Extract waveforms for a list of detections from a stream. :type stream: obspy.core.stream.Stream :param stream: Stream containing the detections. :type detections: list :param detections: list of eqcorrscan.core.match_filter...
python
def _compile(cls, lines): '''Return macro or block name from the current line.''' m = cls.RE_PASTE.match(lines.current) if m is None: raise MacroBlockUsageError( 'Incorrect macro or block usage at line {}, {}\nShould be ' 'something like: #my_macro'.fo...
python
def _get_aug_flow( left, left_type, aug_opnode, right, right_type, context, reverse_context ): """Get the flow for augmented binary operations. The rules are a bit messy: * if left and right have the same type, then left.__augop__(right) is first tried and then left.__op__(right). ...
java
private void addGroup(List<Token> group, List<List<Token>> groups) { if(group.isEmpty()) return; // remove trailing tokens that should be ignored while(!group.isEmpty() && IGNORED_TRAILING_TOKENS.contains( group.get(group.size() - 1).getType())) { group.remove(group.size() - 1); } /...
java
public void setQualifierNameMajorTopic(boolean v) { if (MeshHeading_Type.featOkTst && ((MeshHeading_Type)jcasType).casFeat_qualifierNameMajorTopic == null) jcasType.jcas.throwFeatMissing("qualifierNameMajorTopic", "de.julielab.jules.types.MeshHeading"); jcasType.ll_cas.ll_setBooleanValue(addr, ((MeshHeadi...
java
public final boolean isItemEnabled(final int index) { AbstractItem item = items.get(index); return item instanceof Item && ((Item) item).isEnabled(); }
java
public Observable<AppServiceCertificateResourceInner> getCertificateAsync(String resourceGroupName, String certificateOrderName, String name) { return getCertificateWithServiceResponseAsync(resourceGroupName, certificateOrderName, name).map(new Func1<ServiceResponse<AppServiceCertificateResourceInner>, AppServi...
java
public boolean isTriggeringEvent( final Appender appender, final LoggingEvent event, final String file, final long fileLength) { //System.out.println("Size"+file.length()); return (fileLength >= maxFileSize); }
python
def _group_range(records, method): """ Yield the range of all dates between the extrema of a list of records, separated by a given time delta. """ start_date = records[0].datetime end_date = records[-1].datetime _fun = DATE_GROUPERS[method] d = start_date # Day and week use timede...
java
public static void log (String message, Object... args) { StringBuilder sb = new StringBuilder(); sb.append(message); if (args.length > 1) { sb.append(" ["); for (int ii = 0, ll = args.length/2; ii < ll; ii++) { if (ii > 0) { sb.app...
python
def _count_localizations(df): """ count the most likely localization for each depentent peptide. :param df: allPeptides.txt table. """ grp = df.groupby(_index_columns) counts = grp['DP AA'].apply(lambda x: count(x.str.split(';').values)) counts.index = counts.index.set_names('DP AA', level=4) ...
python
def resolve_peer(self, peer_id: Union[int, str]): """Use this method to get the InputPeer of a known peer_id. This is a utility method intended to be used **only** when working with Raw Functions (i.e: a Telegram API method you wish to use which is not available yet in the ...
java
protected static void closeWelcomePage() { final IIntroManager introManager = PlatformUI.getWorkbench().getIntroManager(); if (introManager != null) { final IIntroPart intro = introManager.getIntro(); if (intro != null) { introManager.closeIntro(intro); } } }
java
public static Node getFunctionBody(Node fn) { checkArgument(fn.isFunction(), fn); return fn.getLastChild(); }
java
public CmsSite matchSite(CmsSiteMatcher matcher) { CmsSite site = m_siteMatcherSites.get(matcher); if (site == null) { // return the default site (might be null as well) site = m_defaultSite; } return site; }
java
public boolean isTransientException (SQLException sqe) { // TODO: Add more error messages here as we encounter them. String msg = sqe.getMessage(); return (msg != null && msg.indexOf("An I/O error occured while sending to the backend") != -1); }
java
private boolean load(InputStream in) throws IOException, StreamCorruptedException { boolean updated = false; Iterable<Version> loadedVersions = loadData(in); for (Version loadedVersion : loadedVersions) { // see https://github.com/ThreeTen/threetenbp/pull/28 for issue wrt ...
java
public static boolean sequenceEqualConstantTime(byte[] self, byte[] other) { if (self == null) { throw new IllegalArgumentException("self"); } if (other == null) { throw new IllegalArgumentException("other"); } // Constant time comparison of two byte arr...
java
public OvhOrder cart_cartId_checkout_POST(String cartId, Boolean autoPayWithPreferredPaymentMethod, Boolean waiveRetractationPeriod) throws IOException { String qPath = "/order/cart/{cartId}/checkout"; StringBuilder sb = path(qPath, cartId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "...
java
@Override public boolean serviceExists(URI serviceUri) throws ServiceException { if (serviceUri == null || !serviceUri.isAbsolute()) { log.warn("The Service URI is either absent or relative. Provide an absolute URI"); return false; } URI graphUri; try { ...
java
public void setLabels(java.util.Collection<LabelDetection> labels) { if (labels == null) { this.labels = null; return; } this.labels = new java.util.ArrayList<LabelDetection>(labels); }
java
Collection<BindingStrategy> collectFromAggregates(Collection<Class<? extends AggregateRoot>> aggregateClasses) { Collection<BindingStrategy> bindingStrategies = new ArrayList<>(); Map<Type[], Key<?>> allGenerics = new HashMap<>(); for (Class<? extends AggregateRoot<?>> aggregateClass : Business...
java
public void setBundleActivator(String bundleActivator) { String old = mainAttributes.get(BUNDLE_ACTIVATOR); if (!bundleActivator.equals(old)) { this.mainAttributes.put(BUNDLE_ACTIVATOR, bundleActivator); this.modified = true; this.bundleActivator = bundleActivator; } }
java
public EClass getRemoteServiceCalled() { if (remoteServiceCalledEClass == null) { remoteServiceCalledEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(LogPackage.eNS_URI) .getEClassifiers().get(31); } return remoteServiceCalledEClass; }
java
public IoTSetResponse setUsingIq(FullJid jid, Collection<? extends SetData> data) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { IoTSetRequest request = new IoTSetRequest(data); request.setTo(jid); IoTSetResponse response = connection().createStanza...
java
public Map<String, String> getStringMap(final Map<String, String> map) { final int len = getVInt(); for (int i = 0; i < len; i++) { map.put(getString(), getString()); } return map; }
java
public void waitForElementPresent(final By by, final int maximumSeconds) { WebDriverWait wait = new WebDriverWait(driver, maximumSeconds); wait.until(ExpectedConditions.presenceOfElementLocated((by))); }
java
public HBeanRowCollector getEager(Set<HBeanRow> rows, FetchType... fetchType) throws HBeanNotFoundException { Set<HBeanRow> result; result = getLazy(rows, fetchType); HBeanRowCollector collector = new HBeanRowCollector(result); getEager(result, collector, FETCH_DEPTH_MAX, fet...
java
public static int compareTimestamps(UUID uuid1, UUID uuid2) { return Longs.compare(uuid1.timestamp(), uuid2.timestamp()); }
java
private static FactorFilter<Executor, ExecutableFlow> getStaticRemainingFlowSizeFilter() { return FactorFilter .create(STATICREMAININGFLOWSIZE_FILTER_NAME, (filteringTarget, referencingObject) -> { if (null == filteringTarget) { logger.debug(String.format("%s : filtering out the target...
java
public TupleCombinerBuilder once( Stream<TupleRef> tupleRefs) { tupleRefs.forEach( tupleRef -> tupleCombiner_.addOnceTuple( tupleRef)); return this; }
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "degrees") public JAXBElement<DegreesType> createDegrees(DegreesType value) { return new JAXBElement<DegreesType>(_Degrees_QNAME, DegreesType.class, null, value); }
java
public long unfilledDependencyToLong(UnfilledDependency dep) { long argNum = dep.getArgumentIndex(); long objectNum, objectWordInd, subjectNum, subjectWordInd, subjectSyntaxNum; if (dep.hasObject()) { IndexedPredicate obj = dep.getObject(); objectNum = dependencyHeadType.getValueIndex(obj.getHe...
java
private ImmutableSetMultimap<Class<? extends Annotation>, Element> validElements( ImmutableMap<String, Optional<? extends Element>> deferredElements, RoundEnvironment roundEnv) { ImmutableSetMultimap.Builder<Class<? extends Annotation>, Element> deferredElementsByAnnotationBuilder = ImmutableSet...
python
def bindings(self, queue, virtual_host='/'): """Get Queue bindings. :param str queue: Queue name :param str virtual_host: Virtual host name :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. ...
python
def tuples_to_coll(cls, generator, coerce=False): """*required virtual method* This class method, part of the sub-class API, converts a generator of ``(K, V)`` tuples (the *tuple protocol*) to one of the underlying collection type. """ if cls != Collection: raise exc....
java
public void init(Record record, BaseField fldDeleteFlag, Record recDetail) { m_fldDeleteFlag = fldDeleteFlag; m_recDetail = recDetail; super.init(record); }
java
public BoxFolder.Info restoreFolder(String folderID) { URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID); BoxAPIRequest request = new BoxAPIRequest(this.api, url, "POST"); JsonObject requestJSON = new JsonObject() .add("", ""); request.setBody(r...
python
def save_attributes(self): ''' Saves the attributes without closing the attributes file. This should probably be called after the attribute holder sets/overrides the attributes in initialization as the del method is not guaranteed to be called. ''' if not self.sav...
python
def send_and_return_status(self, send, expect=None, shutit_pexpect_child=None, timeout=None, fail_on_empty_before=True, record_command=True, ...
python
def check_paths(self, paths, update=None): ''' Check if the path is in the os environ, and if not add it Paramters: paths (OrderedDict): An ordered dict containing all of the paths from the a given section, as key:val = name:path update (bool): ...
java
@Override public ServiceRefAmp session(String name) { String address = "session:///" + name + "/"; return sessionImpl(address); }
python
def StreamMetrics(self, request_iterator, context): """Dispatches metrics streamed by collector""" LOG.debug("StreamMetrics called") # set up arguments collect_args = (next(request_iterator)) max_metrics_buffer = 0 max_collect_duration = 0 cfg = Metric(pb=collect...
java
@Override public final V remove(Object key) { long hash, allocIndex; Segment<K, V> segment; V oldValue; if ((allocIndex = (segment = segment(segmentIndex(hash = keyHashCode(key)))) .remove(this, hash, key, null, false)) > 0) { oldValue = segment.readValue(...
python
def get_path_and_qs(self): """ Parse and obtain the path and query values. We don't care about fragments. Return {'path': ..., 'qs_values': ...} on success Return {'error': ...} on error """ path_parts = self.path.split("?", 1) if len(path_parts) > 1: ...
java
public static String notEmpty(String text, String errorMsgTemplate, Object... params) throws IllegalArgumentException { if (StrUtil.isEmpty(text)) { throw new IllegalArgumentException(StrUtil.format(errorMsgTemplate, params)); } return text; }
python
def copy(self): """ Copy constructor for Sequence objects. """ return Sequence(self.name, self.sequenceData, self.start, self.end, self.strand, self.remaining, self.meta_data, self.mutableString)
python
def service_unavailable(cls, errors=None): """Shortcut API for HTTP 503 `Service Unavailable` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.con...
python
def mark_stages(self, start_time, length, stage_name): """Mark stages, only add the new ones. Parameters ---------- start_time : int start time in s of the epoch being scored. length : int duration in s of the epoch being scored. stage_name : str ...
java
@Nullable public static String getAllCharactersAsString (@Nullable @WillClose final Reader aReader) { if (aReader == null) return null; return getCopy (aReader).getAsString (); }
java
public EClass getTileSize() { if (tileSizeEClass == null) { tileSizeEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(395); } return tileSizeEClass; }
python
def get_site_pattern(agent): """Construct a dictionary of Monomer site states from an Agent. This crates the mapping to the associated PySB monomer from an INDRA Agent object.""" if not isinstance(agent, ist.Agent): return {} pattern = {} # Handle bound conditions for bc in agent.bo...
python
def _persist_inplace(self, **kwargs): """ Persist all Dask arrays in memory """ # access .data to coerce everything to numpy or dask arrays lazy_data = {k: v._data for k, v in self.variables.items() if isinstance(v._data, dask_array_type)} if lazy_data: i...
java
public static <T1, T2, T3> TriPredicate<T1, T2, T3> spy2nd(TriPredicate<T1, T2, T3> predicate, Box<T2> param2) { return spy(predicate, Box.<Boolean>empty(), Box.<T1>empty(), param2, Box.<T3>empty()); }
java
@Override public List<TargetUsageItem> findUsageStatistics( String targetId ) { // Get usage first List<String> appNames; synchronized( LOCK ) { appNames = applicationsThatUse( targetId ); } // Now, let's build the result Set<TargetUsageItem> result = new HashSet<> (); for( Map.Entry<InstanceContext...
python
def make_eps(asset_array, num_samples, seed, correlation): """ :param asset_array: an array of assets :param int num_samples: the number of ruptures :param int seed: a random seed :param float correlation: the correlation coefficient :returns: epsilons matrix of shape (num_assets, num_samples) ...
java
public RouteResponse withResponseModels(java.util.Map<String, String> responseModels) { setResponseModels(responseModels); return this; }
python
def get_output_sensors(self): """ Build the output using lm_sensors. Requires sensors Python module (see docs). """ data = dict() found_sensors = get_sensors() if len(found_sensors) == 0: raise Exception("No sensors detected! " "Ens...
java
public static RoleCreator creator(final String pathServiceSid, final String friendlyName, final Role.RoleType type, final List<String> permission) { return new RoleCreator(pathServiceSid, friendl...
python
def cli(env): """Get price options to create a load balancer with.""" mgr = SoftLayer.LoadBalancerManager(env.client) table = formatting.Table(['price_id', 'capacity', 'description', 'price']) table.sortby = 'price' table.align['price'] = 'r' table.align['capacity'] = 'r' table.align['id'...
java
public synchronized String getAttribute(String key, String defaultValue) { if(attributes.containsKey(key)) { return attributes.get(key).toString(); } return defaultValue; }
java
public Observable<ServiceResponse<ImageAnalysis>> analyzeImageWithServiceResponseAsync(String url, AnalyzeImageOptionalParameter analyzeImageOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null....
python
def download_list(user=None, pwd=None, limit=20, offset=0): """ Lists the downloads created by a user. :param user: [str] A user name, look at env var ``GBIF_USER`` first :param pwd: [str] Your password, look at env var ``GBIF_PWD`` first :param limit: [int] Number of records to return. Default: ``...
python
def on_rule(self, *args): """Make sure to update when the rule changes""" if self.rule is None: return self.rule.connect(self._listen_to_rule)
python
def _get_script(self): """Returns fixed commands script. If `settings.repeat` is `True`, appends command with second attempt of running fuck in case fixed command fails again. """ if settings.repeat: repeat_fuck = '{} --repeat {}--force-command {}'.format( ...
java
protected boolean isLeftmostNode() { @SuppressWarnings("unchecked") K node = (K) this; while (node != null) { K parent = node.getParent(); if (parent != null && parent.leftChild != node) return false; node = parent; } return tru...
python
def indent(txt, spacing=4): """ Indent given text using custom spacing, default is set to 4. """ return prefix(str(txt), ''.join([' ' for _ in range(spacing)]))
java
public static String hexDump(byte[] array, int offset, int length) { if (length < 0) { throw new IllegalArgumentException("length: " + length); } if (length == 0) { return EMPTY_STRING; } int endIndex = offset + length; ...
java
public void setAsynchConsumer(AsynchConsumerCallback consumer, int maxActiveMessages, long messageLockExpiry, int maxBatchSize, OrderingContext orderContext, ...
java
public DrawerView clearProfiles() { for (DrawerProfile profile : mProfileAdapter.getItems()) { profile.detach(); } mProfileAdapter.clear(); updateProfile(); return this; }
java
private static List<String> splitAndEncodeParams(URL url) { if (url.getQuery() == null) { return new ArrayList<>(); } String[] params = url.getQuery().split("&"); List<String> result = new ArrayList<>(params.length); for (String p : params) { String[] kv = p.split("="); kv[0] = PercentEncoding.decode...
java
public final T[] toArray(final Class<T> elementClass) { return Iterables.toArray(toCollection(Lists.<T>newArrayListWithCapacity(256)), elementClass); }
java
public V get(Object key) { TreeMapEntry<K,V> p = getEntry(key); return (p==null ? null : p.value); }
python
def format_index(df): """Create a datetime index from day of year, and time columns. Parameters ---------- df: pd.Dataframe The srml data to reindex. Returns ------- df: pd.Dataframe The Dataframe with a DatetimeIndex localized to 'Etc/GMT+8'. """ # Name of the seco...
java
public static dbuser[] get(nitro_service service, dbuser_args args) throws Exception{ dbuser obj = new dbuser(); options option = new options(); option.set_args(nitro_util.object_to_string_withoutquotes(args)); dbuser[] response = (dbuser[])obj.get_resources(service, option); return response; }
java
public void drawEmphasizedText(Graphics g, Color foreground, Color emphasis, String s, int x, int y) { drawEmphasizedText(g, foreground, emphasis, s, -1, x, y); }
java
public void addColumn(ColumnSchema column) { String name = column.getName().name; if (findColumn(name) >= 0) { throw Error.error(ErrorCode.X_42504, name); } if (column.isIdentity()) { if (identityColumn != -1) { throw Error.error(ErrorCode.X_425...
python
def education(self): """ A list of structures describing the user's education history. Each structure has attributes ``school``, ``year``, ``concentration`` and ``type``. ``school``, ``year`` reference ``Page`` instances, while ``concentration`` is a list of ``Page`` instances....