language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _processArgs(self, entry, *_args, **_kwargs): """ Given an entry, positional and keyword arguments, figure out what the query-string options, payload and api arguments are. """ # We need the args to be a list so we can mutate them args = list(_args) kwargs = copy.dee...
python
def _construct_instance(cls, values): """ method used to construct instances from query results this is where polymorphic deserialization occurs """ # we're going to take the values, which is from the DB as a dict # and translate that into our local fields # the d...
python
def preprocess_uci_adult(data_name): """Some tricks of feature engineering are adapted from tensorflow's wide and deep tutorial. """ csv_columns = [ "age", "workclass", "fnlwgt", "education", "education_num", "marital_status", "occupation", "relationship", "race", "gender", "capi...
java
public static void setDataTableScanFilter( final Scanner scanner, final List<byte[]> group_bys, final ByteMap<byte[][]> row_key_literals, final boolean explicit_tags, final boolean enable_fuzzy_filter, final int end_time) { // no-op if ((group_bys == null || group_bys....
java
public OvhRegistryCredentials serviceName_registry_credentials_credentialsId_GET(String serviceName, String credentialsId) throws IOException { String qPath = "/caas/containers/{serviceName}/registry/credentials/{credentialsId}"; StringBuilder sb = path(qPath, serviceName, credentialsId); String resp = exec(qPath...
java
public void initiateConference( String connId, String destination, KeyValueCollection userData ) throws WorkspaceApiException { this.initiateConference(connId, destination, null, null, userData, null, null); }
java
private synchronized void removeResultTable(){ OWLResultSetTableModel tm = getTableModel(); if (tm != null){ tm.close(); } resultTablePanel.setTableModel(new DefaultTableModel()); }
python
def in_order(self) -> Iterator["BSP"]: """Iterate over this BSP's hierarchy in order. .. versionadded:: 8.3 """ if self.children: yield from self.children[0].in_order() yield self yield from self.children[1].in_order() else: yield ...
java
public void writeProperty(String propertyName, ICalParameters parameters, ICalDataType dataType, JCalValue value) throws IOException { if (stack.isEmpty()) { throw new IllegalStateException(Messages.INSTANCE.getExceptionMessage(2)); } if (componentEnded) { throw new IllegalStateException(Messages.INSTANCE.g...
python
def bytearray_check(*args, func=None): """Check if arguments are bytearray type.""" func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, (bytearray, collections.abc.ByteString, collections.abc.MutableSequence)): name = type(var).__name__ raise Bytearra...
java
private static boolean polygonDisjointEnvelope_(Polygon polygon_a, Envelope envelope_b, double tolerance, ProgressTracker progress_tracker) { // Quick rasterize test to see whether the the geometries are disjoint, // or if one is contained in the other. int relation = tryRasterizedContainsOrDisjoint_(polygo...
java
synchronized QueueStats getStatistics() { int size = this.writes.size(); double fillRatio = calculateFillRatio(this.totalLength, size); int processingTime = this.lastDurationMillis; if (processingTime == 0 && size > 0) { // We get in here when this method is invoked prior to ...
java
public void restore(String versionName, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, RepositoryException, InvalidItemStateException { VersionImpl version = (VersionImpl)versionHistory(false).version(versionName, false); ...
python
def unique(lst): """ Returns a list made up of the unique values found in lst. i.e., it removes the redundant values in lst. """ lst = lst[:] unique_lst = [] # Cycle through the list and add each value to the unique list only once. for item in lst: if unique_lst.count(item) <= ...
python
def __parse_world( world, radius=None, species_list=None, max_count=None, predicator=None): """ Private function to parse world. Return infomation about particles (name, coordinates and particle size) for each species. """ from ecell4_base.core import Species if species_list is...
python
def create(self, data): """ Create a new SyncListItemInstance :param dict data: The data :returns: Newly created SyncListItemInstance :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance """ data = values.of({'Data': serialize.o...
python
def visit_Tuple(self, node: AST, dfltChaining: bool = True) -> str: """Return tuple representation of `node`s elements.""" elems = (self.visit(elt) for elt in node.elts) return f"({', '.join(elems)}{')' if len(node.elts) != 1 else ',)'}"
java
public MonthDay atMonth(Month month) { return MonthDay.of(month, Math.min(day, month.maxLength())); }
java
public JodaBeanSer withIteratorFactory(SerIteratorFactory iteratorFactory) { JodaBeanUtils.notNull(iteratorFactory, "iteratorFactory"); return new JodaBeanSer(indent, newLine, converter, iteratorFactory, shortTypes, deserializers, includeDerived); }
python
def _get_training_data(vrn_files): """Retrieve training data, returning an empty set of information if not available. """ out = {"SNP": [], "INDEL": []} # SNPs for name, train_info in [("train_hapmap", "known=false,training=true,truth=true,prior=15.0"), ("train_omni", "k...
python
def find_windows_executable(bin_path, exe_name): """Given an executable name, search the given location for an executable""" requested_path = get_windows_path(bin_path, exe_name) if os.path.isfile(requested_path): return requested_path try: pathext = os.environ["PATHEXT"] except Key...
python
def schedule_servicegroup_svc_downtime(self, servicegroup, start_time, end_time, fixed, trigger_id, duration, author, comment): """Schedule a service downtime for each service of a servicegroup Format of the line that triggers function call:: SCHEDULE_...
java
public static String[] union(String[] arr1, String[] arr2) { Set<String> set = new HashSet<String>(); for (String str : arr1) { set.add(str); } for (String str : arr2) { set.add(str); } String[] result = {}; return set.toArray(result); }
java
public synchronized int available() throws IOException { int in_stream=in.available(); if (_byteLimit>=0 && in_stream>_byteLimit) in_stream=_byteLimit; return _avail - _pos + in_stream; }
java
public String getDebugModeBuildTimeGenerationPath(String path) { return path.replaceFirst(GeneratorRegistry.PREFIX_SEPARATOR, JawrConstant.URL_SEPARATOR); }
java
@Action(name = "Run Instances", outputs = { @Output(RETURN_CODE), @Output(RETURN_RESULT), @Output(INSTANCE_ID_RESULT), @Output(EXCEPTION) }, responses = { @Response(text = SUCCESS, fie...
python
def initialize_sector_geometry(self, phi): """ Initialize geometry attributes associated with an elliptical sector at the given polar angle ``phi``. This function computes: * the four vertices that define the elliptical sector on the pixel array. * the sector ...
java
public void forAllMembers(String template, Properties attributes) throws XDocletException { if (getCurrentClass() == null) { return; } String className = attributes.getProperty("class"); XClass type = null; if ((className == null) || (className.length()...
python
def message_user(self, username, domain, subject, message): """Currently use send_message_chat and discard subject, because headline messages are not stored by mod_offline.""" kwargs = { 'body': message, 'from': domain, 'to': '%s@%s' % (username, domain), ...
java
private RequestTemplate appendHeader(String name, Iterable<String> values) { if (!values.iterator().hasNext()) { /* empty value, clear the existing values */ this.headers.remove(name); return this; } this.headers.compute(name, (headerName, headerTemplate) -> { if (headerTemplate == n...
python
def build_static(self): """ Build static files """ if not os.path.isdir(self.build_static_dir): os.makedirs(self.build_static_dir) copy_tree(self.static_dir, self.build_static_dir) if self.webassets_cmd: self.webassets_cmd.build()
java
public void setForeground(Drawable drawable) { if (mForeground != drawable) { if (mForeground != null) { mForeground.setCallback(null); unscheduleDrawable(mForeground); } mForeground = drawable; if (drawable != null) { ...
java
public void checkPublishList(CmsPublishList publishList) throws CmsException { for (CmsResource resource : publishList.getAllResources()) { for (ForbiddenFolderEntry entry : m_forbiddenParentFolders.values()) { if (CmsStringUtil.isPrefixPath(entry.getRootPath(), resource.getRootPath...
java
public final static <T> T createInstance(String className, Class<T> expectedType, boolean useCache) throws Err.Compilation, Err.UnloadableClass { try { Object o = createInstance(getCompiledClass(className, useCache)); // a check to see if the class exists T instance = expectedType.cast(o...
python
def image_feature_engineering(features, feature_tensors_dict): """Add a hidden layer on image features. Args: features: features dict feature_tensors_dict: dict of feature-name: tensor """ engineered_features = {} for name, feature_tensor in six.iteritems(feature_tensors_dict): if name in feature...
python
def put(self, request, bot_id, id, format=None): """ Update existing Kik chat state --- serializer: KikChatStateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request "...
python
def from_dict(cls, d): """ Decode a dictionary, as from :meth:`to_dict`, into a Dmrs object. """ def _node(obj): return Node( obj.get('nodeid'), Pred.surface_or_abstract(obj.get('predicate')), sortinfo=obj.get('sortinfo'), ...
python
def import_models(module): """ | Given a module `service`, try to import its models module. :param module: The module's name to import the models. :type module: str :rtype: list :returns: all the models defined. """ try: module = importlib.import_module('{0}.models'.format(modul...
java
public com.google.api.ads.adwords.axis.v201809.ch.ChangeStatus getCampaignChangeStatus() { return campaignChangeStatus; }
python
def run_phenolog(ont, aset, args): """ Like run_enrichment_test, but uses classes from a 2nd ontology/assocset to build the gene set. """ ofactory = OntologyFactory() ont2 = ofactory.create(args.resource2) afactory = AssociationSetFactory() aset2 = afactory.create(ontology=ont2, ...
java
@Override public List<ScopDomain> filterByDomainName(String query) { List<ScopDomain > domains = new ArrayList<ScopDomain>(); if (query.length() <5){ return domains; } String pdbId = query.substring(1,5); List<ScopDomain> doms = getDomainsForPDB(pdbId); if ( doms == null) return domains; quer...
python
def get_resp(url): """Get webpage response as an lxml.html.HtmlElement object.""" try: headers = {'User-Agent': random.choice(USER_AGENTS)} try: request = requests.get(url, headers=headers, proxies=get_proxies()) except MissingSchema: url = add_protocol(url) ...
java
@Override public int compareTo(D calendarVariant) { long t1 = this.getDaysSinceEpochUTC(); long t2 = calendarVariant.getDaysSinceEpochUTC(); if (t1 < t2) { return - 1; } else if (t1 > t2) { return 1; } else { return this.getVariant().comp...
java
public static MozuUrl deleteSynonymDefinitionUrl(Integer synonymId) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/search/synonyms/{synonymId}"); formatter.formatUrl("synonymId", synonymId); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public void remove() { ThreadLocalMap m = getMap(Thread.currentThread()); if (m != null) m.remove(this); }
java
public static base_response add(nitro_service client, lbroute resource) throws Exception { lbroute addresource = new lbroute(); addresource.network = resource.network; addresource.netmask = resource.netmask; addresource.gatewayname = resource.gatewayname; return addresource.add_resource(client); }
java
@JsonProperty("k") @JsonSerialize(using = Base64UrlJsonSerializer.class) @JsonDeserialize(using = Base64UrlJsonDeserializer.class) public byte[] k() { return ByteExtensions.clone(this.k); }
java
public final int getLiveSegmentCount() { int num = 0; for (int i = 0; i < _segList.size(); i++) { if (_segList.get(i) != null) num++; } return num; }
java
public void marshall(CreateUserPoolDomainRequest createUserPoolDomainRequest, ProtocolMarshaller protocolMarshaller) { if (createUserPoolDomainRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
python
def _on_receive(self, client, userdata, message): """Callback called whenever we receive a message on a subscribed topic Args: client (string): The client id of the client receiving the message userdata (string): Any user data set with the underlying MQTT client mess...
java
public List<FacesConfigRedirectViewParamType<FacesConfigRedirectType<T>>> getAllViewParam() { List<FacesConfigRedirectViewParamType<FacesConfigRedirectType<T>>> list = new ArrayList<FacesConfigRedirectViewParamType<FacesConfigRedirectType<T>>>(); List<Node> nodeList = childNode.get("view-param"); f...
python
def _log_info(self): """Output test run information to top of log file.""" if self.cloud == 'ssh': self.results['info'] = { 'platform': self.cloud, 'distro': self.distro_name, 'image': self.instance_ip, 'timestamp': self.time_st...
java
public void registerConvertor(Class src, Class dest, Convertor convertor) { repository.registerConvertor(src, dest, convertor); }
java
public static String rpad(String base, Integer len, String pad) { if (len < 0) { return null; } else if (len == 0) { return ""; } char[] data = new char[len]; int pos = 0; // Copy the base for ( ; pos < base.length() && pos < len; pos++) { data[pos] = base.charAt(pos);...
java
protected void appendList(StringBuilder sql, List<?> list, String init, String sep) { boolean first = true; for (Object s : list) { if (first) { sql.append(init); } else { sql.append(sep); } sql.append(s); firs...
java
public String getTypeNameForCast(Class<?> type) { Integer jdbcType = jdbcTypeMapping.get(type); if (jdbcType == null) { jdbcType = javaTypeMapping.getType(type).getSQLTypes()[0]; } return templates.getCastTypeNameForCode(jdbcType); }
python
def std(self, ddof=1, *args, **kwargs): """ Compute standard deviation of groups, excluding missing values. Parameters ---------- ddof : integer, default 1 Degrees of freedom. """ nv.validate_resampler_func('std', args, kwargs) return self._do...
python
def send_email(sender, msg, driver): """Sends email to me with this message :param sender: Sender of email :param msg: Message to send to me :param driver: GMail authenticator """ driver.users().messages().send( userId=sender, body=msg ).execute()
python
def enforce_cf_variable(var, mask_and_scale=True): """ Given a Variable constructed from GEOS-Chem output, enforce CF-compliant metadata and formatting. Until a bug with lazily-loaded data and masking/scaling is resolved in xarray, you have the option to manually mask and scale the data here. Para...
python
def fixity(self, response_format=None): ''' Issues fixity check, return parsed graph Args: None Returns: (dict): ('verdict':(bool): verdict of fixity check, 'premis_graph':(rdflib.Graph): parsed PREMIS graph from check) ''' # if no response_format, use default if not response_format: response...
python
def _translate_bisz(self, oprnd1, oprnd2, oprnd3): """Return a formula representation of a BISZ instruction. """ assert oprnd1.size and oprnd3.size op1_var = self._translate_src_oprnd(oprnd1) op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3) result = smtfunct...
java
public void clear() { weightParams.clear(); biasParams.clear(); paramsList = null; weightParamsList = null; biasParamsList = null; }
python
def DictToAdditionalPropertyMessage(properties, additional_property_type, sort_items=False): """Convert the given dictionary to an AdditionalProperty message.""" items = properties.items() if sort_items: items = sorted(items) map_ = [] for key, value in it...
python
def path(self, value=None): """ Return or set the path :param string value: the new path to use :returns: string or new :class:`URL` instance """ if value is not None: if not value.startswith('/'): value = '/' + value encoded_value...
python
def make_ready_all(self): """ Marks all targets in a task ready for execution. This is used when the interface needs every target Node to be visited--the canonical example being the "scons -c" option. """ T = self.tm.trace if T: T.write(self.trace_message('Task.m...
python
def create(self): """Create a single instance of notebook.""" # Point to chart repo. out = helm( "repo", "add", "jupyterhub", self.helm_repo ) out = helm("repo", "update") # Get token to secure Jupyterhub secret_yam...
python
def filter_thumbnail_files(chan_path, filenames, metadata_provider): """ We don't want to create `ContentNode` from thumbnail files. """ thumbnail_files_to_skip = metadata_provider.get_thumbnail_paths() filenames_cleaned = [] for filename in filenames: keep = True chan_filepath =...
python
def annotation_spec_path(cls, project, location, dataset, annotation_spec): """Return a fully-qualified annotation_spec string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}", project=...
python
def _init_write_gz(self): """Initialize for writing with gzip compression. """ self.cmp = self.zlib.compressobj(9, self.zlib.DEFLATED, -self.zlib.MAX_WBITS, self.zlib.DEF_MEM_LEVEL, ...
python
def handle_sigint(self, signum, frame): """ Call self.finish() before delegating to the original SIGINT handler. This handler should only be in place while the progress display is active. """ self.finish() self.original_handler(signum, frame)
java
@Override public void draw(Canvas pCanvas, MilestoneStep pStep) { if (mFirst) { mFirst = false; } else { mLineDrawer.add(pStep.getX(), pStep.getY()); } mLineDrawer.add(pStep.getX(), pStep.getY()); }
python
def is_run_as_leaf(self, **kwargs): """Returns True if this assistant was run as last in path, False otherwise.""" # find the last subassistant_N i = 0 while i < len(kwargs): # len(kwargs) is maximum of subassistant_N keys if settings.SUBASSISTANT_N_STRING.format(i) in kwarg...
java
public static String trimTrailing(String str) { if (str == null) { return null; } int len = str.length(); for (; len > 0; len--) { if (!Character.isWhitespace(str.charAt(len - 1))) { break; } } return str.substring(0, le...
java
protected void generatePythonPackage(IStyleAppendable it, String basename) { it.appendNl("# -*- coding: {0} -*-", getCodeConfig().getEncoding().toLowerCase()); //$NON-NLS-1$ it.appendHeader(); it.newLine(); it.append("__all__ = [ ]"); //$NON-NLS-1$ it.newLine(); }
java
public com.google.api.ads.adwords.axis.v201809.cm.Platform getPlatform() { return platform; }
java
private void loadArtwork(final Context context, final String artworkUrl) { mMainThreadHandler.post(new Runnable() { @Override public void run() { final Picasso picasso = Picasso.with(context); picasso.cancelRequest(mMediaSessionArtworkTarget); ...
python
def _perform_validation(self, path, value, results): """ Validates a given value against the schema and configured validation rules. :param path: a dot notation path to the value. :param value: a value to be validated. :param results: a list with validation results to add new ...
java
public void setScope(java.util.Collection<String> scope) { if (scope == null) { this.scope = null; return; } this.scope = new java.util.ArrayList<String>(scope); }
python
def __get_default_structure_ids(): '''COMMENT''' if len(__DEFAULT_STRUCTURE_IDS) == 0: filename = get_file('default_structures.tsv') with io.open(filename, 'r', encoding='cp1252') as textfile: next(textfile) for line in textfile: tokens = line.strip().sp...
python
def dict_copy(func): "copy dict keyword args, to avoid modifying caller's copy" @functools.wraps(func) def wrapper(*args, **kwargs): copied_kwargs = copy.deepcopy(kwargs) return func(*args, **copied_kwargs) return wrapper
java
protected int indexOf(DurationFieldType type) { for (int i = 0, isize = size(); i < isize; i++) { if (getFieldType(i).getDurationType() == type) { return i; } } return -1; }
python
def unstore(self, key, pk, value): """Remove the value/pk from the sorted set index For the parameters, see BaseRangeIndex.store We simple remove the pk as a member from the sorted set """ self.connection.zrem(key, pk)
python
def readColorLUT(infile, distance_modulus, mag_1, mag_2, mag_err_1, mag_err_2): """ Take in a color look-up table and return the signal color evaluated for each object. Consider making the argument a Catalog object rather than magnitudes and uncertainties. """ reader = pyfits.open(infile) dist...
python
def get_windows_tz(iana_tz): """ Returns a valid windows TimeZone from a given pytz TimeZone (Iana/Olson Timezones) Note: Windows Timezones are SHIT!... no ... really THEY ARE HOLY FUCKING SHIT!. """ timezone = IANA_TO_WIN.get( iana_tz.zone if isinstance(iana_tz, tzinfo) else iana_tz) ...
java
public static boolean isValidXMLName(String s) { // Catch the empty string or null. if (s == null || "".equals(s)) { return false; } // Since the string isn't empty, check that the first character is a // valid starting character. if (!isXMLNameStart(s.codePointAt(0))) { return false; } // Loop...
java
static DeploymentContent of(final Path content) { return new DeploymentContent() { @Override void addContentToOperation(final OperationBuilder builder, final ModelNode op) { final ModelNode contentNode = op.get(CONTENT); final ModelNode contentItem = cont...
java
public static void closeSqlSession() { SqlSession sqlSession = tl_sqlSession.get(); if (sqlSession != null) { //关闭SqlSession对象 sqlSession.close(); //与当前线程解绑 tl_sqlSession.remove(); } }
python
def _onGlobal(self, name, line, pos, absPosition, level): """Memorizes a global variable""" # level is ignored for item in self.globals: if item.name == name: return self.globals.append(Global(name, line, pos, absPosition))
python
def load(self, in_fh, header=False, delimit=None, verbose=False): """ Load this data_table from a stream or file. Blank lines in the file are skipped. Any existing values in this dataTable object are cleared before loading the new ones. :param in_fh: load from this stream. Can also be a string,...
java
public Symbol getSymbolForScope(SymbolScope scope) { if (scope.getSymbolForScope() == null) { scope.setSymbolForScope(findSymbolForScope(scope)); } return scope.getSymbolForScope(); }
python
def tls_session_update(self, msg_str): """ Either for parsing or building, we store the server_random along with the raw string representing this handshake message. We also store the session_id, the cipher suite (if recognized), the compression method, and finally we instantiate ...
java
public static void setTenant(TenantContextHolder holder, TenantKey tenantKey) { holder.getPrivilegedContext().setTenant(buildTenant(tenantKey)); }
java
public String getRedelivered() { Object redelivered = getHeader(JmsMessageHeaders.REDELIVERED); if (redelivered != null) { return redelivered.toString(); } return null; }
java
public static GeoLocationRequest getHttpServletRequestGeoLocationFromRequestContext(final RequestContext context) { val servletRequest = getHttpServletRequestFromExternalWebflowContext(context); return getHttpServletRequestGeoLocation(servletRequest); }
python
def cancel_registration(self): """ Cancels the currents client's account with the server. Even if the cancelation is succesful, this method will raise an exception due to he account no longer exists for the server, so the client will fail. To continue with the execution,...
java
public AnimaQuery<T> and(String statement, Object value) { return this.where(statement, value); }
python
def access_time(self): """dfdatetime.DateTimeValues: access time or None if not available.""" timestamp = self._fsapfs_file_entry.get_access_time_as_integer() return dfdatetime_apfs_time.APFSTime(timestamp=timestamp)
java
@Override public void render(Graphic g) { for (final ComponentRenderer component : renderers) { component.render(g, featurables); } }
java
private String createPomPath(String relativePath, String moduleName) { if (!moduleName.contains(".xml")) { // Inside the parent pom, the reference is to the pom.xml file return relativePath + "/" + POM_NAME; } // There is a reference to another xml file, which is not the ...
python
def py_bisplev(x, y, tck, dx=0, dy=0): '''Evaluate a bivariate B-spline or its derivatives. For scalars, returns a float; for other inputs, mimics the formats of SciPy's `bisplev`. Parameters ---------- x : float or list[float] x value (rank 1), [-] y : float or list[float] ...