language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def use_settings(**kwargs): ''' Context manager to temporarily override settings ''' from omnic import singletons singletons.settings.use_settings_dict(kwargs) yield singletons.settings.use_previous_settings()
python
def registerAddon(cls, name, addon, force=False): """ Registers the inputted addon to the class. :param name | <str> addon | <variant> """ prop = '_{0}__addons'.format(cls.__name__) cmds = getattr(cls, prop, {}) if name in c...
python
def query_security_namespaces(self, security_namespace_id=None, local_only=None): """QuerySecurityNamespaces. List all security namespaces or just the specified namespace. :param str security_namespace_id: Security namespace identifier. :param bool local_only: If true, retrieve only loca...
python
def to_ipv4(self): """ Convert (an IPv6) IP address to an IPv4 address, if possible. Only works for IPv4-compat (::/96), IPv4-mapped (::ffff/96), and 6-to-4 (2002::/16) addresses. >>> ip = IP('2002:c000:022a::') >>> print(ip.to_ipv4()) 192.0.2.42 """ ...
python
def read(self): """Reads the data stored in the files we have been initialized with. It will ignore files that cannot be read, possibly leaving an empty configuration :return: Nothing :raise IOError: if a file cannot be handled""" if self._is_initialized: return ...
java
public MeanVariance averageSymmetricGini() { MeanVariance mv = new MeanVariance(); for(int i1 = 0; i1 < size1; i1++) { double purity = 0.0; if(contingency[i1][size2] > 0) { final double cs = contingency[i1][size2]; // sum, as double. for(int i2 = 0; i2 < size2; i2++) { doub...
java
@Override public void writeLongHex(long v) { writeHexByte(buf, pos + 0, (byte) ((v >>> 56L) & 0xff)); writeHexByte(buf, pos + 2, (byte) ((v >>> 48L) & 0xff)); writeHexByte(buf, pos + 4, (byte) ((v >>> 40L) & 0xff)); writeHexByte(buf, pos + 6, (byte) ((v >>> 32L) & 0xff)); writeHexByte(buf, pos + 8, ...
java
public ZealotKhala orEqual(String field, Object value) { return this.doNormal(ZealotConst.OR_PREFIX, field, value, ZealotConst.EQUAL_SUFFIX, true); }
python
def stop(self): """Stop the channel""" self._presubs.remove(self._sdk_presub_params) if self._immediacy == FirstValue.on_value_update: self._unsubscribe_all_matching() super(ResourceValues, self).stop()
python
def unwatch(self): """Get rid of any lingering watchers and remove from list""" if self.watchers is not None: unwatched = [] for watcher in self.watchers: watcher.inst.param.unwatch(watcher) unwatched.append(watcher) self.watchers = [w ...
java
public void marshall(DescribeEntitiesDetectionJobRequest describeEntitiesDetectionJobRequest, ProtocolMarshaller protocolMarshaller) { if (describeEntitiesDetectionJobRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { pr...
python
def best_match( self, req, working_set, installer=None, replace_conflicting=False): """Find distribution best matching `req` and usable on `working_set` This calls the ``find(req)`` method of the `working_set` to see if a suitable distribution is already active. (This may raise ...
python
def deregister_webhook(self, **kwargs): # noqa: E501 """Delete callback URL # noqa: E501 Deletes the callback URL. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/callback -H 'authorization: Bearer {api-key}' # noqa: E501 This method makes a synch...
java
public void setUpdates(java.util.Collection<SizeConstraintSetUpdate> updates) { if (updates == null) { this.updates = null; return; } this.updates = new java.util.ArrayList<SizeConstraintSetUpdate>(updates); }
java
public static Stream<MutableLongTuple> lexicographicalStream( LongTuple max) { return stream(Order.LEXICOGRAPHICAL, LongTuples.zero(max.getSize()), max); }
python
def BVS(self, name, size, min=None, max=None, stride=None, uninitialized=False, explicit_name=None, key=None, eternal=False, inspect=True, events=True, **kwargs): #pylint:disable=redefined-builtin """ Creates a bit-vector symbol (i.e., a variab...
java
public static String getMessage(String code, Object... args) { return getMessage(I18nUtils.getLocale(), code, args); }
java
@RequestMapping("/apply") @ResponseBody public RefundApplyResponse apply(@RequestParam("orderNumber") String orderNumber){ return wepaySupport.refundApply(orderNumber); }
java
public final BooleanExpression notIn(Expression<? extends T>... right) { return Expressions.booleanOperation(Ops.NOT_IN, mixin, Expressions.list(right)); }
java
public Postcard withParcelable(@Nullable String key, @Nullable Parcelable value) { mBundle.putParcelable(key, value); return this; }
java
public long send(Object data) { long seq = NumberSequencer.getNextSequence(); Notification note = new Notification( this.getEvent(), this, seq, System.currentTimeMillis(), "Event notification " + this.getEvent() ); ...
python
def _get_short_description(self): """Return the first line of a multiline description Returns: string: The short description, otherwise None """ if self.description is None: return None lines = [x for x in self.description.split('\n')] if len(li...
python
def over(self, name='usd'): '''Returns a new currency pair with the *over* currency as second part of the pair (Foreign currency).''' name = name.upper() if self.ccy1.code == name.upper(): return ccy_pair(self.ccy2, self.ccy1) else: return self
java
protected static int getValueByBinStr(String binaryString, boolean signed) { Integer value = Integer.parseInt(binaryString, 2); if (signed && binaryString.charAt(0) == '1') { char[] invert = new char[binaryString.length()]; Arrays.fill(invert, '1'); value ^= Integer.parseInt(new String(invert), 2); val...
python
def bundle_for_objs_and_resources(objs, resources): ''' Generate rendered CSS and JS resources suitable for the given collection of Bokeh objects Args: objs (seq[Model or Document]) : resources (BaseResources or tuple[BaseResources]) Returns: tuple ''' if isinstance(r...
python
def getAllCellsInColumns(columns, cellsPerColumn): """ Calculate all cell indices in the specified columns. @param columns (numpy array) @param cellsPerColumn (int) @return (numpy array) All cells within the specified columns. The cells are in the same order as the provided columns, so they're sorted if...
java
public void marshall(UpdateMethodRequest updateMethodRequest, ProtocolMarshaller protocolMarshaller) { if (updateMethodRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateMethodRequest.ge...
python
def fromstring(cls, bitstring): """ Construct BitMap from string """ nbits = len(bitstring) bm = cls(nbits) for i in xrange(nbits): if bitstring[-i-1] == '1': bm.set(i) elif bitstring[-i-1] != '0': raise Exception("I...
java
public ServiceFuture<DatabaseVulnerabilityAssessmentRuleBaselineInner> createOrUpdateAsync(String resourceGroupName, String managedInstanceName, String databaseName, String ruleId, VulnerabilityAssessmentPolicyBaselineName baselineName, List<DatabaseVulnerabilityAssessmentRuleBaselineItem> baselineResults, final Servic...
python
def normalize(self, text): """Normalize unicode, hyphens, whitespace, and some chemistry terms and formatting.""" text = super(ChemNormalizer, self).normalize(text) # Normalize element spelling if self.chem_spell: text = re.sub(r'sulph', r'sulf', text, flags=re.I) ...
java
static void validateValueUniquenessInScope(String qualifiedName, List<TypeElement> nestedElements) { Set<String> names = new LinkedHashSet<>(); for (TypeElement nestedElement : nestedElements) { if (nestedElement instanceof EnumElement) { EnumElement enumElement = (EnumElement) nestedElement...
python
def col_values(self, col, value_render_option='FORMATTED_VALUE'): """Returns a list of all values in column `col`. Empty cells in this list will be rendered as :const:`None`. :param col: Column number. :type col: int :param value_render_option: (optional) Determines how values ...
java
private void initializeShowEditTextDialogPreference() { Preference preference = findPreference(getString(R.string.show_edit_text_dialog_preference_key)); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferen...
java
protected void initObject() { Object o; if (CmsStringUtil.isEmpty(getParamAction()) || CmsDialog.DIALOG_INITIAL.equals(getParamAction())) { // this is the initial dialog call o = new ArrayList(); ((List)o).add("/"); } else { // this is not the in...
python
def base_app(import_name, instance_path=None, static_folder=None, static_url_path='/static', template_folder='templates', instance_relative_config=True, app_class=Flask): """Invenio base application factory. If the instance folder does not exists, it will be created. :param impor...
java
public static final PluginResourceNotFoundException pluginResourceNotFoundException(String resourceName, PluginCoordinates coordinates) { return new PluginResourceNotFoundException(Messages.i18n.format( "PluginResourceNotFound", resourceName, coordinates.toString())); //$NON-NLS-1$ ...
java
public void markSendFailed() { overall_stats.put(QueryStat.TOTAL_TIME, DateTime.nanoTime() - query_start_ns); LOG.info("Completing query=" + JSON.serializeToString(this)); QUERY_LOG.info(this.toString()); }
python
def append_url(base_url, path): """ Append path to base_url in a sensible way. """ if base_url[-1] != "/": base_url += "/" if path[0] == "/": path = path[1:] return urljoin(base_url, path)
java
@Path("/") public SessionResource getSessionResource(@QueryParam("token") String authToken) throws GuacamoleException { // Return a resource exposing the retrieved session GuacamoleSession session = authenticationService.getGuacamoleSession(authToken); return sessionResourceFact...
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { sent_mails_responses result = (sent_mails_responses) service.get_payload_formatter().string_to_resource(sent_mails_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == S...
python
def nextSunrise(jd, lat, lon): """ Returns the JD of the next sunrise. """ return swe.sweNextTransit(const.SUN, jd, lat, lon, 'RISE')
java
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // read basic object and the type s.defaultReadObject(); this.reference = InstantiationUtil.instantiate(type, CopyableValue.class); this.tempReference = null; }
java
public NfsRenameRequest makeRenameRequest(F toFile) throws IOException { return getNfs().makeRenameRequest(getParentFile().getFileHandle(), getName(), toFile.getParentFile().getFileHandle(), toFile.getName()); }
python
def dimension(self): """ output dimension """ if self.C00 is None: # no data yet if isinstance(self.dim, int): # return user choice warnings.warn('Returning user-input for dimension, since this model has not yet been estimated.') return self.dim ...
python
def find_elements_by_xpath(self, xpath): """ Finds multiple elements by xpath. :param xpath: The xpath locator of the elements to be found. :return: See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_ ...
java
public static List<String> getNodeListFromStringLineSeperateOrSpaceSeperate( String listStr, boolean removeDuplicate) { List<String> nodes = new ArrayList<String>(); for (String token : listStr.split("[\\r?\\n| +]+")) { // 20131025: fix if fqdn has space in the end. ...
java
public void scale(double s) { x = s * x; y = s * y; z = s * z; }
java
public static Map<Integer, List<TagWrapper>> getCategoryMappingFromTagList(final Collection<TagWrapper> tags) { final HashMap<Integer, List<TagWrapper>> mapping = new HashMap<Integer, List<TagWrapper>>(); for (final TagWrapper tag : tags) { final List<CategoryInTagWrapper> catList = tag.getC...
python
def index_of(self, data): """ Finds the position of a node in the list. The index of the first occurrence of the data is returned (indexes start at 0) :param data: data of the seeked node :type: object :returns: the int index or -1 if the node is not in the list ...
python
def from_dict(cls, d): """ Reconstitute a DefectEntry object from a dict representation created using as_dict(). Args: d (dict): dict representation of DefectEntry. Returns: DefectEntry object """ defect = MontyDecoder().process_decoded( ...
java
protected void decorateActiveStep(final TutorStep step, StringBuilder sb) { sb.append("<h4>").append(step.summary()).append("</h4>"); sb.append(step.content()); }
java
public boolean removeTable(BaseTable table) { if (m_mapTable != null) { for (Object objKey : m_mapTable.keySet()) { if (table == m_mapTable.get(objKey)) { return (m_mapTable.remove(objKey) != null); } ...
python
def skew_x(self, x): """Skew element along the x-axis by the given angle. Parameters ---------- x : float x-axis skew angle in degrees """ self.root.set("transform", "%s skewX(%f)" % (self.root.get("transform") or '', x)) return ...
java
public final UnbindDeviceFromGatewayResponse unbindDeviceFromGateway( RegistryName parent, String gatewayId, String deviceId) { UnbindDeviceFromGatewayRequest request = UnbindDeviceFromGatewayRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setGatewa...
python
def from_json_file(file: TextIO, check_version=True) -> BELGraph: """Build a graph from the Node-Link JSON contained in the given file.""" graph_json_dict = json.load(file) return from_json(graph_json_dict, check_version=check_version)
python
def num(string): """convert a string to float""" if not isinstance(string, type('')): raise ValueError(type('')) try: string = re.sub('[^a-zA-Z0-9\.\-]', '', string) number = re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", string) return float(number[0]) except Exception as e: ...
java
public final Parser<T> from(Parser<? extends Collection<Token>> lexer) { return Parsers.nested(Parsers.tokens(lexer), followedBy(Parsers.EOF)); }
java
public static String convert15To18(String idCard) { StringBuilder idCard18; if (idCard.length() != CHINA_ID_MIN_LENGTH) { return null; } if (Validator.isNumber(idCard)) { // 获取出生年月日 String birthday = idCard.substring(6, 12); Date birthDate = DateUtil.parse(birthday, "yyMMdd"); // 获取出生年(完...
python
def validate_token_request(self, request): """ :param request: OAuthlib request. :type request: oauthlib.common.Request """ # REQUIRED. Value MUST be set to "authorization_code". if request.grant_type not in ('authorization_code', 'openid'): raise errors.Unsup...
python
def get_method(self, cls_name): """ Generator that returns all registered authenticators based on a specific authentication class. :param acr: Authentication Class :return: generator """ for id, spec in self.db.items(): if spec["method"].__class__.__n...
java
public int setBytes(final long pos, byte[] bytes, final int offset, final int len) throws SQLException { synchronized (this) { if (this.underlying == null) { if (pos > 1) { throw new SQLException("Invalid position: " + pos); ...
java
Observable<ComapiResult<ConversationDetails>> doGetConversation(@NonNull final String token, @NonNull final String conversationId) { return wrapObservable(service.getConversation(AuthManager.addAuthPrefix(token), apiSpaceId, conversationId).map(mapToComapiResult()), log, "Getting conversation" + conversationId)...
python
def setup_ui(self, ): """Setup the ui :returns: None :rtype: None :raises: None """ labels = self.reftrack.get_option_labels() self.browser = ComboBoxBrowser(len(labels), headers=labels) self.browser_vbox.addWidget(self.browser)
java
public void addDynamicServlet( String servletName, String servletClass, String mappingURI, Properties initParameters) throws ServletException, SecurityException { context.addDynamicServlet(servletName, servletClass, mappingURI, initParameters); }
java
@Nullable public static Compression forFileName(final String fileName, @Nullable final Compression fallback) { final int index = fileName.lastIndexOf('.'); final String extension = (index < 0 ? fileName : fileName.substring(index + 1)) .toLowerCase(); for (final C...
java
public long applyAndJournal(Supplier<JournalContext> context, NewBlockEntry entry) { try { long id = applyNewBlock(entry); context.get().append(JournalEntry.newBuilder().setNewBlock(entry).build()); return id; } catch (Throwable t) { ProcessUtils.fatalError(LOG, t, "Failed to apply %s", ...
python
def save(self, reload=False): """Save changes to the file.""" self.wrapper.raw.save() if reload: self.reload()
python
def get_games_by_season(self, season): """ Game schedule for a specified season. """ try: season = int(season) except ValueError: raise FantasyDataError('Error: Invalid method parameters') result = self._method_call("Games/{season}", "stats", seas...
java
public void update(boolean submit) { boolean ok = (m_propertyValidationStatus == VALIDATION_OK) && (m_aliasValidationStatus == VALIDATION_OK); if (submit && ok) { saveProperties(); saveAliases(); hide(); } }
java
@Override public DownloadDefaultKeyPairResult downloadDefaultKeyPair(DownloadDefaultKeyPairRequest request) { request = beforeClientExecution(request); return executeDownloadDefaultKeyPair(request); }
java
public Xml read(String xmlPathQuery, boolean captureContent) { XmlPath xmlPath = XmlPathParser.parse(xmlPathQuery); Xml doc = new Xml(); boolean record = false; int levelIndex = 0; XmlNode node; while((node = pullXmlNode()) != null) { if(node instanceof XmlSt...
python
def save(self, config_loc=None): """Saves current user credentials to user directory. Args: config_loc (str, optional): Location where credentials are to be stored. If no argument is provided, it will be send to the default location. Example: ...
java
public URLNormalizer removeDirectoryIndex() { String path = toURL().getPath(); if (PATTERN_PATH_LAST_SEGMENT.matcher(path).matches()) { url = StringUtils.replaceOnce( url, path, StringUtils.substringBeforeLast(path, "/") + "/"); } return this; }
python
def data(self): """ Get a cached post-processed result of a GitHub API call. Uses Trac cache to avoid constant querying of the remote API. If a previous API call did not succeed, automatically retries after a timeout. """ if self._next_update and datetime.now() > self._ne...
python
def get_best_fit_rot_mat(from_coord, to_coord): """ Compute best-fit rotation matrix. The best-fit rotation matrix rotates from_coord such that the RMSD between the 2 sets of coordinates are minimized after the rotation. Parameters ---------- from_coord, to_coord : np.array ...
java
public IPv4AddressSection getEmbeddedIPv4AddressSection(int startIndex, int endIndex) { if(startIndex == ((IPv6Address.MIXED_ORIGINAL_SEGMENT_COUNT - this.addressSegmentIndex) << 1) && endIndex == (getSegmentCount() << 1)) { return getEmbeddedIPv4AddressSection(); } IPv4AddressCreator creator = getIPv4Network(...
java
public void deleteCertificate(String thumbprintAlgorithm, String thumbprint) throws BatchErrorException, IOException { deleteCertificate(thumbprintAlgorithm, thumbprint, null); }
java
public void directoryToArc(File srcDir, File tgtDir, String prefix) throws IOException { File target[] = {tgtDir}; ARCWriter writer = new ARCWriter(new AtomicInteger(), getSettings(true,prefix,Arrays.asList(target))); File sources[] = srcDir.listFiles(); LOGGER.info("Found " + sources.length + " files...
java
@Override public Object execute(Rose rose) throws Throwable { InvocationBean inv = rose.getInvocation(); ServletRequest request = inv.getRequest(); // if (request.getCharacterEncoding() == null) { request.setCharacterEncoding("UTF-8"); if (logger.isDebugEnabl...
python
def get_assets_by_record_type(self, asset_record_type=None): """Gets an ``AssetList`` containing the given asset record ``Type``. In plenary mode, the returned list contains all known assets or an error results. Otherwise, the returned list may contain only those assets that are accessi...
java
public static Node findNodeByName(Document doc, String pathExpression) { final StringTokenizer tok = new StringTokenizer(pathExpression, "."); final int numToks = tok.countTokens(); NodeList elements; if (numToks == 1) { elements = doc.getElementsByTagNameNS("*", pathExpressi...
python
def resource_types(self): """resource types used by the collection.""" rtypes = set() for p in self.policies: rtypes.add(p.resource_type) return rtypes
java
public static void waitThreadTermination(Thread thread) { while (thread != null && thread.isAlive()) { thread.interrupt(); try { thread.join(); } catch (InterruptedException e) { } } }
java
public void deleteElement(Object parent, String name) { if (isAttached()) { helper.deleteElement(parent, name); } }
java
@Override public AssociateMemberToGroupResult associateMemberToGroup(AssociateMemberToGroupRequest request) { request = beforeClientExecution(request); return executeAssociateMemberToGroup(request); }
java
public int expectUnsigned(int bytes) throws IOException { switch (bytes) { case 4: return expectUInt32(); case 3: return expectUInt24(); case 2: return expectUInt16(); case 1: return expectUInt8(); ...
python
def lambda_B_calc(classes, table, TOP, POP): """ Calculate Goodman and Kruskal's lambda B. :param classes: confusion matrix classes :type classes : list :param table: confusion matrix table :type table : dict :param TOP: test outcome positive :type TOP : dict :param POP: population ...
python
def _needs_evaluation(self) -> bool: """ Returns True when: 1. Where clause is not specified 2. Where WHERE clause is specified and it evaluates to True Returns false if a where clause is specified and it evaluates to False """ return self._schema.when is ...
python
def setThirdStateChecked(src, ids=[], dpth = 0, key = ''): """ Recursively find checked item.""" #tabs = lambda n: ' ' * n * 4 # or 2 or 8 or... #brace = lambda s, n: '%s%s%s' % ('['*n, s, ']'*n) #print('third state nodes: ', third_state_nodes) if isinstance(src, dict): #print "DICT: ", src ...
java
public Response deleteOwner(String roomName, String jid) { return restClient.delete("chatrooms/" + roomName + "/owners/" + jid, new HashMap<String, String>()); }
java
public static ConcatVector readFromProto(ConcatVectorProto.ConcatVector m) { int components = m.getComponentCount(); ConcatVector vec = new ConcatVector(); vec.pointers = new double[components][]; vec.sparse = new boolean[components]; vec.copyOnWrite = new boolean[components]; for (int i = 0; i...
java
public Matrix4x3d m10(double m10) { this.m10 = m10; properties &= ~PROPERTY_ORTHONORMAL; if (m10 != 0.0) properties &= ~(PROPERTY_IDENTITY | PROPERTY_TRANSLATION); return this; }
java
@SlashedClassName @SuppressFBWarnings("TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_ALWAYS_SINK") public static String toSlashedClassName(@SlashedClassName(when = When.UNKNOWN) String className) { if (className.indexOf('.') >= 0) { return className.replace('.', '/'); } return cla...
java
synchronized void deactivate() { paused = false; if (activeTask != null) { activeTask.cancel(); activeTask = null; } this.threadPool = null; }
java
public static String toColorShorthand(String red, String green, String blue) { return shorthandHex(toColor(red, green, blue)); }
python
def _recursive_url_find(self, item, image_list): """ Recursively traverses a dictionary-like data structure for Khan Academy assessment items in order to search for image links in `url` data attributes, and if it finds any it adds them to `image_list` and rewrites `url` attribute. ...
python
def checkAvailable(from_module): """Call me at checkConfig time to properly report config error if neither txrequests or treq is installed """ if txrequests is None and treq is None: config.error("neither txrequests nor treq is installed, but {} is requiring it\n\n{}".form...
java
public static double averageCommonFeatureRank(double[] a, double[] b) { class Pair{ public int i; public double v; public Pair(int index, double value){i=index;v=value;} public void set(int index, double value){ ...
python
def update(self, obj_id, is_public=NotUpdated, is_protected=NotUpdated): """Update a Job Execution.""" data = {} self._copy_if_updated(data, is_public=is_public, is_protected=is_protected) return self._patch('/job-executions/%s' % obj_id, data)
java
protected boolean semanticallyEquivalent(BioPAXElement element) { final kPrime aKPrime = (kPrime) element; return (Float.compare(aKPrime.getIONIC_STRENGTH(), IONIC_STRENGTH) == 0) && (Float.compare(aKPrime.getK_PRIME(), K_PRIME) == 0) && (Float.compare(aKPrime.getPH(), PH) == 0) && (Float.compare(aK...