language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def expect_loop(self, searcher, timeout=-1, searchwindowsize=-1): '''This is the common loop used inside expect. The 'searcher' should be an instance of searcher_re or searcher_string, which describes how and what to search for in the input. See expect() for other arguments, return valu...
java
private void buildMultiJoinTree(TableAlias left, ClassDescriptor cld, String name, boolean useOuterJoin) { DescriptorRepository repository = cld.getRepository(); Class[] multiJoinedClasses = repository.getSubClassesMultipleJoinedTables(cld, false); for (int i = 0; i < multiJoinedClasse...
java
@Override public void registerCacheEventListener(CacheEventListener<? super K, ? super V> listener, EventOrdering ordering, EventFiring firing, EnumSet<EventType> forEventTypes) { EventListenerWrapper<K, V> wrapper = new EventListenerWrapper<>(listener, firing, ordering, forEvent...
python
def merge_fasta(fasta_file, output_dir): """Merge chunks into complete FASTA bins Merge bin chunks by appending consecutive chunks to one another. Parameters ---------- fasta_file : file, str or pathlib.Path The FASTA file containing the chunks to merge. output_dir : str or pathlib.Pa...
java
public String[] getAllTemplateNames(boolean recurse) throws IOException { if (mTemplateProviderMap == null) { synchronized (this) { mTemplateProviderMap = new HashMap<String, CompilationProvider>(); for (CompilationProvider provider : mCompilationPro...
python
def send_messages(self, messages): """Redirect messages to the dummy outbox""" msg_count = 0 for message in messages: # .message() triggers header validation message.message() msg_count += 1 mail.outbox.extend(messages) return msg_count
java
public Class<? extends ThreadContextMap> loadThreadContextMap() { if (threadContextMapClass != null) { return threadContextMapClass; } if (threadContextMap == null) { return null; } final ClassLoader loader = classLoader.get(); if (loader == null) ...
java
public static ExpectedCondition<WebElement> visibilityOf(final WebElement element) { return new ExpectedCondition<WebElement>() { @Override public WebElement apply(WebDriver driver) { return elementIfVisible(element); } @Override public String toString() { return "visi...
python
def _attempt_resumable_download(self, key, fp, headers, cb, num_cb, torrent, version_id): """ Attempts a resumable download. Raises ResumableDownloadException if any problems occur. """ cur_file_size = get_cur_file_size(fp, position_to_eof=Tru...
python
def crack_k_from_sigs(generator, sig1, val1, sig2, val2): """ Given two signatures with the same secret exponent and K value, return that K value. """ # s1 = v1 / k1 + (se * r1) / k1 # s2 = v2 / k2 + (se * r2) / k2 # and k = k1 = k2 # so # k * s1 = v1 + (se * r1) # k * s2 = v2 + (se...
python
def drop_cache(self): ''' Drops all changes in the cache. ''' del self._cache self._cache = {} del self._wqueue self._wqueue = set() self._cur_size = 0
java
public Optional<EventCallable> registerEventPublisher(Identification identification) throws IllegalIDException { if(registered.containsKey(identification)) return Optional.empty(); EventPublisher eventPublisher = new EventPublisher(events); registered.put(identification, eventPublisher); ...
java
public void applyToTypes(Set<String> types) { if (m_removeAllNonExplicitlyAdded) { types.clear(); } for (Map.Entry<String, Boolean> typeUpdateEntry : m_typeUpdateSet.entrySet()) { String typeName = typeUpdateEntry.getKey(); Boolean add = typeUpdateEntry.getVa...
java
private static <E> Entry<PrefixKey, E> getParentEntry( TreeMap<PrefixKey, E> map, PrefixKey upperBound) { NavigableMap<PrefixKey, E> head = map.headMap(upperBound, true).descendingMap(); for (Entry<PrefixKey, E> entry : head.entrySet()) { if (upperBound.isParent(entry.getKey())) { return ent...
java
public static void incrementSessionStep(final UIContext uic) { int step = uic.getEnvironment().getStep(); uic.getEnvironment().setStep(step + 1); }
python
def optimization_loop(self, timeSeries, forecastingMethod, remainingParameters, currentParameterValues=None): """The optimization loop. This function is called recursively, until all parameter values were evaluated. :param TimeSeries timeSeries: TimeSeries instance that requires an optimize...
python
def CRPS(label, pred): """ Custom evaluation metric on CRPS. """ for i in range(pred.shape[0]): for j in range(pred.shape[1] - 1): if pred[i, j] > pred[i, j + 1]: pred[i, j + 1] = pred[i, j] return np.sum(np.square(label - pred)) / label.size
python
def hashes(peaks, f_width=F_WIDTH, t_gap=ROWS_PER_SECOND, t_width=2*ROWS_PER_SECOND): """ Generator function for successive hashes calculated from a mono-channel time-domain audio signal as a set of tuples, (<long>, <int>). The <long> is an integral 64-bit hash so it can be used as a database ID, and ...
python
def _lxml_el_to_data(lxml_el, ns, nsmap, snake=True): """Convert an ``lxml._Element`` instance to a Python tuple.""" tag_name = _to_colon_ns(lxml_el.tag, default_ns=ns, nsmap=nsmap) ret = [tag_name] attributes = _get_el_attributes(lxml_el, ns=ns, nsmap=nsmap) if attributes: ret.append(attrib...
python
def imagery(lon=None, lat=None, dim=None, date=None, cloud_score=None): ''' # ----------QUERY PARAMETERS---------- # Parameter Type Default Description # lat float n/a Latitude # lon float n/a Longitude # dim float 0.025 width and height of image in degrees # date YYYY-MM-DD today date of ...
java
public static void putUser(final String user) { if ((user != null) && (0 < user.length())) { MDC.put(USER, user); } }
java
@SuppressWarnings("rawtypes") private AbstractNode combineIDD(ExternalNode3 n1, InternalNode<?> n2) throws MIDDException { List<Interval> intervals = n2.getIntervals(); List<Interval<?>> complementIntervals = IntervalUtils.complement(intervals); // clone new node from n2 Internal...
python
def speed_d(self): """ The derivative constant for the speed regulation PID. """ self._speed_d, value = self.get_attr_int(self._speed_d, 'speed_pid/Kd') return value
python
def gray2bin(G): """Convert a gray-coded vector into a binary-coded vector.""" return farray([G[i:].uxor() for i, _ in enumerate(G)])
python
def OnSelectCard(self, event): """Called when the user selects a card in the tree.""" item = event.GetItem() if item: itemdata = self.readertreepanel.cardtreectrl.GetItemPyData(item) if isinstance(itemdata, smartcard.Card.Card): self.dialogpanel.OnSelectCa...
python
def create(cls, name, local_admin=False, allow_sudo=False, superuser=False, enabled=True, engine_target=None, can_use_api=True, console_superuser=False, allowed_to_login_in_shared=True, comment=None): """ Create an admin user account. .. vers...
java
@Override public Resource asVisitorResource() { URL url = null; try { url = getURI().toURL(); } catch (MalformedURLException ignore) { } return new VisitorResource(url, ""); //$NON-NLS-1$ }
java
private JButton getBtnCancel() { if (btnCancel == null) { btnCancel = new JButton(); btnCancel.setText(Constant.messages.getString("all.button.cancel")); btnCancel.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { ...
java
public void init() { final String string = getString(); final int bpos = string.indexOf('/'); if (bpos == -1) { prefix = string; surname = ""; suffix = ""; } else { final int epos = string.indexOf('/', bpos + 1); prefix = string...
java
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WCheckBoxSelect select = (WCheckBoxSelect) component; XmlStringBuilder xml = renderContext.getWriter(); int cols = select.getButtonColumns(); boolean readOnly = select.isReadOnly(); xml.appendTagOpen("ui:ch...
java
public long delete(final String pTileSourceName, final int pZoom, final Collection<Rect> pInclude, final Collection<Rect> pExclude) { try { final SQLiteDatabase db = getDb(); if (db == null || !db.isOpen()) { return -1; } ret...
java
public static Properties getSecurityProperties(final String file, final String psw) { return getSecurityProperties(file, psw, null); }
python
def escape(u): """Escape a string in an OAuth-compatible fashion. TODO: verify whether this can in fact be used for OAuth 2 """ if not isinstance(u, unicode_type): raise ValueError('Only unicode objects are escapable.') return quote(u.encode('utf-8'), safe=b'~')
python
def do_confusion_matrix(sorting1, sorting2, unit_map12, labels_st1, labels_st2): """ Compute the confusion matrix between two sorting. Parameters ---------- sorting1: SortingExtractor instance The ground truth sorting. sorting2: SortingExtractor instance The tested sort...
python
def _val_is_unique(val, field): """ Currently only checks the field's uniqueness, not the model validation. """ if val is None: return False if not field.unique: return True field_name = field.name return field.model.objects.filter(**{fie...
java
public static void run(Reporter reporter) { TCK tck = new TCK(new ObjenesisStd(), new ObjenesisSerializer(), reporter); tck.runTests(); }
java
public static MimeType getMimeType(String name, Property property) { MimeType result = null; try { Binary binary = property != null ? property.getBinary() : null; if (binary != null) { try { InputStream input = binary.getStream(); ...
java
public static TypeAnnotationPosition methodParameter(final List<TypePathEntry> location, final JCLambda onLambda, final int parameter_index, final int pos) { return new TypeAnnotationPosition(TargetType.METHOD_FORMAL_PARAMETER, ...
java
public void setContentWidth(int width) { int w = width; if (max_size.width != -1 && w > max_size.width) w = max_size.width; if (min_size.width != -1 && w < min_size.width) w = min_size.width; content.width = w; }
java
public Pair<EntityInfo> getParentCompounds() { Pair<Chain> chains = getParentChains(); if (chains == null) { logger.warn("Could not find parents chains, compounds will be null"); return null; } return new Pair<EntityInfo>(chains.getFirst().getEntityInfo(), chains.getSecond().getEntityInfo()); }
python
def cache(opts, serial): ''' Returns the returner modules ''' return LazyLoader( _module_dirs(opts, 'cache', 'cache'), opts, tag='cache', pack={'__opts__': opts, '__context__': {'serial': serial}}, )
python
def get_uids_from_record(self, record, key): """Returns a list of parsed UIDs from a single form field identified by the given key. A form field ending with `_uid` can contain an empty value, a single UID or multiple UIDs separated by a comma. This method parses the UID value a...
python
def _install_all(destination='', conf_file=''): """Use the conf file to list all the third party Odoo add-ons that will be installed and the patches that should be applied. :param string destination: the folder where add-ons should end up at. Default: pwd/3rd :param strin...
python
def addnot(self, action=None, subject=None, **conditions): """ Defines an ability which cannot be done. """ self.add_rule(Rule(False, action, subject, **conditions))
python
def Save(self): """Saves the current system""" # This method is intercepted to allow ui_sync if self._file_to_save_on_Save: self._iopticalsystem.SaveAs(self._file_to_save_on_Save) else: self._iopticalsystem.Save()
java
public void comment(char ch[], int start, int length) throws SAXException { flushStartDoc(); if (null != m_resultLexicalHandler) m_resultLexicalHandler.comment(ch, start, length); }
python
def substitute_state(target_state_m, state_m_to_insert, as_template=False): """ Substitutes the target state Both, the state to be replaced (the target state) and the state to be inserted (the new state) are passed via parameters. The new state adapts the size and position of the target state. Stat...
python
def get_channel_info(self): """Get the current channel info.""" self.request(EP_GET_CHANNEL_INFO) return {} if self.last_response is None else self.last_response.get('payload')
python
def getName(self, innerFlag=False): """Return the name of currently assigned component of the |ASN.1| object. Returns ------- : :py:class:`str` |ASN.1| component name """ if self._currentIdx is None: raise error.PyAsn1Error('Component not chosen')...
python
def find_available_vc_vers(self): """ Find all available Microsoft Visual C++ versions. """ ms = self.ri.microsoft vckeys = (self.ri.vc, self.ri.vc_for_python, self.ri.vs) vc_vers = [] for hkey in self.ri.HKEYS: for key in vckeys: try: ...
python
def min(self, key=None): """ Find the minimum item in this RDD. :param key: A function used to generate key for comparing >>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0]) >>> rdd.min() 2.0 >>> rdd.min(key=str) 10.0 """ if key is None: ...
python
def row(values, width=WIDTH, format_spec=FMT, align=ALIGN, style=STYLE): """Returns a formatted row of data Parameters ---------- values : array_like An iterable array of data (numbers or strings), each value is printed in a separate column width : int The width of each column (Def...
java
void resetStatistics(boolean clearHistory) { lastTimerPop = System.currentTimeMillis(); previousCompleted = threadPool == null ? 0 : threadPool.getCompletedTaskCount(); previousThroughput = 0; consecutiveQueueEmptyCount = 0; consecutiveNoAdjustment = 0; consecutiveOutlie...
java
public static List<CPInstance> findByGroupId(long groupId, int start, int end) { return getPersistence().findByGroupId(groupId, start, end); }
python
def update(self, networkipv6s): """ Method to update network-ipv6's :param networkipv6s: List containing network-ipv6's desired to updated :return: None """ data = {'networks': networkipv6s} networkipv6s_ids = [str(networkipv6.get('id')) ...
java
public static List<?> workbook2List(ExcelConfig config, Workbook wb) throws Exception { String[] names = config.getNames(); String[] types = config.getTypes(); Field key = config.getKey(); List<Object> list = new ArrayList<Object>(); Sheet sheet = wb.getSheet(config.getSheetNum(...
python
def cut_distant_injections(workflow, inj_file, out_dir, tags=None): "Set up a job for removing injections that are too distant to be seen" if tags is None: tags = [] node = Executable(workflow.cp, 'inj_cut', ifos=workflow.ifos, out_dir=out_dir, tags=tags).create_node() nod...
python
def validate_config(config, schema=CLUSTER_CONFIG_SCHEMA): """Required Dicts indicate that no extra fields can be introduced.""" if not isinstance(config, dict): raise ValueError("Config {} is not a dictionary".format(config)) check_required(config, schema) check_extraneous(config, schema)
python
def get_joined_members(self): """Returns list of joined members (User objects).""" if self._members: return list(self._members.values()) response = self.client.api.get_room_members(self.room_id) for event in response["chunk"]: if event["content"]["membership"] == ...
java
public Object getAdapterInstance() { if (mAdapterInstance == null) { try { mAdapterInstance = mConstructor.newInstance (mEnclosingType, mPropertyName, mAnnotation.getAnnotation()); } catch (Exception e) { ThrowUnchecked.fireFirstD...
java
public ElementBuilder<T> setProperty(String name, Object value, Visibility visibility) { return setProperty(name, value, Metadata.create(FetchHints.ALL), visibility); }
java
protected boolean isValidImplementedType(String className) throws JavaModelException { if (!Strings.isNullOrEmpty(className)) { final IType rootType = getRootSuperInterface(); assert rootType != null; final IType type = getJavaProject().findType(className); assert type != null; final ITypeHierarchy hie...
python
def get(cls, option, default_value=None): """ Return value of given option. If option isn't found - return default_value (None by default). Args: - option: string with path to option with `:` separator """ config = cls.__get_instance() for name in option...
java
public List<DateTimePeriod> toHours() { ArrayList<DateTimePeriod> list = new ArrayList<DateTimePeriod>(); // default "current" hour to start datetime DateTime currentStart = getStart(); // calculate "next" hour DateTime nextStart = currentStart.plusHours(1); // continue ...
python
def force_bytes(value): """ Forces a Unicode string to become a bytestring. """ if IS_PY3: if isinstance(value, str): value = value.encode('utf-8', 'backslashreplace') else: if isinstance(value, unicode): # NOQA: F821 value = value.encode('utf-8') return...
java
private void reindexContent( boolean includeSystemContent, IndexWriter indexes ) { if (indexes.canBeSkipped()) return; // The node type schemata changes every time a node type is (un)registered, so get the snapshot that we'll use throughout RepositoryCache repoCa...
java
public static Argument parse(final String arg) { if (arg.startsWith("-D")) { final String key; final String value; // Check for an = final int index = arg.indexOf('='); if (index == -1) { key = arg.substring(2); value = ...
python
def _validate_parameters(self): """Validate Connection Parameters. :return: """ if not compatibility.is_string(self.parameters['hostname']): raise AMQPInvalidArgument('hostname should be a string') elif not compatibility.is_integer(self.parameters['port']): ...
java
public <T> T flickrUpload(Map<String, String> params, byte[] photoData, Class<T> tClass) throws JinxException { if (this.oAuthAccessToken == null) { throw new JinxException("Jinx has not been configured with an OAuth Access Token."); } params.put("api_key", getApiKey()); return uploadOrReplace(par...
python
def make_grammar(dialect: str) -> SqlGrammar: """ Factory to make an :class:`.SqlGrammar` from the name of an SQL dialect, where the name is one of the members of :class:`.SqlaDialectName`. """ if dialect == SqlaDialectName.MYSQL: return mysql_grammar elif dialect == SqlaDialectName.MSSQ...
python
def duplicated(self, subset=None, keep='first'): """ Return boolean Series denoting duplicate rows, optionally only considering certain columns. Parameters ---------- subset : column label or sequence of labels, optional Only consider certain columns for iden...
java
public void add(Iterable<XElement> elements) { for (XElement e : elements) { e.parent = this; children.add(e); } }
java
public String render() { StringBuilder buf = new StringBuilder(); for (Node node : parsed) { if (node instanceof Symbol) { switch ((Symbol)node) { case MINUS: buf.append('-'); break; case CURRENCY: buf.append(CURRENCY_SYM); break...
python
def register_entry_point(self, entry_point): """ Register a lone entry_point Will raise ImportError if the entry_point leads to an invalid import. """ module = _import_module(entry_point.module_name) self._register_entry_point_module(entry_point, module)
java
public static void setTypeConverter(Class<?> type, Class<? extends Converter<?>> converter) { INSTANCE.setTypeConverter(type, converter); }
java
private Vector3d getNonColinearVector(Vector3d ab) { Vector3d cr = new Vector3d(); cr.cross(ab, XV); if (cr.length() > 0.00001) { return XV; } else { return YV; } }
python
def imdecode(str_img, clip_rect=(0, 0, 0, 0), out=None, index=0, channels=3, mean=None): """DEPRECATED, use mx.img instead Parameters ---------- str_img : str Binary image data clip_rect : iterable of 4 int Clip decoded image to rectangle (x0, y0, x1, y1). out : NDArray ...
python
def load_commands(self, namespace): """Load all the commands from an entrypoint""" for ep in pkg_resources.iter_entry_points(namespace): LOG.debug('found command %r', ep.name) cmd_name = (ep.name.replace('_', ' ') if self.convert_underscores ...
java
public C placeStartAt(int itemIndex, double startOffStart) { C cell = getSizedCell(itemIndex); relocate(cell, 0, startOffStart); cell.getNode().setVisible(true); return cell; }
python
def _safe_sendBreak_v2_7(self): # pylint: disable=invalid-name """! pyserial 2.7 API implementation of sendBreak/setBreak @details Below API is deprecated for pyserial 3.x versions! http://pyserial.readthedocs.org/en/latest/pyserial_api.html#serial.Serial.sendBreak http://pyseri...
python
def views(self, install, comp_sum): """Views packages """ pkg_sum = uni_sum = upg_sum = 0 # fix repositories align repo = self.repo + (" " * (6 - (len(self.repo)))) for pkg, comp in zip(install, comp_sum): pkg_repo = split_package(pkg[:-4]) if find...
java
void printRanges() { RangeDescriptor rlRange; int i; System.out.print("\n\n Nonoverlapping Ranges ...\n"); for (rlRange = fRangeList; rlRange!=null; rlRange=rlRange.fNext) { System.out.print(" " + rlRange.fNum + " " + rlRange.fStartChar + "-" + rlR...
java
public void marshall(ClassifierEvaluationMetrics classifierEvaluationMetrics, ProtocolMarshaller protocolMarshaller) { if (classifierEvaluationMetrics == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
java
private void firePluginStarted(final Plugin plugin) { PluginEvent e = null; synchronized (listenerList) { for (Iterator iter = listenerList.iterator(); iter.hasNext();) { PluginListener l = (PluginListener) iter.next(); if (e == null) { e =...
java
public static MethodIdentifier of(final String containingClass, final String methodName, final String signature, final boolean staticMethod) { final String returnType = JavaUtils.getReturnType(signature); final List<String> parameters = JavaUtils.getParameters(signature); return new MethodIdenti...
python
def get(self, id): """ Return the :class:`~plexapi.settings.Setting` object with the specified id. """ id = utils.lowerFirst(id) if id in self._settings: return self._settings[id] raise NotFound('Invalid setting id: %s' % id)
python
def get(self, part): """ Retrieves a part of the model from redis and stores it. :param part: The part of the model to retrieve. :raises RedisORMException: If the redis type is different from string or list (the only two supported types at this time.) """ red...
java
public synchronized void release(int count) { used -= count; if (used < 0) used = 0; // no negative number of ticket! if (logger.isDebugEnabled()) logger.debug("Released " + count + " tickets! (Now " + this.toString() + ")"); notifyAll(); }
java
public void call(Env env, Scope scope, ExprList exprList, Writer writer) { if (exprList.length() != parameterNames.length) { throw new TemplateException("Wrong number of argument to call the template function, right number is: " + parameterNames.length, location); } scope = new Scope(scope); if (exp...
python
def files_view(request): """The main filecenter view.""" hosts = Host.objects.visible_to_user(request.user) context = {"hosts": hosts} return render(request, "files/home.html", context)
python
def getbalance(self, account=None, minconf=6): """retrieve balance, If [account] is specified, returns the balance in the account.""" if account: return self.req("getbalance", [account, minconf]) else: return self.req("getbalance")
java
public static IntConsumer intConsumer(CheckedIntConsumer consumer, Consumer<Throwable> handler) { return i -> { try { consumer.accept(i); } catch (Throwable e) { handler.accept(e); throw new IllegalStateException("Exception han...
python
def _atexit_callback(cls): """Create Python script copies with updated baselines. For any baseline that had a miscompare, make a copy of the source file which contained the baseline and update the baseline with the new string value. :returns: record of every Python ...
python
def load_and_merge(file_path=None, defaults=None): """ Load a given file and apply defaults as specified to any values not present in the file. Does a merge of the file and defaults and returns a dict with the results :param file_path: file to load. Supports .yaml and .json files :param defaults: di...
java
public void setMeshCreatorInputPositions(float[] values) { meshCreatorInputPositions = new float[ values.length ]; for (int i = 0; i < values.length; i++) { meshCreatorInputPositions[i] = values[i]; } }
python
def cast_in(self, element): """encode the element into the internal tag list.""" if _debug: Any._debug("cast_in %r", element) t = TagList() if isinstance(element, Atomic): tag = Tag() element.encode(tag) t.append(tag) elif isinstance(element, ...
python
def handle_special(self, send_body, method_str): """Handles a dynamic request. If this method returns False the request is interpreted as static file request. Methods can be registered using the `add_TYPE_METHOD_mask` methods of QuickServer. Parameters ---------- s...
java
public void endElement(String uri, String localName, String qName) throws RepositoryException { tree.pop(); xmlCharactersProperty = null; }
java
void broadcast(Iterator<String> peers, Message message) { transport.broadcast(peers, message); }
python
def _get_closest_week(self, metric_date): """ Gets the closest monday to the date provided. """ #find the offset to the closest monday days_after_monday = metric_date.isoweekday() - 1 return metric_date - datetime.timedelta(days=days_after_monday)