language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public AddIpRoutesResult addIpRoutes(AddIpRoutesRequest request) { request = beforeClientExecution(request); return executeAddIpRoutes(request); }
python
def update_one(self, filter, update, upsert=False, bypass_document_validation=False, collation=None, array_filters=None, session=None): """Update a single document matching the filter. >>> for doc in db.test.find(): ... print(doc) ... ...
python
def handle_args_and_set_context(args): """ Args: args: the command line args, probably passed from main() as sys.argv[1:] Returns: a populated Context object based on CLI args """ parser = argparse.ArgumentParser() parser.add_argument("env", help="environment") parser.add_argument("path_to_templat...
java
public Object startupService(BundleContext bundleContext) { Map<String,Object> props = this.getServiceProperties(); Environment env = (Environment)this.getService(Env.class); props = Utility.putAllIfNew(props, env.getProperties()); // Use the same params as environment // Note the o...
java
public List<Change> asAddedChanges() { final List<Change> changes = new ArrayList<>(); for (final HourRange hr : hourRanges) { changes.add(new Change(ChangeType.ADDED, dayOfTheWeek, hr)); } return changes; }
java
public static PrivateKey generatePrivateKey(String algorithm, byte[] key) { if (null == key) { return null; } return generatePrivateKey(algorithm, new PKCS8EncodedKeySpec(key)); }
python
def fill_extents(self): """Computes a bounding box in user-space coordinates covering the area that would be affected, (the "inked" area), by a :meth:`fill` operation given the current path and fill parameters. If the current path is empty, returns an empty rectangle ``(0, 0, 0, ...
java
public static void printf(Closure self, String format, Object[] values) { Object owner = getClosureOwner(self); Object[] newValues = new Object[values.length + 1]; newValues[0] = format; System.arraycopy(values, 0, newValues, 1, values.length); InvokerHelper.invokeMethod(owner, "...
java
public static <T extends TypeDefinition> ElementMatcher.Junction<T> ofSort(TypeDefinition.Sort sort) { return ofSort(is(sort)); }
python
def decode(mode=unicode_errors_default): """Configure automatic encoding/decoding of strings.""" def dec(f): f._nvim_decode = mode return f return dec
python
def get_lexicons(self, num_terms=10): ''' Parameters ---------- num_terms, int Returns ------- dict ''' return {k: v.index[:num_terms] for k, v in self.lexicons.items()}
python
def _from_deprecated_son(cls, id_dict, run): """Deprecated. See BlockUsageLocator._from_deprecated_son""" cls._deprecation_warning() return AssetLocator._from_deprecated_son(id_dict, run)
java
private static boolean pointEqualsEnvelope_(Point2D pt_a, Envelope2D env_b, double tolerance, ProgressTracker progress_tracker) { Envelope2D env_a = new Envelope2D(); env_a.setCoords(pt_a); return envelopeEqualsEnvelope_(env_a, env_b, tolerance, progress_tracker); }
java
public int valueForYPosition(int yPos) { int value; int minValue = slider.getMinimum(); int maxValue = slider.getMaximum(); int trackTop = trackRect.y + thumbRect.height / 2 + trackBorder; int trackBottom = trackRect.y + trackRect.height - thumbRect.height / 2 - trackBorder; ...
python
def check(self, request, consumer, token, signature): """ Returns whether the given signature is the correct signature for the given consumer and token signing the given request. """ built = self.sign(request, consumer, token) if isinstance(signature, STRING_TYPES): ...
java
@Override public Iterable<JsonObject> convertRecord(JsonArray outputSchema, String strInputRecord, WorkUnitState workUnit) throws DataConversionException { JsonParser jsonParser = new JsonParser(); JsonObject inputRecord = (JsonObject) jsonParser.parse(strInputRecord); if (!this.unpackComplexSchema...
java
@NotNull public Stream<T> limit(final long maxSize) { if (maxSize < 0) { throw new IllegalArgumentException("maxSize cannot be negative"); } if (maxSize == 0) { return Stream.empty(); } return new Stream<T>(params, new ObjLimit<T>(iterator, maxSize)); ...
java
public void write(byte[] b, int off, int len) throws IOException { Boolean result = (Boolean) callback.call(consoleId.get(), new String(b, off, len)); if (result) { out.write(b, off, len); } }
python
def get_handler_fp(logger): """ Get handler_fp. This method is integrated to LoggerFactory Object in the future. :param logging.Logger logger: Python logging.Logger. logger instance. :rtype: logging.Logger.handlers.BaseRotatingHandler :return: Handler or Handler's stream. We call it `handler_fp`...
python
def get_user_information(): """ Returns the user's information :rtype: (str, int, str) """ try: import pwd _username = pwd.getpwuid(os.getuid())[0] _userid = os.getuid() _uname = os.uname()[1] except ImportError: import getpass _username = getpass...
java
private void cancelInvokable(AbstractInvokable invokable) { // in case of an exception during execution, we still call "cancel()" on the task if (invokable != null && invokableHasBeenCanceled.compareAndSet(false, true)) { try { invokable.cancel(); } catch (Throwable t) { LOG.error("Error while canc...
python
def online_trial(self, bandit=None, payout=None, strategy='eps_greedy', parameters=None): ''' Update the bandits with the results of the previous live, online trial. Next run a the selection algorithm. If the stopping criteria is met, return the best arm esti...
python
def run(self, tmp=None, task_vars=None): """ Override run() to notify Connection of task-specific data, so it has a chance to know e.g. the Python interpreter in use. """ self._connection.on_action_run( task_vars=task_vars, delegate_to_hostname=self._task....
python
def _expectation(p, constant_mean, none, kern, feat, nghp=None): """ Compute the expectation: expectation[n] = <m(x_n)^T K_{x_n, Z}>_p(x_n) - m(x_i) = c :: Constant function - K_{.,.} :: Kernel function :return: NxQxM """ with params_as_tensors_for(constant_mean): c =...
java
private void sawLoad(int seen, int pc) { int reg = RegisterUtils.getLoadReg(this, seen); if (!ignoreRegs.get(reg)) { ScopeBlock sb = findScopeBlock(rootScopeBlock, pc); if (sb != null) { sb.addLoad(reg, pc); } else { ignoreRegs.set(reg)...
java
public void setOufqn(String oufqn) { if (oufqn != null) { if (!oufqn.endsWith("/")) { oufqn += '/'; } } else { oufqn = "/"; } String name = m_project.getSimpleName(); if (name == null) { name = ""; } ...
python
def serialize(self): """ Serializes the Peer data as a simple JSON map string. """ return json.dumps({ "name": self.name, "ip": self.ip, "port": self.port }, sort_keys=True)
java
@Override public final void modifiedService(ServiceReference<PageFactory<? extends IRequestablePage>> reference, PageFactory<? extends IRequestablePage> service) { String appName = (String) reference.getProperty(APPLICATION_NAME); if (!applicationName.equals(appName)) { paxWi...
python
def copyKeyMultipart(srcBucketName, srcKeyName, srcKeyVersion, dstBucketName, dstKeyName, sseAlgorithm=None, sseKey=None, copySourceSseAlgorithm=None, copySourceSseKey=None): """ Copies a key from a source key to a destination key in multiple parts. Note that if the destination key exis...
java
private static ImmutableSortedSet<String> buildNodeModulesFoldersRegistry( Iterable<String> modulePaths, Iterable<String> moduleRootPaths) { SortedSet<String> registry = new TreeSet<>( // TODO(b/28382956): Take better advantage of Java8 comparing() to simplify this (a, b) -> { ...
java
@NonNull public Caffeine<K, V> softValues() { requireState(valueStrength == null, "Value strength was already set to %s", valueStrength); valueStrength = Strength.SOFT; return this; }
java
protected DOMOutputElement createAndAttachChild(Element element) { if (mRootNode != null) { mRootNode.appendChild(element); } else { mElement.appendChild(element); } return createChild(element); }
python
def clear(self): """ Remove all entries from the cache and delete all data. :return: """ for f in [x['content'] for x in self.metadata.values()]: os.remove(f) self.metadata = {} self._flush()
java
protected GenericConverter getConverter(TypeDescriptor sourceType, TypeDescriptor targetType) { ConverterCacheKey key = new ConverterCacheKey(sourceType, targetType); GenericConverter converter = this.converterCache.get(key); if (converter != null) { return (converter != NO_MATCH ? converter : null); } co...
java
public Head createHead() { final Head head = new Head(getRoot(), "Head"); getRoot().insert(head); return head; }
java
public Partition refine(Partition coarser) { Partition finer = new Partition(coarser); // start the queue with the blocks of a in reverse order blocksToRefine = new LinkedList<Set<Integer>>(); for (int i = 0; i < finer.size(); i++) { blocksToRefine.add(finer.copyBlock(i)); ...
python
def reset_in_ec(self, ec_index): '''Reset this component in an execution context. @param ec_index The index of the execution context to reset in. This index is into the total array of contexts, that is both owned and participating contexts. If the value o...
python
def _all_classes(self, classes): """ Return a list of all classes that are ancestors of *classes*. """ all_classes = {} def recurse(cls): all_classes[cls] = None for c in cls.__bases__: if c not in all_classes: recurse(...
java
private static int inv_mcol(int x) { int t0, t1; t0 = x; t1 = t0 ^ shift(t0, 8); t0 ^= FFmulX(t1); t1 ^= FFmulX2(t0); t0 ^= t1 ^ shift(t1, 16); return t0; }
python
def list_surveys(session): """retrieve a list of surveys from current user""" params = {'sUser': session['user'], 'sSessionKey': session['token']} data = set_params('list_surveys', params) req = requests.post(session['url'], data=data, headers=headers) return req.text
java
@Reference(policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MULTIPLE, target = "(!(objectClass=com.ibm.ws.security.registry.FederationRegistry))") protected Map<String, Object> setUserRegistry(ServiceReference<UserRegistry> ref) { String configId = (String) ref.getProperty(KEY_CONFIG_ID)...
java
public static void escapeUriFragmentId(final Reader reader, final Writer writer) throws IOException { escapeUriFragmentId(reader, writer, DEFAULT_ENCODING); }
java
protected boolean isSlowTracker(String taskTracker) { if (trackerMapStats.get(taskTracker) != null && trackerMapStats.get(taskTracker).mean() - mapTaskStats.mean() > mapTaskStats.std()*slowNodeThreshold) { if (LOG.isDebugEnabled()) { LOG.debug("Tracker " + taskTracker + " d...
java
@PostMapping(value = "/{entityTypeId}", params = "_method=DELETE") @ResponseStatus(NO_CONTENT) public void deleteAllPost(@PathVariable("entityTypeId") String entityTypeId) { dataService.deleteAll(entityTypeId); }
java
@JsonIgnore public <T> T getAsTypeWithDefault(Class<T> type, T defaultValue) { return TypeConverter.toTypeWithDefault(type, _value, defaultValue); }
python
def as_dict(self): """ Dict representation of NEBAnalysis. Returns: JSON serializable dict representation. """ return {"@module": self.__class__.__module__, "@class": self.__class__.__name__, 'r': jsanitize(self.r), 'en...
java
@Override public void close() { if (!this.closed.getAndSet(true)) { if (this.currentLedger != null) { try { Ledgers.close(this.currentLedger.handle); } catch (DurableDataLogException bkEx) { log.error("Unable to close Ledger...
python
def _page_text(page, nowrap=False): """ returns assembled text output """ title = page.data['title'] title = "%s\n%s" % (title, "=" * len(title)) desc = page.data.get('description') if desc: desc = "_%s_" % desc img = _text_image(page) pars = page.data.get('extext') i...
java
@Override public <T> long persistObjects(Collection<T> coll) throws CpoException { return getCurrentResource().persistObjects(coll); }
python
def parse_response(self, response, header=None): """Parses the response message. The following graph shows the structure of response messages. :: +----------+ +--+ data sep +<-+ ...
python
def reload_config(self, _): ''' Reload config. ''' restart_server = False if (self.server.is_server_running() == 'yes' or self.server.is_server_running() == 'maybe'): user_input = raw_input("Reloading configuration requires the server " ...
python
def build_attrs(self, *args, **kwargs): "Helper function for building an attribute dictionary." self.attrs = self.widget.build_attrs(*args, **kwargs) return self.attrs
python
def _select_phase_left_bound(self, epoch_number): """ Return number of current phase. Return index of first phase not done after all up to epoch_number were done. """ idx = bisect.bisect_left(self.ladder, epoch_number) if idx >= len(self.ladder): return len(s...
python
def delete_all_metadata(self): """ :: DELETE /:login/machines/:id/metadata :Returns: current metadata :rtype: empty :py:class:`dict` Deletes all the metadata stored for this machine. Also explicitly requests and returns the machine ...
python
def username(self): """The username of the issuer.""" entry = self._proto.commandQueueEntry if entry.HasField('username'): return entry.username return None
python
def shapeless_placeholder(x, axis, name): """ Make the static shape of a tensor less specific. If you want to feed to a tensor, the shape of the feed value must match the tensor's static shape. This function creates a placeholder which defaults to x if not fed, but has a less specific static shape ...
python
def _groups_of(length, total_length): """ Return an iterator of tuples for slicing, in 'length' chunks. Parameters ---------- length : int Length of each chunk. total_length : int Length of the object we are slicing Returns ------- iterable of tuples Values ...
python
def train(cls, rdd, k=10, maxIterations=20, docConcentration=-1.0, topicConcentration=-1.0, seed=None, checkpointInterval=10, optimizer="em"): """Train a LDA model. :param rdd: RDD of documents, which are tuples of document IDs and term (word) count vectors. The term c...
python
def csrf_protect_all_post_and_cross_origin_requests(): """returns None upon success""" success = None if is_cross_origin(request): logger.warning("Received cross origin request. Aborting") abort(403) if request.method in ["POST", "PUT"]: token = session.get("csrf_token") ...
python
def from_incomplete_data(cls, vertices, normals=(), texcoords=(), **kwargs): """Return a Mesh with (vertices, normals, texcoords) as arrays, in that order. Useful for when you want a standardized array location format across different amounts of info in each mesh.""" normals = normals if hasa...
java
@InterfaceAudience.Public public void setCreateTarget(boolean createTarget) { properties.put(ReplicationField.CREATE_TARGET, createTarget); replicationInternal.setCreateTarget(createTarget); }
python
def compute_log_likelihood(ll_func, parameters, data=None, cl_runtime_info=None): """Calculate and return the log likelihood of the given model for the given parameters. This calculates the log likelihoods for every problem in the model (typically after optimization), or a log likelihood for every sample o...
python
def _is_tail_call_optimization(self, g : networkx.DiGraph, src_addr, dst_addr, src_function, all_edges, known_functions, blockaddr_to_function): """ If source and destination belong to the same function, and the following criteria apply: - source node has only ...
java
public BaseField getFieldTarget() { BaseField fldTarget = m_fldTarget; if (fldTarget == null) if (targetFieldName != null) fldTarget = (NumberField)(this.getOwner().getRecord().getField(targetFieldName)); if (fldTarget == null) fldTarget = this.getOwne...
java
public void closeToRight() { if (viewDragHelper.smoothSlideViewTo(dragView, transformer.getOriginalWidth(), getHeight() - transformer.getMinHeightPlusMargin())) { ViewCompat.postInvalidateOnAnimation(this); notifyCloseToRightListener(); } }
python
def subject(name, meta_data=None, check_path=True): ''' subject(name) yields a freesurfer Subject object for the subject with the given name. Subjects are cached and not reloaded, so multiple calls to subject(name) will yield the same immutable subject object.. Note that subects returned by fre...
python
def _value_parser(self, value, columnname=False, placeholder='%s'): """ Input: {'c1': 'v', 'c2': None, '#c3': 'uuid()'} Output: ('%s, %s, uuid()', [None, 'v']) # insert; columnname=False ('`c2` = %s, `c1` = %s, `c3` = uuid()', [None, 'v']) # upd...
java
private static int mergeSameBuckets(double[] values, double[] weights, int nextIndex) { sort(values, weights, nextIndex); int current = 0; for (int i = 1; i < nextIndex; i++) { if (values[current] == values[i]) { weights[current] += weights[i]; } ...
python
def regon(self) -> str: """Generate random valid 9-digit REGON. :return: Valid 9-digit REGON """ regon_coeffs = (8, 9, 2, 3, 4, 5, 6, 7) regon_digits = [self.random.randint(0, 9) for _ in range(8)] sum_v = sum([nc * nd for nc, nd in zip(regon_coeffs,...
java
public void marshall(CoverageNormalizedUnits coverageNormalizedUnits, ProtocolMarshaller protocolMarshaller) { if (coverageNormalizedUnits == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(coverageNo...
java
public Class<?> tryDefineType(String name, ClassNotFoundException cnfe) throws ClassNotFoundException { byte[] bytecode = getBytecode(convertClassToResourcePath(name)); if (bytecode == null) { if (CACHE_NON_EXISTING_CLASSES) { nonExistingClasses.add(name); } ...
python
def effective_max_ar_order(self): """The maximum number of AR coefficients that shall or can be determined. It is the minimum of |ARMA.max_ar_order| and the number of coefficients of the pure |MA| after their turning point. """ return min(self.max_ar_order, self.ma.order...
python
async def reseed_apply(self) -> DIDInfo: """ Replace verification key with new verification key from reseed operation. Raise WalletState if wallet is closed. :return: DIDInfo with new verification key and metadata for DID """ LOGGER.debug('Wallet.reseed_apply >>>') ...
python
def remove_node_by_value(self, value): """ Delete all nodes in ``self.node_list`` with the value ``value``. Args: value (Any): The value to find and delete owners of. Returns: None Example: >>> from blur.markov.node import Node >>> node_1 = ...
python
def delete_bandwidth_group(self, name): """Deletes a new bandwidth group. in name of type str Name of the bandwidth group to delete. """ if not isinstance(name, basestring): raise TypeError("name can only be an instance of type basestring") self._call("d...
java
public static WebsocketServerTransport create(int port) { HttpServer httpServer = HttpServer.create().port(port); return create(httpServer); }
java
public static List<Type> decode( String rawInput, List<TypeReference<Type>> outputParameters) { String input = Numeric.cleanHexPrefix(rawInput); if (Strings.isEmpty(input)) { return Collections.emptyList(); } else { return build(input, outputParameters); ...
java
@Bean public boolean adminToolMbeansExported(MBeanServer server, BeanFactory beanFactory, List<AdminToolConfig> configs) throws MalformedObjectNameException { MBeanExporter mbeanExporter = new MBeanExporter(); mbeanExporter.setServer(server); mbeanExporter.setBeanFactory(beanFactory); SimpleReflectiveMBeanInf...
java
public Connection getConnection() throws IOException { Connection conn = null; if (this.datasource != null) { try { conn = this.datasource.getConnection(); } catch (SQLException e) { throw new IOException(e); } } return conn; }
java
@Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) protected View onCreateView(View parent, String name, AttributeSet attrs) throws ClassNotFoundException { return mCalligraphyFactory.onViewCreated(super.onCreateView(parent, name, attrs), getContext(), attrs); }
java
protected boolean canConsume(Context context) { Set<String> contentTypes = context.getContentTypes(); if (!declaredConsumes.isEmpty()) { if (declaredConsumes.contains(Consumes.ALL)) { log.debug("{} will handle Request because it consumes '{}'", Util.toString(method), Consume...
python
def _build_tree(self): """Build the KDTree for the observed data """ if not self.nn_ready: self.kdtree = scipy.spatial.cKDTree(self.data) self.nn_ready = True
python
def node_stat_delta(self, char, node, *, store=True): """Return a dictionary describing changes to a node's stats since the last time you looked at it. Deleted keys have the value ``None``. If the node's been deleted, this returns ``None``. """ try: old = se...
java
private Set<Key<?>> getKeysToRemove(DependencyGraph graph, Collection<Key<?>> discovered) { Set<Key<?>> toRemove = new LinkedHashSet<Key<?>>(); while (!discovered.isEmpty()) { toRemove.addAll(discovered); discovered = getRequiredSourcesTargeting(graph, discovered); discovered.removeAll(toRemov...
java
public void getSubFolders(final String folder, final AsyncCallback<List<CmsVfsEntryBean>> callback) { CmsRpcAction<List<CmsVfsEntryBean>> action = new CmsRpcAction<List<CmsVfsEntryBean>>() { @Override public void execute() { start(0, false); getGalleryS...
python
def write_summary(stats, options, fw_type = None): """ writes contents of stats to outname_stats.csv :param stats: {'num_of_queries' : [(auc, auclow, auchigh),(fpf, ef, eflow, efhigh),(fpf, ef, eflow, efhigh),...,]} if fw_type is not None, stats has the form given below {'num_of_queries' : [(auc, au...
java
public void build(Node rootNode, SimpleApplication app) { house = (Node) app.getAssetManager().loadModel(urlResource); house.setUserData("ID", houseId); house.setUserData("ROLE", "House"); System.out.println("\n\nBuinding " + house.getName()); physicalEntities = (Node) house.getC...
python
def get_next_record(in_uid, kind='1'): ''' Get next record by time_create. ''' current_rec = MPost.get_by_uid(in_uid) recs = TabPost.select().where( (TabPost.kind == kind) & (TabPost.time_create < current_rec.time_create) ).order_by(TabPost.time_cr...
java
@Override public GrantFlowEntitlementsResult grantFlowEntitlements(GrantFlowEntitlementsRequest request) { request = beforeClientExecution(request); return executeGrantFlowEntitlements(request); }
java
private void onPerspectiveChanged(@Observes PluginSaved event) { Plugin plugin = event.getPlugin(); String pluginName = plugin.getName(); if (perspectiveIds.contains(pluginName)) { super.refresh(); } }
python
def reindex(self, request): """ Recreate the Search Index. """ r = redis.StrictRedis.from_url(request.registry.settings["celery.scheduler_url"]) try: with SearchLock(r, timeout=30 * 60, blocking_timeout=30): p = urllib.parse.urlparse(request.registry.settings["elasticsearch.url"]...
python
def retrieveVals(self): """Retrieve values for graphs.""" ntpinfo = NTPinfo() stats = ntpinfo.getHostOffset(self._remoteHost) if stats: graph_name = 'ntp_host_stratum_%s' % self._remoteHost if self.hasGraph(graph_name): self.setGraphVal(graph_name,...
java
public Object[] toArray() { Object[] result = new Object[size]; int i = 0; for (Node<E> x = first; x != null; x = x.next) result[i++] = x.item; return result; }
java
private static String getClassMethod(Class clazz, Method method) { StringBuilder builder = new StringBuilder(); builder.append(clazz.getName()).append(".").append(method.getName()); builder.append("("); if (method.getParameterCount() > 0) { for (int i = 0; i < method.getParameterCount(); i++) { Parameter...
java
protected @Nonnull WatchKey registerPath(@Nonnull Path dir) throws IOException { return dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY ); }
java
protected static Logger getLogger(final String fqcn, final String name) { return factory.getContext(fqcn, null, null, false).getLogger(name); }
python
def save(self): """Save the session for later retrieval :raises: IOError """ try: with open(self._filename, 'wb') as session_file: session_file.write(self.dumps()) except IOError as error: LOGGER.error('Session file error: %s', error) ...
java
public UUID getAccountId(final UUID objectId, final ObjectType objectType, final TenantContext context) { final Long accountRecordId = getAccountRecordIdSafe(objectId, objectType, context); if (accountRecordId != null) { return nonEntityDao.retrieveIdFromObject(accountRecordId, ObjectType.AC...
python
def connect(self, ctx): """ establish xbahn connection and store on click context """ if hasattr(ctx,"conn") or "host" not in ctx.params: return ctx.conn = conn = connect(ctx.params["host"]) lnk = link.Link() lnk.wire("main", receive=conn, send=conn...
java
public static long safeMultiply( long op1, long op2 ) { if (op2 == 1L) { return op1; } if ( (op2 > 0) ? (op1 > Long.MAX_VALUE / op2) || (op1 < Long.MIN_VALUE / op2) : ((op2 < -1) ? (op1 > Long.MIN_VALUE / op2) ...