language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def register_hid_device(screen_width, screen_height, absolute=False, integrated_display=False): """Create a new REGISTER_HID_DEVICE_MESSAGE.""" message = create(protobuf.REGISTER_HID_DEVICE_MESSAGE) descriptor = message.inner().deviceDescriptor descriptor.absolute = 1 if absolute...
python
def create_connection(self, room, ws_url, agent, cookies): """Creates a new connection""" urlparts = urlsplit(ws_url) req = Request("GET", ws_url) cookies = get_cookie_header(cookies, req) if cookies: headers = dict(Cookie=cookies) else: headers =...
java
public String[] reportDiff(String[] textOnLeft, String[] textOnRight) { List<String> _report = new LinkedList<String>(); int _currentLeft = 0; int _currentRight = 0; while (_currentLeft < textOnLeft.length || _currentRight < textOnRight.length) { if (_currentLeft < textOnLeft.length && _currentRight < te...
python
def csv(self): """Parse raw response as csv and return row object list. """ lines = self._parsecsv(self.raw) # set keys from header line (first line) keys = next(lines) for line in lines: yield dict(zip(keys, line))
java
public CMAArray<CMAWebhook> fetchAll(Map<String, String> query) { throwIfEnvironmentIdIsSet(); return fetchAll(spaceId, query); }
python
def query_closest(self, query_item): """ closest = store.query_closest({"type": "...", "item_1": "...", "timestamp": "..."}) # returns a list of the closest items to a given thing """ if not isinstance(query_item, dict): raise TypeError("The query query_item isn't a dict...
java
@Override public ValueRange range(TemporalField field) { if (field == YEAR_OF_ERA) { return (getYear() <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE)); } return Temporal.super.range(field); }
java
public void processSeeAlsoInjections(final SpecNodeWithRelationships specNode, final Document doc, final Element node, final boolean useFixedUrls) { // Make sure we have some links to inject if (specNode.getRelatedRelationships().isEmpty()) return; // Create the paragraph and list o...
java
public Quaternionf normalize() { float invNorm = (float) (1.0 / Math.sqrt(x * x + y * y + z * z + w * w)); x *= invNorm; y *= invNorm; z *= invNorm; w *= invNorm; return this; }
java
public VfsInputStream readFile(@NotNull final Transaction txn, @NotNull final File file) { return new VfsInputStream(this, txn, file.getDescriptor()); }
java
public void close() throws IOException { if (outStream == null && outWriter == null) { throw new IllegalStateException(); } if (outStream != null) { outStream.close(); } if (outWriter != null) { outWriter.close(); } }
python
def get_unique_filename(filename, new_filename=None, new_extension=None): """ Génère un nouveau nom pour un fichier en gardant son extension Soit le nouveau nom est généré à partir de la date (heures+minutes+secondes+microsecondes) soit un nouveau nom est spécifié et on l'utilise tel quel. ...
java
public static void scheduleAtFixedRate(ScheduledExecutorService exec, Duration rate, Runnable runnable) { scheduleAtFixedRate(exec, rate, rate, runnable); }
python
def file(suffix='', prefix='tmp', parent=None): ''' Create a temporary file CLI Example: .. code-block:: bash salt '*' temp.file salt '*' temp.file prefix='mytemp-' parent='/var/run/' ''' fh_, tmp_ = tempfile.mkstemp(suffix, prefix, parent) os.close(fh_) return tmp_
python
def _verify_client_authentication(self, request_body, http_headers=None): # type (str, Optional[Mapping[str, str]] -> Mapping[str, str] """ Verifies the client authentication. :param request_body: urlencoded token request :param http_headers: :return: The parsed request b...
python
def _populate_setup(self): """Just create a local marker file since the actual database should already be created on the Fuseki server. """ makedirs(os.path.dirname(self._cache_marker)) with codecs.open(self._cache_marker, 'w', encoding='utf-8') as fobj: fobj.write(s...
java
private void setUpTemporaryUserSubject() throws Exception { temporarySubject = new Subject(); temporarySubject.getPrivateCredentials().add(recreatedToken); UserRegistry ur = getUserRegistry(); String securityName = ur.getUserSecurityName(AccessIdUtil.getUniqueId(accessId)); secur...
java
public final <U> CompletionStage<U> supplyAsync(Supplier<U> supplier) { return supplyAsync(supplier, defaultAsyncExecutor); }
python
def __listeners_for_thread(self): """All Listeners for the current thread""" thread = get_thread_ident() with self.lock: return [l for tid, l in self.listeners.items() if tid == thread]
python
def extract(self, sampler, feature_extractor, number_of_examples_per_scale = (100, 100), similarity_thresholds = (0.5, 0.8), parallel = None, mirror = False, use_every_nth_negative_scale = 1): """Extracts features from **all** images in **all** scales and writes them to file. This function iterates over all im...
python
def do_stacktrace(self) -> None: """Print a stack trace from the event loop thread""" frame = sys._current_frames()[self._event_loop_thread_id] traceback.print_stack(frame, file=self._sout)
java
protected final void loadQueryString(Map<String, String[]> params) { for (Map.Entry<String, String[]> param : params.entrySet()) { loadKeys(param.getKey(), param.getValue()); } }
python
def best_parent( self, node, tree_type=None ): """Choose the best parent for a given node""" parents = self.parents(node) selected_parent = None if node['type'] == 'type': module = ".".join( node['name'].split( '.' )[:-1] ) if module: for mod in pa...
python
def _remote_chown(self, paths, user, sudoable=False): """ Issue an asynchronous os.chown() call for every path in `paths`, then format the resulting return value list with fake_shell(). """ LOG.debug('_remote_chown(%r, user=%r, sudoable=%r)', paths, user, sudoab...
java
private Content processParamTags(boolean isNonTypeParams, ParamTag[] paramTags, Map<String, String> rankMap, TagletWriter writer, Set<String> alreadyDocumented) { Content result = writer.getOutputInstance(); if (paramTags.length > 0) { for (int i = 0; i < paramTags.le...
java
public void rmLittlePathByScore() { int maxTo = -1; Term temp = null; for (int i = 0; i < terms.length; i++) { if (terms[i] == null) { continue; } Term maxTerm = null; double maxScore = 0; Term term = terms[i]; ...
python
def write_grid_tpl(name, tpl_file, suffix, zn_array=None, shape=None, spatial_reference=None,longnames=False): """ write a grid-based template file Parameters ---------- name : str the base parameter name tpl_file : str the template file to write - include path ...
java
private static String yearAndQuarter(Calendar cal) { return new StringBuilder().append(cal.get(Calendar.YEAR)).append(cal.get(Calendar.MONTH) / 3 + 1).toString(); }
java
@SuppressWarnings("unchecked") public static <T, V> ImmutableMap<V, Alignment<T, T>> splitAlignmentByKeyFunction( Alignment<? extends T, ? extends T> alignment, Function<? super T, ? extends V> keyFunction) { // we first determine all keys we could ever encounter to ensure we can construct our map ...
java
public IfcGeometricProjectionEnum createIfcGeometricProjectionEnumFromString(EDataType eDataType, String initialValue) { IfcGeometricProjectionEnum result = IfcGeometricProjectionEnum.get(initialValue); if (result == null) throw new IllegalArgumentException( "The value '" + initialValue + "' is not ...
java
public final EObject ruleReferenceOrLiteral() throws RecognitionException { EObject current = null; AntlrDatatypeRuleToken lv_name_0_0 = null; enterRule(); try { // InternalSimpleAntlr.g:1241:28: ( ( (lv_name_0_0= ruleQName ) ) ) // InternalSimpl...
python
def get_index_from_base_index(self, base_index): """Get index into this array's data given the index into the base array """ r = self.rawdata try: index = r.get_reverse_index(base_index) except IndexError: raise IndexError("index %d not in this segment" % ...
python
def send_registered_email(self, user, user_email, request_email_confirmation): """Send the 'user has registered' notification email.""" # Verify config settings if not self.user_manager.USER_ENABLE_EMAIL: return if not self.user_manager.USER_SEND_REGISTERED_EMAIL: return # The ...
python
def _get_emptydirs(self, files): '''Find empty directories and return them Only works for actual files in dap''' emptydirs = [] for f in files: if self._is_dir(f): empty = True for ff in files: if ff.startswith(f + '/'): ...
java
public static RoundedMoney of(BigDecimal number, CurrencyUnit currency, MathContext mathContext) { return new RoundedMoney(number, currency, mathContext); }
java
public static String mangleName(Method method, boolean isFull) { StringBuffer sb = new StringBuffer(); sb.append(method.getName()); Class[] params = method.getParameterTypes(); for (int i = 0; i < params.length; i++) { sb.append('_'); sb.append(mangleClass(p...
java
public Tree setName(String name) { if (parent == null) { throw new UnsupportedOperationException("Root node has no name!"); } if (!parent.isMap()) { throw new UnsupportedOperationException("Unable to set name (this node's parent is not a Map)!"); } parent.remove((String) key); key = name; p...
python
def get_slugignores(root, fname='.slugignore'): """ Given a root path, read any .slugignore file inside and return a list of patterns that should be removed prior to slug compilation. Return empty list if file does not exist. """ try: with open(os.path.join(root, fname)) as f: ...
python
def delete_product_by_id(cls, product_id, **kwargs): """Delete Product Delete an instance of Product by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_product_by_id(product_id,...
java
public static Protos.Value.Range range(long begin, long end) { return Protos.Value.Range.newBuilder().setBegin(begin).setEnd(end).build(); }
python
def entityId(self, partial, channel=None): '''Get an entity's full id provided a partial one. Raises EntityNotFound if partial cannot be resolved. @param partial The partial id (e.g. mysql, precise/mysql). @param channel Optional channel name. ''' url = '{}/{}/meta/any'....
python
def get_dir_backup(): """ retrieves directory backup """ args = parser.parse_args() s3_get_dir_backup( args.aws_access_key_id, args.aws_secret_access_key, args.bucket_name, args.s3_folder, args.zip_backups_dir, args.project)
python
def _check_for_more_pages(self): """ Check for more pages. The last item will be sliced off. """ self._has_more = len(self._items) > self.per_page self._items = self._items[0 : self.per_page]
java
private void initResourceBundlesFromFullMapping(List<JoinableResourceBundle> resourceBundles) { if (LOGGER.isInfoEnabled()) { LOGGER.info("Building bundles from the full bundle mapping. Only modified bundles will be processed."); } Properties mappingProperties = resourceBundleHandler.getJawrBundleMapping(); ...
python
def load_data(self): """ Run the job specified in data_script """ options=self.options command = open(self.options.data_script).read() self.result["data_script"]=command t0=time.time() data=None #fallback data exec(command) #creates variabl...
java
private Transformer createTransformer(boolean indent) { try { Transformer result = this.transformerFactory.newTransformer(); if (indent) { result.setOutputProperty(OutputKeys.INDENT, "yes"); } return result; } catch (TransformerConfigurationException e) { throw new Illegal...
java
public synchronized int read(long position, byte[] buffer, int offset, int length) throws IOException { long oldPos = getPos(); int nread = -1; try { seek(position); nread = read(buffer, offset, length); } finally { seek(oldPos); } return nread; }
java
@SuppressWarnings("deprecation") @Override public final URL[] findResourcesByClasspath() { List<URL> list = new ArrayList<URL>(); String classpath = System.getProperty("java.class.path"); StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator); while (...
python
def get_current_membership_for_org(self, account_num, verbose=False): """Return a current membership for this org, or, None if there is none. """ all_memberships = self.get_memberships_for_org( account_num=account_num, verbose=verbose) # Look for first mem...
java
@SuppressWarnings("serial") private Button createSaveExitButton() { Button saveExitBtn = CmsToolBar.createButton( FontOpenCms.SAVE_EXIT, m_messages.key(Messages.GUI_BUTTON_SAVE_AND_EXIT_0)); saveExitBtn.addClickListener(new ClickListener() { public void buttonCl...
java
public void setCellFormatAttributes(WritableCellFormat cellFormat, FileColumn column) { try { if(cellFormat != null && column != null) { Alignment a = Alignment.GENERAL; short align = column.getAlign(); if(align == FileColumn.AL...
python
def calc_radiation_stats(self, data_daily=None, day_length=None, how='all'): """ Calculates statistics in order to derive solar radiation from sunshine duration or minimum/maximum temperature. Parameters ---------- data_daily : DataFrame, optional Daily data ...
java
public static <K, V> Map<K, V> zipMapPartial(Iterable<K> keys, Iterable<V> values) { Map<K, V> retVal = new LinkedHashMap<>(); Iterator<K> keysIter = keys.iterator(); Iterator<V> valsIter = values.iterator(); while (keysIter.hasNext()) { final K key = keysIter.next(); if(valsIter.hasNex...
python
def get_type(self): """ Returns either 'File' or 'String'. The type attribute (e.g., java.io.File, java.lang.Integer, java.lang.Float), which might give a hint as to what string should represent, is not enforced and not employed consistently across all tasks, so we ignore. ...
python
def hmset(self, hashkey, value): """Emulate hmset.""" redis_hash = self._get_hash(hashkey, 'HMSET', create=True) for key, value in value.items(): attribute = self._encode(key) redis_hash[attribute] = self._encode(value) return True
python
def BEQ(self, params): """ BEQ label Branch to the instruction at label if the Z flag is set """ label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) # BEQ label def BEQ_func(): if self.is_Z_...
java
private <V> BiMap<V, Integer> createIndex(Set<V> values) { if (values == null) { return null; } ImmutableBiMap.Builder<V, Integer> builder = ImmutableBiMap.builder(); int idx = 0; for (V value : values) { builder.put(value, idx++); } return builder.build(); }
java
private boolean atomNeedsQuoting(final String s) { char c; if (s.length() == 0) { return true; } if (!isErlangLower(s.charAt(0))) { return true; } final int len = s.length(); for (int i = 1; i < len; i++) { c = s.charAt(i); ...
python
def check_is_declared_explicit(lineno, id_, classname='variable'): """ Check if the current ID is already declared. If not, triggers a "undeclared identifier" error, if the --explicit command line flag is enabled (or #pragma option strict is in use). If not in strict mode, passes it silently. "...
python
def save_stat( self, name, address=True, overall_param=None, class_param=None, class_name=None): """ Save ConfusionMatrix in .pycm (flat file format). :param name: filename :type name : str :param address: f...
java
public T evolve(int generation, double threshold) { if (generation <= 0) { throw new IllegalArgumentException("Invalid number of generations to go: " + generation); } // Calculate the fitness of each chromosome. try { MulticoreExecutor.run(tasks); ...
java
public int getListNumber(RtfList list) { if(lists.contains(list)) { return lists.indexOf(list); } else { lists.add(list); return lists.size(); } }
python
def max_input_length(self) -> int: """ Returns maximum input length for TranslatorInput objects passed to translate() """ if self.source_with_eos: return self._max_input_length - C.SPACE_FOR_XOS else: return self._max_input_length
java
public void init(Object parent, Object record) { super.init(parent, record); this.addSubPanels(this); TraversableGridPolicy.addGridTraversalPolicy(this.getControl(), this); }
python
def vertex_neighbors(self): """ The vertex neighbors of each vertex of the mesh, determined from the cached vertex_adjacency_graph, if already existent. Returns ---------- vertex_neighbors : (len(self.vertices),) int Represents immediate neighbors of each verte...
java
public static int skipLeadingAsciiWhitespace(String input, int pos, int limit) { for (int i = pos; i < limit; i++) { switch (input.charAt(i)) { case '\t': case '\n': case '\f': case '\r': case ' ': continue; default: return i; } } ...
java
@Override public Map<String, String> getValues() { HashMap<String, String> result = new HashMap<>(); if (status != null) result.put("Status", status.toString()); if (type != null) result.put("Type", type.toString()); if (beforeDate != null) result.put("BeforeDate", Long.toString(bef...
java
@Override public boolean matches(Object entity) { T left = property.get(entity); return operator().matches(left.compareTo(value())); }
java
@Override public double getValueAt(final int at) { if (userPrecAtCutoff.containsKey(at)) { int n = 0; double prec = 0.0; for (U u : userPrecAtCutoff.get(at).keySet()) { double uprec = getValueAt(u, at); if (!Double.isNaN(uprec)) { ...
java
public static void addLast(ChannelPipeline pipeline, long timeout, TimeUnit unit, BasicCounter httpRequestReadTimeoutCounter) { HttpRequestReadTimeoutHandler handler = new HttpRequestReadTimeoutHandler(timeout, unit, httpRequestReadTimeoutCounter); pipeline.addLast(HANDLER_NAME, handler); }
java
private static List<JsonNode> requestAsSortedJsonNodes( TextChannel channel, int limit, long before, long after, boolean reversed) { List<JsonNode> messageJsonNodes = requestAsJsonNodes(channel, limit, before, after); Comparator<JsonNode> idComparator = Comparator.comparingLong(jsonNode -> j...
python
def get_playlists(self, *args, **kwargs): """Convenience method for `get_music_library_information` with ``search_type='playlists'``. For details of other arguments, see `that method <#soco.music_library.MusicLibrary.get_music_library_information>`_. Note: The playli...
python
def get_descendants(self): """ :returns: A queryset of all the node's descendants as DFS, doesn't include the node itself """ if self.is_leaf(): return get_result_class(self.__class__).objects.none() return self.__class__.get_tree(self).exclude(pk=self.pk)
python
def list_inappproducts(self): """temp function to list inapp products.""" result = self.service.inappproducts().list( packageName=self.package_name).execute() if result is not None: return result.get('inappproduct', list()) return list()
java
public static <T> Constructor<T> bestConstructor(Constructor<T>[] constructors, Object[] args) throws AmbiguousConstructorMatchException { return bestConstructor(constructors, collectArgTypes(args)); }
java
public WebSocketEventStream events(Token token, long sessionIdleTimeout, long idleTimeout, int maxMsgSize, EventListener... listeners) throws SaltException { return new WebSocketEventStream(uri, token, sessionIdleTimeout, idleTimeout, maxMsgSize, listeners); }
python
def calc_bounds(xy, entity): """ For an entity with width and height attributes, determine the bounding box if were positioned at ``(x, y)``. """ left, top = xy right, bottom = left + entity.width, top + entity.height return [left, top, right, bottom]
python
def _handle_caption_upload( self, *, media_ids: List[str], captions: Optional[List[str]], ) -> None: """ Handle uploading all captions. :param media_ids: media ids of uploads to attach captions to. :param captions: captions to be attac...
python
def get_endpoint_subscriptions(self, device_id, **kwargs): # noqa: E501 """Read endpoints subscriptions # noqa: E501 Lists all subscribed resources from a single endpoint. **Example usage:** curl -X GET \\ https://api.us-east-1.mbedcloud.com/v2/subscriptions/{device-id} \\ -H 'autho...
java
@Nonnull public static File findOrCreateCacheFile() { final File file = new File(CACHE_DIR, PREFIX + SUFFIX); if (!file.exists()) { try { file.createNewFile(); } catch (final IOException e) { throw new IllegalStateOfArgumentException("Can not create a cache file.", e); } } return file; }
python
def marshal_with_model(model, excludes=None, only=None, extends=None): """With this decorator, you can return ORM model instance, or ORM query in view function directly. We'll transform these objects to standard python data structures, like Flask-RESTFul's `marshal_with` decorator. And, you don't need defin...
java
public static <R extends Resource<JobEntity>> Mono<Void> waitForCompletion(CloudFoundryClient cloudFoundryClient, Duration completionTimeout, R resource) { return waitForCompletion(cloudFoundryClient, completionTimeout, ResourceUtils.getEntity(resource)); }
python
def run(self): """ Run the plugin. """ metadatas = {} # get all the build annotations and labels from the orchestrator build_result = self.workflow.build_result annotations = build_result.annotations worker_builds = annotations['worker-builds'] ...
java
public final AsymmetricDecryptResponse asymmetricDecrypt(String name, ByteString ciphertext) { AsymmetricDecryptRequest request = AsymmetricDecryptRequest.newBuilder().setName(name).setCiphertext(ciphertext).build(); return asymmetricDecrypt(request); }
java
public static ReportQueryByCriteria newReportQuery(Class classToSearchFrom, String[] columns, Criteria criteria, boolean distinct) { criteria = addCriteriaForOjbConcreteClasses(getRepository().getDescriptorFor(classToSearchFrom), criteria); return new ReportQueryByCriteria(classToSearchFrom, colu...
java
public static String generate(String encrypt, String signature, String timestamp, String nonce) { String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n" + "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n" + "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>"; ...
python
def handle_one_request(self): """Handle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST. """ try: self.raw_requestline = self.rf...
python
def match_score(self, supported: 'Language') -> int: """ Suppose that `self` is the language that the user desires, and `supported` is a language that is actually supported. This method returns a number from 0 to 100 indicating how similar the supported language is (higher number...
python
def traverse_tree(cls, static_dir): """traverse the static folders an look for at least one file ending in .scss/.sass""" for root, dirs, files in os.walk(static_dir): for filename in files: if cls._pattern.match(filename): APPS_INCLUDE_DIRS.append(static_...
java
static public void writeStringAsCharArray(Writer writer, String str, int off, int len) throws IOException { if (!enabled) { writeStringFallback(writer, str, off, len); return; } char[] value; int internalOffset=0; try { value = (char[])valueFi...
python
def _emit(self, s): """Append content to the main report file.""" if os.path.exists(self._html_dir): # Make sure we're not immediately after a clean-all. self._report_file.write(s) self._report_file.flush()
python
def setConfigurable(self, state): """ Sets whether or not this logger widget is configurable. :param state | <bool> """ self._configurable = state self._configButton.setVisible(state)
python
def clear_db(): """Clear the entire db.""" cursor = '0' while cursor != 0: cursor, keys = DB.scan(cursor, match='*', count=5000) if keys: DB.delete(*keys)
python
def get_last_nonce(app, key, nonce): """ This method is only an example! Replace it with a real nonce database. :param str key: the public key the nonce belongs to :param int nonce: the latest nonce """ if not hasattr(app, 'example_nonce_db'): # store nonces as a pair {key: lastnonce} ...
java
public static String calculatePath(String uri) { if (!uri.startsWith("/")) { return "/"; } int idx = uri.lastIndexOf('/'); return uri.substring(0, idx + 1); }
python
def find_centroid(region): """ Finds an approximate centroid for a region that is within the region. Parameters ---------- region : np.ndarray(shape=(m, n), dtype='bool') mask of the region. Returns ------- i, j : tuple(int, int) 2d index within the region nearest t...
python
def from_element(self, element, defaults={}): """Populate object variables from SVD element""" if isinstance(defaults, SvdElement): defaults = vars(defaults) for key in self.props: try: value = element.find(key).text except AttributeError: # M...
python
def residuals(self,Y): """ Creates the model residuals Parameters ---------- Y : np.array The dependent variables Y Returns ---------- The model residuals """ return (Y-np.dot(self._create_B(Y),self._create_Z(Y)))
python
def add_line(self, string): """ Adds a line to the LISP code to execute :param string: The line to add :return: None """ self.code_strings.append(string) code = '' if len(self.code_strings) == 1: code = '(setv result ' + self.code_strings[0] +...
java
@SuppressWarnings("unchecked") private void invokePartitionChangeListener() { if (!triggerListeners.isEmpty()) { Map<PartitionEntry, Integer> current = (Map<PartitionEntry, Integer>) partitionCache.get(CURRENT); Map<PartitionEntry, Integer> previous = (Map<PartitionEntry, Integer>) p...