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...
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.s...
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 Conc...
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); } ...
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(fut...
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=pa...
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 = '/credi...
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() ...
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.co...
java
@Override public void cacheResult(List<CPDefinitionLink> cpDefinitionLinks) { for (CPDefinitionLink cpDefinitionLink : cpDefinitionLinks) { if (entityCache.getResult( CPDefinitionLinkModelImpl.ENTITY_CACHE_ENABLED, CPDefinitionLinkImpl.class, cpDefinitionLink.getPrimaryKey()) == null) { cach...
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, ...
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_adj...
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)) ...
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...
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()...
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....
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: reques...
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)...
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('...
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 o...
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['Placem...
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 ...
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 sha...
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) || isSequ...
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 thi...
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...
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=resou...
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 i...
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); } r...
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 '*' cs...
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 InitSelecto...
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: ...
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, ...
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({ ...
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;...
java
private List<BitcoinTransactionOutput> readListOfOutputsFromTable(ListObjectInspector loi, Object listOfOutputsObject) { int listLength=loi.getListLength(listOfOutputsObject); List<BitcoinTransactionOutput> result=new ArrayList<>(listLength); StructObjectInspector listOfOutputsElementObjectInspector = (StructObjectInsp...
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 """ ret...
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(describeClust...
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 ...
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...
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 norma...
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.s...
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....
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.i...
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[...
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 ...
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(...
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 :...
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 ...
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 (maxC...
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(); ...
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 HomeO...
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; } } ...
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` i...
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...
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 ...
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)...
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 bett...
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 Toke...
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 "...
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 ...
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) ...
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...
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.que...
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...
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 = []...
java
public void writeLargeString( String s ) { final byte[] bytes = DynamicByteBufferHelper.bytes( s ); this.add( bytes.length ); this.add( bytes ); }