language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Nullable public static Long parseLongObj (@Nullable final String sStr, @Nonnegative final int nRadix, @Nullable final Long aDefault) { if (sStr != null && sStr.length () > 0) try { return Long.valueOf (sStr, nRadix); ...
python
def the_context(self, content, silent_build=False): """Return either a file with the content written to it, or a whole new context tar""" if isinstance(content, six.string_types): with a_temp_file() as fle: fle.write(content.encode('utf-8')) fle.seek(0) ...
java
@Pure public static Point2d L1_L4(double x, double y) { final Point2d ntfLambdaPhi = NTFLambert_NTFLambdaPhi(x, y, LAMBERT_1_N, LAMBERT_1_C, LAMBERT_1_XS, LAMBERT_1_YS); return NTFLambdaPhi_NTFLambert( ntfLambdaPhi.getX(), ntfLambdaPhi.getY(), LAMBERT_4_N, LAMBERT_4_C, LAMBERT_4_XS,...
java
public PointSeries addNumberPoint(final Number y) { Point point = new Point(y); addPoint(point); return this; }
java
public void offer(final byte[] request, final HttpException e) { if (!e.isClientError()) { resendQueue.offer(new HttpResendQueueItem(request)); } }
java
private static int[] string2Ints(String st, int target_length) { int[] numbers = new int[target_length]; int st_len = st.length(); char ch; for (int i = 0; i < st_len; i++) { ch = st.charAt(i); numbers[target_length - st_len + i] = ch - '0'; } re...
java
protected int getLastPropertySeparatorIndex(String propertyPath) { boolean inKey = false; for (int i = propertyPath.length() - 1; i >= 0; i--) { switch (propertyPath.charAt(i)) { case PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR: inKey = true; break; case PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR: ...
python
def equivalentClass(self, *others): """ as implemented this acts as a permenant bag union operator and therefore should be used with extreme caution since in any given context the computed label/identifier will no longer reflect the entailed/reasoned bag In a sta...
java
public Observable<CheckSkuAvailabilityResultListInner> listAsync(String location, List<SkuName> skus, Kind kind, String type) { return listWithServiceResponseAsync(location, skus, kind, type).map(new Func1<ServiceResponse<CheckSkuAvailabilityResultListInner>, CheckSkuAvailabilityResultListInner>() { ...
python
def write_file(infile: str, outfile: str, progress_callback: Callable[[float], None], chunk_size: int = 1024, file_size: int = None): """ Write a file to another file with progress callbacks. :param infile: The input filepath :param outfile: The o...
python
def confusion_performance(mat, fn): """Apply a performance function to a confusion matrix :param mat: confusion matrix :type mat: square matrix :param function fn: performance function """ if mat.shape[0] != mat.shape[1] or mat.shape < (2, 2): raise TypeError('{} is not a confusion ...
python
def topsort(graph): """ For the given graph, returns a list of nodes in topological order In py3 the behaviour of this function differs from py2, the resulting order will change with every execution in py3 while in py2 the order stays the same :param graph: :return: """ count = defa...
java
public Iterator<InternalFactHandle> iterateFactHandles(org.kie.api.runtime.ObjectFilter filter) { return getObjectStore().iterateFactHandles(filter); }
java
public static Map<MediaType, QualityValue> getMediaTypeQualityValues(String header) { if (header == null) return null; header = header.trim(); if (header.length() == 0) return null; Map<MediaType, QualityValue> result = new LinkedHashMap<MediaType, QualityValue>(); in...
java
@SuppressWarnings("rawtypes") private static Object createIntermediate(JsonNode node, StringBuffer pathSofar, String index, String nextIndex) { if (node instanceof POJONode) { return createIntermediate(extractValue((POJONode) node), pathSofar, index, nextIndex); } if ...
java
public Object[][] getContents() { return new Object[][] { /** Error message ID that has a null message, but takes in a single object. */ {"ER0000" , "{0}" }, { ER_NO_CURLYBRACE, "Error: Can not have '{' within expression"}, { ER_ILLEGAL_ATTRIBUTE , "{0} ha...
java
public static String toStringHadoopFileSplit(FileSplit fs) { StringBuilder sb = new StringBuilder(); sb.append("HadoopFileSplit: Path: ").append(fs.getPath()); sb.append(" , Start: ").append(fs.getStart()); sb.append(" , Length: ").append(fs.getLength()); sb.append(" , Hosts: "); String[] locs; ...
java
public static <T extends MethodDescription> ElementMatcher.Junction<T> isSetter() { return nameStartsWith("set").and(takesArguments(1)).and(returns(TypeDescription.VOID)); }
python
def records(self): """ Yield BLAST records, as read by the BioPython NCBIXML.parse method. Set self.params from data in the first record. """ first = True with as_handle(self._filename) as fp: for record in NCBIXML.parse(fp): if first: ...
java
@Override public boolean subscribeChange(ClientIdentity identity) { if (StringUtils.isNotEmpty(identity.getFilter())) { logger.info("subscribe filter change to " + identity.getFilter()); AviaterRegexFilter aviaterFilter = new AviaterRegexFilter(identity.getFilter()); boo...
java
public SessionLockManager getSessionLockManager(String sessionId, SessionDataManager transientManager) { CacheableSessionLockManager sessionManager = new CacheableSessionLockManager(sessionId, this, transientManager); sessionLockManagers.put(sessionId, sessionManager); return sessionManager; }
java
public static int maxCount(final Multiset<?> multiset) { int ret = 0; for (final Multiset.Entry<?> entry : multiset.entrySet()) { if (entry.getCount() > ret) { ret = entry.getCount(); } } return ret; }
python
def _list_records(self, rtype=None, name=None, content=None): """List all record for the domain in the active Gandi zone.""" if self.protocol == 'rpc': return self.rpc_helper.list_records(rtype, name, content) try: if name is not None: if rtype is not Non...
python
def has_better_coverage(self): """ Return `True` if coverage of has improved, `False` otherwise. This does not ensure that all changes have been covered. If this is what you want, use `CoberturaDiff.has_all_changes_covered()` instead. """ for filename in self.files(): ...
java
public void marshalling(Xdr xdr) { super.marshalling(xdr); xdr.putString(_name); xdr.putInt(_createMode.getValue()); if (_createMode != NfsCreateMode.EXCLUSIVE) { _attributes.marshalling(xdr); } else { xdr.putByteArray(_verifier); } }
python
def smash(self): """ Smash the given stack Args: None Returns: True if True Todo: Figure out what could go wrong and take steps to hanlde problems. """ self._initialize_smash() try: stack_name ...
java
public void setProjectProperties(final Properties properties) { generateProjectPropertiesFile(getName(), propertyFile, true, properties, false, null, false); loadProperties(); }
java
void adjustLeft(float newValue) { Object[] o = (Object[])attributes.get(Chunk.TAB); if (o != null) { attributes.put(Chunk.TAB, new Object[]{o[0], o[1], o[2], new Float(newValue)}); } }
java
public synchronized String getOrg(long ipnum) { try { int seekOrg = seekCountry(ipnum); return readOrgRecord(seekOrg); } catch (IOException e) { throw new InvalidDatabaseException("Error while reading org", e); } }
java
@SuppressWarnings("unchecked") public static <T extends Config> T get(Object key) { return (T) CACHE.get(key); }
java
public String getMessageWithoutCheckName() { return linkUrl != null ? String.format("%s\n%s", rawMessage, linkTextForDiagnostic(linkUrl)) : String.format("%s", rawMessage); }
java
protected void addViolation(ClassNode node, String message) { addViolation((ASTNode) node, String.format( "Violation in class %s. %s", node.getNameWithoutPackage(), message )); }
java
public static Value fecho(Value fval, Value tval, Value dval) { return IO.fecho(fval, tval, dval); }
java
SoyJsSrcOptions toJsSrcOptions() { SoyJsSrcOptions jsSrcOptions = new SoyJsSrcOptions(); // Only goog.module generation supported jsSrcOptions.setShouldGenerateGoogModules(true); jsSrcOptions.setShouldGenerateGoogMsgDefs(true); jsSrcOptions.setGoogMsgsAreExternal(true); jsSrcOptions.setBidiGloba...
python
def make_dict(fields, fields_kwargs): """lot's of methods take a dict or kwargs, this combines those Basically, we do a lot of def method(fields, **kwargs) and we want to merge those into one super dict with kwargs taking precedence, this does that fields -- dict -- a passed in dict fields_kwargs ...
python
def get_currentDim(self): ''' returns the current dimensions of the object ''' selfDim = self._dimensions.copy() if not isinstance(selfDim,dimStr): if selfDim.has_key('_ndims') : nself = selfDim.pop('_ndims') else : self.warning(1,...
java
public void setYocUnits(Integer newYocUnits) { Integer oldYocUnits = yocUnits; yocUnits = newYocUnits; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.CDD__YOC_UNITS, oldYocUnits, yocUnits)); }
java
public IAtom getUnplacedRingHeavyAtom(IAtomContainer molecule, IAtom atom) { List<IBond> bonds = molecule.getConnectedBondsList(atom); IAtom connectedAtom = null; for (IBond bond : bonds) { connectedAtom = bond.getOther(atom); if (isUnplacedHeavyAtom(connectedAtom) && con...
python
async def get_subscription(self, name, root): """ Retrieve the data associated with a named subscription Returns None if there is no data associated with `name` If root is not None, then only return the subscription data that matches both root and name. When used in this way, ...
python
def parent_after_fork_release(): """ Call all parent after fork callables, release the lock and print all prepare and parent callback exceptions. """ prepare_exceptions = list(_prepare_call_exceptions) del _prepare_call_exceptions[:] exceptions = _call_atfork_list(_parent_call_list) _for...
python
def save_state_machine_to_path(state_machine, base_path, delete_old_state_machine=False, as_copy=False): """Saves a state machine recursively to the file system The `as_copy` flag determines whether the state machine is saved as copy. If so (`as_copy=True`), some state machine attributes will be left untou...
python
def get_2mass_epoch (tmra, tmdec, debug=False): """Given a 2MASS position, look up the epoch when it was observed. This function uses the CDS Vizier web service to look up information in the 2MASS point source database. Arguments are: tmra The source's J2000 right ascension, in radians. tmde...
java
public <R> R wrapClassLoader(Supplier<R> supplier) { try (TemporaryClassLoaderContext tmpCl = new TemporaryClassLoaderContext(classLoader)){ return supplier.get(); } }
java
public ServiceFuture<String> generatevpnclientpackageAsync(String resourceGroupName, String virtualNetworkGatewayName, VpnClientParameters parameters, final ServiceCallback<String> serviceCallback) { return ServiceFuture.fromResponse(generatevpnclientpackageWithServiceResponseAsync(resourceGroupName, virtualNet...
java
public static CPDefinitionOptionRel fetchByUuid_Last(String uuid, OrderByComparator<CPDefinitionOptionRel> orderByComparator) { return getPersistence().fetchByUuid_Last(uuid, orderByComparator); }
python
def robust_rmtree(path, logger=None, max_retries=10): """Robustly tries to delete paths. Retries several times (with increasing delays) if an OSError occurs. If the final attempt fails, the Exception is propagated to the caller. """ for i in range(max_retries): try: shutil....
python
def sort_references_dict(refs): """Sorts a reference dictionary into a standard order The keys of the references are also sorted, and the keys for the data for each reference are put in a more canonical order. """ if _use_odict: refs_sorted = OrderedDict() else: refs_sorted = d...
python
def run(cmd, outdir=None, logfile=None, inlist=None, void=True, errorpass=False, env=None): """ | wrapper for subprocess execution including logfile writing and command prompt piping | this is a convenience wrapper around the :mod:`subprocess` module and calls its class :class:`~subprocess.Popen` inte...
python
def save(filepath, obj, on_overwrite = 'ignore'): """ Serialize `object` to a file denoted by `filepath`. Parameters ---------- filepath : str A filename. If the suffix is `.joblib` and joblib can be imported, `joblib.dump` is used in place of the regular pickling mechanisms...
java
public void invoke(StartupLifecycle lifecycle) { this.initializeAsciiLogo(); this.printLogo(); lifecycle.willInitialize(); this.logInitializationStart(); lifecycle.willCreateSpringContext(); this.initializeApplicationContext(); lifecycle.didCreateSpringContext(...
python
def type(self): """ Returns the shape of the data array associated with this file.""" hdu = self.open() _type = hdu.data.dtype.name if not self.inmemory: self.close() del hdu return _type
java
public ServiceFuture<PoolStatistics> getAllLifetimeStatisticsAsync(final ServiceCallback<PoolStatistics> serviceCallback) { return ServiceFuture.fromHeaderResponse(getAllLifetimeStatisticsWithServiceResponseAsync(), serviceCallback); }
java
public void delete(String name) throws IOException { if (name.equalsIgnoreCase(DATE)) { date = null; } else { throw new IOException ("Name not supported by InvalidityDateExtension"); } encodeThis(); }
python
def append(self, value): """Append a new value to the end of the array.""" self.database.run_script( 'array_append', keys=[self.key], args=[value])
java
public static Kernel2D_S32 random2D_I32(int width , int offset, int min, int max, Random rand) { Kernel2D_S32 ret = new Kernel2D_S32(width,offset); int range = max - min; for (int i = 0; i < ret.data.length; i++) { ret.data[i] = rand.nextInt(range) + min; } return ret; }
python
def _parse_on_demand_syllabus(self, course_name, page, reverse=False, unrestricted_filenames=False, subtitle_language='en', video_resolution=None, download_quizzes=False, ...
java
RunListener wrapIfNotThreadSafe(RunListener listener) { return listener.getClass().isAnnotationPresent(RunListener.ThreadSafe.class) ? listener : new SynchronizedRunListener(listener, this); }
python
def prop2qid(self, prop, value): """ Lookup the local item QID for a Wikidata item that has a certain `prop` -> `value` in the case where the local item has a `equivalent item` statement to that wikidata item Example: In my wikibase, I have CDK2 (Q79363) with the only statement: ...
python
def _get_local_dict(self): """Retrieve (or initialize) the thread-local data to use.""" try: return getattr(THREAD_STORE, self.namespace) except AttributeError: local_var = dict(*self.args, **self.kwargs) setattr(THREAD_STORE, self.namespace, local_var) ...
java
void unregisterNodeType( Collection<Name> nodeTypeNames, boolean failIfNodeTypesAreUsed ) throws NoSuchNodeTypeException, InvalidNodeTypeDefinitionException, RepositoryException { CheckArg.isNotNull(nodeTypeNames, "nodeTypeNames"); if (nodeTypeNames.isEmpty()) return...
java
public OptionsPostResponseStatusSuccess optionsPost(OptionsPost body) throws ApiException { ApiResponse<OptionsPostResponseStatusSuccess> resp = optionsPostWithHttpInfo(body); return resp.getData(); }
python
def requires_auth(f): """ Class decorator for XML-RPC functions that requires auth """ @wraps(f) def decorated(self, *args, **kwargs): """ """ # Fetch auth options from args auth_options = {} nipap_args = {} # validate function arguments if len(...
java
public static Group groupsCreate(String access_token,String name){ String groupJson = String.format("{\"group\":{\"name\":\"%1$s\"}}",name); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(jsonHeader) .setUri(BASE_URI+"/cgi-bin/groups/create") .addParameter(PARAM_ACCES...
java
@Override public RegisterWebhookWithThirdPartyResult registerWebhookWithThirdParty(RegisterWebhookWithThirdPartyRequest request) { request = beforeClientExecution(request); return executeRegisterWebhookWithThirdParty(request); }
java
public static AppLinkData createFromActivity(Activity activity) { Validate.notNull(activity, "activity"); Intent intent = activity.getIntent(); if (intent == null) { return null; } AppLinkData appLinkData = createFromAlApplinkData(intent); if (appLinkData == ...
python
def get_public_cms_page_urls(*, language_code): """ :param language_code: e.g.: "en" or "de" :return: Tuple with all public urls in the given language """ pages = Page.objects.public() urls = [page.get_absolute_url(language=language_code) for page in pages] urls.sort() return tuple(urls)
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AfplibPackage.MFC__MFC_FLGS: return getMFCFlgs(); case AfplibPackage.MFC__MED_COLL: return getMedColl(); case AfplibPackage.MFC__MFC_SCPE: return getMFCScpe(); case AfplibPackage.MFC__TR...
python
def from_unit_cube(self, x): """ Used by multinest :param x: 0 < x < 1 :param lower_bound: :param upper_bound: :return: """ cosdec_min = np.cos(deg2rad*(90.0 + self.lower_bound.value)) cosdec_max = np.cos(deg2rad*(90.0 + self.upper_bound.value)) ...
java
@Override public void fullRedraw() { if(!(getWidth() > 0 && getHeight() > 0)) { LoggingUtil.warning("Thumbnail of zero size requested: " + visFactory); return; } if(thumbid < 0) { // LoggingUtil.warning("Generating new thumbnail " + this); layer.appendChild(SVGUtil.svgWaitIcon(plot...
python
def security_rule_create_or_update(name, access, direction, priority, protocol, security_group, resource_group, source_address_prefix=None, destination_address_prefix=None, source_port_range=None, destination_port_range=None, source_address_prefixes=...
python
def on_drag_event(self, event): '''handle mouse drags''' state = self.state if not state.can_drag: return newpos = self.image_coordinates(event.GetPosition()) dx = -(newpos.x - self.mouse_down.x) dy = -(newpos.y - self.mouse_down.y) self.dragpos = wx.P...
python
def _import_module(self, s): """ Import a module. """ mod = __import__(s) parts = s.split('.') for part in parts[1:]: mod = getattr(mod, part) return mod
java
public static DenseMatrix block(Matrix a, Matrix b, Matrix c, Matrix d) { return Basic2DMatrix.block(a, b, c, d); }
java
public List<Integer> getAllContinentRegionID(int continentID, int floorID) throws GuildWars2Exception { try { Response<List<Integer>> response = gw2API.getAllContinentRegionIDs(Integer.toString(continentID), Integer.toString(floorID)).execute(); if (!response.isSuccessful()) throwError(response.code(), res...
java
public void setFeature(final String uri, final boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { reader.setFeature(uri, value); }
java
protected DbColumnType toPdbType(final int type, final String typeName) { switch (type) { case Types.BIT: case Types.BOOLEAN: return DbColumnType.BOOLEAN; case Types.CHAR: case Types.LONGNVARCHAR: case Types.LONGVARCHAR: ca...
python
def main(global_settings, **settings): """Entrypoint for WSGI app.""" my_session_factory = SignedCookieSessionFactory('itsaseekreet') # Add session engine config = Configurator( settings=settings, session_factory=my_session_factory ) # Add static and templates config.add_stat...
java
public void close() { try { if (conn != null) { conn.close(); } } catch (IOException ignored) { } if (zkClient != null) { zkClient.stopAndWait(); } }
java
@Override public final void createCatalog(ClusterName targetCluster, CatalogMetadata catalogMetadata) throws ExecutionException, UnsupportedException { try { connectionHandler.startJob(targetCluster.getName()); if (logger.isDebugEnabled()) { logger.debug...
java
public void open() { if (!open) { super.open(); writer.open(); rootOutline = new PdfOutline(writer); currentOutline = rootOutline; } try { initPage(); } catch(DocumentException de) { throw new ExceptionConver...
java
public static String getMapFieldType(Field field) { String k = getMapFieldKeyType(field); String v = getMapFieldValueType(field); return "java.util.Map<" + k + ", " + v + ">"; }
java
@Override public Subject authenticate(String username, @Sensitive String password) throws AuthenticationException { AuthenticationData authenticationData = createAuthenticationData(username, password); return authenticationService.authenticate(jaasEntryName, authenticationData, null); }
java
private NumberFormat getNumberFormat(Locale locale) { if (pattern == null && type == null) { throw new IllegalArgumentException("Either pattern or type must" + " be specified."); } // PENDING(craigmcc) - Implement pooling if needed for performance? // If p...
python
def _format_regular_value(self, str_in): # type: (Text) -> Text """ we need to reformat integer strings, as there can be different strings for the same integer. The strategy of unification here is to first parse the integer string to an Integer type. Thus all of ...
java
@Override public void onConnect(final int rst, final HuaweiApiClient client) { //需要在子线程中执行获取push状态的操作 ThreadUtil.INST.excute(new Runnable() { @Override public void run() { if (client == null || !ApiClientMgr.INST.isConnect(client)) { ...
python
def get_changed_files_from(old_commit_sha, new_commit_sha): """ Returns a list of the files changed between two commits """ return check_output( "git diff-tree --no-commit-id --name-only -r {0}..{1}".format( old_commit_sha, new_commit_sha ...
java
@Override public DescribeGlobalClustersResult describeGlobalClusters(DescribeGlobalClustersRequest request) { request = beforeClientExecution(request); return executeDescribeGlobalClusters(request); }
java
public static BufferedReader getReader(Path path, Charset charset) throws IORuntimeException { return IoUtil.getReader(getInputStream(path), charset); }
java
public void extendedPut(String remoteFileName, DataSource source, MarkerListener mListener) throws IOException, ServerException, ClientException{ extendedPut(remoteFileName, 0, s...
python
def extract_audioclip_samples(d) -> dict: """ Extract all the sample data from an AudioClip and convert it from FSB5 if needed. """ ret = {} if not d.data: # eg. StreamedResource not available return {} try: from fsb5 import FSB5 except ImportError as e: raise RuntimeError("python-fsb5 is required to ...
java
public void setCursorPos(int pos) { cursorPos = pos; if (cursorPos > value.length()) { cursorPos = value.length(); } }
java
public static Object getRequestBody(PageContext pc, boolean deserialized, Object defaultValue) { HttpServletRequest req = pc.getHttpServletRequest(); MimeType contentType = getContentType(pc); String strContentType = contentType == MimeType.ALL ? null : contentType.toString(); Charset cs = getCharacterEncoding(pc...
python
def check_consistent_parameter_grouping(self): """ Ensures this object does not have conflicting groups of parameters. :raises ValueError: For conflicting or absent parameters. """ parameter_groups = {} if self.indices_per_axis is not None: parameter_groups["...
java
private boolean isFacebookAppInstalled() { boolean isInstalled = false; try { // An exception will be thrown if the package is not found. mContext.getPackageManager().getApplicationInfo(FACEBOOK_APP_PACKAGE, 0); isInstalled = true; } catch (PackageManager.Name...
java
public void setData(List<ImageItem> images) { selectedImages.clear(); if (images != null && images.size() > 0) { this.images = images; } else { this.images.clear(); } notifyDataSetChanged(); }
java
public Module loadModule(String l) { Module m = Module.load(l); modules.put(m.name(), m); return m; }
java
protected static void internalAlarmHandler(Object arg) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "internalAlarmHandler", arg); ResendRecord record = (ResendRecord) arg; synchronized (_requestMap) { Long key = new Long(record.requestID); ...
python
def get_user_password (self, url): """Get tuple (user, password) from configured authentication that matches the given URL. Both user and password can be None if not specified, or no authentication matches the given URL. """ for auth in self["authentication"]: ...
java
public ModifierAdjustment withConstructorModifiers(ElementMatcher<? super MethodDescription> matcher, List<? extends ModifierContributor.ForMethod> modifierContributors) { return withInvokableModifiers(isConstructor().and(matcher), modifierContributors); ...
java
public static void assertNoCheckedExceptionsAreThrown(final Method method, Class<? extends Annotation> annotation) { Class<?>[] declaredExceptions = method.getExceptionTypes(); for (int i = 0; i < declaredExceptions.length; i++) { Class<?> exception = declaredExceptions[i]; if (!...