language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_commit_from_gitpython(self, commit: GitCommit) -> Commit: """ Build a PyDriller commit object from a GitPython commit object. This is internal of PyDriller, I don't think users generally will need it. :param GitCommit commit: GitPython commit :return: Commit comm...
python
def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None: """Calls the given callback on the next IOLoop iteration. As of Tornado 6.0, this method is equivalent to `add_callback`. .. versionadded:: 4.0 """ self.add_callback(callback, *args, **kwargs)
python
def get_col_info(table_name, col_name, meta_file): """Return the content and metadata of a fiven column. Args: table_name(str): Name of the table. col_name(str): Name of the column. meta_file(str): Path to the meta.json file. Returns: tuple(pandas.Series, dict) """ ...
java
public static SortedSet<String> getIdsFromParameters(SolrParams params, String prefix) { SortedSet<String> ids = new TreeSet<>(); Iterator<String> it = params.getParameterNamesIterator(); Pattern pattern = Pattern .compile("^" + Pattern.quote(prefix) + "\\.([^\\.]+)(\\..*|$)"); while (it.h...
java
public List getControlsFor(Command command) { List controlsForCommand = new ArrayList(); for (Iterator it = commands.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); Control key = (Control) entry.getKey(); Command value = (Command) entry.getValue(); if (value == command...
python
def re_ask(self, with_help=True): """Re-asks user the last question :param with_help: True iff you want to show help on how to answer questions :return: user answer """ if with_help: self.show_help() return self.get_answer(self.last_question)
java
@Override public void set(double x1, double y1, double z1) { this.x = x1; this.y = y1; this.z = z1; }
java
public static Map<String, String> retrieveOverwriteElements(Element element) { Map<String, String> overwrites = new HashMap<String, String>(); NodeList elementsByTagName = element.getElementsByTagNameNS("*", "overwrite"); for (int i = 0; i < elementsByTagName.getLength(); i++) { Elem...
java
protected ArrayList<ArrayList<String>> parseFormula(HashMap<IAtomicConceptOfLabel, String> hashConceptNumber, Map<String, IAtomicConceptOfLabel> acolsMap, INode node) { ArrayList<ArrayList<String>> representation = new ArrayList<ArrayList<String>>(); ...
python
def dictlist_convert_to_int(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to an integer. If that fails, convert it to ``None``. """ for d in dict_list: try: d[key] = int(d[key]) ...
java
public void maybeBuildSecondaryIndexes(Collection<SSTableReader> sstables, Set<String> idxNames) { if (idxNames.isEmpty()) return; logger.info(String.format("Submitting index build of %s for data in %s", idxNames, StringUtils.join(sstables, ", "))); ...
java
private String getHierarchyTable(ClassDescriptorDef classDef) { ArrayList queue = new ArrayList(); String tableName = null; queue.add(classDef); while (!queue.isEmpty()) { ClassDescriptorDef curClassDef = (ClassDescriptorDef)queue.get(0); ...
python
def _WaitForStatusNotRunning(self): """Waits for the status is running to change to false.""" # We wait slightly longer than the status check sleep time. time.sleep(2.0) time_slept = 2.0 while self._status_is_running: time.sleep(0.5) time_slept += 0.5 if time_slept >= self._PROCESS...
java
@Override public ResourceSet<National> read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); }
python
def field_or_value(clause): """ For a clause that could be a field or value, create the right one and return it """ if hasattr(clause, "getName") and clause.getName() != "field": if clause.getName() == "set_function": return SetFunction.from_clause(clause) else: ...
python
def csv_print(classes, class_stat, digit=5, class_param=None): """ Return csv file data. :param classes: classes list :type classes:list :param class_stat: statistic result for each class :type class_stat:dict :param digit: scale (the number of digits to the right of the decimal point in a ...
python
def add_scale(self, name, W, b, has_bias, input_name, output_name, shape_scale = [1], shape_bias = [1]): """ Add scale layer to the model. Parameters ---------- name: str The name of this layer. W: int | numpy.array Scale of the input. b: ...
java
public void setVpcEndpointConnections(java.util.Collection<VpcEndpointConnection> vpcEndpointConnections) { if (vpcEndpointConnections == null) { this.vpcEndpointConnections = null; return; } this.vpcEndpointConnections = new com.amazonaws.internal.SdkInternalList<VpcEnd...
java
public Aliases add(String alias,String reference){ if (aliases.get(alias) == null){ aliases.put(alias,reference); } else { throw new IllegalArgumentException("Alias '" + alias + "' already exists"); } return this; }
java
public SQLSelect addTablePart(final String _tableName, final Integer _tableIndex) { parts.add(new FromTable(tablePrefix, _tableName, _tableIndex)); return this; }
python
def reload(self): 'Generate histrow for each row and then reverse-sort by length.' self.rows = [] # if len(self.origCols) == 1 and self.origCols[0].type in (int, float, currency): # self.numericBinning() # else: self.discreteBinning() # automatically add cache ...
python
def is_scheme(scheme, slashes=True): """Return whether *scheme* is valid for external links.""" scheme = scheme.lower() if slashes: return scheme in URI_SCHEMES return scheme in URI_SCHEMES and not URI_SCHEMES[scheme]
java
public static void main(String[] args) throws SolverException { // RandomVariableDifferentiableAAD is possible here! // RandomVariable[] initialParameters = new RandomVariable[] { new RandomVariableDifferentiableAAD(2), new RandomVariableDifferentiableAAD(2) }; RandomVariable[] initialParameters = new RandomVaria...
python
def to_product_form(self): """ Convert this instance of `DiscreteDP` to the "product" form. The product form uses the version of the init method taking `R`, `Q` and `beta`. Parameters ---------- Returns ------- ddp_sa : DiscreteDP Th...
java
public static IsLessThanOrEqual isLessThanOrEqual(NumberExpression left, Object constant) { if (!(constant instanceof Number)) throw new IllegalArgumentException("constant is not a Number"); return new IsLessThanOrEqual(left, constant((Number)constant)); }
java
public void convertAllPrefixesToHosts() { SurtPrefixSet iterCopy = (SurtPrefixSet) this.clone(); Iterator<String> iter = iterCopy.iterator(); while (iter.hasNext()) { String prefix = (String) iter.next(); String convPrefix = convertPrefixToHost(prefix); if(pre...
python
def add_conditional_state(self, name, state, validator, class_validator=None, cache_for=None, label=None): """ Add a conditional state that combines an existing state with a validator that must also pass. The validator receives the object on which the property is present as a parameter. ...
java
public DataSet<T> closeWith(DataSet<T> iterationResult) { return new BulkIterationResultSet<T>(getExecutionEnvironment(), getType(), this, iterationResult); }
java
protected void processResult(RO result) { for (ResultHandler<RO> resultHandler : resultHandlers) { resultHandler.handleResult(result); } }
python
def security_label(self, name, description=None, color=None): """Return instance of SecurityLabel. .. note:: The provided security label will be create if it doesn't exist. If the security label already exists nothing will be changed. Args: name (str): The value for thi...
python
def flags(cls): """A decorator for creating an int flags class. Makes the values a subclass of the type and implements repr/str. The new class will be a subclass of int. Args: cls (type): The class to convert to an flags Returns: type: A new class :: @flags c...
python
def placeOrder(self, id, contract, order): """placeOrder(EClientSocketBase self, OrderId id, Contract contract, Order order)""" return _swigibpy.EClientSocketBase_placeOrder(self, id, contract, order)
python
def check_X_y(X, y): """ tool to ensure input and output data have the same number of samples Parameters ---------- X : array-like y : array-like Returns ------- None """ if len(X) != len(y): raise ValueError('Inconsistent input and output data shapes. '\ ...
python
def plot(self,**kwargs): """ get a cheap plot of the Vario2d Parameters ---------- **kwargs : (dict) keyword arguments to use for plotting Returns ------- ax : matplotlib.pyplot.axis Note ---- optional arguments in kwargs inc...
python
def edit_permissions(self): """Creates the view used to edit permissions. To create the view, data in the following format is passed to the UI in the objects field: .. code-block:: python { "type": "tree-toggle", "action": "set_permission", ...
java
void waitRun(long waitMillis, int waitNanos, boolean cancelOnTimeOut) { if (!mDone) { synchronized (this) { if (!mDone) { try { this.wait(waitMillis, waitNanos); } catch (InterruptedException ignored) { ...
python
def pic_loggedrequiredremoterelease_v2(self): """Update the receiver link sequence.""" log = self.sequences.logs.fastaccess rec = self.sequences.receivers.fastaccess log.loggedrequiredremoterelease[0] = rec.s[0]
python
def start(self, *args, **kwargs):#pylint:disable=unused-argument """ | Launch the consumer. | It can listen forever for messages or just wait for one. :param forever: If set, the consumer listens forever. Default to `True`. :type forever: bool :param timeout: If set, the...
python
def patternVector(self, vector): """ Replaces vector with patterns. Used for loading inputs or targets from a file and still preserving patterns. """ if not self.patterned: return vector if type(vector) == int: if self.getWord(vector) != '': re...
python
def iterate(self, src, tgt, update=True, training=True): """ Performs one iteration of the training/validation. :param src: batch of examples from the source language :param tgt: batch of examples from the target language :param update: if True: optimizer does update of the weig...
python
def bounding_box(locations): """Computes the bounding box of an iterable of (x, y) coordinates. Args: locations: iterable of (x, y) tuples. Returns: `Rect`: Coordinates of the bounding box. """ x_values = list(map(itemgetter(0), locations)) x_min, x_max = min(x_values), max(x_v...
python
def get(self, request, *args, **kwargs): """ method called on GET request on this view :param django.http.HttpRequest request: The current request object """ logger.info("logout requested") # initialize the class attributes self.init_get(request) ...
java
public String getTexCoordShaderVar(String texName) { GVRTexture tex = textures.get(texName); if (tex != null) { return tex.getTexCoordShaderVar(); } return null; }
java
public static String cleanupStr(String name, boolean allowDottedKeys) { if (name == null) { return null; } Pattern pattern; if (!allowDottedKeys) { pattern = DOT_SLASH_UNDERSCORE_PAT; } else { pattern = SLASH_UNDERSCORE_PAT; } String clean = pattern.matcher(name).replaceAll("_"); clean = SPACE_...
java
public static <A, B, C, T> Parser<T> sequence( final Parser<A> p1, final Parser<B> p2, final Parser<C> p3, final Map3<? super A, ? super B, ? super C, ? extends T> map) { return new Parser<T>() { @Override boolean apply(ParseContext ctxt) { boolean r1 = p1.apply(ctxt); if (!r1) ret...
python
def _update_class(self, oldclass, newclass): """Update a class object.""" olddict = oldclass.__dict__ newdict = newclass.__dict__ oldnames = set(olddict) newnames = set(newdict) for name in newnames - oldnames: setattr(oldclass, name, newdict[name]) ...
python
def set_path(self, path, is_user=False): """ :param bool is_user: this event was fired by user """ self.clear_buttons() pathlist = util.rec_split_path(path) for (abspath, name) in pathlist: self.append_button(abspath, name) if is_user: sel...
java
@Override public void eUnset(int featureID) { switch (featureID) { case XbasePackage.XCATCH_CLAUSE__EXPRESSION: setExpression((XExpression)null); return; case XbasePackage.XCATCH_CLAUSE__DECLARED_PARAM: setDeclaredParam((JvmFormalParameter)null); return; } super.eUnset(featureID); }
python
def latex_to_img(tex): """Return a pygame image from a latex template.""" with tempfile.TemporaryDirectory() as tmpdirname: with open(tmpdirname + r'\tex.tex', 'w') as f: f.write(tex) os.system(r"latex {0}\tex.tex -halt-on-error -interaction=batchmode -disable-in...
python
def send_and_wait(self, path, message, timeout=0, responder=None): """ Send a message and block until a response is received. Return response message """ message.on("response", lambda x,event_origin,source:None, once=True) if timeout > 0: ts = time.time() el...
python
def AddForwardedIp(self, address, interface): """Configure a new IP address on the network interface. Args: address: string, the IP address to configure. interface: string, the output device to use. """ for ip in list(netaddr.IPNetwork(address)): self._RunIfconfig(args=[interface, 'al...
python
def set_index(self, index): """ Sets the pd dataframe index of all dataframes in the system to index """ for df in self.get_DataFrame(data=True, with_population=False): df.index = index
python
def get(self, bug_number): """ Get a bug from Bugzilla. If there is a login token created during object initialisation it will be part of the query string passed to Bugzilla :param bug_number: Bug Number that will be searched. If found will ...
python
def get_system_spec() -> Dict[str, str]: """Collect information about the system and installation. """ import pkg_resources import platform if sys.platform == 'darwin': system_info = 'macOS {} {}'.format( platform.mac_ver()[0], platform.architecture()[0], ) ...
python
def on_any_event(self, event): """File created or modified""" if os.path.isfile(event.src_path): self.callback(event.src_path, **self.kwargs)
java
private boolean isNotAssignedToOwnSlice(JavaClass javaClass) { List<String> dependencyIdentifier = sliceAssignment.getIdentifierOf(javaClass).getParts(); return !dependencyIdentifier.equals(matchingGroups); }
python
def read(fname): """ Return content of specified file """ path = os.path.join(SCRIPTDIR, fname) if PY3: f = open(path, 'r', encoding='utf8') else: f = open(path, 'r') content = f.read() f.close() return content
java
private static Set<File> getMatchingDescendants(File f, List<String>[] stackLists) { Set<File> rslt = new TreeSet<File>(); for (List<String> stack : stackLists) { rslt.addAll(getMatchingDescendants(f, stack)); } return rslt; }
java
private void addPostParams(final Request request) { if (username != null) { request.addPostParam("Username", username); } if (password != null) { request.addPostParam("Password", password); } }
java
public synchronized Constant getVal(int offset, Type type) { int size; byte[] byteVal = null; // Check the length of bytes if (type.isFixedSize()) { size = type.maxSize(); } else { byteVal = new byte[ByteHelper.INT_SIZE]; contents.get(offset, byteVal); size = ByteHelper.toInteger(byteVa...
python
def fold(self, **_3to2kwargs): policy = _3to2kwargs['policy']; del _3to2kwargs['policy'] """Fold header according to policy. The parsed representation of the header is folded according to RFC5322 rules, as modified by the policy. If the parse tree contains surrogateescaped byte...
java
public ServiceFuture<Void> updateAsync(String jobScheduleId, JobScheduleUpdateParameter jobScheduleUpdateParameter, JobScheduleUpdateOptions jobScheduleUpdateOptions, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromHeaderResponse(updateWithServiceResponseAsync(jobScheduleId, jobScheduleU...
java
@Override public void sendRawResponseBody(WsByteBuffer[] body) throws IOException, MessageSentException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "sendRawResponseBody(sync)"); } setRawBody(true); sendResponseBody(body); if (...
java
private void linearScan(Relation<? extends O> relation, DBIDIter iter, O obj, double range, ModifiableDoubleDBIDList result) { final PrimitiveDistanceFunction<? super O> rawdist = this.rawdist; while(iter.valid()) { final double distance = rawdist.distance(obj, relation.get(iter)); if(distance <= ra...
java
public static void main(String[] args) throws IOException { // check parameter count if (args.length < 2) { System.out.println("KMeansDataGenerator -points <num> -k <num clusters> [-output <output-path>] [-stddev <relative stddev>] [-range <centroid range>] [-seed <seed>]"); System.exit(1); } // parse p...
python
def swo_stop(self): """Stops collecting SWO data. Args: self (JLink): the ``JLink`` instance Returns: ``None`` Raises: JLinkException: on error """ res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.STOP, 0) if res < 0: ...
python
def connection_made(self, transport): """Connect to device is successful. Start configuring RTSP session. Schedule time out handle in case device doesn't respond. """ self.transport = transport self.transport.write(self.method.message.encode()) self.time_out_hand...
java
synchronized public List<ParserProvider> getAllProviders(boolean sort) { List<ParserProvider> providers = new ArrayList<>(); for(ParserProvider pp : loader) { providers.add(pp); } if (sort) { Collections.sort(providers, PARSER_PROVIDER_COMPARATOR); } return providers; }
java
public String getPropertyValue(final String propertyName, final String defaultPropertyValue) { return defaultIfUnset(getPropertyValue(propertyName, NOT_REQUIRED), defaultPropertyValue); }
python
def plot_hdd(HDD, B, M, s): """ Function to make hysteresis, deltaM and DdeltaM plots Parameters: _______________ Input HDD : dictionary with figure numbers for the keys: 'hyst' : hysteresis plot normalized to maximum value 'deltaM' : Delta M plot 'Ddelt...
python
def playbook_treeview(playbook): """ Creates a fake filesystem with playbook files and uses generate_tree() to recurse and return a JSON structure suitable for bootstrap-treeview. """ fs = fake_filesystem.FakeFilesystem() mock_os = fake_filesystem.FakeOsModule(fs) files = models.File.query....
python
def vequg(v1, ndim): """ Make one double precision vector of arbitrary dimension equal to another. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vequg_c.html :param v1: ndim-dimensional double precision vector. :type v1: list[ndim] :param ndim: Dimension of vin (and also vout). ...
java
public static Instance findRootInstance( Instance instance ) { Instance rootInstance = instance; while( rootInstance.getParent() != null ) rootInstance = rootInstance.getParent(); return rootInstance; }
python
def reg(name): ''' Activate this register to turn on a minion status tracking register, this register keeps the current status beacon data and the time that each beacon was last checked in. ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} ...
java
private int findValueIndicesIndexForSubColumn() { final DimensionSelector keySelector = getKeySelector(); final DimensionSelector valueSelector = getValueSelector(); final IndexedInts keyIndices = keySelector.getRow(); final IndexedInts valueIndices = valueSelector.getRow(); final int limit = Ma...
python
def add_embedding_path(self, x, dimensions, vectors_path, metadata=None, image_shape=None, image=None): """ Adds a new embedding with optional metadata. Example how to generate vectors based on 2D numpy array: # 4 vectors, each size of 3 vectors = [ [2.3, 4....
java
private NamingException throwCannotInstanciateObjectException(EJBBinding binding, JavaColonNamespace jndiType, String lookupName, ...
python
def authorization_code_pkce(self, client_id, code_verifier, code, redirect_uri, grant_type='authorization_code'): """Authorization code pkce grant This is the OAuth 2.0 grant that mobile apps utilize in order to access an API. Use this endpoint to exchange an Aut...
python
def unmount(self, path): """ Remove a mountpoint from the filesystem. """ del self._mountpoints[self._join_chunks(self._normalize_path(path))]
python
def replace_cluster_custom_object_scale(self, group, version, plural, name, body, **kwargs): """ replace scale of the specified cluster scoped custom object This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >...
java
@Override public Planar<T> subimage(int x0, int y0, int x1, int y1, Planar<T> subimage) { if (x0 < 0 || y0 < 0) throw new IllegalArgumentException("x0 or y0 is less than zero"); if (x1 < x0 || y1 < y0) throw new IllegalArgumentException("x1 or y1 is less than x0 or y0 respectively"); if (x1 > width || y1 >...
java
public void setMonthParams(HashMap<String, Integer> params) { if (!params.containsKey(VIEW_PARAMS_MONTH) && !params.containsKey(VIEW_PARAMS_YEAR)) { throw new InvalidParameterException("You must specify the month and year for this view"); } setTag(params); // We keep the curr...
python
def cardinality(gym_space): """Number of elements that can be represented by the space. Makes the most sense for Discrete or Box type with integral dtype, ex: number of actions in an action space. Args: gym_space: The gym space. Returns: np.int64 number of observations that can be represented by th...
python
def _delete_temp_logs(self, family_name: str): """Delete temporary logs for the current family.""" for temp_log in self.store.analyses(family=family_name, temp=True): log.debug(f"delete temporary log: {temp_log.id} - {temp_log.status}") temp_log.delete()
python
def get_row_list(self, row_idx): """ get a feature vector for the nth row :param row_idx: which row :return: a list of feature values, ordered by column_names """ try: row = self._rows[row_idx] except TypeError: row = self._rows[self._row_name_id...
python
def update(self, environments): """ Method to update environments vip :param environments vip: List containing environments vip desired to updated :return: None """ data = {'environments_vip': environments} environments_ids = [st...
python
def get_version_of_tools(): """ get versions of tools reactor is using (specified in constants.TOOLS_USED) :returns list of dicts, [{"name": "docker-py", "version": "1.2.3"}, ...] """ response = [] for tool in TOOLS_USED: pkg_name = tool["pkg_name"] try: tool_module ...
java
public SAXRecords process(double[] timeseries, int threadsNum, int slidingWindowSize, int paaSize, int alphabetSize, NumerosityReductionStrategy numRedStrategy, double normalizationThreshold) throws SAXException { LOGGER.debug("Starting the parallel SAX"); NormalAlphabet na = new NormalAlphabet();...
python
def check_python_version(): """Check if the currently running Python version is new enough.""" # Required due to multiple with statements on one line req_version = (2, 7) cur_version = sys.version_info if cur_version >= req_version: print("Python version... %sOK%s (found %s, requires %s)" % ...
java
public static <T> Set<T> toSet(Iterator<T> self) { Set<T> answer = new HashSet<T>(); while (self.hasNext()) { answer.add(self.next()); } return answer; }
python
def get_volumes(self): """Recursively gets a list of all subvolumes and the current volume.""" if self.volumes: volumes = [] for v in self.volumes: volumes.extend(v.get_volumes()) volumes.append(self) return volumes else: ...
python
def encode(self): """Encodes matrix :return: Encoder used """ encoder = LabelEncoder() # encoder values = self.get_as_list() encoded = encoder.fit_transform(values) # long list of encoded n_columns = len(self.matrix[0]) n_rows = len(self.matrix) ...
java
public static AFPChain fastaFileToAfpChain(File fastaFile, Structure structure1, Structure structure2) throws IOException, StructureException { InputStream inStream = new FileInputStream(fastaFile); SequenceCreatorInterface<AminoAcidCompound> creator = new CasePreservingProteinSequenceCreator( AminoAcidCompo...
python
def from_utctimestamp(self, timestamp): """Create a **UTC datetime** object that number of seconds after UTC 1970-01-01 00:00:00. If you want local time, use :meth:`Rolex.from_timestamp` Because python doesn't support negative timestamp to datetime so we have to implement my own...
java
protected List<CRFDatum> extractDatumSequence(int[][][] allData, int beginPosition, int endPosition, List<IN> labeledWordInfos) { List<CRFDatum> result = new ArrayList<CRFDatum>(); int beginContext = beginPosition - windowSize + 1; if (beginContext < 0) { beginContext = 0; } // fo...
java
public int size() { int size = 0; for(K key : keys()) { size += getValues(key).size(); } return size; }
java
private void checkKeyVisibilityConvention(Node key, Node parent) { JSDocInfo info = key.getJSDocInfo(); if (info == null) { return; } if (!isPrivateByConvention(key.getString())) { return; } Node assign = parent.getParent(); if (assign == null || !assign.isAssign()) { retur...
java
public double[] foldRows(VectorAccumulator accumulator) { double[] result = new double[rows]; for (int i = 0; i < rows; i++) { result[i] = foldRow(i, accumulator); } return result; }
java
public static byte[] getBytes(long val, long size) { byte[] res = new byte[(int) size]; long bv = val; for (int i = (int) size - 1; i >= 0; --i) { res[i] = (byte) (bv & 0xFF); bv >>= BIT_IN_BYTE; } return res; }
python
def _federation_indicators(catalog, central_catalog, identifier_search=False): """Cuenta la cantidad de datasets incluídos tanto en la lista 'catalogs' como en el catálogo central, y genera indicadores a partir de esa información. Args: catalog (dict): catálogo ya par...