language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static void write(DataOutput out, FsPermission masked) throws IOException { FsPermission perm = new FsPermission(masked); perm.write(out); }
java
@Override public void putAll(Map<? extends TypeK, ? extends TypeV> m) { for (Map.Entry<? extends TypeK, ? extends TypeV> e : m.entrySet()) put(e.getKey(), e.getValue()); } /** Removes all of the mappings from this map. */ @Override public void clear() { // Smack a new empty table down O...
java
public String getSessionId(boolean create) { String result = ""; if (defaultExternalContext != null) { result = defaultExternalContext.getSessionId(create); } else { throw new UnsupportedOperationException(); } return result; }
java
@Override public Shape toSpatial4j(SpatialContext spatialContext) { double kms = distance.getValue(GeoDistanceUnit.KILOMETRES); double d = DistanceUtils.dist2Degrees(kms, DistanceUtils.EARTH_MEAN_RADIUS_KM); return spatialContext.makeCircle(longitude, latitude, d); }
java
@Deprecated public AtomixClusterBuilder setBroadcastInterval(Duration interval) { GroupMembershipProtocolConfig protocolConfig = config.getProtocolConfig(); if (protocolConfig instanceof HeartbeatMembershipProtocolConfig) { ((HeartbeatMembershipProtocolConfig) protocolConfig).setHeartbeatInterval(interv...
python
def get_qr(self, filename=None): """Get pairing QR code from client""" if "Click to reload QR code" in self.driver.page_source: self.reload_qr() qr = self.driver.find_element_by_css_selector(self._SELECTORS['qrCode']) if filename is None: fd, fn_png = tempfile.mks...
python
def Scan(self, matcher): """Yields spans occurrences of a given pattern within the chunk. Only matches that span over regular (non-overlapped) chunk bytes are returned. Matches lying completely within the overlapped zone are ought to be returned by the previous chunk. Args: matcher: A `Match...
python
def find_package_version(self): """ Find the installed version of the specified package, and as much information about it as possible (source URL, git ref or tag, etc.) This attempts, to the best of our ability, to find out if the package was installed from git, and if so, provi...
java
public List<ExtensionElement> getExtendedInfoAsList() { List<ExtensionElement> res = null; if (extendedInfo != null) { res = new ArrayList<>(1); res.add(extendedInfo); } return res; }
python
def set_bfd_ip(self, name, vrid, value=None, disable=False, default=False, run=True): """Set the bfd_ip property of the vrrp Args: name (string): The interface to configure. vrid (integer): The vrid number for the vrrp to be managed. value (string)...
python
def samples_by_indices_nomapping(self, indices): """ Gather a batch of samples by indices *without* applying any index mapping. Parameters ---------- indices: list of either 1D-array of ints or slice A list of index arrays or slices; one for each data source ...
python
def compare_nouns(self, word1, word2): """ compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as nouns return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 ...
python
def add(self, items): '''add a submenu''' if not isinstance(items, list): items = [items] for m in items: updated = False for i in range(len(self.items)): if self.items[i].name == m.name: self.items[i] = m ...
python
def enqueue(self, obj, *args, **kwargs): """Enqueue a function call or :doc:`job` instance. :param func: Function or :doc:`job <job>`. Must be serializable and importable by :doc:`worker <worker>` processes. :type func: callable | :doc:`kq.Job <job>` :param args: Positional ...
python
def parse_rss_file(filename: str) -> RSSChannel: """Parse an RSS feed from a local XML file.""" root = parse_xml(filename).getroot() return _parse_rss(root)
python
def parse_PRIK(chunk, encryption_key): """Parse PRIK chunk which contains private RSA key""" decrypted = decode_aes256('cbc', encryption_key[:16], decode_hex(chunk.payload), encryption_key) hex_key = re.match(br'^Last...
java
@VisibleForTesting boolean onMinLevel(int k) { float kAsFloat = k; int exponent = Math.getExponent(kAsFloat); return exponent % 2 == 0; }
python
def post(self, request, *args, **kwargs): """ Handles POST requests. """ return self.update_type(request, *args, **kwargs)
java
public static void putIntegerList(Writer writer, List<Integer> values) throws IOException { if (values == null) { writer.write("null"); } else { startArray(writer); for (int i = 0; i < values.size(); i++) { put(writer, values.get(i)); if (i != values.size() - 1) { addSeparator(writer); } ...
python
def add_to_known_hosts(self, hosts, known_hosts=DEFAULT_KNOWN_HOSTS, dry=False): """ Add the remote host SSH public key to the `known_hosts` file. :param hosts: the list of the remote `Host` objects. :param known_hosts: the `known_hosts` file to store the SSH public keys. :param...
python
def get_data_times_for_job_legacy(self, num_job): """ Get the data that this job will need to read in. """ # Should all be integers, so no rounding needed shift_dur = self.curr_seg[0] + int(self.job_time_shift * num_job) job_data_seg = self.data_chunk.shift(shift_dur) # If this ...
java
public WrappedByteBuffer skip(int size) { _autoExpand(size); _buf.position(_buf.position() + size); return this; }
python
def start(self): """ Start the periodic runner """ if self._isRunning: return if self._cease.is_set(): self._cease.clear() # restart class Runner(threading.Thread): @classmethod def run(cls): nextRunAt = c...
python
def get_old_value(self, args, kwargs, default=None): # type: (List[Any], Dict[str, Any], Any) -> Any """Returns the old value of the named argument without replacing it. Returns ``default`` if the argument is not present. """ if self.arg_pos is not None and len(args) > self.arg_...
java
public org.tensorflow.framework.TensorShapeProto getShape() { if (valueCase_ == 7) { return (org.tensorflow.framework.TensorShapeProto) value_; } return org.tensorflow.framework.TensorShapeProto.getDefaultInstance(); }
java
@SuppressWarnings("all") public static Completable save(Map pathDataMap) { return SingleRxXian.call("cosService", "batchCosWrite", new JSONObject() {{ put("files", pathDataMap); }}).toCompletable(); }
python
def device_type_from_string(cl_device_type_str): """Converts values like ``gpu`` to a pyopencl device type string. Supported values are: ``accelerator``, ``cpu``, ``custom``, ``gpu``. If ``all`` is given, None is returned. Args: cl_device_type_str (str): The string we want to convert to a device t...
java
public double getSolution(double targetValue, double initGuess) { double rMax = 1.0; double oldValue = -1; for (int i = 0; i < MAXIMUM_ITERATION; ++i) { double value = targetFunction(rMax); if (value >= targetValue) { break; } if (equals(value, oldValue)) { return rMa...
python
def is_subset(a, b): """Excluding same size""" return b.left <= a.left and b.right > a.right or b.left < a.left and b.right >= a.right
python
def _group_groups(perm_list): """Group permissions by group. Input is list of tuples of length 3, where each tuple is in following format:: (<group_id>, <group_name>, <single_permission>) Permissions are regrouped and returned in such way that there is only one tuple for each group:: ...
python
def create_env(self): """Create a virtual environment.""" virtualenv(self.env, _err=sys.stderr) os.mkdir(self.env_bin)
java
@CheckReturnValue private LocalSyncWriteModelContainer replaceOrUpsertOneFromRemote( final NamespaceSynchronizationConfig nsConfig, final BsonValue documentId, final BsonDocument remoteDocument, final BsonDocument atVersion ) { final MongoNamespace namespace = nsConfig.getNamespace(); ...
java
public Observable<ServiceResponse<Page<ResourceMetricDefinitionInner>>> listWorkerPoolInstanceMetricDefinitionsNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } ...
java
public synchronized void writeValue(MessageItem msgItem) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "writeValue", msgItem); timeLastMsgReceived = System.currentTimeMillis(); if(msgItem.getMessage().getGuaranteedValueValueTick() > lastTick) { ...
python
def format_location(ctx, text): """ Takes a single parameter (administrative boundary as a string) and returns the name of the leaf boundary """ text = conversions.to_string(text, ctx) return text.split(">")[-1].strip()
python
def OnChar(self, event): """Key event method * Forces grid update on <Enter> key * Handles insertion of cell access code """ if not self.ignore_changes: # Handle special keys keycode = event.GetKeyCode() if keycode == 13 and not self.Get...
python
def print_ssl_error_message(exception): """ Print SSLError message with URL to instructions on how to fix it. """ message = """ ##################################################################### # ATTENTION! PLEASE READ THIS! # # The following error has just occurred: # %s %s # # Please read instruct...
python
def visit_module(self, node): """ A interface will be called when visiting a module. @param node: The module node to check. """ recorder = PyCodeStyleWarningRecorder(node.file) self._outputMessages(recorder.warnings, node)
java
Object get(final Object target, final FieldColumnInfo fcInfo) { if (fcInfo == null) { throw new RuntimeException("FieldColumnInfo must not be null. Type is " + target.getClass().getCanonicalName()); } try { Object value = fcInfo.field.get(target); // Fix-up column value ...
java
public void parseTagedLine(String line) { String[] toks = line.split("(\\s| | |\\t)+"); words = new String[toks.length]; tags = new String[toks.length]; for(int i=0;i<toks.length;i++){ String[] tt = toks[i].split("/"); if(tt.length!=2) System.err.println("Wrong Format"); words[i] = tt[0]; tags[i...
python
def Sign(self, data, signing_key, verify_key=None): """Use the data to sign this blob. Args: data: String containing the blob data. signing_key: The key to sign with. verify_key: Key to verify with. If None we assume the signing key also contains the public key. Returns: se...
java
public Matrix transposeMultiply(Matrix B, ExecutorService threadPool) { Matrix C = new DenseMatrix(this.cols(), B.cols()); transposeMultiply(B, C, threadPool); return C; }
python
def store(self, key=None, ttl=DEFAULT_STORE_TTL): """ Will call the collection and store the result in Redis, and return a new collection based on this stored result. Note that only primary keys are stored, ie calls to values/values_list are ignored when storing result. But choic...
java
public static String hidePassword(@Sensitive String s) { if ((s.indexOf("password") == -1) && (s.indexOf("PASSWORD") == -1)) { return s; } else { String ss = ""; int indexLowerCase = s.indexOf("password"); int indexUpperCase = s.indexOf("PASSWORD"); ...
python
def _rescale_and_convert_field_inplace(self, array, name, scale, zero): """ Apply fits scalings. Also, convert bool to proper numpy boolean values """ self._rescale_array(array[name], scale, zero) if array[name].dtype == numpy.bool: array[name] = self._conver...
java
@SuppressWarnings("unchecked") @Override public Boolean execute() { validateCommand(); Room room = CommandUtil.getSfsRoom(roomName, extension); validateRoom(room); List<User> recipients = room.getUserList(); for(String exUser : excludedUsers) recipients.remov...
python
def id_for(self, city_name): """ Returns the long ID corresponding to the first city found that matches the provided city name. The lookup is case insensitive. .. deprecated:: 3.0.0 Use :func:`ids_for` instead. :param city_name: the city name whose ID is looked up ...
python
def positions_with_tile(self): """Generate all positions and tiles as tuples of (row,col), tile. docstring to make my IDE stop assuming tile is a standard dtype. sorry! :rtype : tuple """ for p, tile in numpy.ndenumerate(self._array): yield p, tile
python
def clipstr(s, dispw): '''Return clipped string and width in terminal display characters. Note: width may differ from len(s) if East Asian chars are 'fullwidth'.''' w = 0 ret = '' ambig_width = options.disp_ambig_width for c in s: if c != ' ' and unicodedata.category(c) in ('Cc', 'Zs', ...
java
public java.util.List<String> getReplyToAddresses() { if (replyToAddresses == null) { replyToAddresses = new com.amazonaws.internal.SdkInternalList<String>(); } return replyToAddresses; }
java
private static Integer getEarliestTimestampLineIndex(List<LineAndTime> lines) { Integer i = 0; for (LineAndTime line : lines) { if (isExactEarthTimestamp(line.getLine())) return i; else i++; } return null; }
python
def gt(self, v, limit=None, offset=None): """Returns the list of the members of the set that have scores greater than v. """ if limit is not None and offset is None: offset = 0 return self.zrangebyscore("(%f" % v, self._max_score, start=offset, num=lim...
python
def _cimdatetime_representer(dumper, cimdatetime): """ PyYAML representer function for CIMDateTime objects. This is needed for yaml.safe_dump() to support CIMDateTime. """ cimdatetime_str = str(cimdatetime) node = dumper.represent_scalar(CIMDATETIME_TAG, cimdatetime_str) return node
python
def _possibly_convert_objects(values): """Convert arrays of datetime.datetime and datetime.timedelta objects into datetime64 and timedelta64, according to the pandas convention. """ return np.asarray(pd.Series(values.ravel())).reshape(values.shape)
python
def poll(self): """ Main loop which maintains the node in the hash ring. Can be run in a greenlet or separate thread. This takes care of: * Updating the heartbeat * Checking for ring updates * Cleaning up expired nodes periodically """ pubsub = self.conn...
java
@Nullable public static EmailAddress getAsEmailAddress (@Nullable final InternetAddress aInternetAddress) { return aInternetAddress == null ? null : new EmailAddress (aInternetAddress.getAddress (), aInternetAddress.getPersonal ()); }
python
def generate_dmu_over_dt(species, propensity, n_counter, stoichiometry_matrix): r""" Calculate :math:`\frac{d\mu_i}{dt}` in eq. 6 (see Ale et al. 2013). .. math:: \frac{d\mu_i}{dt} = S \begin{bmatrix} \sum_{l} \sum_{n_1=0}^{\infty} ... \sum_{n_d=0}^{\infty} \frac{1}{\mathb...
python
def _create_bvals_bvecs(grouped_dicoms, bval_file, bvec_file): """ Write the bvals from the sorted dicom files to a bval file """ # get the bvals and bvecs bvals, bvecs = _get_bvals_bvecs(grouped_dicoms) # save the found bvecs to the file common.write_bval_file(bvals, bval_file) common...
java
public StringBuffer rewriteUrl(String originalCssPath, String newCssPath, String originalCssContent) throws IOException { // Rewrite each css image url path Matcher matcher = URL_PATTERN.matcher(originalCssContent); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String url = getUrlPath(m...
python
def get_on_tmdb(uri, **kwargs): """ Get a resource on TMDB. """ kwargs['api_key'] = app.config['TMDB_API_KEY'] response = requests_session.get((TMDB_API_URL + uri).encode('utf8'), params=kwargs) response.raise_for_status() return json.loads(response.text)
java
protected void prepareBody(CardView view, SMailPostingMessage message) { final String plainText = toCompletePlainText(view); final OptionalThing<String> optHtmlText = toCompleteHtmlText(view); message.savePlainTextForDisplay(plainText); message.saveHtmlTextForDisplay(optHtmlText); ...
java
public void clickOnToggleButton(String text) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "clickOnToggleButton(\""+text+"\")"); } clicker.clickOn(ToggleButton.class, text); }
python
def create_new_migration_record(self): """ Create a new migration record for this migration set """ migration_record = self.migration_model( name=self.name, version=self.latest_migration) self.session.add(migration_record) self.session.commit()
java
private void flushBuffer() throws IOException { if (this.dirty_) { if (this.diskPos_ != this.lo_) { super.seek(this.lo_); } int len = (int) (this.curr_ - this.lo_); super.write(this.buff_, 0, len); this.diskPos_ = this.curr_; this.dirty_ = false; } }
python
def derivatives(self, x, y, coeffs, beta, center_x=0, center_y=0): """ returns df/dx and df/dy of the function """ shapelets = self._createShapelet(coeffs) n_order = self._get_num_n(len(coeffs)) dx_shapelets = self._dx_shapelets(shapelets, beta) dy_shapelets = sel...
java
@Override public ExternalStorageLocation getLocation(Operation operation, PayloadType payloadType, String path) { String uri; switch (payloadType) { case WORKFLOW_INPUT: case WORKFLOW_OUTPUT: uri = "workflow"; break; case TASK_INPUT...
java
@Override public EClass getIfcOpenShell() { if (ifcOpenShellEClass == null) { ifcOpenShellEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(396); } return ifcOpenShellEClass; }
python
def set_ylim_cb(self, redraw=True): """Set plot limit based on user values.""" try: ymin = float(self.w.y_lo.get_text()) except Exception: set_min = True else: set_min = False try: ymax = float(self.w.y_hi.get_text()) excep...
java
public Matrix4x3d sub(Matrix4x3dc subtrahend, Matrix4x3d dest) { dest.m00 = m00 - subtrahend.m00(); dest.m01 = m01 - subtrahend.m01(); dest.m02 = m02 - subtrahend.m02(); dest.m10 = m10 - subtrahend.m10(); dest.m11 = m11 - subtrahend.m11(); dest.m12 = m12 - subtrahend.m12(...
java
private void processGeneralOptions(Configuration conf, CommandLine line) { if (line.hasOption("fs")) { FileSystem.setDefaultUri(conf, line.getOptionValue("fs")); } if (line.hasOption("jt")) { conf.set("mapred.job.tracker", line.getOptionValue("jt")); } if (line.hasOption("conf")) ...
python
def vrp_solver(path_graph, initial_solution=None, runtime_seconds=60): """Solve a path using or-tools' Vehicle Routing Problem solver. Params: path_graph the PathGraph representing the problem initial_solution a solution to start with (list of indices, not inclu...
python
def _delete(self, *criterion): """ Delete a model by some criterion. Avoids race-condition check-then-delete logic by checking the count of affected rows. :raises `ResourceNotFound` if the row cannot be deleted. """ with self.flushing(): count = self._query...
java
public ServiceFuture<AdvisorListResultInner> listByServerAsync(String resourceGroupName, String serverName, final ServiceCallback<AdvisorListResultInner> serviceCallback) { return ServiceFuture.fromResponse(listByServerWithServiceResponseAsync(resourceGroupName, serverName), serviceCallback); }
java
public final R visit(DocTree node, P p) { return (node == null) ? null : node.accept(this, p); }
java
public void loadRules(Engine engine) { List<String> exceptions = new ArrayList<String>(); for (Rule rule : this.rules) { if (rule.isLoaded()) { rule.unload(); } try { rule.load(engine); } catch (Exception ex) { ...
python
def GetHist(tag_name, start_time, end_time, period=5, mode="raw", desc_as_label=False, label=None, high_speed=False, utc=False): """ Retrieves data from eDNA history for a given tag. :param tag_name: fully-qualified (site.service.tag) eDNA tag :param start_time: must be in format mm/d...
java
public static Method changeMethodAccess(Class<?> clazz, String methodName, String srgName, boolean silenced, Class<?>... params) { try { Method m = clazz.getDeclaredMethod(MalisisCore.isObfEnv ? srgName : methodName, params); m.setAccessible(true); return m; } catch (ReflectiveOperationException e) ...
java
@Override public void commitBlock(long workerId, long usedBytesOnTier, String tierAlias, long blockId, long length) throws NotFoundException, UnavailableException { LOG.debug("Commit block from workerId: {}, usedBytesOnTier: {}, blockId: {}, length: {}", workerId, usedBytesOnTier, blockId, length); ...
java
public ClassGraph blacklistClasses(final String... classNames) { enableClassInfo(); for (final String className : classNames) { if (className.contains("*")) { throw new IllegalArgumentException("Cannot use a glob wildcard here: " + className); } final ...
python
def get_directory_as_zip(self, remote_path, local_file): """Downloads a remote directory as zip :param remote_path: path to the remote directory to download :param local_file: path and name of the target local file :returns: True if the operation succeeded, False otherwise :rais...
python
def db_restore(self, block_number=None): """ Restore the database and clear the indexing lockfile. Restore to a given block if given; otherwise use the most recent valid backup. Return True on success Return False if there is no state to restore Raise exception on error ...
python
def get_valid_units(self, ureg, from_unit, target_unit): """ Returns the firt match `pint.unit.Unit` object for from_unit and target_unit strings from a possible variation of metric unit names supported by pint library. :param ureg: unit registry which units are defined and hand...
python
def get_pre_auth_url_m(self, redirect_uri): """ 快速获取pre auth url,可以直接微信中发送该链接,直接授权 """ url = "https://mp.weixin.qq.com/safe/bindcomponent?action=bindcomponent&auth_type=3&no_scan=1&" redirect_uri = quote(redirect_uri, safe='') return "{0}component_appid={1}&pre_auth_code=...
java
@Override protected void transform(final XtendConstructor source, final JvmGenericType container) { final String constructorName = container.getSimpleName(); // Special case: static constructor if (source.isStatic()) { final JvmOperation staticConstructor = this.typesFactory.createJvmOperation(); containe...
python
def _build_arguments(self): """ build arguments for command. """ self._parser.add_argument( '-a', '--alias', required=False, default='default', type=str, help='registry alias created in freight-forwarder.yml. Example: tune_dev' ...
java
@Override public void reset(final long mNodeKey) { super.reset(mNodeKey); if (mInputExpr != null) { mInputExpr.reset(mNodeKey); } }
java
public Task add() { Task task = new Task(m_projectFile, (Task) null); add(task); m_projectFile.getChildTasks().add(task); return task; }
python
def get_provides_by_kind(self, kind): """ Returns an array of provides of a certain kind """ provs = [] for p in self.provides: if p.kind == kind: provs.append(p) return provs
python
def import_csv(csv_file, **kwargs): """Imports data and checks that all required columns are there.""" records = get_imported_data(csv_file, **kwargs) _check_required_columns(csv_file, records.results) return records
java
public T withLabel(String text, String languageCode) { withLabel(factory.getMonolingualTextValue(text, languageCode)); return getThis(); }
python
def interpret(self, ilines, xlines, offsets=None, sorting=TraceSortingFormat.INLINE_SORTING): """ (Re-)interpret structure on top of a file (Re-)interpret the structure of the file given the new sorting, ilines, xlines and offset indices. Note that file itself is not changed in any way...
python
def no_update_last_login(): """ Disconnect any signals to update_last_login() for the scope of the context manager, then restore. """ kw = {'receiver': update_last_login} kw_id = {'receiver': update_last_login, 'dispatch_uid': 'update_last_login'} was_connected = user_logged_in.disconnect(*...
java
public static byte[] set( final byte[] data, final int index, final boolean value ) { return value ? set(data, index) : unset(data, index); }
java
public void performClear(Transaction tx, Resource... contexts) { if(notNull(contexts)) { for (int i = 0; i < contexts.length; i++) { if (notNull(contexts[i])) { graphManager.delete(contexts[i].stringValue(), tx); } else { graphM...
java
public FileDeleteFromTaskOptions withOcpDate(DateTime ocpDate) { if (ocpDate == null) { this.ocpDate = null; } else { this.ocpDate = new DateTimeRfc1123(ocpDate); } return this; }
java
public <T extends IsVueComponent> VNode el(VueJsConstructor<T> vueJsConstructor, Object... children) { return el(vueJsConstructor, null, children); }
python
def limit(self, limit): """ Limit the number of rows returned from the database. :param limit: The number of rows to return in the recipe. 0 will return all rows. :type limit: int """ if self._limit != limit: self.dirty = True self._...
python
def add(self, user, status=None, symmetrical=False): """ Add a relationship from one user to another with the given status, which defaults to "following". Adding a relationship is by default asymmetrical (akin to following someone on twitter). Specify a symmetrical relationship...
java
private void visitNonMethodMember(Node member, ClassDeclarationMetadata metadata) { if (member.isComputedProp() && member.isStaticMember()) { cannotConvertYet(compiler, member, "Static computed property"); return; } if (member.isComputedProp() && !member.getFirstChild().isQualifiedName()) { ...
java
public Link createLink(String name, String url, boolean onMenu) { return getInstance().create().link(name, this, url, onMenu); }