language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def remove_value(self, keys, value): """ Remove a value (data item) from this tree node and its children. Also updates the tree node's cumulative child count. """ self.count -= 1 if not self.key: keys = self.__value_reverse_mapping[value] d...
python
def remove_receiver(self, receiver): """ Remove a receiver to the list of receivers. :param receiver: a callable variable """ if receiver in self.event_receivers: self.event_receivers.remove(receiver)
python
def move_down(lines=1, file=sys.stdout): """ Move the cursor down a number of lines. Esc[<lines>B: Moves the cursor down by the specified number of lines without changing columns. If the cursor is already on the bottom line, ANSI.SYS ignores this sequence. """ move.down(line...
python
def timeCall(*funcAndArgs, **kwargs): r"""Return the time (in ms) it takes to call a function (the first argument) with the remaining arguments and `kwargs`. Examples: To find out how long ``func('foo', spam=1)`` takes to execute, do: ``timeCall(func, foo, spam=1)`` """ func, args = func...
python
def repeat(self, repeats, axis=None): """ Repeat elements of a Series. Returns a new Series where each element of the current Series is repeated consecutively a given number of times. Parameters ---------- repeats : int or array of ints The number of...
python
def WriteHeader(self): """Connects to the Elasticsearch server and creates the index.""" mappings = {} if self._raw_fields: if self._document_type not in mappings: mappings[self._document_type] = {} mappings[self._document_type]['dynamic_templates'] = [{ 'strings': { ...
java
public void writeResources() { StreamOut out = null; Record registration = this.getMainRecord(); Resource resource = (Resource)this.getRecord(Resource.RESOURCE_FILE); String strCurrentFileName = "none"; String strCurrentLanguage = "none"; String strCurrentLoc...
python
def run_outdated(cls, options): """Print outdated user packages.""" latest_versions = sorted( cls.find_packages_latest_versions(cls.options), key=lambda p: p[0].project_name.lower()) for dist, latest_version, typ in latest_versions: if latest_version > dist.p...
java
public static String parseCH(String inputText, boolean partialAllowed) { if (StringUtils.isEmpty(inputText)) return null; String text = cutNonDigitsAtBegin(inputText); if (StringUtils.isEmpty(text)) return ""; text = cutNonDigitsAtEnd(text); if (StringUtils.isEmpty(text)) return ""; // Nun hat der String...
java
private TabularData convertTabularDataFromFullRepresentation(JSONObject pValue, TabularType pType) { JSONAware jsonVal; jsonVal = (JSONAware) pValue.get("values"); if (!(jsonVal instanceof JSONArray)) { throw new IllegalArgumentException("Values for tabular data of type " + ...
python
def transform_y(self, tfms:TfmList=None, **kwargs): "Set `tfms` to be applied to the targets only." _check_kwargs(self.y, tfms, **kwargs) self.tfm_y=True if tfms is None: self.tfms_y = list(filter(lambda t: t.use_on_y, listify(self.tfms))) self.tfmargs_y = {**self...
java
public static int roundHalfUp(final Object obj) { if (obj instanceof Short) { return (short) obj; } if (obj instanceof Integer) { return (int) obj; } if (obj instanceof Long) { return ((Long) obj).intValue(); } if (obj instanceo...
python
def usage(path): ''' Show in which disk the chunks are allocated. CLI Example: .. code-block:: bash salt '*' btrfs.usage /your/mountpoint ''' out = __salt__['cmd.run_all']("btrfs filesystem usage {0}".format(path)) salt.utils.fsutils._verify_run(out) ret = {} for section ...
python
def _extract(archive, compression, cmd, format, verbosity, outdir): """Extract an LZMA or XZ archive with the lzma Python module.""" targetname = util.get_single_outfile(outdir, archive) try: with lzma.LZMAFile(archive, **_get_lzma_options(format)) as lzmafile: with open(targetname, 'wb'...
python
def search_globs(path, patterns): # type: (str, List[str]) -> bool """ Test whether the given *path* contains any patterns in *patterns* Args: path (str): A file path to test for matches. patterns (list[str]): A list of glob string patterns to test against. If *path*...
java
private boolean validateExistingTopicTags(final ITopicNode topicNode, final BaseTopicWrapper<?> topic) { // Ignore validating revision topics if (topicNode.getRevision() != null) { return true; } boolean valid = true; final List<String> tagNames = topicNode.getTags(t...
python
def auto_reuse_variable_scope(func): """ A decorator which automatically reuses the current variable scope if the function has been called with the same variable scope before. Example: .. code-block:: python @auto_reuse_variable_scope def myfunc(x): return tf.layers.co...
python
def createClientCertificate(self, name, noPass = True, keyLength = 2048, days = 375): """Create a client certificate """ if not name: raise ValueError('Require name') configPath, keyPath, csrPath, certPath = \ os.path.join(self.basePath, self.FILE_CONFIG), \ ...
python
def basic_network(cm=False): """A 3-node network of logic gates. Diagram:: +~~~~~~~~+ +~~~~>| A |<~~~~+ | | (OR) +~~~+ | | +~~~~~~~~+ | | | | | | v | +~+~~~~~~+ +~~~~~+~+ ...
java
@Override public int compareTo(CurrencyUnit currency) { Objects.requireNonNull(currency); return getCurrencyCode().compareTo(currency.getCurrencyCode()); }
python
def assignmentComplete(): """ASSIGNMENT COMPLETE Section 9.1.3""" a = TpPd(pd=0x6) b = MessageType(mesType=0x29) # 00101001 c = RrCause() packet = a / b / c return packet
java
public void setOnFocus(String onfocus) { _anchorState.registerAttribute(AbstractHtmlState.ATTR_JAVASCRIPT, HtmlConstants.ONFOCUS, onfocus); }
java
public static Vector subtract(Vector vector1, Vector vector2) { if (vector2.length() != vector1.length()) throw new IllegalArgumentException( "Vectors of different sizes cannot be added"); if (vector2 instanceof IntegerVector && vector1 instanceof DoubleVector...
python
def Network_setCookie(self, name, value, **kwargs): """ Function path: Network.setCookie Domain: Network Method name: setCookie WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'name' (type: string) -> Cookie name. 'value' (type: string) -> Cookie valu...
java
public TaiInstant plus(Duration duration) { long secsToAdd = duration.getSeconds(); int nanosToAdd = duration.getNano(); if ((secsToAdd | nanosToAdd) == 0) { return this; } long secs = Math.addExact(seconds, secsToAdd); long nanoAdjustment = ((long) nanos) + n...
java
public static void init(Context context) { String apiKey = readApiKey(context); init(context, apiKey); }
java
protected void destroyConnection(ConnectionHandle conn) { postDestroyConnection(conn); conn.setInReplayMode(true); // we're dead, stop attempting to replay anything try { conn.internalClose(); } catch (SQLException e) { logger.error("Error in attempting to close connection", e); } }
python
def user_organisations(cls, user_id, state=None, include_deactivated=False): """ Get organisations that the user has joined :param user_id: the user ID :param state: the user's "join" state :param include_deactivated: Include deactivated resources in response :returns: l...
python
def show(self, only_status=False, show_cluster=True): """ Print infos on this node configuration. """ self.__update_status() indent = ''.join([" " for i in xrange(0, len(self.name) + 2)]) print_("{}: {}".format(self.name, self.__get_status_string())) if not only_s...
java
private synchronized void closeIdleClients() { List<Client> candidates = new LinkedList<Client>(openClients.values()); logger.debug("Scanning for idle clients; " + candidates.size() + " candidates."); for (Client client : candidates) { if ((useCounts.get(client) < 1) && ...
java
public T withTags(Iterable<Tag> tags) { for (Tag t : tags) { extraTags.add(t); } return (T) this; }
python
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._time_responded is not None: ...
python
def visible_security_group_mapping(self, filter=None): # @ReservedAssignment """ Return all security groups assigned to VSS container types. This is only available on SMC >= 6.5. :param str filter: filter for searching by name :raises ActionCommandFailed: element not fo...
python
def utime(self, path, times): """ Set the access and modified times of the file specified by ``path``. If ``times`` is ``None``, then the file's access and modified times are set to the current time. Otherwise, ``times`` must be a 2-tuple of numbers, of the form ``(atime, mtime)...
java
public List<LanguageProfile> read(String profileDirectory, Collection<String> profileFileNames) throws IOException { return read(LanguageProfileReader.class.getClassLoader(), profileDirectory, profileFileNames); }
python
def random_quaternion(rand=None): """Return uniform random unit quaternion. rand: array like or None Three independent random variables that are uniformly distributed between 0 and 1. >>> q = random_quaternion() >>> np.allclose(1, vector_norm(q)) True >>> q = random_quaternion(...
java
private boolean isSpecial(final char paramInput) { return (paramInput == ')') || (paramInput == ';') || (paramInput == ',') || (paramInput == '@') || (paramInput == '[') || (paramInput == ']') || (paramInput == '=') || (paramInput == '"') || (paramInput == '\'') || (paramInput == '$') |...
python
def markdown(self,md,project): """ Process the documentation with Markdown to produce HTML. """ if len(self.doc) > 0: if len(self.doc) == 1 and ':' in self.doc[0]: words = self.doc[0].split(':')[0].strip() if words.lower() not in ['author','dat...
java
private void create(Connection conn) throws SQLException { logger.debug("enter - create()"); try { PreparedStatement stmt = null; ResultSet rs = null; try { stmt = conn.prepareStatement(CREATE_SEQ); stmt.setString(INS_NAME,...
java
public ClasspathScanDescriptorProvider scanPackage(final String packageName, final boolean recursive) { return scanPackage(packageName, recursive, ClassLoaderUtils.getParentClassLoader(), false); }
python
def get_vcsrc(self): """ Returns in-memory created module pointing at user's configuration and extra code/commands. By default tries to create module from :setting:`VCSRC_PATH`. """ try: vimrc = create_module('vcsrc', settings.VCSRC_PATH) except IOErro...
python
def add_option(self, opts, dest, action=None, nargs=1, const=None, obj=None): """Adds a new option named `dest` to the parser. The destination is not inferred (unlike with optparse) and needs to be explicitly provided. Action can be any of ``store``, ``store_const``, ...
python
def service_table(format='simple', authenticated=False): """ Returns a string depicting all services currently installed. """ if authenticated: all_services = ExchangeUniverse.get_authenticated_services() else: all_services = ALL_SERVICES if format == 'html': linkify = l...
java
public void info (String msg, Object... args) { info(format(msg, args), getCause(args)); }
java
public void removeExternalCacheAdapter(String groupId, String address) throws DynamicCacheServiceNotStarted { if (servletCacheUnit == null) { throw new DynamicCacheServiceNotStarted("Servlet cache service has not been started."); } servletCacheUnit.removeExternalCacheAdapter(groupId, address); ...
python
def create_room(room): """Creates a MUC room on the XMPP server.""" if room.custom_server: return def _create_room(xmpp): muc = xmpp.plugin['xep_0045'] muc.joinMUC(room.jid, xmpp.requested_jid.user) muc.configureRoom(room.jid, _set_form_values(xmpp, room)) current_plug...
python
def angle_3points(p0, p1, p2): ''' compute the angle in radians between three 3D points Calculated as the angle between p1-p0 and p2-p0. Args: p0, p1, p2: indexable objects with indices 0, 1, 2 corresponding to 3D cartesian coordinates. Returns: Angle in radians between (p1-p...
java
public static void horizontal(Kernel1D_F32 kernel, GrayF32 input, GrayF32 output , ImageBorder_F32 border ) { InputSanityCheck.checkSameShape(input, output); boolean processed = BOverrideConvolveImage.invokeNativeHorizontal(kernel,input,output,border); if( !processed ) { border.setImage(input); ...
python
def getResults(self, parFound = None): ''' Function to obtain the Dictionarythat represents this object. :param parFound: values to return. :return: The output format will be like: [{"type" : "i3visio.email", "value": "foo@bar.com", "attri...
java
public static Class<?> getType(Object object) { Class<?> type = null; if (isClass(object)) { type = (Class<?>) object; } else if (object != null) { type = object.getClass(); } return type; }
java
@Override public BaseDestinationHandler getResolvedDestinationHandler() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.entry(tc, "getResolvedDestinationHandler"); SibTr.exit(tc, "getResolvedDestinationHandler", this); } return t...
java
public static long firstLongKey(PreparedStatement stmt) throws SQLException { stmt.execute(); ResultSet rs = stmt.getGeneratedKeys(); long key = rs.next() ? rs.getLong(1) : 0L; stmt.close(); return key; }
java
public void setMinZoomLevel(@FloatRange(from = MINIMUM_ZOOM, to = MAXIMUM_ZOOM) float minZoomLevel) { this.minZoomLevel = minZoomLevel; if (!style.isFullyLoaded()) { // We are in progress of loading a new style return; } fillExtrusionLayer.setMinZoom(minZoomL...
java
public String getProperty(String property, boolean required) { if (properties == null) { throw new GeoPackageException( "Properties must be loaded before reading"); } String value = properties.getProperty(property); if (value == null && required) { throw new GeoPackageException(GEOPACKAGE_PROPERTIE...
java
protected CmsStaticExportData getRfsExportData(CmsObject cms, String uri) { // cut export prefix from name String rfsName = uri.substring(getRfsPrefixForRfsName(uri).length()); // check if we have the result already in the cache CmsStaticExportData data = null; String siteRoot ...
java
void handleEdit(CmsClientSitemapEntry editEntry, final String newTitle) { if (CmsStringUtil.isEmpty(newTitle)) { String dialogTitle = Messages.get().key(Messages.GUI_EDIT_TITLE_ERROR_DIALOG_TITLE_0); String dialogText = Messages.get().key(Messages.GUI_TITLE_CANT_BE_EMPTY_0); ...
java
@Override public double[][] getValue(double evaluationnTime, double time, DoubleUnaryOperator values, FiniteDifference1DBoundary boundary) { FDMThetaMethod solver = new FDMThetaMethod(this, boundary, time, center, theta); return solver.getValue(evaluationnTime, time, values); }
python
def total_charge(self): """Total charged used in the unit of mAh. """ charge = (sum(self.data_points) / self.hz) * 1000 / 3600 return round(charge, self.sr)
python
def update(self): """Update the user's details on Todoist. This method must be called to register any local attribute changes with Todoist. >>> from pytodoist import todoist >>> user = todoist.login('john.doe@gmail.com', 'password') >>> user.full_name = 'John Smith' ...
python
def from_yamlf(cls, fpath: str, encoding: str='utf8', force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> T: """From yaml file path to instance :param fpath: Yaml file path :param encoding: Yaml file encoding :param force_snake_case: Keys are transf...
python
def use_kwargs(self, *args, **kwargs): """Decorator that injects parsed arguments into a view function or method as keyword arguments. This is a shortcut to :meth:`use_args` with ``as_kwargs=True``. Example usage with Flask: :: @app.route('/echo', methods=['get', 'post']) ...
java
@Override AbstractConfigValue resolveSubstitutions(ResolveContext context) { context.source().replace(this, ResolveReplacer.cycleResolveReplacer); try { AbstractConfigValue v; try { v = context.source().lookupSubst(context, expr, prefixLength); } c...
java
@Override public void add(final int x) { final short hb = BufferUtil.highbits(x); final int i = highLowContainer.getIndex(hb); if (i >= 0) { getMappeableRoaringArray().setContainerAtIndex(i, highLowContainer.getContainerAtIndex(i).add(BufferUtil.lowbits(x))); } else { final Mappe...
python
def _make_context(context=None): """Create the namespace of items already pre-imported when using shell. Accepts a dict with the desired namespace as the key, and the object as the value. """ namespace = {'db': db, 'session': db.session} namespace.update(_iter_context()) if context is not ...
java
public Content getEnumConstantsDetailsTreeHeader(ClassDoc classDoc, Content memberDetailsTree) { memberDetailsTree.addContent(HtmlConstants.START_OF_ENUM_CONSTANT_DETAILS); Content enumConstantsDetailsTree = writer.getMemberTreeHeader(); enumConstantsDetailsTree.addContent(writer.get...
python
def forward_ocr(self, img_): """Forward the image through the LSTM network model Parameters ---------- img_: int of array Returns ---------- label_list: string of list """ img_ = cv2.resize(img_, (80, 30)) img_ = img_.transpose(1, 0) ...
java
public static DeviceSearchResult deviceSearch(String accessToken, DeviceSearch deviceSearch) { return deviceSearch(accessToken, JsonUtil.toJSONString(deviceSearch)); }
python
def all_substrings(s): ''' yields all substrings of a string ''' join = ''.join for i in range(1, len(s) + 1): for sub in window(s, i): yield join(sub)
java
public int indexOf(int[] sequence) { int index = -1; for (int i = 0; index == -1 && i <= currentSize - sequence.length; i++) { if (buffer[i] == sequence[0]) { boolean matches = true; for (int j = 1; matches && j < sequence.length; j++) { ...
java
public static String getWhereClause (String sql) { if (null == sql ) return null; String s = sql.trim(); int len = s.length(); int last = s.lastIndexOf("AND"); if (len > 0 && (last == len -3)) { if (s.indexOf("WHERE") == -1) { s = "WHERE " + s.substri...
python
def _document_root(self, fully_qualified=True): """ Return the mets Element for the document root. """ nsmap = {"xsi": utils.NAMESPACES["xsi"], "xlink": utils.NAMESPACES["xlink"]} if fully_qualified: nsmap["mets"] = utils.NAMESPACES["mets"] else: n...
java
protected static final String formatUsingFormat(Long value, DateTimeFormat fmt) { if (value == null) { return ""; } else { // midnight GMT Date date = new Date(0); // offset by timezone and value date.setTime(UTCDateBox.timezoneOffsetMi...
java
public static boolean intersectRaySphere(float originX, float originY, float originZ, float dirX, float dirY, float dirZ, float centerX, float centerY, float centerZ, float radiusSquared, Vector2f result) { float Lx = centerX - originX; float Ly = centerY - originY; float Lz = center...
java
private static void speedUpDTMManager() throws Exception { // https://github.com/aws/aws-sdk-java/issues/238 // http://stackoverflow.com/questions/6340802/java-xpath-apache-jaxp-implementation-performance if (System.getProperty(DTM_MANAGER_DEFAULT_PROP_NAME) == null) { Class<?> XPath...
java
@Nonnull @OverrideOnDemand protected Finder createFinder (@Nonnull final String sOriginalQuery, @Nonnull final LECTYPE aLEC) { return new Finder (aLEC.getDisplayLocale ()).initialize (sOriginalQuery); }
java
public Datatype.Builder setValueType(TypeClass valueType) { this.valueType = Objects.requireNonNull(valueType); _unsetProperties.remove(Property.VALUE_TYPE); return (Datatype.Builder) this; }
python
def get_topclasses(cls): """Gets the base classes that are in pycbc.""" bases = [c for c in inspect.getmro(cls) if c.__module__.startswith('pycbc') and c != cls] return ', '.join(['{}.{}'.format(c.__module__, c.__name__) for c in bases])
python
def fromints(cls, ints): """Series from integer rank arguments.""" return cls.frombitsets(map(cls.BitSet.fromint, ints))
python
def _process_worker(call_queue, result_queue, shutdown): """Evaluates calls from call_queue and places the results in result_queue. This worker is run in a seperate process. Args: call_queue: A multiprocessing.Queue of _CallItems that will be read and evaluated by the worker. r...
python
def getValue(self): """ Returns PromisedRequirement value """ func = dill.loads(self._func) return func(*self._args)
java
public static void scale( double alpha , DMatrix4 a , DMatrix4 b ) { b.a1 = a.a1*alpha; b.a2 = a.a2*alpha; b.a3 = a.a3*alpha; b.a4 = a.a4*alpha; }
python
def _get_target_nearest(self): """Get nearest target for each origin""" reps_query = """ SELECT DISTINCT ON(g2.cartodb_id) g1.cartodb_id As origin_id, g2.the_geom, g2.cartodb_id + {maxorigin} as cartodb_id, g2.the_geom_webm...
java
@Override public List<CommerceAccountUserRel> findByCommerceAccountUserId( long commerceAccountUserId, int start, int end, OrderByComparator<CommerceAccountUserRel> orderByComparator) { return findByCommerceAccountUserId(commerceAccountUserId, start, end, orderByComparator, true); }
java
public static <ITEM extends Item> Predicate<ITEM> isAlive() { return new Predicate<ITEM>() { @Override public boolean apply(ITEM item) { return !from(GHEventsSubscriber.all()).filter(isApplicableFor(item)).toList().isEmpty(); } }; }
python
def add(parent, idx, value): """Add a value to a dict.""" if isinstance(parent, dict): if idx in parent: raise JSONPatchError("Item already exists") parent[idx] = value elif isinstance(parent, list): if idx == "" or idx == "~": parent.append(value) else: parent.insert(int(idx), v...
java
private static int processPoly(Polygon poly, Element element, StringTokenizer tokens) throws ParsingException { int count = 0; while (tokens.hasMoreTokens()) { String nextToken = tokens.nextToken(); if (nextToken.equals("L")) { continue; } if (nextToken.equals("z")) { break; } ...
python
def avail_locations(call=None): ''' List all available locations ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) ret = {} conn = get_conn(ser...
java
@Override public void addProduct(IAtomContainer product, Double coefficient) { logger.debug("Adding product with coefficient: ", product, "" + coefficient); super.addProduct(product, coefficient); }
python
def clean(args): """ %prog clean fastafile Remove irregular chars in FASTA seqs. """ p = OptionParser(clean.__doc__) p.add_option("--fancy", default=False, action="store_true", help="Pretty print the sequence [default: %default]") p.add_option("--canonical", default=False, ...
python
def parts(self): """Return an array of batch parts to submit""" parts = [] upserts = dict() deletes = [] # we keep track of the batch size as we go (pretty close approximation!) so we can chunk it small enough # to limit the HTTP posts to under 700KB - server limits to...
java
public static void fetchAttributes(RequestAdapter requestAdapter, ProcessResult processResult) { if (processResult != null) { for (ContentResult contentResult : processResult) { for (ActionResult actionResult : contentResult) { Object actionResultValue = actionRes...
java
public SDVariable stack(String name, int axis, SDVariable... values) { validateSameType("stack", false, values); SDVariable ret = f().stack(values, axis); return updateVariableNameAndReference(ret, name); }
python
def WriteRow(self, values): """Writes a single row to the underlying buffer. Args: values: A list of string values to be inserted into the CSV output. """ precondition.AssertIterableType(values, text) if compatibility.PY2: self._csv.writerow([value.encode("utf-8") for value in values])...
java
public static List<Field> getAllDeclaredFields(Class<? extends ParaObject> clazz) { LinkedList<Field> fields = new LinkedList<>(); if (clazz == null) { return fields; } Class<?> parent = clazz; do { for (Field field : parent.getDeclaredFields()) { if (!Modifier.isTransient(field.getModifiers()) && ...
python
def from_api_repr(cls, resource, client): """Factory: construct a project given its API representation. :type resource: dict :param resource: project resource representation returned from the API :type client: :class:`google.cloud.resource_manager.client.Client` :param client:...
python
def do_file_show(client, args): """Output file contents to stdout""" for src_uri in args.uris: client.download_file(src_uri, sys.stdout.buffer) return True
python
def reload_libraries(library_directories: list = None): """ Reload the libraries stored in the project's local and shared library directories """ directories = library_directories or [] project = cauldron.project.get_internal_project() if project: directories += project.library_direc...
java
public JRecordExtractor<T, SparseLabeledPoint> extractWithSubsetSettingsSparseLabeledPoint(String settings) { return new JRecordExtractor<>(JavaOps.extractWithSubsetSettingsSparseLabeledPoint(self, settings)); }
java
@Override public Date firstBetween(Date start, Date end) { return rule.firstBetween(start, end); }
java
protected synchronized void do_send(final OtpOutputStream header, final OtpOutputStream payload) throws IOException { try { if (traceLevel >= sendThreshold) { // Need to decode header and output buffer to show trace // message! // First mak...