language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public YamlLoader getLoader(String name) { for (YamlProperties yamlProp : yamlProps) { if (yamlProp.getRoot().containsKey(name)) { return yamlProp.getLoader(); } } return null; }
java
public static Codec<int[], IntegerGene> ofVector(final IntRange... domains) { if (domains.length == 0) { throw new IllegalArgumentException("Domains must not be empty."); } final ISeq<IntegerChromosome> chromosomes = Stream.of(domains) .peek(Objects::requireNonNull) .map(IntegerGene::of) .map(Integer...
python
def get_all_components(user, topic_id): """Get all components of a topic.""" args = schemas.args(flask.request.args.to_dict()) query = v1_utils.QueryBuilder(_TABLE, args, _C_COLUMNS) query.add_extra_condition(sql.and_( _TABLE.c.topic_id == topic_id, _TABLE.c.state != 'archived')) ...
python
def _draw_frame(self, framedata): """Reads, processes and draws the frames. If needed for color maps, conversions to gray scale are performed. In case the images are no color images and no custom color maps are defined, the colormap `gray` is applied. This function is called by...
python
def _ixor(self, other): """Set self to the symmetric difference between the sets. if isinstance(other, _basebag): This runs in O(other.num_unique_elements()) else: This runs in O(len(other)) """ if isinstance(other, _basebag): for elem, other_count in other.counts(): count = abs(self.count(elem)...
python
def update_cached_fields_pre_save(self, update_fields: list): """ Call on pre_save signal for objects (to automatically refresh on save). :param update_fields: list of fields to update """ if self.id and update_fields is None: self.update_cached_fields(commit=False, e...
python
def _evaluate(self,R,phi=0.,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential at R,phi,t INPUT: R - Galactocentric cylindrical radius phi - azimuth t - time OUTPUT: Phi(R,phi,t) HISTORY: ...
python
def uricompose(scheme=None, authority=None, path='', query=None, fragment=None, userinfo=None, host=None, port=None, querysep='&', encoding='utf-8'): """Compose a URI reference string from its individual components.""" # RFC 3986 3.1: Scheme names consist of a sequence of characte...
python
def _check_graph(self, graph): """the atomic numbers must match""" if graph.num_vertices != self.size: raise TypeError("The number of vertices in the graph does not " "match the length of the atomic numbers array.") # In practice these are typically the same arrays us...
python
def create(self, r, r_, R=200): '''Create new spirograph image with given arguments. Returned image is scaled to agent's preferred image size. ''' x, y = give_dots(R, r, r_, spins=20) xy = np.array([x, y]).T xy = np.array(np.around(xy), dtype=np.int64) xy = xy[(xy...
java
static void createGeneratedFilesDirectory(String apiName) { File folder = new File(getDestinationDirectory(apiName)); if (!folder.exists()){ //noinspection ResultOfMethodCallIgnored folder.mkdirs(); } }
java
public Block[] getBlocksBeingWrittenReport(int namespaceId) throws IOException { LightWeightHashSet<Block> blockSet = new LightWeightHashSet<Block>(); volumes.getBlocksBeingWrittenInfo(namespaceId, blockSet); Block blockTable[] = new Block[blockSet.size()]; int i = 0; for (Iterator<Block> it = blo...
java
public static void deleteRole(DbConn cnx, int id, boolean force) { if (force) { cnx.runUpdate("user_remove_role", id); } else { int userUsingRole = cnx.runSelectSingle("user_select_count_using_role", Integer.class, id); if (userUsingRole > ...
python
def store(self, bank, key, data): ''' Store data using the specified module :param bank: The name of the location inside the cache which will hold the key and its associated data. :param key: The name of the key (or file inside a directory) which wil...
java
@Override public DescribeBackupVaultResult describeBackupVault(DescribeBackupVaultRequest request) { request = beforeClientExecution(request); return executeDescribeBackupVault(request); }
python
def subkeys(self, path): """ A generalized form that can return multiple subkeys. """ for _ in subpaths_for_path_range(path, hardening_chars="'pH"): yield self.subkey(_)
python
def cook_layout(layout, ajax): """Return main_template compatible layout""" # Fix XHTML layouts with CR[+LF] line endings layout = re.sub('\r', '\n', re.sub('\r\n', '\n', layout)) # Parse layout if isinstance(layout, six.text_type): result = getHTMLSerializer([layout.encode('utf-8')], encod...
python
def has_attribute_type(self, attribute: str, typ: Type) -> bool: """Whether the given attribute exists and has a compatible type. Returns true iff the attribute exists and is an instance of \ the given type. Matching between types passed as typ and \ yaml node types is as follows: ...
java
public static int cardinality(long[] v) { int sum = 0; for(int i = 0; i < v.length; i++) { sum += Long.bitCount(v[i]); } return sum; }
java
public void unbindView() { if (mContentView != null) { this.mContentView.setAdapter(null); this.mContentView.setLayoutManager(null); this.mContentView = null; } }
python
def register_entity_to_group(self, entity, group): ''' Add entity to a group. If group does not exist, entity will be added as first member entity is of type Entity group is a string that is the name of the group ''' if entity in self._entities: if gro...
python
def batch_keep_absolute_retrain__r2(X, y, model_generator, method_name, num_fcounts=11): """ Batch Keep Absolute (retrain) xlabel = "Fraction of features kept" ylabel = "R^2" transform = "identity" sort_order = 13 """ return __run_batch_abs_metric(measures.batch_keep_retrain, X, y, model_gen...
java
private void improveGermanSentences(JCas jcas) { /* * these POS tag sequences will decide whether we want to merge two sentences * that have (supposedly wrongfully) been split. */ HashSet<String[]> posRules = new HashSet<String[]>(); posRules.add(new String[] {"CARD", "\\$.", "NN"}); posRules.add(new ...
java
private void addFace(String data) { matcher = facePattern.matcher(data); List<Vertex> faceVertex = new ArrayList<>(); List<Vector> faceNormals = new ArrayList<>(); int v = 0, t = 0, n = 0; String strV, strT, strN; Vertex vertex, vertexCopy; UV uv = null; Vector normal; while (matcher.find()) { ...
python
def rmi(self, force=False, via_name=False): """ remove this image :param force: bool, force removal of the image :param via_name: bool, refer to the image via name, if false, refer via ID, not used now :return: None """ return os.remove(self.local_location)
java
@Override public void sawOpcode(int seen) { IOIUserValue uvSawType = null; try { switch (seen) { case Const.INVOKESPECIAL: uvSawType = processInvokeSpecial(); break; case Const.INVOKESTATIC: processInvokeStatic(); ...
python
def parse_lines(self, file, boundary, content_length): """Generate parts of ``('begin_form', (headers, name))`` ``('begin_file', (headers, name, filename))`` ``('cont', bytestring)`` ``('end', None)`` Always obeys the grammar parts = ( begin_form cont* end | ...
java
public void executeMethods(final List<Method> methods) throws Exception { for (final Method method : methods) { // TODO - curious about the findSuitableInstancesOf ? won't // method.getDeclaringClass be ok?? for (final Object object : findSuitableInstancesOf(method.getDecl...
java
@Nullable public PaymentIntent confirmPaymentIntentSynchronous( @NonNull PaymentIntentParams paymentIntentParams, @NonNull String publishableKey) throws AuthenticationException, InvalidRequestException, APIConnectionException, APIException { return...
python
def draw(self, **kwargs): """ Called from the fit method, this method creates the canvas and draws the distribution plot on it. Parameters ---------- kwargs: generic keyword arguments. """ # Prepare the data bins = np.arange(self.N) word...
python
def get_sentence(sentence_id=None): """Retrieve a randomly-generated sentence as a unicode string. :param sentence_id: Allows you to optionally specify an integer representing the sentence_id from the database table. This allows you to retrieve a specific sentence each tim...
python
def parseString( self, instring, parseAll=False ): """Execute the parse expression with the given string. This is the main interface to the client code, once the complete expression has been built. If you want the grammar to require that the entire input string be su...
java
public void insert_uc(final byte argin) { final byte[] values = new byte[1]; attrval.r_dim.dim_x = 1; values[0] = argin; attrval.r_dim.dim_y = 0; DevVarCharArrayHelper.insert(attrval.value, values); }
java
public Optional<Board> getOptionalBoard(Object projectIdOrPath, Integer boardId) { try { return (Optional.ofNullable(getBoard(projectIdOrPath, boardId))); } catch (GitLabApiException glae) { return (GitLabApi.createOptionalFromException(glae)); } }
java
public List<PrivacyItem> setPrivacyList(String listName, List<PrivacyItem> listItem) { // Add new list to the itemLists this.getItemLists().put(listName, listItem); return listItem; }
python
def use_plenary_proficiency_view(self): """Pass through to provider ProficiencyLookupSession.use_plenary_proficiency_view""" self._object_views['proficiency'] = PLENARY # self._get_provider_session('proficiency_lookup_session') # To make sure the session is tracked for session in self._g...
python
def stream_replicate(): """Monitor changes in approximately real-time and replicate them""" stream = primary.stream(SomeDataBlob, "trim_horizon") next_heartbeat = pendulum.now() while True: now = pendulum.now() if now >= next_heartbeat: stream.heartbeat() next_hea...
python
def add_errback(self, fn, *args, **kwargs): """ Like :meth:`.add_callback()`, but handles error cases. An Exception instance will be passed as the first positional argument to `fn`. """ run_now = False with self._callback_lock: # Always add fn to self....
java
public com.google.api.ads.adwords.axis.v201809.cm.FeedStatus getFeedStatus() { return feedStatus; }
python
def commandlineargs(self): """Obtain a string of all parameters, using the paramater flags they were defined with, in order to pass to an external command. This is shell-safe by definition.""" commandlineargs = [] for parametergroup, parameters in self.parameters: #pylint: disable=unused-variabl...
python
def from_dict(cls, d): """ Create Site from dict representation """ atoms_n_occu = {} for sp_occu in d["species"]: if "oxidation_state" in sp_occu and Element.is_valid_symbol( sp_occu["element"]): sp = Specie.from_dict(sp_occu) ...
python
def execute_after_delay(time_s, func, *args, **kwargs): """A function that executes the given function after a delay. Executes func in a separate thread after a delay, so that this function returns immediately. Note that any exceptions raised by func will be ignored (but logged). Also, if time_s is a PolledT...
python
def get_keys_for(self, value, include_uncommitted=False): """Get keys for a given value. :param value: The value to look for :type value: object :param include_uncommitted: Include uncommitted values in results :type include_uncommitted: bool :return: The keys for the gi...
python
def pvalues(self): """Association p-value for candidate markers.""" self.compute_statistics() lml_alts = self.alt_lmls() lml_null = self.null_lml() lrs = -2 * lml_null + 2 * asarray(lml_alts) from scipy.stats import chi2 chi2 = chi2(df=1) return chi2.s...
python
def get_certs(context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE): ''' Get the available certificates in the given store. :param str context: The name of the certificate store location context. :param str store: The name of the certificate store. :return: A dictionary of the certificate thumbprints an...
java
private void updatePov() { MapView mapView = getMapModel().getMapView(); WorldViewTransformer transformer = new WorldViewTransformer(mapView); Bbox targetBox = targetMap.getMapModel().getMapView().getBounds(); Bbox overviewBox = mapView.getBounds(); // check if bounds are valid if (Double.isNaN(overviewBox...
java
protected void setColumnVisibilities() { m_colVisibilities = new HashMap<Integer, Boolean>(16); // set explorer configurable column visibilities int preferences = new CmsUserSettings(getCms()).getExplorerSettings(); setColumnVisibility(CmsUserSettings.FILELIST_TITLE, preferences); ...
java
@NonNull public static CreateKeyspaceStart createKeyspace(@NonNull String keyspaceName) { return createKeyspace(CqlIdentifier.fromCql(keyspaceName)); }
python
def get_events( self, obj_id, search='', include_events=None, exclude_events=None, order_by='', order_by_dir='ASC', page=1 ): """ Get a list of a contact's engagement events :param obj_id: int Contact ID :param search: ...
java
public PartialResponseChangesType<T> eval(String ... values) { if (values != null) { for(String name: values) { childNode.createChild("eval").text(name); } } return this; }
python
def tv_distance(a, b): '''Get the Total Variation (TV) distance between two densities a and b.''' if len(a.shape) == 1: return np.sum(np.abs(a - b)) return np.sum(np.abs(a - b), axis=1)
python
def remove_escalation_policy(self, escalation_policy, **kwargs): """Remove an escalation policy from this team.""" if isinstance(escalation_policy, Entity): escalation_policy = escalation_policy['id'] assert isinstance(escalation_policy, six.string_types) endpoint = '{0}/{1...
python
def submit_completion(self, user, course_key, block_key, completion): """ Update the completion value for the specified record. Parameters: * user (django.contrib.auth.models.User): The user for whom the completion is being submitted. * course_key (opaque_k...
python
def save(self, *args, **kwargs): """Make sure token is added.""" self.save_prep(instance_or_instances=self) return super(AbstractTokenModel, self).save(*args, **kwargs)
java
public void setAttribute(String name, String value, String facet) throws JspException { // validate the name attribute, in the case of an error simply return. if (name == null || name.length() <= 0) { String s = Bundle.getString("Tags_AttributeNameNotSet"); regist...
python
def makeHist(x_val, y_val, fit=spline_base.fit2d, bins=[np.linspace(-36.5,36.5,74),np.linspace(-180,180,361)]): """ Constructs a (fitted) histogram of the given data. Parameters: x_val : array The data to be histogrammed along the x-axis. y_val : array ...
java
public ItemRequest<User> findById(String user) { String path = String.format("/users/%s", user); return new ItemRequest<User>(this, User.class, path, "GET"); }
python
def get_crab(registry): """ Get the Crab Gateway :rtype: :class:`crabpy.gateway.crab.CrabGateway` # argument might be a config or a request """ # argument might be a config or a request regis = getattr(registry, 'registry', None) if regis is None: regis = registry return re...
python
def _preprocess_data(self, X, Y=None, idxs=None, train=False): """ Preprocess the data: 1. Make sentence with mention into sequence data for LSTM. 2. Select subset of the input if idxs exists. :param X: The input data of the model. :type X: pair with candidates and corre...
python
def get_soap_object(self, client): """ Override default get_soap_object behavior to account for child Record types """ record_data = super().get_soap_object(client) record_data.records = [Record(r).get_soap_object(client) for r in record_data.records] return record_data
python
def linearization_error(nodes): """Image for :func:`.linearization_error` docstring.""" if NO_IMAGES: return curve = bezier.Curve.from_nodes(nodes) line = bezier.Curve.from_nodes(nodes[:, (0, -1)]) midpoints = np.hstack([curve.evaluate(0.5), line.evaluate(0.5)]) ax = curve.plot(256) ...
java
private static String getParameterName(Method m, int paramIndex) { PName pName = getParameterAnnotation(m, paramIndex, PName.class); if (pName != null) { return pName.value(); } else { return ""; } }
python
def signature_unsafe(m, sk, pk, hash_func=H): """ Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only. """ h = hash_func(sk) a = 2 ** (b - 2) + sum(2 ** i * bit(h, i) for i in range(3, b - 2)) r = Hint(bytearray([h[j] for j in...
python
def remove_model(self, model, **kwargs): """ Remove a 'model' from the bundle :parameter str twig: twig to filter for the model :parameter **kwargs: any other tags to do the filter (except twig or context) """ kwargs['model'] = model kwargs['context']...
java
public static String dateToString(Date date) { final TimeZone utc = TimeZone.getTimeZone("UTC"); SimpleDateFormat tformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); tformat.setTimeZone(utc); return tformat.format(date); }
python
def execute(action): """ Execute the given action. An action is any object with a ``forwards()`` and ``backwards()`` method. .. code-block:: python class CreateUser(object): def __init__(self, userinfo): self.userinfo = userinfo self.user_id = Non...
python
def item_related_name(self): """ The ManyToMany field on the item class pointing to this class. If there is more than one field, this value will be None. """ if not hasattr(self, '_item_related_name'): many_to_many_rels = \ get_section_many_to_many_re...
python
def status(self, key, value): """Update the status of a build""" value = value.lower() if value not in valid_statuses: raise ValueError("Build Status must have a value from:\n{}".format(", ".join(valid_statuses))) self.obj['status'][key] = value self.changes.append("...
python
def _validate_required(self, settings, name, value): """ Validate a required setting (value can not be empty) Args: settings (dict): Current settings. name (str): Setting name. value (str): Required value to validate. Raises: boussole.exc...
java
protected boolean tryBridgeMethod(MethodNode target, Expression receiver, boolean implicitThis, TupleExpression args) { ClassNode lookupClassNode; if (target.isProtected()) { lookupClassNode = controller.getClassNode(); if (controller.isInClosure()) { lookupClassN...
java
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled...
java
public ClientStatsContext fetch() { m_current = m_distributor.getStatsSnapshot(); m_currentIO = m_distributor.getIOStatsSnapshot(); m_currentTS = System.currentTimeMillis(); m_currentAffinity = m_distributor.getAffinityStatsSnapshot(); return this; }
java
private static String format(Date date, boolean millis, TimeZone tz) { Calendar calendar = new GregorianCalendar(tz, Locale.US); calendar.setTime(date); // estimate capacity of buffer as close as we can (yeah, that's pedantic ;) int capacity = "yyyy-MM-ddThh:mm:ss".length(); capacity += m...
java
public void deltaTotalGetTime(long delta) { if (enabled.get() && delta > 0) { totalGetTime.addAndGet(delta); totalGetTimeInvocations.incrementAndGet(); if (delta > maxGetTime.get()) maxGetTime.set(delta); } }
python
def iris_enrich(self, *domains, **kwargs): """Returns back enriched data related to the specified domains using our Iris Enrich service each domain should be passed in as an un-named argument to the method: iris_enrich('domaintools.com', 'google.com') api.iris_enrich(*DOMAI...
java
public static File zip(File zipFile, String path, String data, Charset charset) throws UtilException { return zip(zipFile, path, IoUtil.toStream(data, charset), charset); }
python
def get_windows_interfaces(): """ Get Windows interfaces. :returns: list of windows interfaces """ import win32com.client import pywintypes interfaces = [] try: locator = win32com.client.Dispatch("WbemScripting.SWbemLocator") service = locator.ConnectServer(".", "root\...
python
def display_to_value(value, default_value, ignore_errors=True): """Convert back to value""" from qtpy.compat import from_qvariant value = from_qvariant(value, to_text_string) try: np_dtype = get_numpy_dtype(default_value) if isinstance(default_value, bool): # We must test for...
python
def _any_would_run(func, filenames, *args): """True if a linter function would be called on any of filenames.""" if os.environ.get("_POLYSQUARE_GENERIC_FILE_LINTER_NO_STAMPING", None): return True for filename in filenames: # suppress(E204) stamp_args, stamp_kwargs = _run_lint_on_fi...
python
def _simulate_coef_from_bootstraps( self, n_draws, coef_bootstraps, cov_bootstraps): """Simulate coefficients using bootstrap samples.""" # Sample indices uniformly from {0, ..., n_bootstraps - 1} # (Wood pg. 199 step 6) random_bootstrap_indices = np.random.choice( ...
java
private void removeFolders() throws CmsImportExportException { try { int size = m_folderStorage.size(); m_report.println(Messages.get().container(Messages.RPT_DELFOLDER_START_0), I_CmsReport.FORMAT_HEADLINE); // iterate though all collected folders. Iteration must start at...
python
def iter_lines(self, section): """Iterate over all lines in a section. This will skip 'header' lines. """ try: section = self._get_section(section, create=False) except KeyError: return for block in section: for line in block: ...
java
public <T> T post(final Class<T> type, final Consumer<HttpConfig> configuration) { return type.cast(interceptors.get(HttpVerb.POST).apply(configureRequest(type, HttpVerb.POST, configuration), this::doPost)); }
python
def _serialize_dict(cls, dict_): """ :type dict_ dict :rtype: dict """ obj_serialized = {} for key in dict_.keys(): item_serialized = cls.serialize(dict_[key]) if item_serialized is not None: key = key.rstrip(cls._SUFFIX_KEY_OVE...
java
public void getAllLegendID(Callback<List<String>> callback) throws NullPointerException { gw2API.getAllLegendIDs().enqueue(callback); }
python
def _get(self, *rules): # type: (Iterable[Type[Rule]]) -> Generator[Type[Rule]] """ Get rules representing parameters. The return rules can be different from parameters, in case parameter define multiple rules in one class. :param rules: For which rules get the representation. ...
java
public static boolean hasGeoPackageExtension(File file) { String extension = GeoPackageIOUtils.getFileExtension(file); boolean isGeoPackage = extension != null && (extension .equalsIgnoreCase(GeoPackageConstants.GEOPACKAGE_EXTENSION) || extension .equalsIgnoreCase(GeoPackageConstants.GEOPACKAGE_EXTE...
java
public static Object getLazyString(LazyEvaluation lazyLambda) { return new Object() { @Override public String toString() { try { return lazyLambda.getString(); } catch (Exception e...
python
def send_offset_commit_request(self, group, payloads=None, fail_on_error=True, callback=None, group_generation_id=-1, consumer_id=''): """Send a list of OffsetCommitRequests to the Kafka broker for the ...
java
public void marshall(StartJobRequest startJobRequest, ProtocolMarshaller protocolMarshaller) { if (startJobRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(startJobRequest.getAppId(), APPID_...
java
@Nonnull @ReturnsMutableCopy public ICommonsList <String> getAllUserGroupIDsWithAssignedUser (@Nullable final String sUserID) { if (StringHelper.hasNoText (sUserID)) return new CommonsArrayList <> (); return getAllMapped (aUserGroup -> aUserGroup.containsUserID (sUserID), aUserGroup -> aUserGroup.g...
python
def ensureVisible(self, viewType): """ Find and switch to the first tab of the specified view type. If the type does not exist, add it. :param viewType | <subclass of XView> :return <XView> || None """ # make sure we're not trying to switch to the same ty...
java
@Nonnull public String createBackupKey( @Nonnull final String origKey ) { if ( origKey == null ) { throw new IllegalArgumentException( "The origKey must not be null." ); } return BACKUP_PREFIX + _storageKeyFormat.format(origKey); }
python
def do_stop_role(self, role): """ Stop a role Usage: > stop_role <role> Stops this role """ if not role: return None if not self.has_cluster(): return None if '-' not in role: print("Please enter a valid role name...
python
def get_data_for_name(cls, service_name): """Get the data relating to a named music service. Args: service_name (str): The name of the music service for which data is required. Returns: dict: Data relating to the music service. Raises: ...
java
public void updateComputeNodeUser(String poolId, String nodeId, String userName, String password, DateTime expiryTime, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException { NodeUpdateUserParameter param = new NodeUpdateUserParameter(); param.withPassword(password);...
java
public final ListModelEvaluationsPagedResponse listModelEvaluations(String parent) { ListModelEvaluationsRequest request = ListModelEvaluationsRequest.newBuilder().setParent(parent).build(); return listModelEvaluations(request); }
java
public Iterator<T> getInputSplits() { final InputSplitProvider provider = getEnvironment().getInputSplitProvider(); return new Iterator<T>() { private T nextSplit; @Override public boolean hasNext() { if (this.nextSplit == null) { final InputSplit split = provider.getNextInputSplit(); i...
java
public void doAdd(@FormGroup("canalInfo") Group canalInfo, @FormGroup("canalParameterInfo") Group canalParameterInfo, @FormField(name = "formCanalError", group = "canalInfo") CustomErrors err, @FormField(name = "formHeartBeatError", group = "canalParamet...
java
public static void runExample( AdWordsServicesInterface adWordsServices, AdWordsSession session, String conversionName, String gclId, OfflineConversionAdjustmentType adjustmentType, String conversionTime, String adjustmentTime, @Nullable Double adjustedValue) throws...