language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static InterceptionContext forConstructorInterception(InterceptionModel interceptionModel, CreationalContext<?> ctx, BeanManagerImpl manager, SlimAnnotatedType<?> type) { return of(interceptionModel, ctx, manager, null, type); }
python
def get_kbr_keys(kb_name, searchkey="", searchvalue="", searchtype='s'): """Return an array of keys. :param kb_name: the name of the knowledge base :param searchkey: search using this key :param searchvalue: search using this value :param searchtype: s = substring, e=exact """ if searchtype == 's' and searchkey: searchkey = '%'+searchkey+'%' if searchtype == 's' and searchvalue: searchvalue = '%'+searchvalue+'%' if searchtype == 'sw' and searchvalue: # startswith searchvalue = searchvalue+'%' if not searchvalue: searchvalue = '%' if not searchkey: searchkey = '%' query = db.session.query(models.KnwKBRVAL).join(models.KnwKB) \ .filter(models.KnwKBRVAL.m_key.like(searchkey), models.KnwKBRVAL.m_value.like(searchvalue), models.KnwKB.name.like(kb_name)) return [(k.m_key,) for k in query.all()]
java
public JSONObject sameHqDeleteBySign(String contSign, HashMap<String, String> options) { AipRequest request = new AipRequest(); preOperation(request); request.addBody("cont_sign", contSign); if (options != null) { request.addBody(options); } request.setUri(ImageSearchConsts.SAME_HQ_DELETE); postOperation(request); return requestServer(request); }
python
def switch_onoff(self, device, status): """Switch a Socket""" if status == 1 or status == True or status == '1': return self.switch_on(device) else: return self.switch_off(device)
java
public static Validator<CharSequence> iPv6Address(@NonNull final Context context, @StringRes final int resourceId) { return new IPv6AddressValidator(context, resourceId); }
java
protected synchronized void clear() throws ObjectManagerException { final String methodName = "clear"; if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.entry(this, cclass, methodName); super.clear(); inMemoryManagedObjects = new ConcurrentHashMap(concurrency); if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.exit(this, cclass, "clear"); }
java
private File getTempUploadDir() throws Exception { if (m_tempUploadDir == null) { try { m_tempUploadDir = getServer().getUploadDir(); } catch (InitializationException e) { throw new Exception("Unable to get server: " + e.getMessage(), e); } } return m_tempUploadDir; }
python
def pad(segment, size): """Add zeroes to a segment until it reaches a certain size. :param segment: the segment to pad :param size: the size to which to pad the segment """ for i in range(size - len(segment)): segment.append(0) assert len(segment) == size
java
public static void asyncExecute(Runnable runnable) { if (runnable != null) { try { Para.getExecutorService().execute(runnable); } catch (RejectedExecutionException ex) { logger.warn(ex.getMessage()); try { runnable.run(); } catch (Exception e) { logger.error(null, e); } } } }
python
def _write_fragments(self, fragments): """ :param fragments: A generator of messages """ answer = tornado.gen.Future() if not fragments: answer.set_result(None) return answer io_loop = IOLoop.current() def _write_fragment(future): if future and future.exception(): return answer.set_exc_info(future.exc_info()) try: fragment = fragments.next() except StopIteration: return answer.set_result(None) io_loop.add_future(self.writer.put(fragment), _write_fragment) _write_fragment(None) return answer
python
def fetch(self): """ Fetch a MediaInstance :returns: Fetched MediaInstance :rtype: twilio.rest.api.v2010.account.message.media.MediaInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, params=params, ) return MediaInstance( self._version, payload, account_sid=self._solution['account_sid'], message_sid=self._solution['message_sid'], sid=self._solution['sid'], )
python
def create(self,params=None, headers=None): """Create a creditor bank account. Creates a new creditor bank account object. Args: params (dict, optional): Request body. Returns: ListResponse of CreditorBankAccount instances """ path = '/creditor_bank_accounts' if params is not None: params = {self._envelope_key(): params} try: response = self._perform_request('POST', path, params, headers, retry_failures=True) except errors.IdempotentCreationConflictError as err: return self.get(identity=err.conflicting_resource_id, params=params, headers=headers) return self._resource_for(response)
java
public String getResourceType(CmsFileInfo file) { String typeName = null; typeName = getExtensionMapping().get(file.getFileSuffix().toLowerCase()); if (typeName == null) { typeName = "plain"; } return typeName; }
python
def create_brand(cls, brand, **kwargs): """Create Brand Create a new Brand This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_brand(brand, async=True) >>> result = thread.get() :param async bool :param Brand brand: Attributes of brand to create (required) :return: Brand If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_brand_with_http_info(brand, **kwargs) else: (data) = cls._create_brand_with_http_info(brand, **kwargs) return data
python
def infer(self, expl_dims, inf_dims, x): """ Use the sensorimotor model to compute the expected value on inf_dims given that the value on expl_dims is x. .. note:: This corresponds to a prediction if expl_dims=self.conf.m_dims and inf_dims=self.conf.s_dims and to inverse prediction if expl_dims=self.conf.s_dims and inf_dims=self.conf.m_dims. """ try: if self.n_bootstrap > 0: self.n_bootstrap -= 1 raise ExplautoBootstrapError y = self.sensorimotor_model.infer(expl_dims, inf_dims, x.flatten()) except ExplautoBootstrapError: logger.warning('Sensorimotor model not bootstrapped yet') y = rand_bounds(self.conf.bounds[:, inf_dims]).flatten() return y
java
@Override public void cacheResult(List<CPDefinitionLink> cpDefinitionLinks) { for (CPDefinitionLink cpDefinitionLink : cpDefinitionLinks) { if (entityCache.getResult( CPDefinitionLinkModelImpl.ENTITY_CACHE_ENABLED, CPDefinitionLinkImpl.class, cpDefinitionLink.getPrimaryKey()) == null) { cacheResult(cpDefinitionLink); } else { cpDefinitionLink.resetOriginalValues(); } } }
java
public static boolean intersectRayAab(Vector3dc origin, Vector3dc dir, Vector3dc min, Vector3dc max, Vector2d result) { return intersectRayAab(origin.x(), origin.y(), origin.z(), dir.x(), dir.y(), dir.z(), min.x(), min.y(), min.z(), max.x(), max.y(), max.z(), result); }
python
def predict_moments(self, X, nsamples=200, likelihood_args=()): r""" Predictive moments, in particular mean and variance, of a Bayesian GLM. This function uses Monte-Carlo sampling to evaluate the predictive mean and variance of a Bayesian GLM. The exact expressions evaluated are, .. math :: \mathbb{E}[y^* | \mathbf{x^*}, \mathbf{X}, y] &= \int \mathbb{E}[y^* | \mathbf{w}, \phi(\mathbf{x}^*)] p(\mathbf{w} | \mathbf{y}, \boldsymbol\Phi) d\mathbf{w}, \mathbb{V}[y^* | \mathbf{x^*}, \mathbf{X}, y] &= \int \left(\mathbb{E}[y^* | \mathbf{w}, \phi(\mathbf{x}^*)] - \mathbb{E}[y^* | \mathbf{x^*}, \mathbf{X}, y]\right)^2 p(\mathbf{w} | \mathbf{y}, \boldsymbol\Phi) d\mathbf{w}, where :math:`\mathbb{E}[y^* | \mathbf{w}, \phi(\mathbf{x}^*)]` is the the expected value of :math:`y^*` from the likelihood, and :math:`p(\mathbf{w} | \mathbf{y}, \boldsymbol\Phi)` is the posterior distribution over weights (from ``learn``). Here are few concrete examples of how we can use these values, - Gaussian likelihood: these are just the predicted mean and variance, see ``revrand.regression.predict`` - Bernoulli likelihood: The expected value is the probability, :math:`p(y^* = 1)`, i.e. the probability of class one. The variance may not be so useful. - Poisson likelihood: The expected value is similar conceptually to the Gaussian case, and is also a *continuous* value. The median (50% quantile) from ``predict_interval`` is a discrete value. Again, the variance in this instance may not be so useful. Parameters ---------- X : ndarray (N*,d) array query input dataset (N* samples, d dimensions). nsamples : int, optional Number of samples for sampling the expected moments from the predictive distribution. likelihood_args : sequence, optional sequence of arguments to pass to the likelihood function. These are non-learnable parameters. They can be scalars or arrays of length N. Returns ------- Ey : ndarray The expected value of y* for the query inputs, X* of shape (N*,). Vy : ndarray The expected variance of y* (excluding likelihood noise terms) for the query inputs, X* of shape (N*,). """ # Get latent function samples N = X.shape[0] ys = np.empty((N, nsamples)) fsamples = self._sample_func(X, nsamples) # Push samples though likelihood expected value Eyargs = tuple(chain(atleast_list(self.like_hypers_), likelihood_args)) for i, f in enumerate(fsamples): ys[:, i] = self.likelihood.Ey(f, *Eyargs) # Average transformed samples (MC integration) Ey = ys.mean(axis=1) Vy = ((ys - Ey[:, np.newaxis])**2).mean(axis=1) return Ey, Vy
java
@Override public CreateSubnetResult createSubnet(CreateSubnetRequest request) { request = beforeClientExecution(request); return executeCreateSubnet(request); }
python
def face_adjacency_angles(self): """ Return the angle between adjacent faces Returns -------- adjacency_angle : (n,) float Angle between adjacent faces Each value corresponds with self.face_adjacency """ pairs = self.face_normals[self.face_adjacency] angles = geometry.vector_angle(pairs) return angles
java
public CommandLine setSeparator(String separator) { getCommandSpec().parser().separator(Assert.notNull(separator, "separator")); for (CommandLine command : getCommandSpec().subcommands().values()) { command.setSeparator(separator); } return this; }
python
def apply_default_constraints(self): """Applies default secthresh & exclusion radius constraints """ try: self.apply_secthresh(pipeline_weaksec(self.koi)) except NoWeakSecondaryError: logging.warning('No secondary eclipse threshold set for {}'.format(self.koi)) self.set_maxrad(default_r_exclusion(self.koi))
python
def delete_state(key, namespace=None, table_name=None, environment=None, layer=None, stage=None, shard_id=None, consistent=True, wait_exponential_multiplier=500, wait_exponential_max=5000, stop_max_delay=10000): """Delete Lambda state value.""" if table_name is None: table_name = _state_table_name(environment=environment, layer=layer, stage=stage) if not table_name: msg = ("Can't produce state table name: unable to set state " "item '{}'".format(key)) logger.error(msg) raise StateTableError(msg) return dynamodb = boto3.resource("dynamodb") table = dynamodb.Table(table_name) logger.info("Deleting {} in DynamoDB table {}".format(key, table_name)) if namespace: key = "{}:{}".format(namespace, key) if shard_id: key = "{}:{}".format(shard_id, key) @retry(retry_on_exception=_is_critical_exception, wait_exponential_multiplier=500, wait_exponential_max=5000, stop_max_delay=10000) def delete_item(): try: return table.delete_item(Key={"id": key}) except Exception as err: if _is_dynamodb_critical_exception(err): raise CriticalError(err) else: raise resp = delete_item() logger.info("Response from DynamoDB: '{}'".format(resp)) return resp
java
private ZooClassDef newVersion(ClientSessionCache cache, ZooClassDef newSuper) { if (nextVersion != null) { throw new IllegalStateException(); } if (newSuper == null) { //no new version of super available newSuper = superDef; } long oid = jdoZooGetContext().getNode().getOidBuffer().allocateOid(); ZooClassDef newDef = new ZooClassDef(className, oid, newSuper.getOid(), schemaId, versionId + 1); //super-class newDef.associateSuperDef(newSuper); //caches cache.addSchema(newDef, false, jdoZooGetContext().getNode()); //versions newDef.prevVersionOid = jdoZooGetOid(); newDef.prevVersion = this; nextVersion = newDef; //API class newDef.versionProxy = versionProxy; versionProxy.newVersion(newDef); //context newDef.providedContext = new PCContext(newDef, providedContext.getSession(), providedContext.getNode()); //fields for (ZooFieldDef f: localFields) { ZooFieldDef fNew = new ZooFieldDef(f, newDef); newDef.localFields.add(fNew); if (fNew.getProxy() != null) { fNew.getProxy().updateVersion(fNew); } } newDef.associateFields(); return newDef; }
java
private WebSocketMessage getMessageForEvent(final SecurityContext securityContext, final ModificationEvent modificationEvent) throws FrameworkException { final String callbackId = modificationEvent.getCallbackId(); if (modificationEvent.isNode()) { final NodeInterface node = (NodeInterface) modificationEvent.getGraphObject(); if (modificationEvent.isDeleted()) { final WebSocketMessage message = createMessage("DELETE", callbackId); message.setId(modificationEvent.getRemovedProperties().get(GraphObject.id)); message.setCode(200); return message; } if (modificationEvent.isCreated()) { final WebSocketMessage message = createMessage("CREATE", callbackId); message.setGraphObject(node); message.setResult(Arrays.asList(node)); message.setCode(201); return message; } if (modificationEvent.isModified()) { final WebSocketMessage message = createMessage("UPDATE", callbackId); // at login the securityContext is still null if (securityContext != null) { // only include changed properties (+ id and type) final LinkedHashSet<String> propertySet = new LinkedHashSet(); propertySet.add("id"); propertySet.add("type"); for (Iterator<PropertyKey> it = modificationEvent.getModifiedProperties().keySet().iterator(); it.hasNext(); ) { final String jsonName = ((PropertyKey)it.next()).jsonName(); if (!propertySet.contains(jsonName)) { propertySet.add(jsonName); } } for (Iterator<PropertyKey> it = modificationEvent.getRemovedProperties().keySet().iterator(); it.hasNext(); ) { final String jsonName = ((PropertyKey)it.next()).jsonName(); if (!propertySet.contains(jsonName)) { propertySet.add(jsonName); } } if (propertySet.size() > 2) { securityContext.setCustomView(propertySet); } } message.setGraphObject(node); message.setResult(Arrays.asList(node)); message.setId(node.getUuid()); message.getModifiedProperties().addAll(modificationEvent.getModifiedProperties().keySet()); message.getRemovedProperties().addAll(modificationEvent.getRemovedProperties().keySet()); message.setNodeData(modificationEvent.getData(securityContext)); message.setCode(200); if (securityContext != null) { // Clear custom view here. This is necessary because the security context is reused for all websocket frames. securityContext.clearCustomView(); } return message; } } else { // handle relationship final RelationshipInterface relationship = (RelationshipInterface) modificationEvent.getGraphObject(); final RelationshipType relType = modificationEvent.getRelationshipType(); // special treatment of CONTAINS relationships if ("CONTAINS".equals(relType.name())) { if (modificationEvent.isDeleted()) { final WebSocketMessage message = createMessage("REMOVE_CHILD", callbackId); message.setNodeData("parentId", relationship.getSourceNodeId()); message.setId(relationship.getTargetNodeId()); message.setCode(200); return message; } if (modificationEvent.isCreated()) { final WebSocketMessage message = new WebSocketMessage(); final NodeInterface startNode = relationship.getSourceNode(); final NodeInterface endNode = relationship.getTargetNode(); // If either start or end node are not visible for the user to be notified, // don't send a notification if (startNode == null || endNode == null) { return null; } message.setResult(Arrays.asList(new GraphObject[]{endNode})); message.setId(endNode.getUuid()); message.setNodeData("parentId", startNode.getUuid()); message.setCode(200); message.setCommand("APPEND_CHILD"); if (endNode instanceof DOMNode) { org.w3c.dom.Node refNode = ((DOMNode) endNode).getNextSibling(); if (refNode != null) { message.setCommand("INSERT_BEFORE"); message.setNodeData("refId", ((AbstractNode) refNode).getUuid()); } } else if (endNode instanceof User || endNode instanceof Group) { message.setCommand("APPEND_MEMBER"); message.setNodeData("refId", startNode.getUuid()); } else if (endNode instanceof AbstractFile) { message.setCommand("APPEND_FILE"); message.setNodeData("refId", startNode.getUuid()); } return message; } } if (modificationEvent.isDeleted()) { final WebSocketMessage message = createMessage("DELETE", callbackId); message.setId(modificationEvent.getRemovedProperties().get(GraphObject.id)); message.setCode(200); return message; } if (modificationEvent.isModified()) { final WebSocketMessage message = createMessage("UPDATE", callbackId); message.getModifiedProperties().addAll(modificationEvent.getModifiedProperties().keySet()); message.getRemovedProperties().addAll(modificationEvent.getRemovedProperties().keySet()); message.setNodeData(modificationEvent.getData(securityContext)); message.setGraphObject(relationship); message.setId(relationship.getUuid()); message.setCode(200); final PropertyMap relProperties = relationship.getProperties(); //final NodeInterface startNode = relationship.getSourceNode(); //final NodeInterface endNode = relationship.getTargetNode(); //relProperties.put(new StringProperty("startNodeId"), startNode.getUuid()); //relProperties.put(new StringProperty("endNodeId"), endNode.getUuid()); final Map<String, Object> properties = PropertyMap.javaTypeToInputType(securityContext, relationship.getClass(), relProperties); message.setRelData(properties); return message; } } return null; }
python
def pdf2text(path, password="", headers=None): """从pdf文件中提取文本 :param path: str pdf文件在本地的地址或者url地址 :param password: str pdf文件的打开密码,默认为空 :param headers: dict 请求url所需要的 header,默认值为 None :return: text """ if path.startswith("http"): if headers: request = Request(url=path, headers=headers) else: request = Request(url=path, headers={}) fp = urlopen(request) # 打开在线PDF文档 else: fp = open(path, 'rb') parser = PDFParser(fp) doc = PDFDocument() parser.set_document(doc) doc.set_parser(parser) # 提供初始化密码 # 如果没有密码 就创建一个空的字符串 doc.initialize(password) # 检测文档是否提供txt转换,不提供就忽略 if not doc.is_extractable: raise PDFTextExtractionNotAllowed else: rsrcmgr = PDFResourceManager() laparams = LAParams() device = PDFPageAggregator(rsrcmgr, laparams=laparams) interpreter = PDFPageInterpreter(rsrcmgr, device) text = [] for page in doc.get_pages(): interpreter.process_page(page) layout = device.get_result() for x in layout: if isinstance(x, LTTextBoxHorizontal): text.append(x.get_text()) return text
python
def next(self): """ Returns the next attribute from the Instances object. :return: the next Attribute object :rtype: Attribute """ if self.col < self.data.num_attributes: index = self.col self.col += 1 return self.data.attribute(index) else: raise StopIteration()
java
public static com.liferay.commerce.discount.model.CommerceDiscountUserSegmentRel deleteCommerceDiscountUserSegmentRel( com.liferay.commerce.discount.model.CommerceDiscountUserSegmentRel commerceDiscountUserSegmentRel) { return getService() .deleteCommerceDiscountUserSegmentRel(commerceDiscountUserSegmentRel); }
java
public static String paramMapToString(final Map<String, String[]> parameters) { final StringBuffer result = new StringBuffer(); for (final String key : parameters.keySet()) { String[] values = parameters.get(key); if (null == values) { result.append(key).append('&'); } else { for (final String value : parameters.get(key)) { result.append(key).append('=').append(CmsEncoder.encode(value)).append('&'); } } } // remove last '&' if (result.length() > 0) { result.setLength(result.length() - 1); } return result.toString(); }
python
def listdir(self, target_directory): """Return a list of file names in target_directory. Args: target_directory: Path to the target directory within the fake filesystem. Returns: A list of file names within the target directory in arbitrary order. Raises: OSError: if the target is not a directory. """ target_directory = self.resolve_path(target_directory, allow_fd=True) directory = self.confirmdir(target_directory) directory_contents = directory.contents return list(directory_contents.keys())
python
def get_placement_group_dict(): """Returns dictionary of {placement_group_name: (state, strategy)}""" client = get_ec2_client() response = client.describe_placement_groups() assert is_good_response(response) result = OrderedDict() ec2 = get_ec2_resource() for placement_group_response in response['PlacementGroups']: key = placement_group_response['GroupName'] if key in result: util.log(f"Warning: Duplicate placement_group group {key}") if DUPLICATE_CHECKING: assert False result[key] = ec2.PlacementGroup(key) return result
python
def folderitem(self, obj, item, index): """Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by the template :index: current index of the item """ title = obj.Title() description = obj.Description() url = obj.absolute_url() item["replace"]["Title"] = get_link(url, value=title) item["Description"] = description item["Formula"] = obj.getMinifiedFormula() return item
python
def export_yaml(obj, file_name): """ Exports curves and surfaces in YAML format. .. note:: Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package. YAML format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>`_ as a way to input shape data from the command line. :param obj: input geometry :type obj: abstract.SplineGeometry, multi.AbstractContainer :param file_name: name of the output file :type file_name: str :raises GeomdlException: an error occurred writing the file """ def callback(data): # Ref: https://yaml.readthedocs.io/en/latest/example.html#output-of-dump-as-a-string stream = StringIO() yaml = YAML() yaml.dump(data, stream) return stream.getvalue() # Check if it is possible to import 'ruamel.yaml' try: from ruamel.yaml import YAML except ImportError: raise exch.GeomdlException("Please install 'ruamel.yaml' package to use YAML format: pip install ruamel.yaml") # Export data exported_data = exch.export_dict_str(obj=obj, callback=callback) # Write to file return exch.write_file(file_name, exported_data)
java
private String encode(Object value) { return BaseEncoding.base16().encode(valueSerializer.encode(value)); }
java
public static DifferenceEvaluator ignorePrologDifferencesExceptDoctype() { return new DifferenceEvaluator() { @Override public ComparisonResult evaluate(Comparison comparison, ComparisonResult orig) { return belongsToProlog(comparison, false) || isSequenceOfRootElement(comparison) ? ComparisonResult.EQUAL : orig; } }; }
python
def from_sky(cls, magnitudelimit=None): ''' Create a Constellation from a criteria search of the whole sky. Parameters ---------- magnitudelimit : float Maximum magnitude (for Ve = "estimated V"). ''' # define a query for cone search surrounding this center criteria = {} if magnitudelimit is not None: criteria[cls.defaultfilter + 'mag'] = '<{}'.format(magnitudelimit) v = Vizier(columns=cls.columns, column_filters=criteria) v.ROW_LIMIT = -1 # run the query print('querying Vizier for {}, for {}<{}'.format(cls.name, cls.defaultfilter, magnitudelimit)) table = v.query_constraints(catalog=cls.catalog, **criteria)[0] # store the search parameters in this object c = cls(cls.standardize_table(table)) c.standardized.meta['catalog'] = cls.catalog c.standardized.meta['criteria'] = criteria c.standardized.meta['magnitudelimit'] = magnitudelimit or c.magnitudelimit #c.magnitudelimit = magnitudelimit or c.magnitudelimit return c
java
@Override public IReactionSet initiate(IAtomContainerSet reactants, IAtomContainerSet agents) throws CDKException { logger.debug("initiate reaction: ElectronImpactNBEReaction"); if (reactants.getAtomContainerCount() != 1) { throw new CDKException("ElectronImpactNBEReaction only expects one reactant"); } if (agents != null) { throw new CDKException("ElectronImpactNBEReaction don't expects agents"); } IReactionSet setOfReactions = reactants.getBuilder().newInstance(IReactionSet.class); IAtomContainer reactant = reactants.getAtomContainer(0); /* * if the parameter hasActiveCenter is not fixed yet, set the active * centers */ IParameterReact ipr = super.getParameterClass(SetReactionCenter.class); if (ipr != null && !ipr.isSetParameter()) setActiveCenters(reactant); Iterator<IAtom> atoms = reactant.atoms().iterator(); while (atoms.hasNext()) { IAtom atom = atoms.next(); if (atom.getFlag(CDKConstants.REACTIVE_CENTER) && reactant.getConnectedLonePairsCount(atom) > 0 && reactant.getConnectedSingleElectronsCount(atom) == 0) { ArrayList<IAtom> atomList = new ArrayList<IAtom>(); atomList.add(atom); IAtomContainerSet moleculeSet = reactant.getBuilder().newInstance(IAtomContainerSet.class); moleculeSet.addAtomContainer(reactant); IReaction reaction = mechanism.initiate(moleculeSet, atomList, null); if (reaction == null) continue; else setOfReactions.addReaction(reaction); } } return setOfReactions; }
java
public void setDate(final int parameterIndex, final Date date) throws SQLException { if(date == null) { setNull(parameterIndex, Types.DATE); return; } setParameter(parameterIndex, new DateParameter(date.getTime())); }
python
def delete_branch(self, resource_id=None, db_session=None, *args, **kwargs): """ This deletes whole branch with children starting from resource_id :param resource_id: :param db_session: :return: """ return self.service.delete_branch( resource_id=resource_id, db_session=db_session, *args, **kwargs )
python
def frame_indexing(frame, multi_index, level_i, indexing_type='label'): """Index dataframe based on one level of MultiIndex. Arguments --------- frame : pandas.DataFrame The datafrme to select records from. multi_index : pandas.MultiIndex A pandas multiindex were one fo the levels is used to sample the dataframe with. level_i : int, str The level of the multiIndex to index on. indexing_type : str The type of indexing. The value can be 'label' or 'position'. Default 'label'. """ if indexing_type == "label": data = frame.loc[multi_index.get_level_values(level_i)] data.index = multi_index elif indexing_type == "position": data = frame.iloc[multi_index.get_level_values(level_i)] data.index = multi_index else: raise ValueError("indexing_type needs to be 'label' or 'position'") return data
java
public PutComplianceItemsRequest withItems(ComplianceItemEntry... items) { if (this.items == null) { setItems(new com.amazonaws.internal.SdkInternalList<ComplianceItemEntry>(items.length)); } for (ComplianceItemEntry ele : items) { this.items.add(ele); } return this; }
python
def deny(ip, port=None, proto='tcp', direction='in', port_origin='d', ip_origin='d', ttl=None, comment=''): ''' Add an rule to csf denied hosts See :func:`_access_rule`. 1- Deny an IP: CLI Example: .. code-block:: bash salt '*' csf.deny 127.0.0.1 salt '*' csf.deny 127.0.0.1 comment="Too localhosty" ''' return _access_rule('deny', ip, port, proto, direction, port_origin, ip_origin, comment)
java
public static Selector getSelector(MutableCallSite callSite, Class sender, String methodName, int callID, boolean safeNavigation, boolean thisCall, boolean spreadCall, Object[] arguments) { CALL_TYPES callType = CALL_TYPES_VALUES[callID]; switch (callType) { case INIT: return new InitSelector(callSite, sender, methodName, callType, safeNavigation, thisCall, spreadCall, arguments); case METHOD: return new MethodSelector(callSite, sender, methodName, callType, safeNavigation, thisCall, spreadCall, arguments); case GET: return new PropertySelector(callSite, sender, methodName, callType, safeNavigation, thisCall, spreadCall, arguments); case SET: throw new GroovyBugError("your call tried to do a property set, which is not supported."); case CAST: return new CastSelector(callSite, arguments); default: throw new GroovyBugError("unexpected call type"); } }
java
private Object writeReplace() throws ObjectStreamException { return new UnbackedMemberIdentifier<X>(getDeclaringType(), AnnotatedTypes.createConstructorId(constructor, getAnnotations(), getParameters())); }
python
def iter(self, root=None): """ Create an iterator of (directory, control_dict) tuples for all valid parameter choices in this :class:`Nest`. :param root: Root directory :rtype: Generator of ``(directory, control_dictionary)`` tuples. """ if root is None: return iter(self._controls) return ((os.path.join(root, outdir), control) for outdir, control in self._controls)
python
def install_postgres(user=None, dbname=None, password=None): """Install Postgres on remote""" execute(pydiploy.django.install_postgres_server, user=user, dbname=dbname, password=password)
java
@NonNull public IconicsDrawable iconOffsetXDp(@Dimension(unit = DP) int sizeDp) { return iconOffsetXPx(Utils.convertDpToPx(mContext, sizeDp)); }
java
boolean serveStaticResource(HttpServletRequest req, StaplerResponse rsp, OpenConnection con, long expiration) throws IOException { if (con == null) return false; try { return serveStaticResource(req, rsp, con.stream, con.getLastModified(), expiration, con.connection.getContentLength(), con.connection.getURL().toString()); } finally { con.close(); } }
python
def upload_check(self, filename=None, folder_key=None, filedrop_key=None, size=None, hash_=None, path=None, resumable=None): """upload/check http://www.mediafire.com/developers/core_api/1.3/upload/#check """ return self.request('upload/check', QueryParams({ 'filename': filename, 'folder_key': folder_key, 'filedrop_key': filedrop_key, 'size': size, 'hash': hash_, 'path': path, 'resumable': resumable }))
java
public static Expression asBoxedList(List<SoyExpression> items) { List<Expression> childExprs = new ArrayList<>(items.size()); for (SoyExpression child : items) { childExprs.add(child.box()); } return BytecodeUtils.asList(childExprs); }
java
public void initializeRuleStatistics(RuleClassification rl, Predicates pred, Instance inst) { rl.predicateSet.add(pred); rl.obserClassDistrib=new DoubleVector(); rl.observers=new AutoExpandVector<AttributeClassObserver>(); rl.observersGauss=new AutoExpandVector<AttributeClassObserver>(); rl.instancesSeen = 0; rl.attributeStatistics = new DoubleVector(); rl.squaredAttributeStatistics = new DoubleVector(); rl.attributeStatisticsSupervised = new ArrayList<ArrayList<Double>>(); rl.squaredAttributeStatisticsSupervised = new ArrayList<ArrayList<Double>>(); rl.attributeMissingValues = new DoubleVector(); }
java
private List<BitcoinTransactionOutput> readListOfOutputsFromTable(ListObjectInspector loi, Object listOfOutputsObject) { int listLength=loi.getListLength(listOfOutputsObject); List<BitcoinTransactionOutput> result=new ArrayList<>(listLength); StructObjectInspector listOfOutputsElementObjectInspector = (StructObjectInspector)loi.getListElementObjectInspector(); for (int i=0;i<listLength;i++) { Object currentListOfOutputsObject = loi.getListElement(listOfOutputsObject,i); StructField valueSF = listOfOutputsElementObjectInspector.getStructFieldRef("value"); StructField txoutscriptlengthSF = listOfOutputsElementObjectInspector.getStructFieldRef("txoutscriptlength"); StructField txoutscriptSF = listOfOutputsElementObjectInspector.getStructFieldRef("txoutscript"); if ((valueSF==null) || (txoutscriptlengthSF==null) || (txoutscriptSF==null)) { LOG.warn("Invalid BitcoinTransactionOutput detected at position "+i); return new ArrayList<>(); } HiveDecimal currentValue=hdoi.getPrimitiveJavaObject(listOfOutputsElementObjectInspector.getStructFieldData(currentListOfOutputsObject,valueSF)); byte[] currentTxOutScriptLength=wboi.getPrimitiveJavaObject(listOfOutputsElementObjectInspector.getStructFieldData(currentListOfOutputsObject,txoutscriptlengthSF)); byte[] currentTxOutScript=wboi.getPrimitiveJavaObject(listOfOutputsElementObjectInspector.getStructFieldData(currentListOfOutputsObject,txoutscriptSF)); BitcoinTransactionOutput currentBitcoinTransactionOutput = new BitcoinTransactionOutput(currentValue.bigDecimalValue().toBigIntegerExact(),currentTxOutScriptLength,currentTxOutScript); result.add(currentBitcoinTransactionOutput); } return result; }
python
def get(self, sid): """ Constructs a PhoneNumberContext :param sid: The unique string that identifies the resource :returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext :rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberContext """ return PhoneNumberContext(self._version, service_sid=self._solution['service_sid'], sid=sid, )
python
def _send(self, data): """Send data to statsd.""" if not self._sock: self.connect() self._do_send(data)
java
public void marshall(DescribeClusterRequest describeClusterRequest, ProtocolMarshaller protocolMarshaller) { if (describeClusterRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeClusterRequest.getName(), NAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
python
def imread(filename, masked = False): """Convenience function that uses the QImage_ constructor to read an image from the given file and return an `rgb_view` of the result. This is intentionally similar to scipy.ndimage.imread (which uses PIL), scipy.misc.imread, or matplotlib.pyplot.imread (using PIL for non-PNGs). For grayscale images, return 2D array (even if it comes from a 32-bit representation; this is a consequence of the QImage API). For images with an alpha channel, the resulting number of channels will be 2 (grayscale+alpha) or 4 (RGB+alpha). Alternatively, one may pass `masked = True` in order to get `masked arrays`_ back. Note that only fully transparent pixels are masked (and that masked arrays only support binary masks). The value of `masked` is ignored when the loaded image has no alpha channel (i.e., one would not get a masked array in that case). This function has been added in version 1.3. """ qImage = _qt.QImage(filename) if qImage.isNull(): raise IOError('loading %r failed' % filename) isGray = qImage.isGrayscale() if isGray and qImage.depth() == 8: return byte_view(qImage)[...,0] hasAlpha = qImage.hasAlphaChannel() if hasAlpha: targetFormat = _qt.QImage.Format_ARGB32 else: targetFormat = _qt.QImage.Format_RGB32 if qImage.format() != targetFormat: qImage = qImage.convertToFormat(targetFormat) result = rgb_view(qImage) if isGray: result = result[...,0] if hasAlpha: if masked: mask = (alpha_view(qImage) == 0) if _np.ndim(result) == 3: mask = _np.repeat(mask[...,None], 3, axis = 2) result = _np.ma.masked_array(result, mask) else: result = _np.dstack((result, alpha_view(qImage))) return result
java
List<MemberState> getActiveMemberStates(Comparator<MemberState> comparator) { List<MemberState> activeMembers = new ArrayList<>(getActiveMemberStates()); Collections.sort(activeMembers, comparator); return activeMembers; }
java
private Object executeBatch(StatementRuntime... runtimes) { int[] updatedArray = new int[runtimes.length]; Map<String, List<StatementRuntime>> batchs = new HashMap<String, List<StatementRuntime>>(); for (int i = 0; i < runtimes.length; i++) { StatementRuntime runtime = runtimes[i]; List<StatementRuntime> batch = batchs.get(runtime.getSQL()); if (batch == null) { batch = new ArrayList<StatementRuntime>(runtimes.length); batchs.put(runtime.getSQL(), batch); } runtime.setAttribute("_index_at_batch_", i); // 该runtime在batch中的位置 batch.add(runtime); } // TODO: 多个真正的batch可以考虑并行执行(而非顺序执行)~待定 for (Map.Entry<String, List<StatementRuntime>> batch : batchs.entrySet()) { String sql = batch.getKey(); List<StatementRuntime> batchRuntimes = batch.getValue(); StatementRuntime runtime = batchRuntimes.get(0); DataAccess dataAccess = dataAccessFactory.getDataAccess(// runtime.getMetaData(), runtime.getAttributes()); List<Object[]> argsList = new ArrayList<Object[]>(batchRuntimes.size()); for (StatementRuntime batchRuntime : batchRuntimes) { argsList.add(batchRuntime.getArgs()); } int[] batchResult = dataAccess.batchUpdate(sql, argsList); if (batchs.size() == 1) { updatedArray = batchResult; } else { int index_at_sub_batch = 0; for (StatementRuntime batchRuntime : batchRuntimes) { Integer _index_at_batch_ = batchRuntime.getAttribute("_index_at_batch_"); updatedArray[_index_at_batch_] = batchResult[index_at_sub_batch++]; } } } if (returnType == void.class) { return null; } if (returnType == int[].class) { return updatedArray; } if (returnType == Integer.class || returnType == Boolean.class) { int updated = 0; for (int value : updatedArray) { updated += value; } return returnType == Boolean.class ? updated > 0 : updated; } throw new InvalidDataAccessApiUsageException( "bad return type for batch update: " + runtimes[0].getMetaData().getMethod()); }
python
def run(self, build_requests=None, callback=None): """ Run the client in a loop, calling the callback each time the debugger stops. """ if callback: self.callback = callback if build_requests: self.build_requests = build_requests def normalise_requests_err(e): try: msg = e.message.args[1].strerror except: try: msg = e.message.args[0] except: msg = str(e) return msg while not self.done: try: # get the server version info if not self.server_version: self.server_version = self.perform_request('version') # if the server supports async mode, use it, as some views may only work in async mode if self.server_version.capabilities and 'async' in self.server_version.capabilities: self.update() self.block = False elif self.supports_blocking: self.block = True else: raise BlockingNotSupportedError("Debugger requires blocking mode") if self.block: # synchronous requests self.update() else: # async requests, block using a null request until the debugger stops again res = self.perform_request('null', block=True) if res.is_success: self.server_version = res self.update() except ConnectionError as e: self.callback(error='Error: {}'.format(normalise_requests_err(e))) self.server_version = None time.sleep(1)
python
def run(self): """ Run an infinite REQ/REP loop. """ while True: req = self.socket.recv_json() try: answer = self.handle_request(req) self.socket.send(json.dumps(answer)) except (AttributeError, TypeError) as e: self.socket.send_json({'error': str(e)})
java
@Override public PutScheduledUpdateGroupActionResult putScheduledUpdateGroupAction(PutScheduledUpdateGroupActionRequest request) { request = beforeClientExecution(request); return executePutScheduledUpdateGroupAction(request); }
java
public void push(T val) { backChunk.values[backPos] = val; backChunk = endChunk; backPos = endPos; if (++endPos != size) { return; } Chunk<T> sc = spareChunk; if (sc != beginChunk) { spareChunk = spareChunk.next; endChunk.next = sc; sc.prev = endChunk; } else { endChunk.next = new Chunk<>(size, memoryPtr); memoryPtr += size; endChunk.next.prev = endChunk; } endChunk = endChunk.next; endPos = 0; }
python
def list_keys(self): """List your API Keys.""" keys = self._curl_bitmex("/apiKey/") print(json.dumps(keys, sort_keys=True, indent=4))
java
public static void unescapeCsv(final String text, final Writer writer) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } CsvEscapeUtil.unescape(new InternalStringReader(text), writer); }
java
public EClass getIfcCoveringType() { if (ifcCoveringTypeEClass == null) { ifcCoveringTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(126); } return ifcCoveringTypeEClass; }
python
def filesfile_string(self): """String with the list of files and prefixes needed to execute ABINIT.""" lines = [] app = lines.append #optic.in ! Name of input file #optic.out ! Unused #optic ! Root name for all files that will be produced app(self.input_file.path) # Path to the input file app(os.path.join(self.workdir, "unused")) # Path to the output file app(os.path.join(self.workdir, self.prefix.odata)) # Prefix for output data return "\n".join(lines)
python
def is_tenant_manager(user, group=None, tenant=None): """Returns True if user is a tenant manager either for the group/tenant or any group/tenant.""" roles = get_user_roles(user) return any( x[1] == TenantRole.ROLE_TENANT_MANAGER and (not group or x[0] == group) and (not tenant or x[2] == tenant) for x in roles )
java
public ServiceFuture<PrebuiltEntityExtractor> getPrebuiltAsync(UUID appId, String versionId, UUID prebuiltId, final ServiceCallback<PrebuiltEntityExtractor> serviceCallback) { return ServiceFuture.fromResponse(getPrebuiltWithServiceResponseAsync(appId, versionId, prebuiltId), serviceCallback); }
java
public OrientModule withCustomTypes(final Class<? extends OObjectSerializer>... serializers) { customTypes.addAll(Arrays.asList(serializers)); return this; }
java
public <U> SimpleReactStream<U> from(final Stream<U> stream) { final Stream s = stream.map(it -> CompletableFuture.completedFuture(it)); return construct(s); }
python
def complete_offset_upload(self, chunk_num): # type: (Descriptor, int) -> None """Complete the upload for the offset :param Descriptor self: this :param int chunk_num: chunk num completed """ with self._meta_lock: self._outstanding_ops -= 1 # save resume state if self.is_resumable: # only set resumable completed if all replicas for this # chunk are complete if blobxfer.util.is_not_empty(self._dst_ase.replica_targets): if chunk_num not in self._replica_counters: # start counter at -1 since we need 1 "extra" for the # primary in addition to the replica targets self._replica_counters[chunk_num] = -1 self._replica_counters[chunk_num] += 1 if (self._replica_counters[chunk_num] != len(self._dst_ase.replica_targets)): return else: self._replica_counters.pop(chunk_num) self._completed_chunks.set(True, chunk_num) completed = self._outstanding_ops == 0 self._resume_mgr.add_or_update_record( self._dst_ase, self._src_block_list, self._offset, self._chunk_size, self._total_chunks, self._completed_chunks.int, completed, )
java
public static PopupMenu newPopupMenu(final List<MenuItemBean> menuItemBeans) { final PopupMenu popupMenu = new PopupMenu(); for (final MenuItemBean menuItemBean : menuItemBeans) { final MenuItem miBringToFront = new MenuItem(menuItemBean.getLabel()); miBringToFront.setActionCommand(menuItemBean.getCommand()); miBringToFront.addActionListener(menuItemBean.getActionListener()); popupMenu.add(miBringToFront); } return popupMenu; }
python
def random_sample(obj, n_samples, seed=None): """Create a random array by sampling a ROOT function or histogram. Parameters ---------- obj : TH[1|2|3] or TF[1|2|3] The ROOT function or histogram to sample. n_samples : positive int The number of random samples to generate. seed : None, positive int or 0, optional (default=None) The random seed, set via ROOT.gRandom.SetSeed(seed): http://root.cern.ch/root/html/TRandom3.html#TRandom3:SetSeed If 0, the seed will be random. If None (the default), ROOT.gRandom will not be touched and the current seed will be used. Returns ------- array : a numpy array A numpy array with a shape corresponding to the dimensionality of the function or histogram. A flat array is returned when sampling TF1 or TH1. An array with shape [n_samples, n_dimensions] is returned when sampling TF2, TF3, TH2, or TH3. Examples -------- >>> from root_numpy import random_sample >>> from ROOT import TF1, TF2, TF3 >>> random_sample(TF1("f1", "TMath::DiLog(x)"), 10000, seed=1) array([ 0.68307934, 0.9988919 , 0.87198158, ..., 0.50331049, 0.53895257, 0.57576984]) >>> random_sample(TF2("f2", "sin(x)*sin(y)/(x*y)"), 10000, seed=1) array([[ 0.93425084, 0.39990616], [ 0.00819315, 0.73108525], [ 0.00307176, 0.00427081], ..., [ 0.66931215, 0.0421913 ], [ 0.06469985, 0.10253632], [ 0.31059832, 0.75892702]]) >>> random_sample(TF3("f3", "sin(x)*sin(y)*sin(z)/(x*y*z)"), 10000, seed=1) array([[ 0.03323949, 0.95734415, 0.39775191], [ 0.07093748, 0.01007775, 0.03330135], [ 0.80786963, 0.13641129, 0.14655269], ..., [ 0.96223632, 0.43916482, 0.05542078], [ 0.06631163, 0.0015063 , 0.46550416], [ 0.88154752, 0.24332142, 0.66746564]]) """ import ROOT if n_samples <= 0: raise ValueError("n_samples must be greater than 0") if seed is not None: if seed < 0: raise ValueError("seed must be positive or 0") ROOT.gRandom.SetSeed(seed) # functions if isinstance(obj, ROOT.TF1): if isinstance(obj, ROOT.TF3): return _librootnumpy.sample_f3( ROOT.AsCObject(obj), n_samples) elif isinstance(obj, ROOT.TF2): return _librootnumpy.sample_f2( ROOT.AsCObject(obj), n_samples) return _librootnumpy.sample_f1(ROOT.AsCObject(obj), n_samples) # histograms elif isinstance(obj, ROOT.TH1): if isinstance(obj, ROOT.TH3): return _librootnumpy.sample_h3( ROOT.AsCObject(obj), n_samples) elif isinstance(obj, ROOT.TH2): return _librootnumpy.sample_h2( ROOT.AsCObject(obj), n_samples) return _librootnumpy.sample_h1(ROOT.AsCObject(obj), n_samples) raise TypeError( "obj must be a ROOT function or histogram")
java
public String[] namedEntityRecognize(String[] wordArray, String[] posArray) { if (neRecognizer == null) { throw new IllegalStateException("未提供命名实体识别模型"); } return recognize(wordArray, posArray); }
java
public static GalleryTabId parseTabId(String tabId) { try { return GalleryTabId.valueOf("cms_tab_" + tabId); } catch (Throwable e) { return null; } }
python
def _ratelimited_get(self, *args, **kwargs): """Perform get request, handling rate limiting.""" with self._ratelimiter: resp = self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen if a script is cancelled # before it has finished sleeping to satisfy the rate limit and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp.status_code == 500: # Let's only retry if the error page tells us it's a rate limit # violation. if 'violated your query rate limit' in resp.text: # Mimic the RateLimiter callback behaviour. until = time.time() + self._ratelimiter.period t = threading.Thread(target=self._ratelimit_callback, args=(until,)) t.daemon = True t.start() time.sleep(self._ratelimiter.period) # Now retry with self._ratelimiter: resp = self.session.get(*args, **kwargs) return resp
java
@Override public EClass getExtendedDataSchema() { if (extendedDataSchemaEClass == null) { extendedDataSchemaEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(48); } return extendedDataSchemaEClass; }
java
@Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { try { if (keepAliveManager != null) { keepAliveManager.onTransportTermination(); } if (maxConnectionIdleManager != null) { maxConnectionIdleManager.onTransportTermination(); } if (maxConnectionAgeMonitor != null) { maxConnectionAgeMonitor.cancel(false); } final Status status = Status.UNAVAILABLE.withDescription("connection terminated for unknown reason"); // Any streams that are still active must be closed connection().forEachActiveStream(new Http2StreamVisitor() { @Override public boolean visit(Http2Stream stream) throws Http2Exception { NettyServerStream.TransportState serverStream = serverStream(stream); if (serverStream != null) { serverStream.transportReportStatus(status); } return true; } }); } finally { super.channelInactive(ctx); } }
java
public double getExactMass(Integer atomicNumber, Integer massNumber) { if (atomicNumber == null || massNumber == null) return 0; for (IIsotope isotope : this.isotopes[atomicNumber]) { if (isotope.getMassNumber().equals(massNumber)) return isotope.getExactMass(); } return 0; }
java
public HomeInternal getHome(J2EEName name) //197121 { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "getHome : " + name); HomeInternal result = null; // Name is the HomeOfHomes special name when referencing an // EJBHome; return the HomeOfHomes if (name.equals(homeOfHomesJ2EEName)) { result = this; } // Name is the EJBFactory special name when referencing the // HomeOfHomes for EJB-Link or Auto-Link; return the // EJBFactoryHome. d440604 else if (name.equals(ivEJBFactoryHome.ivJ2eeName)) { result = ivEJBFactoryHome; } // Otherwise, the J2EEName is for a reference to an EJB // instance; return the EJBHome. else { HomeRecord hr = homesByName.get(name); // d366845.3 if (hr != null) { result = hr.homeInternal; if (result == null) { if (hr.bmd.ivDeferEJBInitialization) { result = hr.getHomeAndInitialize(); // d648522 } else { // Request for a non-deferred bean that hasn't quite finished // initializing; return null since bean doesn't exist just yet. // Caller will throw appropriate exception. PM98090 if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "Non-deferred EJB not yet available : " + name); } } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, "getHome : " + result); return result; }
java
public int getMaximumTextLength(Locale locale) { int max = getMaximumValue(); if (max >= 0) { if (max < 10) { return 1; } else if (max < 100) { return 2; } else if (max < 1000) { return 3; } } return Integer.toString(max).length(); }
python
def get_pwm_list(motif_name_list, pseudocountProb=0.0001): """Get a list of ENCODE PWM's. # Arguments pwm_id_list: List of id's from the `PWM_id` column in `get_metadata()` table pseudocountProb: Added pseudocount probabilities to the PWM # Returns List of `concise.utils.pwm.PWM` instances. """ l = _load_motifs() l = {k.split()[0]: v for k, v in l.items()} pwm_list = [PWM(l[m] + pseudocountProb, name=m) for m in motif_name_list] return pwm_list
python
def save_formset(self, request, form, formset, change): """ Given an inline formset save it to the database. """ formset.save() for form in formset.forms: if hasattr(form, 'nested_formsets') and form not in formset.deleted_forms: for nested_formset in form.nested_formsets: self.save_formset(request, form, nested_formset, change)
python
def get_overlays(self, **kw): """ See Overlay.match() for arguments. """ return [o for o in self.overlays if o.match(**kw)]
java
private void readAssignments(Resource mpxjResource, net.sf.mpxj.phoenix.schema.Project.Storepoints.Storepoint.Resources.Resource res) { for (Assignment assignment : res.getAssignment()) { readAssignment(mpxjResource, assignment); } }
java
@Override public void close(ClusterName clusterName) { logger.info("Close connection to cluster [" + clusterName + "] from connector [" + this.getClass().getSimpleName() + "]"); connectionHandler.closeConnection(clusterName.getName()); }
python
def _lincomb(self, a, f1, b, f2, out): """Linear combination of ``f1`` and ``f2``. Notes ----- The additions and multiplications are implemented via simple Python functions, so non-vectorized versions are slow. """ # Avoid infinite recursions by making a copy of the functions f1_copy = f1.copy() f2_copy = f2.copy() def lincomb_oop(x, **kwargs): """Linear combination, out-of-place version.""" # Not optimized since that raises issues with alignment # of input and partial results out = a * np.asarray(f1_copy(x, **kwargs), dtype=self.scalar_out_dtype) tmp = b * np.asarray(f2_copy(x, **kwargs), dtype=self.scalar_out_dtype) out += tmp return out out._call_out_of_place = lincomb_oop decorator = preload_first_arg(out, 'in-place') out._call_in_place = decorator(_default_in_place) out._call_has_out = out._call_out_optional = False return out
python
def check_matrix(m): """Check the sanity of the given 4x4 transformation matrix""" if m.shape != (4, 4): raise ValueError("The argument must be a 4x4 array.") if max(abs(m[3, 0:3])) > eps: raise ValueError("The given matrix does not have correct translational part") if abs(m[3, 3] - 1.0) > eps: raise ValueError("The lower right element of the given matrix must be 1.0.")
python
def generate_uuid4(self) -> list: """Generate a list of parts of a UUID version 4 string. Usually, these parts are concatenated together using dashes. """ # uuid4: 8-4-4-4-12: xxxxxxxx-xxxx-4xxx-{8,9,a,b}xxx-xxxxxxxxxxxx # instead of requesting small amounts of bytes, it's better to do it # for the full amount of them. hexstr = randhex(30) uuid4 = [ hexstr[:8], hexstr[8:12], '4' + hexstr[12:15], '{:x}{}'.format(randbetween(8, 11), hexstr[15:18]), hexstr[18:] ] self.last_result = uuid4 return uuid4
java
Expression readDefaultClause(Type dataType) { Expression e = null; boolean minus = false; if (dataType.isDateTimeType() || dataType.isIntervalType()) { switch (token.tokenType) { case Tokens.DATE : case Tokens.TIME : case Tokens.TIMESTAMP : case Tokens.INTERVAL : { e = readDateTimeIntervalLiteral(); if (e.dataType.typeCode != dataType.typeCode) { // error message throw unexpectedToken(); } Object defaultValue = e.getValue(session, dataType); return new ExpressionValue(defaultValue, dataType); } case Tokens.X_VALUE : break; default : e = XreadDateTimeValueFunctionOrNull(); break; } } else if (dataType.isNumberType()) { if (token.tokenType == Tokens.MINUS) { read(); minus = true; } } else if (dataType.isCharacterType()) { switch (token.tokenType) { case Tokens.USER : case Tokens.CURRENT_USER : case Tokens.CURRENT_ROLE : case Tokens.SESSION_USER : case Tokens.SYSTEM_USER : case Tokens.CURRENT_CATALOG : case Tokens.CURRENT_SCHEMA : case Tokens.CURRENT_PATH : FunctionSQL function = FunctionSQL.newSQLFunction(token.tokenString, compileContext); if (function == null) { throw unexpectedToken(); } e = readSQLFunction(function); break; default : } } else if (dataType.isBooleanType()) { switch (token.tokenType) { case Tokens.TRUE : read(); return Expression.EXPR_TRUE; case Tokens.FALSE : read(); return Expression.EXPR_FALSE; } } if (e == null) { if (token.tokenType == Tokens.NULL) { read(); return new ExpressionValue(null, dataType); } if (token.tokenType == Tokens.X_VALUE) { e = new ExpressionValue(token.tokenValue, token.dataType); if (minus) { e = new ExpressionArithmetic(OpTypes.NEGATE, e); e.resolveTypes(session, null); } read(); Object defaultValue = e.getValue(session, dataType); if ((dataType.typeCode == Types.TINYINT && ((int) defaultValue) == Byte.MIN_VALUE) || (dataType.typeCode == Types.SQL_SMALLINT && ((int) defaultValue) == Short.MIN_VALUE) || (dataType.typeCode == Types.SQL_INTEGER && ((int) defaultValue) == Integer.MIN_VALUE) || (dataType.typeCode == Types.SQL_BIGINT && ((long) defaultValue) == Long.MIN_VALUE)){ throw Error.error(ErrorCode.X_22003); // data exception: numeric value out of range } return new ExpressionValue(defaultValue, dataType); } else { throw unexpectedToken(); } } e.resolveTypes(session, null); // check type and length compatibility of datetime and character functions return e; }
python
def get_success_url(self): """ After the event is deleted there are three options for redirect, tried in this order: # Try to find a 'next' GET variable # If the key word argument redirect is set # Lastly redirect to the event detail of the recently create event """ url_val = 'fullcalendar' if USE_FULLCALENDAR else 'day_calendar' next_url = self.kwargs.get('next') or reverse(url_val, args=[self.object.calendar.slug]) next_url = get_next_url(self.request, next_url) return next_url
python
def hw(self, hw): """ Hardware operations """ if hw.upper() == "INIT": self._raw(HW_INIT) elif hw.upper() == "SELECT": self._raw(HW_SELECT) elif hw.upper() == "RESET": self._raw(HW_RESET) else: # DEFAULT: DOES NOTHING pass
java
void deregister(List<URL> urls) { for (URL url : urls) { _data.remove(url.getFile()); } }
python
def select_lines(self, start=0, end=-1, apply_selection=True): """ Selects entire lines between start and end line numbers. This functions apply the selection and returns the text cursor that contains the selection. Optionally it is possible to prevent the selection from being applied on the code editor widget by setting ``apply_selection`` to False. :param start: Start line number (0 based) :param end: End line number (0 based). Use -1 to select up to the end of the document :param apply_selection: True to apply the selection before returning the QTextCursor. :returns: A QTextCursor that holds the requested selection """ editor = self._editor if end == -1: end = self.line_count() - 1 if start < 0: start = 0 text_cursor = self.move_cursor_to(start) if end > start: # Going down text_cursor.movePosition(text_cursor.Down, text_cursor.KeepAnchor, end - start) text_cursor.movePosition(text_cursor.EndOfLine, text_cursor.KeepAnchor) elif end < start: # going up # don't miss end of line ! text_cursor.movePosition(text_cursor.EndOfLine, text_cursor.MoveAnchor) text_cursor.movePosition(text_cursor.Up, text_cursor.KeepAnchor, start - end) text_cursor.movePosition(text_cursor.StartOfLine, text_cursor.KeepAnchor) else: text_cursor.movePosition(text_cursor.EndOfLine, text_cursor.KeepAnchor) if apply_selection: editor.setTextCursor(text_cursor) return text_cursor
python
def create_list_stories( list_id_stories, number_of_stories, shuffle, max_threads ): """Show in a formatted way the stories for each item of the list.""" list_stories = [] with ThreadPoolExecutor(max_workers=max_threads) as executor: futures = { executor.submit(get_story, new) for new in list_id_stories[:number_of_stories] } for future in tqdm( as_completed(futures), desc='Getting results', unit=' news', ): list_stories.append(future.result()) if shuffle: random.shuffle(list_stories) return list_stories
java
void mapColumnProperty(ResultSet pRSet, int pIndex, String pProperty, Object pObj) { if (pRSet == null || pProperty == null || pObj == null) throw new IllegalArgumentException("ResultSet, Property or Object" + " arguments cannot be null!"); if (pIndex <= 0) throw new IllegalArgumentException("Index parameter must be > 0!"); String methodName = "set" + StringUtil.capitalize(pProperty); Method setMethod = (Method) mMethods.get(methodName); if (setMethod == null) { // No setMethod for this property mLog.logError("No set method for property \"" + pProperty + "\" in " + pObj.getClass() + "!"); return; } // System.err.println("DEBUG: setMethod=" + setMethod); Method getMethod = null; String type = ""; try { Class[] cl = {Integer.TYPE}; type = setMethod.getParameterTypes()[0].getName(); type = type.substring(type.lastIndexOf(".") + 1); // There is no getInteger, use getInt instead if (type.equals("Integer")) { type = "int"; } // System.err.println("DEBUG: type=" + type); getMethod = pRSet.getClass(). getMethod("get" + StringUtil.capitalize(type), cl); } catch (Exception e) { mLog.logError("Can't find method \"get" + StringUtil.capitalize(type) + "(int)\" " + "(for class " + StringUtil.capitalize(type) + ") in ResultSet", e); return; } try { // Get the data from the DB // System.err.println("DEBUG: " + getMethod.getName() + "(" + (i + 1) + ")"); Object[] colIdx = {new Integer(pIndex)}; Object[] arg = {getMethod.invoke(pRSet, colIdx)}; // Set it to the object // System.err.println("DEBUG: " + setMethod.getName() + "(" + arg[0] + ")"); setMethod.invoke(pObj, arg); } catch (InvocationTargetException ite) { mLog.logError(ite); // ite.printStackTrace(); } catch (IllegalAccessException iae) { mLog.logError(iae); // iae.printStackTrace(); } }
python
def create_queue_service(self): ''' Creates a QueueService object with the settings specified in the CloudStorageAccount. :return: A service object. :rtype: :class:`~azure.storage.queue.queueservice.QueueService` ''' try: from azure.storage.queue.queueservice import QueueService return QueueService(self.account_name, self.account_key, sas_token=self.sas_token, is_emulated=self.is_emulated) except ImportError: raise Exception('The package azure-storage-queue is required. ' + 'Please install it using "pip install azure-storage-queue"')
python
def resources(): """Upload a new resource for an individual.""" ind_id = request.form['ind_id'] upload_dir = os.path.abspath(app.config['UPLOAD_DIR']) req_file = request.files['file'] filename = secure_filename(req_file.filename) file_path = os.path.join(upload_dir, filename) name = request.form['name'] or filename req_file.save(file_path) ind_obj = app.db.individual(ind_id) app.db.add_resource(name, file_path, ind_obj) return redirect(request.referrer)
python
def get_ancestor_class_names(mention): """Return the HTML classes of the Mention's ancestors. If a candidate is passed in, only the ancestors of its first Mention are returned. :param mention: The Mention to evaluate :rtype: list of strings """ span = _to_span(mention) class_names = [] i = _get_node(span.sentence) while i is not None: class_names.insert(0, str(i.get("class"))) i = i.getparent() return class_names
java
public void writeLargeString( String s ) { final byte[] bytes = DynamicByteBufferHelper.bytes( s ); this.add( bytes.length ); this.add( bytes ); }