language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@NotNull static MetaTreeImpl.Proto saveMetaTree(@NotNull final ITreeMutable metaTree, @NotNull final EnvironmentImpl env, @NotNull final ExpiredLoggableCollection expired) { final long newMetaTreeAddress = metaTree.save();...
java
public <T> V fetch(K key, Functor<V, T> functor, T argument) throws Exception { return locate(key).get(functor, argument); }
python
def open(cls, filename, band_names=None, lazy_load=True, mutable=False, **kwargs): """ Read a georaster from a file. :param filename: url :param band_names: list of strings, or string. if None - will try to read from image, otherwise - these will be ['0', ..]...
java
public static String weightingToFileName(Weighting w, boolean edgeBased) { return toLowerCase(w.toString()).replaceAll("\\|", "_") + (edgeBased ? "_edge" : "_node"); }
java
private static byte[] extract(byte[] salt, byte[] inputKeyingMaterial) { return initHmacSha256(salt == null ? NULL_SALT : salt).doFinal(inputKeyingMaterial); }
python
def _get_gcloud_records(self, gcloud_zone, page_token=None): """ Generator function which yields ResourceRecordSet for the managed gcloud zone, until there are no more records to pull. :param gcloud_zone: zone to pull records from :type gcloud_zone: google.cloud.dns.ManagedZ...
java
private void updateAperture(int newValue, long now) { int previous = targetAperture; targetAperture = newValue; targetAperture = Math.max(minAperture, targetAperture); int maxAperture = Math.min(this.maxAperture, activeSockets.size() + pool.poolSize()); targetAperture = Math.min(maxAperture, targetA...
java
public SDVariable[] batchMmul(String[] names, SDVariable[] matricesA, SDVariable[] matricesB, boolean transposeA, boolean transposeB) { validateSameType("batchMmul", true, matricesA); validateSameType("batchMmul", true, matricesB); SDVariable[] result = f().batc...
java
private String toTag(String name, Archive source, Analyzer.Type type) { if (!isJDKArchive(source)) { return source.getName(); } JDKArchive jdk = (JDKArchive)source; boolean isExported = false; if (type == CLASS || type == VERBOSE) { isExported = jdk.isExp...
java
public ValidDBInstanceModificationsMessage withValidProcessorFeatures(AvailableProcessorFeature... validProcessorFeatures) { if (this.validProcessorFeatures == null) { setValidProcessorFeatures(new com.amazonaws.internal.SdkInternalList<AvailableProcessorFeature>(validProcessorFeatures.length)); ...
python
def libvlc_media_player_has_vout(p_mi): '''How many video outputs does this media player have? @param p_mi: the media player. @return: the number of video outputs. ''' f = _Cfunctions.get('libvlc_media_player_has_vout', None) or \ _Cfunction('libvlc_media_player_has_vout', ((1,),), None, ...
java
@Override public void start(BundleContext context) throws Exception { this.bundleContext = context; this.bundle = context.getBundle(); try { // check if another version of the bundle exists long myId = this.bundle.getBundleId(); String myName = this.bundl...
python
def handle_resource_not_found(resource): """ Set resource state to ERRED and append/create "not found" error message. """ resource.set_erred() resource.runtime_state = '' message = 'Does not exist at backend.' if message not in resource.error_message: if not resource.error_message: ...
java
public static String generateExactMatchPattern(URI origin, URI destination, String bindingVar, boolean includeUrisBound) { List<String> patterns = new ArrayList<String>(); // Exact match pattern StringBuffer query = new StringBuffer(); ...
java
private Mapper createMapper(Class<?> clazz) { Mapper mapper; if (Enum.class.isAssignableFrom(clazz)) { mapper = new EnumMapper(clazz); } else if (Map.class.isAssignableFrom(clazz)) { mapper = new MapMapper(clazz); } else if (clazz.isAnnotationPresent(Embeddable.class)) { mapper = new E...
java
public boolean recordDeprecationReason(String reason) { if (currentInfo.setDeprecationReason(reason)) { populated = true; return true; } else { return false; } }
python
def _queue_declare_ok(self, args): """ confirms a queue definition This method confirms a Declare method and confirms the name of the queue, essential for automatically-named queues. PARAMETERS: queue: shortstr Reports the name of the queue. If the ...
java
public Coding addAdditionalMaterial() { //3 Coding t = new Coding(); if (this.additionalMaterial == null) this.additionalMaterial = new ArrayList<Coding>(); this.additionalMaterial.add(t); return t; }
python
def kill_all(self, kill_signal, kill_shell=False): """Kill all running processes.""" for key in self.processes.keys(): self.kill_process(key, kill_signal, kill_shell)
python
def sub_working_days(self, day, delta, extra_working_days=None, extra_holidays=None, keep_datetime=False): """ Substract `delta` working days to the date. This method is a shortcut / helper. Users may want to use either:: cal.add_wo...
python
def prune(t): """Returns the currently defining instance of t. As a side effect, collapses the list of type instances. The function Prune is used whenever a type expression has to be inspected: it will always return a type expression which is either an uninstantiated type variable or a type operato...
java
public static boolean deleteOrDie(@Nonnull final String file) throws IOException { // this returns true if the file was actually deleted // and false for 2 cases: // 1. file did not exist to start with // 2. File.delete() failed at some point for some reason // so we dis...
python
def create_307_response(self): """ Creates a 307 "Temporary Redirect" response including a HTTP Warning header with code 299 that contains the user message received during processing the request. """ request = get_current_request() msg_mb = UserMessageMember(self....
python
def options(self, context, module_options): ''' PATH Path to dll/exe to inject PROCID Process ID to inject into (default: current powershell process) EXEARGS Arguments to pass to the executable being reflectively loaded (default: None) ''' if not 'PATH...
python
def format_atomic(value): """Format atomic value This function also takes care of escaping the value in case one of the reserved characters occurs in the value. """ # Perform escaping if isinstance(value, str): if any(r in value for r in record.RESERVED_CHARS): for k, v in r...
python
def extract_data(self): """Extracts data from archive. Returns: PackageData object containing the extracted data. """ data = PackageData( local_file=self.local_file, name=self.name, pkg_name=self.rpm_name or self.name_convertor.rpm_name( ...
java
public static void hexToBits(String s, BitSet ba, int length) { byte[] b = hexToBytes(s); bytesToBits(b, ba, length); }
java
private void processCachedTimerDataSettings(BeanMetaData bmd) { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) { Tr.entry(tc, "processCachedTimerDataSettings " + AllowCachedTimerDataFor); } //F001419: start if (A...
java
public void setEveryWorkingDay(final boolean isEveryWorkingDay) { if (m_model.isEveryWorkingDay() != isEveryWorkingDay) { removeExceptionsOnChange(new Command() { public void execute() { m_model.setEveryWorkingDay(Boolean.valueOf(isEveryWorkingDay)); ...
python
def update_function(self, function_name, # type: str zip_contents, # type: str environment_variables=None, # type: StrMap runtime=None, # type: OptStr tags...
java
public final void mT__96() throws RecognitionException { try { int _type = T__96; int _channel = DEFAULT_TOKEN_CHANNEL; // BELScript.g:83:7: ( 'substitution' ) // BELScript.g:83:9: 'substitution' { match("substitution"); } ...
python
def _get_aliases(self): u"""Creates a dict with aliases. The key is a normalized tagname, value the original tagname. """ if self._aliases is None: self._aliases = {} if self._xml is not None: for child in self._xml.iterchildren(): ...
java
public String getFamilyName() { if (DocumentSpecies_Type.featOkTst && ((DocumentSpecies_Type)jcasType).casFeat_familyName == null) jcasType.jcas.throwFeatMissing("familyName", "ch.epfl.bbp.uima.types.DocumentSpecies"); return jcasType.ll_cas.ll_getStringValue(addr, ((DocumentSpecies_Type)jcasType).casFeat...
python
def factor_for_trace(ls: HilbertSpace, op: Operator) -> Operator: r'''Given a :class:`.LocalSpace` `ls` to take the partial trace over and an operator `op`, factor the trace such that operators acting on disjoint degrees of freedom are pulled out of the trace. If the operator acts trivially on ls the tr...
java
public TableInformation getRealTableInformation(final Connection _con, final String _tableName) throws SQLException { final TableInformation tableInfo = new TableInformation(_tableName.toUpperCase()); final Map<String, TableInformation> ta...
python
def contains_pyversion(marker): """Check whether a marker contains a python_version operand. """ if not marker: return False marker = _ensure_marker(marker) return _markers_contains_pyversion(marker._markers)
python
def _update_info(self): """ Update metadata for this HDU """ try: self._FITS.movabs_hdu(self._ext+1) except IOError: raise RuntimeError("no such hdu") self._info = self._FITS.get_hdu_info(self._ext+1)
java
public SightPublish setPublishStatus(long sightId, SightPublish sightPublish) throws SmartsheetException { Util.throwIfNull(sightPublish); return this.updateResource("sights/" + sightId + "/publish", SightPublish.class, sightPublish); }
java
public static void process(CharSequence html, OutputStream output) { new TableToXls().doProcess( html instanceof String ? (String) html : html.toString(), output); }
python
def safe_str(value): """ Returns: * a `str` instance (bytes) in Python 2.x, or * a `str` instance (Unicode) in Python 3.x. """ if sys.version_info < (3,0) and isinstance(value, unicode): return value.encode('utf-8') else: return str(value)
java
public static List<TagEntryAO> tagsMapToTagEntries(Map<String, String> tagsMap) { if (tagsMap==null) return Collections.EMPTY_LIST; List<TagEntryAO> tagEntries = new ArrayList<>(tagsMap.size()); for (Map.Entry<String,String> entry : tagsMap.entrySet()) tagEntries.add( ...
python
def dedent(string, indent_str=' ', max_levels=None): """Revert the effect of indentation. Examples -------- Remove a simple one-level indentation: >>> text = '''<->This is line 1. ... <->Next line. ... <->And another one.''' >>> print(text) <->This is line 1. <->Next line. ...
python
def read_dictionary_file(dictionary_path): """Return all words in dictionary file as set.""" try: return _user_dictionary_cache[dictionary_path] except KeyError: if dictionary_path and os.path.exists(dictionary_path): with open(dictionary_path, "rt") as dict_f: wo...
python
def convertASTtoThreeAddrForm(ast): """Convert an AST to a three address form. Three address form is (op, reg1, reg2, reg3), where reg1 is the destination of the result of the instruction. I suppose this should be called three register form, but three address form is found in compiler theory. ...
python
def get_store_credit_transaction_by_id(cls, store_credit_transaction_id, **kwargs): """Find StoreCreditTransaction Return single instance of StoreCreditTransaction by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async...
python
def get_staking_cutoff(self, round_num=0, tournament=1): """Compute staking cutoff for the given round and tournament. Args: round_num (int, optional): The round you are interested in, defaults to current round. tournament (int, optional): ID of the tournament, d...
python
def find_callback(args, kw=None): 'Return callback whether passed as a last argument or as a keyword' if args and callable(args[-1]): return args[-1], args[:-1] try: return kw['callback'], args except (KeyError, TypeError): return None, args
java
protected PdfIndirectReference copyIndirect(PRIndirectReference in) throws IOException, BadPdfFormatException { PdfIndirectReference theRef; RefKey key = new RefKey(in); IndirectReferences iRef = (IndirectReferences)indirects.get(key); if (iRef != null) { theRef = iRef.getRef...
java
public K findKey (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { K[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != null && valueTable[i] == null) return keyTable[i]; } else if (identity) { for (int i = capaci...
python
def shlex_split(s, **kwargs): ''' Only split if variable is a string ''' if isinstance(s, six.string_types): # On PY2, shlex.split will fail with unicode types if there are # non-ascii characters in the string. So, we need to make sure we # invoke it with a str type, and then dec...
python
def info2dicts(info, in_place=False): """ Return info with: 1) `packages` list replaced by a 'packages' dict indexed by 'project' 2) `releases` list replaced by a 'releases' dict indexed by 'name' """ if 'packages' not in info and 'releases' not in info: return info if in_place: ...
python
def check_url(url): ''' Check if resource at URL is fetchable. (by trying to fetch it and checking for 200 status. Args: url (str): Url to check. Returns: Returns a tuple of {True/False, response code} ''' request = urllib2.Request(url) ...
python
def select_storage_for(cls, section_name, storage): """Selects the data storage for a config section within the :param:`storage`. The primary config section is normally merged into the :param:`storage`. :param section_name: Config section (name) to process. :param storage: ...
java
final void randomizePrefix() { byte[] cb = new byte[preLen]; // Use SecureRandom for prefix only srand.nextBytes(cb); for (int i = 0; i < preLen; i++) { pre[i] = digits[(cb[i] & 0xFF) % base]; } }
java
public void putDefaultClasspathEntriesIn(Collection<IClasspathEntry> classpathEntries) { final IPath newPath = this.jreGroup.getJREContainerPath(); if (newPath != null) { classpathEntries.add(JavaCore.newContainerEntry(newPath)); } else { final IClasspathEntry[] entries = PreferenceConstants.getDefaultJRELi...
java
public Matrix4 setToTransform (IVector3 translation, IQuaternion rotation) { return setToRotation(rotation).setTranslation(translation); }
java
public void process() { try { check(); boolean isReconcilePhase = false; // In the Eclipse IDE's integration between JDT and APT, annotation processors // run in two phases -- reconcile and build. These translate into the // check and ge...
python
def _run(self): # type: (SyncCopy) -> None """Execute SyncCopy :param SyncCopy self: this """ # mark start self._start_time = blobxfer.util.datetime_now() logger.info('blobxfer start time: {0}'.format(self._start_time)) # initialize resume db if specified ...
java
private byte[] alloc() { position = 0; chunk++; if (chunk >= pool.size()) { byte[] bytes = new byte[chunk == 0 ? initialSize : incrementalSize]; pool.add(bytes); } return chunk(); }
java
public synchronized void removeCommandPolling(final CommandImpl command) throws DevFailed { if (commandCacheMap.containsKey(command)) { final CommandCache cache = commandCacheMap.get(command); cache.stopRefresh(); commandCacheMap.remove(command); } else if (extTrigCom...
java
protected Element grabArticle(boolean preserveUnlikelyCandidates) { /** * First, node prepping. Trash nodes that look cruddy (like ones with * the class name "comment", etc), and turn divs into P tags where they * have been used inappropriately (as in, where they contain no other ...
java
public final BaseTable makeTable(Record record) { BaseTable table = this.doMakeTable(record); if (DBConstants.TRUE.equalsIgnoreCase(this.getProperty(DBConstants.BASE_TABLE_ONLY))) return this.returnBaseTable(table); int iRawDBType = (record.getDatabaseType() & DBConstants.T...
python
def absolute_abundance(coverage, total_bases): """ absolute abundance = (number of bases mapped to genome / total number of bases in sample) * 100 """ absolute = {} for genome in coverage: absolute[genome] = [] index = 0 for calc in coverage[genome]: bases = calc[0] total = total_bases[index] absolu...
python
def parse (self, lines): """Parse the input lines from a robot.txt file. We allow that a user-agent: line is not preceded by one or more blank lines. @return: None """ log.debug(LOG_CHECK, "%r parse lines", self.url) state = 0 linenumber = 0 entry...
java
public com.squareup.okhttp.Call getCharactersCharacterIdFwStatsAsync(Integer characterId, String datasource, String ifNoneMatch, String token, final ApiCallback<CharacterFwStatsResponse> callback) throws ApiException { com.squareup.okhttp.Call call = getCharactersCharacterIdFwStatsValidateBeforeCal...
python
def list_feeds(): """List all feeds in plain text and give their aliases""" with Database("feeds") as feeds, Database("aliases") as aliases_db: for feed in feeds: name = feed url = feeds[feed] aliases = [] for k, v in zip(list(aliases_db.keys()), list(alia...
python
def begin(self): """Start a new transaction.""" if self.in_transaction: # we're already in a transaction... if self._auto_transaction: self._auto_transaction = False return self.commit() self.in_transaction = True for collection, s...
python
def done(self, result, noraise=False): """This method is called when a task has finished executing. Subclass can override this method if desired, but should call superclass method at the end. """ # [??] Should this be in a critical section? # Has done() already been call...
java
public String stats(int printPrecision) { StringBuilder sb = new StringBuilder(); //Report: Accuracy, precision, recall, F1. Then: confusion matrix int maxLabelsLength = 15; if (labels != null) { for (String s : labels) { maxLabelsLength = Math.max(s.length...
java
void register(String repoFullName) { lock.writeLock().lock(); try { if (!entityListenersByRepo.containsKey(requireNonNull(repoFullName))) { entityListenersByRepo.put(repoFullName, HashMultimap.create()); } } finally { lock.writeLock().unlock(); } }
java
public void marshall(GetKeyRotationStatusRequest getKeyRotationStatusRequest, ProtocolMarshaller protocolMarshaller) { if (getKeyRotationStatusRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
java
public Quaterniond rotationTo(Vector3dc fromDir, Vector3dc toDir) { return rotationTo(fromDir.x(), fromDir.y(), fromDir.z(), toDir.x(), toDir.y(), toDir.z()); }
python
def is_matching_rule(self, request): """Check according to the rules defined in the class docstring.""" # First, if in DEBUG mode and with django-debug-toolbar, we skip # this entire process. if settings.DEBUG and request.path.startswith("/__debug__"): return True # Second we check against matches mat...
java
public List<CmsModelPageEntry> getModelGroups() { List<CmsModelPageEntry> result = new ArrayList<CmsModelPageEntry>(); CmsResourceTypeConfig config = m_adeConfig.getResourceType( CmsResourceTypeXmlContainerPage.MODEL_GROUP_TYPE_NAME); if ((config != null) && !config.isDisabled()) { ...
python
def steps(self, *steps_cfg:StartOptEnd): "Build anneal schedule for all of the parameters." return [Scheduler(step, n_iter, func=func) for (step,(n_iter,func)) in zip(steps_cfg, self.phases)]
java
public static String parseToHtmlTag(String emoji_str){ if(emoji_str != null){ String str = EmojiParser.parseToHtmlHexadecimal(emoji_str); return htmlHexadecimalToHtmlTag(str); } return null; }
java
public void setSubFolders(java.util.Collection<Folder> subFolders) { if (subFolders == null) { this.subFolders = null; return; } this.subFolders = new java.util.ArrayList<Folder>(subFolders); }
java
public void setRepCoEx(Integer newRepCoEx) { Integer oldRepCoEx = repCoEx; repCoEx = newRepCoEx; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.COLOR_FIDELITY__REP_CO_EX, oldRepCoEx, repCoEx)); }
java
protected void handleAnnotationGroup(ProtoNetwork protoNetwork, Map<String, Annotation> annotationMap, AnnotationGroup ag) { if (ag != null) { // handle citation if (ag.getCitation() != null) { handleCitationAnnotations(protoNetwork, ag.getCitation(), ...
java
public static <E> List<E> constrainedList(List<E> list, Constraint<? super E> constraint) { return (list instanceof RandomAccess) ? new ConstrainedRandomAccessList<E>(list, constraint) : new ConstrainedList<E>(list, constraint); }
python
def getMirrorTextureGL(self, eEye): """Access to mirror textures from OpenGL.""" fn = self.function_table.getMirrorTextureGL pglTextureId = glUInt_t() pglSharedTextureHandle = glSharedTextureHandle_t() result = fn(eEye, byref(pglTextureId), byref(pglSharedTextureHandle)) ...
python
def rounded_rectangle_region(width, height, radius): """ Returns a rounded rectangle wx.Region """ bmp = wx.Bitmap.FromRGBA(width, height) # Mask color is #000000 dc = wx.MemoryDC(bmp) dc.Brush = wx.Brush((255,) * 3) # Any non-black would do dc.DrawRoundedRectangle(0, 0, width, height, radius) dc.Select...
java
public SqlPara getSqlParaByString(String content, Map data) { Template template = engine.getTemplateByString(content); SqlPara sqlPara = new SqlPara(); data.put(SQL_PARA_KEY, sqlPara); sqlPara.setSql(template.renderToString(data)); data.remove(SQL_PARA_KEY); // 避免污染传入的 Map return sqlPara; }
java
public Long getInteger(int key) { PebbleTuple tuple = getTuple(key, PebbleTuple.TupleType.INT); if (tuple == null) { return null; } return (Long) tuple.value; }
java
public <U extends T, A, B, C> OngoingMatchingC3<T, U, A, B, C> when( DecomposableMatchBuilder3<U, A, B, C> decomposableMatchBuilder) { return new OngoingMatchingC3<>(this, decomposableMatchBuilder.build()); }
python
def visit_BoolOp(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s operator and operands as inlined expression.""" op = node.op with self.op_man(op): src = self.visit(op).join([self.visit(node.values[0])] + [self.visit(val, df...
python
def patch(source, sink): """Create a direct link between a source and a sink. Implementation:: sink = sink() for value in source(): sink.send(value) .. |patch| replace:: :py:func:`patch` """ sink = sink() for v in source(): try: sink.send(v) ...
java
public void setImage(Image image) { column.setText(null); table = null; this.image = image; }
java
public short[] getPixelValues(BufferedImage image) { validateImageType(image); WritableRaster raster = image.getRaster(); short[] pixelValues = getPixelValues(raster); return pixelValues; }
python
def parameters(self): """ Returns a dictionary of all parameters for this source. We use the parameter path as the key because it's guaranteed to be unique, unlike the parameter name. :return: """ all_parameters = collections.OrderedDict() for component...
java
public static Polygon makePolygon(Geometry shell) throws IllegalArgumentException { if(shell == null) { return null; } LinearRing outerLine = checkLineString(shell); return shell.getFactory().createPolygon(outerLine, null); }
java
public static void setPreferredAttributeNameForLaneCount(String name) { final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkConstants.class); if (prefs != null) { if (name == null || "".equals(name) || DEFAULT_ATTR_LANE_COUNT.equalsIgnoreCase(name)) { //$NON-NLS-1$ prefs.remove("LANE_COUNT_AT...
java
private Class<?> generateLobLoader(JDBCStorableProperty<S> property, Class<?> loaderType) throws SupportException { ClassInjector ci = ClassInjector.create (property.getEnclosingType().getName(), mParentClassLoader); ClassFile cf = new ClassFile(ci.getClassName()); ...
python
def rt_update(self, statement, element, mode, linenum, lineparser): """Performs a real-time update of the specified statement that is in the body of the module. :arg statement: the lines of code that was added/removed/changed on the element after it had alread been parsed. Th...
java
public void keyReleased(KeyEvent event) { lastKeyName = EMPTY_KEY_NAME; lastCode = NO_KEY_CODE; final Integer key = Integer.valueOf(event.getCode()); keys.remove(key); pressed.remove(key); }
java
public static <K1, V1, K2, V2> void setReducer(JobConf job, Class<? extends Reducer<K1, V1, K2, V2>> klass, Class<? extends K1> inputKeyClass, Class<? extends V1> inputValueClass, Class<? extends K2> outputKeyCla...
java
public DiscriminatorJdbcSubBuilder when(String value, TypeReference<? extends T> type) { return when(value, type.getType()); }
java
@Override public ResourceSet<UsageRecord> read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); }
java
protected boolean handleJsonBody(ActionRuntime runtime, VirtualForm virtualForm) { final ActionFormMeta formMeta = virtualForm.getFormMeta(); if (formMeta.isJsonBodyMapping()) { if (formMeta.isRootSymbolForm()) { mappingJsonBody(runtime, virtualForm, prepareJsonFromRequestBod...
java
@Override public void deleteDurableSubscription(String subscriptionName, String durableSubscriptionHome) throws SIConnectionUnavailableException, SIConnectionDroppedException, SIResourceException, SIConnectionLostException, ...