language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _sign_data(secret, data): """ Sign data. :param data: the string to sign :return: string base64 encoding of the HMAC-SHA1 hash of the data parameter using {@code secretKey} as cipher key. """ sha1_hash = hmac.new(secret.encode(), data.encode(), sha1) return binascii.b2a_base64(sha1_hash...
java
protected void setCurrRowRef(QueryRow qr) throws JspCoreException { if (qr == null) { throw new JspCoreException(JspConstants.InvalidCurrRowRef); } this.currRowRef = qr; }
python
def stop_video_recording(self): """Stop the video recording """ self.runner.info_log("Stopping video recording...") self.execute_command("./stop_recording.sh") # self.runner.info_log("output: %s"%output) sleep(5) self.scp_file_remote_to_local( self...
java
public Object getConfigParameter(final ConfigurationKeys configParameter) throws ConfigurationException { Object o = this.config.getConfigParameter(configParameter); if (o != null) { return o; } //return standard values for some of the parameters if they //are not set in the configuration //this is ...
python
def store(self, value, context=None): """ Converts the value to one that is safe to store on a record within the record values dictionary :param value | <variant> :return <variant> """ if isinstance(value, (str, unicode)) and self.testFlag(self.Flags.En...
python
def _do_not_run(self): """The master arbiter tells to its spare arbiters to not run. A master arbiter will ignore this request and it will return an object containing some properties: '_status': 'ERR' because of the error `_message`: some more explanations about the error ...
python
def _calc_font_size(self, win_wd): """Heuristic to calculate an appropriate font size based on the width of the viewer window. Parameters ---------- win_wd : int The width of the viewer window. Returns ------- font_size : int Appr...
python
def wrap_deepmind(env, dim=84, framestack=True): """Configure environment for DeepMind-style Atari. Note that we assume reward clipping is done outside the wrapper. Args: dim (int): Dimension to resize observations to (dim x dim). framestack (bool): Whether to framestack observations. ...
java
void readLimitConstraintCondition(Constraint c) { readThis(Tokens.PARTITION); readThis(Tokens.ROWS); int rowsLimit = readInteger(); c.rowsLimit = rowsLimit; // The optional EXECUTE (DELETE ...) clause if (readIfThis(Tokens.EXECUTE)) { // Capture the statemen...
java
public List<String> getStructureValueList() { if ((m_structureValueList == null) && (m_structureValue != null)) { // use lazy initializing of the list m_structureValueList = createListFromValue(m_structureValue); m_structureValueList = Collections.unmodifiableList(m_structur...
python
def _where(self, **kwargs): '''use this to filter VLists with kv pairs''' out = self for k,v in kwargs.items(): out = out.where(k, lambda i:i==v) return out
java
public static CommerceRegion fetchByCommerceCountryId_First( long commerceCountryId, OrderByComparator<CommerceRegion> orderByComparator) { return getPersistence() .fetchByCommerceCountryId_First(commerceCountryId, orderByComparator); }
python
def timerEvent(self, event): """ Reimplemented to hide the widget when the hide timer fires. """ if event.timerId() == self._hide_timer.timerId(): self._hide_timer.stop() self.hide()
java
public static List<String> readDataFromCVSFileToList(final File input, final int position, final boolean putFirstLine, final String encoding) throws IOException { return readDataFromCVSFileToList(input, position, putFirstLine, ",", encoding); }
java
private static String concatenateStrings(String... stringsToConcatenate) { StringBuilder builder = new StringBuilder(); final int stringsLength = stringsToConcatenate.length; for (int i = 0; i < stringsLength; i++) { if (i == stringsLength - 1 && stringsLength != 1) { ...
python
def update_id(self, sequence_id=None, force=True): """Alter the sequence id, and all of the names and ids derived from it. This often needs to be don after an IntegrityError in a multiprocessing run""" from ..identity import ObjectNumber if sequence_id: self.sequence_id = se...
java
public static String concatenateAndUriEncode(Collection<?> list, String delimiter) { Collection<String> escaped = new ArrayList<String>(); if (list != null) { for (Object object : list) { escaped.add(encode(object.toString())); } } return StringUt...
python
def create_parser(): """Builds the command parser. This needs to be exported in order for Sphinx to document it correctly. Returns: An instance of an ``argparse.ArgumentParser`` that parses all the commands supported by the PyLink CLI. """ parser = argparse.ArgumentParser(prog=pylink._...
python
def read_adjacency_matrix(file_path, separator, undirected): """ Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format. Inputs: - file_path: The path where the adjacency matrix is stored. - separator: The delimiter among values (e.g. ",", "\t", " ...
python
def subtract(self, **kwargs): """Returns a new MayaDT object with the given offsets.""" return self.from_datetime( pendulum.instance(self.datetime()).subtract(**kwargs) )
java
public static <T> Iterator<T> take(Iterator<T> self, int num) { return new TakeIterator<T>(self, num); }
java
public String convertIfcElementCompositionEnumToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
python
def to_verify_funds(pronac, dt): """ Checks how much money is left for the project to verify, using raised_funds - verified_funds This value can be negative (a project can verify more money than the value approved) """ project_raised_funds = data.raised_funds_by_project.loc[pronac]['Captacao...
java
@Nullable public static String getWithoutForbiddenCharsAndNormalized (@Nullable final String s) { String sValue = s; // Removed forbidden chars first if (sValue == null) return null; sValue = getWithoutForbiddenChars (sValue); // than normalize if (sValue == null) return null; ...
python
def is_valid_transition(cls, from_value, to_value): """ Will check if to_value is a valid transition from from_value. Returns true if it is a valid transition. :param from_value: Start transition point :param to_value: End transition point :type from_value: int :type to_value: in...
python
def set_is_pallets_theme(app): """Set the ``is_pallets_theme`` config to ``True`` if the current theme is a decedent of the ``pocoo`` theme. """ if app.config.is_pallets_theme is not None: return theme = getattr(app.builder, "theme", None) while theme is not None: if theme.name...
python
def add(self, model): """Adds a single model. Parameters ---------- model : `Estimator` """ if isinstance(model, (Regressor, Classifier)): self.models.append(model) else: raise ValueError('Unrecognized estimator.')
java
public EncryptionMaterials addDescription(String name, String value) { desc.put(name, value); return this; }
java
public void extract(@NotNull final byte[] xmpBytes, @NotNull Metadata metadata) { extract(xmpBytes, metadata, null); }
java
public void marshall(ListCreateAccountStatusRequest listCreateAccountStatusRequest, ProtocolMarshaller protocolMarshaller) { if (listCreateAccountStatusRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshalle...
java
protected void configureRegistry() { setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS, PollCachingESRegistry.class.getName()); setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS + ".client.type", "jest"); setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS + ".client.protocol"...
python
def SchemaValidate(self, xsd): """Use W3C XSD schema to validate the document as it is processed. Activation is only possible before the first Read(). If @xsd is None, then XML Schema validation is deactivated. """ ret = libxml2mod.xmlTextReaderSchemaValidate(self._o, xsd)...
python
def makedir(self): """ Create model_dir directory """ try: os.makedirs(self.model_dir) except OSError as exception: if exception.errno != errno.EEXIST: raise
python
def submit_jobs(self, link, job_dict=None, job_archive=None, stream=sys.stdout): """Run the `Link` with all of the items job_dict as input. If job_dict is None, the job_dict will be take from link.jobs Returns a `JobStatus` enum """ failed = False if job_dict is None: ...
python
def masked_language_model(vocab, model, mask_prob=0.15): """Convert a model into a BERT-style masked language model""" random_words = _RandomWords(vocab) def mlm_forward(docs, drop=0.0): mask, docs = _apply_mask(docs, random_words, mask_prob=mask_prob) mask = model.ops.asarray(mask).reshap...
python
def get_work_unit_status(self, work_spec_name, work_unit_key): '''Get a high-level status for some work unit. The return value is a dictionary. The only required key is ``status``, which could be any of: ``missing`` The work unit does not exist anywhere ``available``...
java
@InterfaceStability.Unstable public synchronized String[] getPropertySources(String name) { if (properties == null) { // If properties is null, it means a resource was newly added // but the props were cleared so as to load it upon future // requests. So lets force a load by asking a properties list. get...
python
def bitdepth(self): """The number of bits per sample in the audio encoding (an int). Only available for certain file formats (zero where unavailable). """ if hasattr(self.mgfile.info, 'bits_per_sample'): return self.mgfile.info.bits_per_sample return 0
python
def upload_file(self, source_path, dir_name): '''上传一个文件''' row = self.get_task_db(source_path) source_dir, filename = os.path.split(source_path) path = os.path.join(dir_name, filename) size = os.path.getsize(source_path) total_size = util.get_human_size(size)[0] ...
java
public static <E> boolean every(Iterable<E> iterable, Predicate<E> predicate) { dbc.precondition(iterable != null, "cannot call every with a null iterable"); return new Every<E>(predicate).test(iterable.iterator()); }
java
protected void addAssociatedEntitiesToDocument(EntityMetadata metadata, Object entity, Document document, MetamodelImpl metaModel) { try { IndexCollection indexes = metadata.getEntityClazz().getAnnotation(IndexCollection.class); if (indexes != null) { List<String>...
python
def find_side(ls, side): """ Given a shapely LineString which is assumed to be rectangular, return the line corresponding to a given side of the rectangle. """ minx, miny, maxx, maxy = ls.bounds points = {'left': [(minx, miny), (minx, maxy)], 'right': [(maxx, miny), (maxx, max...
python
def setup_app(command, conf, vars): """Place any commands to setup studio here""" load_environment(conf.global_conf, conf.local_conf) # Merge and minify JavaScript code input_file = config['js_tmpl'] public_dir = config['pylons.paths']['static_files'] output_file = os.path.join(public_dir, 'js'...
python
def _call_linker_cb(env, callback, args, result = None): """Returns the result of env['LINKCALLBACKS'][callback](*args) if env['LINKCALLBACKS'] is a dictionary and env['LINKCALLBACKS'][callback] is callable. If these conditions are not met, return the value provided as the *result* argument. This functi...
python
def get_instance(): """Get a resource based on the application environment. Returns a `Resource` configured for the current environment, or None if the environment is unknown or unsupported. :rtype: :class:`opencensus.common.resource.Resource` or None :return: A `Resource` configured for the curre...
python
def listMembers(self, id, headers=None, query_params=None, content_type="application/json"): """ Get a list of network members It is method for GET /network/{id}/member """ uri = self.client.base_url + "/network/"+id+"/member" return self.client.get(uri, None, headers, qu...
python
def delete_user_rating(self, item_type, item_id): """ Deletes from the list of rating of the current user, the rating provided for the specified element type. :param item_type: One of: series, episode, banner. :param item_id: The TheTVDB Id of the item. :return: a python diction...
java
@Deprecated public Database determineDatabase(DataSource dataSource) { if (this.database != null) { return this.database; } return DatabaseLookup.getDatabase(dataSource); }
python
def grok_keys(config): """Will retrieve a GPG key from either Keybase or GPG directly""" key_ids = [] for key in config['pgp_keys']: if key.startswith('keybase:'): key_id = from_keybase(key[8:]) LOG.debug("Encrypting for keybase user %s", key[8:]) else: if...
python
def get_dimension(self, dataset, dimension): """The method is getting information about dimension with items""" path = '/api/1.0/meta/dataset/{}/dimension/{}' return self._api_get(definition.Dimension, path.format(dataset, dimension))
java
public static File getPathtoProject(final URI filename, final URI traceFilename, final URI inputMap, final Job job) { assert traceFilename.isAbsolute(); assert inputMap.isAbsolute(); // FIXME out generation has already been determined, why do it here again? if (job.getGeneratecopyouter()...
java
ArgumentsBuilder intersperse(String param, List<String> values) { if (values != null) { for (String value : values) { args.add(param); args.add(value); } } return this; }
python
def available_gpus(): """List of GPU device names detected by TensorFlow.""" local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU']
java
public void setSubscribers(java.util.Collection<String> subscribers) { if (subscribers == null) { this.subscribers = null; return; } this.subscribers = new java.util.ArrayList<String>(subscribers); }
python
def get_global_placeholder_data(placeholder_frontend_data_dict): """ In some rare cases you need to post process the placeholder data and add additional, global data to the route object. Define your post-processor in the DJANGOCMS_SPA_VUE_JS_PLACEHOLDER_DATA_POST_PROCESSOR setting variable (e.g. `my_app...
python
def publish(self): """ Publishes the object. The decorator `assert_draft` makes sure that you cannot publish a published object. :param self: The object to tbe published. :return: The published object. """ if self.is_draft: # If the object has...
python
def _set_BC(self, pores, bctype, bcvalues=None, mode='merge'): r""" Apply boundary conditions to specified pores if no source terms are already assigned to these pores. Otherwise, raise an error. Parameters ---------- pores : array_like The pores where the bo...
java
private <R extends Row, T> ApiFuture<Result> issueAsyncRowRequest( Row row, Batch.Callback<T> callback, Object[] results, int index) { LOG.trace("issueRowRequest(Row, Batch.Callback, Object[], index"); SettableApiFuture<Result> resultFuture = SettableApiFuture.create(); RpcResultFutureCallback<T...
java
private void processCalendarData(ProjectCalendar calendar, List<ResultSetRow> calendarData) { for (ResultSetRow row : calendarData) { processCalendarData(calendar, row); } }
python
def explicit_images(images, image_destination, rootname, config): """ The method used to handle an explicitly defined image directory by the user as a parsed argument. """ log.info('Explicit image directory specified: {0}'.format(images)) if '*' in images: images = images.replace('*', ro...
python
def add_to_item_list(self, item_urls, item_list_url): """ Instruct the server to add the given items to the specified Item List :type item_urls: List or ItemGroup :param item_urls: List of URLs for the items to add, or an ItemGroup object :type item_list_url: String ...
java
public List<SecStrucState> calculate(Structure s, boolean assign) throws StructureException { List<SecStrucState> secstruc = new ArrayList<SecStrucState>(); for(int i=0; i<s.nrModels(); i++) { // Reinitialise the global vars ladders = new ArrayList<Ladder>(); bridges = new ArrayList<BetaBridge>(); g...
python
def new_site(name, rgba=RED, pos=(0, 0, 0), size=(0.005,), **kwargs): """ Creates a site element with attributes specified by @**kwargs. Args: name (str): site name. rgba: color and transparency. Defaults to solid red. pos: 3d position of the site. size ([float]): site size ...
python
def get_object_or_none(cls, **kwargs): """ Returns model instance or None if not found. :param cls: Class or queryset :param kwargs: Filters for get() call :return: Object or None """ from django.shortcuts import _get_queryset qs = _get_queryset(cls) try: return qs.get(**kwar...
python
def to_struct(self, value): """Cast `date` object to string.""" if self.str_format: return value.strftime(self.str_format) return value.strftime(self.default_format)
java
public GenericColor lighten(ColorFactor factor) { return valueOf(this.red.increase(factor), this.green.increase(factor), this.blue.increase(factor), this.alpha); }
java
public boolean isAllowedCachedRight(final ContextEntry[] context, final Tuple tuple) { for (int i = indexed; i < constraints.length; i++) { if ( !constraints[i].isAllowedCachedRight(tuple, context[i]) ) { return false; } } ...
python
def output_stderr(self, text): "*text* should be bytes" binary_stderr.write(b''.join([ self._red, b't=%07d' % (time.time() - self._t0), self._reset, b' ', text, ])) binary_stderr.flush()
python
def build(self, context, variant, build_path, install_path, install=False, build_type=BuildType.local): """Perform the build. Note that most of the func args aren't used here - that's because this info is already passed to the custom build command via environment variables...
python
def language(cls): """ Return language of the comic as a human-readable language name instead of a 2-character ISO639-1 code. """ lang = 'Unknown (%s)' % cls.lang if pycountry is None: if cls.lang in languages.Languages: lang = languages.Langua...
java
public static KeywordInfo getKeywordInfo(String keyword, ApplicationContext context, Map<String, String> beanMap) { Object bean = context.getBean(beanMap.get(keyword)); return AnnotationUtils.findAnnotation(bean.getClass(), KeywordInfo.class); }
python
def iter_multi_items(mapping): """Iterates over the items of a mapping yielding keys and values without dropping any from more complex structures. """ if isinstance(mapping, MultiDict): for item in iteritems(mapping, multi=True): yield item elif isinstance(mapping, dict): ...
python
def tarbell_install_blueprint(command, args): """ Install a project template. """ with ensure_settings(command, args) as settings: name = None error = None template_url = args.get(0) matches = [template for template in settings.config["project_templates"] if template.get(...
java
public static final char[] append(char[] array, char suffix) { if (array == null) { return new char[] { suffix }; } int length = array.length; System.arraycopy(array, 0, array = new char[length + 1], 0, length); array[length] = suffix; return array; }
python
def to_timestamp(self, freq=None, how='start'): """ Cast to DatetimeArray/Index. Parameters ---------- freq : string or DateOffset, optional Target frequency. The default is 'D' for week or longer, 'S' otherwise how : {'s', 'e', 'start', 'end'} ...
python
def exists(self, table_name, timeout=None): ''' Returns a boolean indicating whether the table exists. :param str table_name: The name of table to check for existence. :param int timeout: The server timeout, expressed in seconds. :return: A boolean indica...
java
public void marshall(Button button, ProtocolMarshaller protocolMarshaller) { if (button == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(button.getText(), TEXT_BINDING); protocolMarshall...
java
private void addToolbarButtons() { Button add = CmsToolBar.createButton(FontOpenCms.WAND, CmsVaadinUtils.getMessageText(Messages.GUI_SITE_ADD_0)); add.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent eve...
java
public String createInfix(Expression root) { String str = ""; String closeParen = ""; String leftOpenParen = ""; String leftCloseParen = ""; if(root == null) { return str; } if (ExpressionParser.isOperand(root.getType(), var)) { str +...
python
def export_serving(self, filename, tags=[tf.saved_model.SERVING if is_tfv2() else tf.saved_model.tag_constants.SERVING], signature_name='prediction_pipeline'): """ Converts a checkpoint and graph to a servable for TensorFlow Serving. Use TF's `SavedM...
python
def find_table(self, table): """ Finds a table by name or alias. The FROM tables and JOIN tables are included in the search. :type table: str or :class:`ModelBase <django:django.db.models.base.ModelBase>` :param table: string of the table name or alias or a ModelBase instance ...
java
private Node<T> removeMax(Node<T> h, boolean updateLast) { if (h.left != null && h.left.red) h = rotateRight(h); if (h.right == null) return null; if (!h.right.red && (h.right.left == null || !h.right.left.red)) h = moveRedRight(h); h.rig...
java
public synchronized boolean createShareRequest(String filePath, Destination destination) { boolean isSuccessful = false; SQLiteDatabase db = null; try { db = getWritableDatabase(); // Create new record. ContentValues values = new ContentValues(); ...
java
private static boolean isValueAValidGeoQuery(final Object value) { if (value instanceof DBObject) { String key = ((DBObject) value).keySet().iterator().next(); return key.equals("$box") || key.equals("$center") || key.equals("$centerSphere") || key.equals("$polygon"); } r...
python
def total_form_count(self): """ This rewrite of total_form_count allows to add an empty form to the formset only when no initial data is provided. """ total_forms = super().total_form_count() if not self.data and not self.files and self.initial_form_count() > 0: ...
python
def _run(self) -> Generator[Any, None, None]: """ 创建 Server """ ssl_context = self._create_ssl_context() # access_logger = self.log.access_log if self.cfg.accesslog else None for sock in self.sockets: # max_fields_size = self.cfg.limit_request_fields * self.cf...
python
def asset_asset_swap( self, asset1_id, asset1_transfer_spec, asset2_id, asset2_transfer_spec, fees): """ Creates a transaction for swapping an asset for another asset. :param bytes asset1_id: The ID of the first asset. :param TransferParameters asset1_transfer_spec: The para...
python
def portal(self, portalID=None): """returns a specific reference to a portal""" if portalID is None: portalID = self.portalSelf.id url = "%s/%s" % (self.root, portalID) return Portal(url=url, securityHandler=self._securityHandler, proxy_url...
python
def _build_toc_node(docname, anchor="anchor", text="test text", bullet=False): """ Create the node structure that Sphinx expects for TOC Tree entries. The ``bullet`` argument wraps it in a ``nodes.bullet_list``, which is how you nest TOC Tree entries. """ reference = nodes.reference( ""...
java
public ServiceFuture<BuildTaskInner> updateAsync(String resourceGroupName, String registryName, String buildTaskName, BuildTaskUpdateParameters buildTaskUpdateParameters, final ServiceCallback<BuildTaskInner> serviceCallback) { return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, ...
python
def delete_fabric_fw(self, tenant_id, fw_dict, is_fw_virt, result): """Top level routine to unconfigure the fabric. """ try: with self.mutex_lock: ret = self.delete_fabric_fw_internal(tenant_id, fw_dict, is_fw_virt, result)...
java
public JSONObject getRoomByOffer(String company, String offerId, HashMap<String, String> params) throws JSONException { return oClient.get("/messages/v3/" + company + "/rooms/offers/" + offerId, params); }
python
def _get_section_start_index(self, section): '''Get start of a section's content. :param section: string name of section :return: integer index of section's beginning :raises: NonextantSectionException ''' sec_start_re = r'%s\s*\{' % section found = re.search(s...
python
def sollen(tex, command): r"""Measure solution length :param Union[str,buffer] tex: the LaTeX source as a string or file buffer :param str command: the command denoting a solution i.e., if the tex file uses '\answer{<answer here>}', then the command is 'answer'. :return int: the solution length...
python
def log_rule_info(self): """Collects rule information and send to logit function to log to syslog""" for c in sorted(self.broker.get_by_type(rule), key=dr.get_name): v = self.broker[c] _type = v.get("type") if _type: if _type != "skip": ...
python
def _batches(self, request, points_per_request): """ Generator for creating 'request batches'. Each batch contains a maximum of "points_per_request" points to read. :params: request a list of point_name as a list :params: (int) points_per_request :returns: (iter) ...
python
def connect(self, name=None, remoteId=None, ha=None, verKeyRaw=None, publicKeyRaw=None): """ Connect to the node specified by name. """ if not name: raise ValueError('Remote name should be specifi...
java
@Deprecated public String print(String parameterName, String parameterValue, char escapeChar) { setEscapeChar(escapeChar); return print(parameterName, parameterValue); }
java
private static HeaderProvider buildHeaderProvider(String userAgent){ return FixedHeaderProvider.create(USER_AGENT_KEY.name(), VENEER_ADAPTER + userAgent); }
java
private OnClickListener createNegativeButtonListener() { return new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getActivity(), R.string.negative_button_toast, Toast.LENGTH_SHORT) .show(); ...