language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def makeLinearcFunc(self,mNrm,cNrm): ''' Make a linear interpolation to represent the (unconstrained) consumption function conditional on the current period state. Parameters ---------- mNrm : np.array Array of normalized market resource values for interpolation. cNrm : np.array Array of normalized consumption values for interpolation. Returns ------- cFuncUnc: an instance of HARK.interpolation.LinearInterp ''' cFuncUnc = LinearInterp(mNrm,cNrm,self.MPCminNow_j*self.hNrmNow_j,self.MPCminNow_j) return cFuncUnc
java
@Override protected Client instantiateClient(String persistenceUnit) { return new HBaseClient(indexManager, conf, connection, reader, persistenceUnit, externalProperties, clientMetadata, kunderaMetadata); }
python
def plus(*args): ''' plus(a, b...) returns the sum of all the values as a numpy array object. Unlike numpy's add function or a+b syntax, plus will thread over the earliest dimension possible; thus if a.shape a.shape is (4,2) and b.shape is 4, plus(a,b) is a equivalent to [ai+bi for (ai,bi) in zip(a,b)]. ''' n = len(args) if n == 0: return np.asarray(0) elif n == 1: return np.asarray(args[0]) elif n > 2: return reduce(plus, args) (a,b) = unbroadcast(*args) return a + b
java
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
java
@SuppressWarnings("unchecked") protected void fromHierarchicalMap(Map<String, Object> map) { for (Entry<String, Object> entry : map.entrySet()) { SimpleConfigProperties child = (SimpleConfigProperties) getChild(entry.getKey(), true); Object childObject = entry.getValue(); if (childObject instanceof Map) { child.fromHierarchicalMap((Map<String, Object>) childObject); } else { child.value = childObject.toString(); } } }
python
def sparkline(data): ''' Return a spark line for the given data set. :value data: sequence of numeric values >>> print sparkline([1, 2, 3, 4, 5, 6, 5, 4, 3, 1, 5, 6]) # doctest: +SKIP ▁▂▃▄▅▆▅▄▃▁▅▆ ''' min_value = float(min(data)) max_value = float(max(data)) steps = (max_value - min_value) / float(len(SPARKCHAR) - 1) return ''.join([ SPARKCHAR[int((float(value) - min_value) / steps)] for value in data ])
python
def process_figures(key, value, fmt, meta): # pylint: disable=unused-argument """Processes the figures.""" global has_unnumbered_figures # pylint: disable=global-statement # Process figures wrapped in Para elements if key == 'Para' and len(value) == 1 and \ value[0]['t'] == 'Image' and value[0]['c'][-1][1].startswith('fig:'): # Inspect the image if len(value[0]['c']) == 2: # Unattributed, bail out has_unnumbered_figures = True if fmt == 'latex': return [RawBlock('tex', r'\begin{no-prefix-figure-caption}'), Para(value), RawBlock('tex', r'\end{no-prefix-figure-caption}')] return None # Process the figure fig = _process_figure(value, fmt) # Context-dependent output attrs = fig['attrs'] if fig['is_unnumbered']: # Unnumbered is also unreferenceable if fmt == 'latex': return [ RawBlock('tex', r'\begin{no-prefix-figure-caption}'), Para(value), RawBlock('tex', r'\end{no-prefix-figure-caption}')] elif fmt in ['latex', 'beamer']: key = attrs[0] if PANDOCVERSION >= '1.17': # Remove id from the image attributes. It is incorrectly # handled by pandoc's TeX writer for these versions. if LABEL_PATTERN.match(attrs[0]): attrs[0] = '' if fig['is_tagged']: # Code in the tags tex = '\n'.join([r'\let\oldthefigure=\thefigure', r'\renewcommand\thefigure{%s}'%\ references[key]]) pre = RawBlock('tex', tex) tex = '\n'.join([r'\let\thefigure=\oldthefigure', r'\addtocounter{figure}{-1}']) post = RawBlock('tex', tex) return [pre, Para(value), post] elif fig['is_unreferenceable']: attrs[0] = '' # The label isn't needed any further elif PANDOCVERSION < '1.16' and fmt in ('html', 'html5') \ and LABEL_PATTERN.match(attrs[0]): # Insert anchor anchor = RawBlock('html', '<a name="%s"></a>'%attrs[0]) return [anchor, Para(value)] elif fmt == 'docx': # As per http://officeopenxml.com/WPhyperlink.php bookmarkstart = \ RawBlock('openxml', '<w:bookmarkStart w:id="0" w:name="%s"/>' %attrs[0]) bookmarkend = \ RawBlock('openxml', '<w:bookmarkEnd w:id="0"/>') return [bookmarkstart, Para(value), bookmarkend] return None
java
@Override public boolean updateValuesForField(String currentValue) { boolean bUpdated = false; FieldDefinition fieldDef = m_tableDef.getFieldDef(m_fieldName); if (fieldDef == null || !fieldDef.isCollection()) { bUpdated = updateSVScalar(currentValue); } else { bUpdated = updateMVScalar(currentValue); } return bUpdated; }
java
public NodeInterval findNode(final SearchCallback callback) { Preconditions.checkNotNull(callback); if (callback.isMatch(this)) { return this; } NodeInterval curChild = leftChild; while (curChild != null) { final NodeInterval result = curChild.findNode(callback); if (result != null) { return result; } curChild = curChild.getRightSibling(); } return null; }
python
def run_in_executor(self, callback): """ Run a long running function in a background thread. (This is recommended for code that could block the event loop.) Similar to Twisted's ``deferToThread``. """ # Wait until the main thread is idle. # We start the thread by using `call_from_executor`. The event loop # favours processing input over `calls_from_executor`, so the thread # will not start until there is no more input to process and the main # thread becomes idle for an instant. This is good, because Python # threading favours CPU over I/O -- an autocompletion thread in the # background would cause a significantly slow down of the main thread. # It is mostly noticable when pasting large portions of text while # having real time autocompletion while typing on. def start_executor(): threading.Thread(target=callback).start() self.call_from_executor(start_executor)
python
def on_receive(self, broker): """ This handler is only called after the stream is registered with the IO loop, the descriptor is manually read/written by _connect_bootstrap() prior to that. """ buf = self.receive_side.read() if not buf: return self.on_disconnect(broker) self.buf += buf.decode('utf-8', 'replace') while u'\n' in self.buf: lines = self.buf.split('\n') self.buf = lines[-1] for line in lines[:-1]: LOG.debug('%s: %s', self.stream.name, line.rstrip())
java
public static void bytes (Object o, TraceComponent tc, byte[] data, int start) { int length = 0; if (data != null) length = data.length; bytes(o, tc, data, start, length, ""); }
java
@Override public void setup(Context context) throws IOException ,InterruptedException { this.context = context; inputLabels = context.getConfiguration().getStrings(SimpleJob.FILETER_OUTPUT_LABELS); if (inputLabels == null) { inputLabels = context.getConfiguration().getStrings(SimpleJob.BEFORE_SUMMARIZER_OUTPUT_LABELS); } boolean label = context.getConfiguration().getStrings(SimpleJob.SUMMARIZER_OUTPUT_LABELS) == null ? true : false; writer = new BasicWriter(label); summarizerSetup(); }
java
public DirectedGraph<ModuleId, DefaultEdge> getModuleNameGraph() { SimpleDirectedGraph<ModuleId, DefaultEdge> graph = new SimpleDirectedGraph<ModuleId, DefaultEdge>(DefaultEdge.class); Map<ModuleId, ModuleIdentifier> moduleIdentifiers = getLatestRevisionIds(); GraphUtils.addAllVertices(graph, moduleIdentifiers.keySet()); for (Entry<ModuleId, ModuleIdentifier> entry : moduleIdentifiers.entrySet()) { ModuleId scriptModuleId = entry.getKey(); ModuleIdentifier revisionID = entry.getValue(); ModuleSpec moduleSpec = moduleSpecs.get(revisionID); Set<ModuleId> dependencyNames = getDependencyScriptModuleIds(moduleSpec); GraphUtils.addOutgoingEdges(graph, scriptModuleId, dependencyNames); } return graph; }
python
def get_hoisted(dct, child_name): """Pulls all of a child's keys up to the parent, with the names unchanged.""" child = dct[child_name] del dct[child_name] dct.update(child) return dct
java
public void add(String name, Object value) { if (value != null) { this.content.put(name, value); } }
python
def clear(self): """Clears the server list""" if len(self.list): self._LOG.debug("List cleared.") self.list.clear()
java
public LocalTime minusMillis(int millis) { if (millis == 0) { return this; } long instant = getChronology().millis().subtract(getLocalMillis(), millis); return withLocalMillis(instant); }
python
def _serialize_list(cls, list_): """ :type list_: list :rtype: list """ list_serialized = [] for item in list_: item_serialized = cls.serialize(item) list_serialized.append(item_serialized) return list_serialized
java
public boolean flushPipelinedData() throws IOException { if (buffer == null || (buffer.getBuffer().position() == 0 && allAreClear(state, FLUSHING))) { return next.flush(); } return flushBuffer(); }
python
def OnQuote(self, event): """Quotes selection or if none the current cell""" grid = self.grid grid.DisableCellEditControl() with undo.group(_("Quote cell(s)")): # Is a selection present? if self.grid.IsSelection(): # Enclose all selected cells self.grid.actions.quote_selection() # Update grid self.grid.ForceRefresh() else: row = self.grid.GetGridCursorRow() col = self.grid.GetGridCursorCol() key = row, col, grid.current_table self.grid.actions.quote_code(key) grid.MoveCursorDown(False)
java
public static synchronized void staticFiles(String url, String docPath) { checkStarted(); instance().endpoints.add(HandlerUtil.staticFiles(url, docPath)); }
java
public boolean isPure() { if (soyFunction instanceof BuiltinFunction) { return ((BuiltinFunction) soyFunction).isPure(); } return soyFunction.getClass().isAnnotationPresent(SoyPureFunction.class); }
python
def JMS_to_Fierz_lep(C, ddll): """From JMS to semileptonic Fierz basis for Class V. `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.""" if ddll[:2] == 'uc': s = uflav[ddll[0]] b = uflav[ddll[1]] q = 'u' else: s = dflav[ddll[0]] b = dflav[ddll[1]] q = 'd' l = lflav[ddll[4:ddll.find('n')]] lp = lflav[ddll[ddll.find('_',5)+1:len(ddll)]] ind = ddll.replace('l_','').replace('nu_','') return { 'F' + ind + '9' : C["V" + q + "eLR"][s, b, l, lp] / 2 + C["Ve" + q + "LL"][l, lp, s, b] / 2, 'F' + ind + '10' : C["V" + q + "eLR"][s, b, l, lp] / 2 - C["Ve" + q + "LL"][l, lp, s, b] / 2, 'F' + ind + 'S' : C["Se" + q + "RL"][lp, l, b, s].conj() / 2 + C["Se" + q + "RR"][l, lp, s, b] / 2, 'F' + ind + 'P' : - C["Se" + q + "RL"][lp, l, b, s].conj() / 2 + C["Se" + q + "RR"][l, lp, s, b] / 2, 'F' + ind + 'T' : C["Te" + q + "RR"][l, lp, s, b] / 2 + C["Te" + q + "RR"][lp, l, b, s].conj() / 2, 'F' + ind + 'T5' : C["Te" + q + "RR"][l, lp, s, b] / 2 - C["Te" + q + "RR"][lp, l, b, s].conj() / 2, 'F' + ind + '9p' : C["Ve" + q + "LR"][l, lp, s, b] / 2 + C["Ve" + q + "RR"][l, lp, s, b] / 2, 'F' + ind + '10p' : -C["Ve" + q + "LR"][l, lp, s, b] / 2 + C["Ve" + q + "RR"][l, lp, s, b] / 2, 'F' + ind + 'Sp' : C["Se" + q + "RL"][l, lp, s, b] / 2 + C["Se" + q + "RR"][lp, l, b, s].conj() / 2, 'F' + ind + 'Pp' : C["Se" + q + "RL"][l, lp, s, b] / 2 - C["Se" + q + "RR"][lp, l, b, s].conj() / 2, }
python
def stream(self, timeout=None): """ Streams the MapReduce query (returns an iterator). Shortcut for :meth:`riak.client.RiakClient.stream_mapred`. :param timeout: Timeout in milliseconds :type timeout: integer :rtype: iterator that yields (phase_num, data) tuples """ query, lrf = self._normalize_query() return self._client.stream_mapred(self._inputs, query, timeout)
python
def include(cls, name, range_key, includes): """ Create an index that projects key attributes plus some others """ return cls(cls.INCLUDE, name, range_key, includes)
java
E getBlockingUntilAvailableOrTimeout(final PoolKey<K> key, final long timeout, final TimeUnit unit, final PoolWaitFuture<E> future) throws InterruptedException, TimeoutException { Date deadline = null; if (timeout > 0) { deadline = new Date(System.currentTimeMillis() + unit.toMillis(timeout)); } lock.lock(); try { E entry = null; for(;;) { validateShutdown(); entry = createOrAttemptToBorrow(key); if (entry != null) return entry.flagOwner(); if (!await(future, key, deadline) && deadline != null && deadline.getTime() <= System.currentTimeMillis()) break; } throw new TimeoutException("Timeout waiting for Pool for Key: " + key); } finally { lock.unlock(); } }
java
public List<JAXBElement<Object>> get_GenericApplicationPropertyOfIntTunnelInstallation() { if (_GenericApplicationPropertyOfIntTunnelInstallation == null) { _GenericApplicationPropertyOfIntTunnelInstallation = new ArrayList<JAXBElement<Object>>(); } return this._GenericApplicationPropertyOfIntTunnelInstallation; }
python
def get_rendered_fields(self, ctx=None): ''' :param ctx: rendering context in which the method was called :return: ordered list of the fields that will be rendered ''' if ctx is None: ctx = RenderContext() ctx.push(self) current = self._fields[self._field_idx] res = current.get_rendered_fields(ctx) ctx.pop() return res
python
def timedelta2period(duration): """Convert timedelta to different formats.""" seconds = duration.seconds minutes = (seconds % 3600) // 60 seconds = (seconds % 60) return '{0:0>2}:{1:0>2}'.format(minutes, seconds)
java
public synchronized boolean put(byte value) { if (available == capacity) { return false; } buffer[idxPut] = value; idxPut = (idxPut + 1) % capacity; available++; return true; }
java
private static boolean openBrowserJava6(String url) throws Exception { final Class<?> desktopClass; try { desktopClass = Class.forName("java.awt.Desktop"); } catch (ClassNotFoundException e) { return false; } Boolean supported = (Boolean) desktopClass.getMethod("isDesktopSupported", new Class[0]).invoke(null); if (supported) { Object desktop = desktopClass.getMethod("getDesktop", new Class[0]).invoke(null); desktopClass.getMethod("browse", new Class[]{URI.class}).invoke(desktop, new URI(url)); return true; } return false; }
python
def _walk(recursion): """Returns a recursive or non-recursive directory walker""" try: from scandir import walk as walk_function except ImportError: from os import walk as walk_function if recursion: walk = partial(walk_function) else: def walk(path): # pylint: disable=C0111 try: yield next(walk_function(path)) except NameError: yield walk_function(path) return walk
python
def create_status(self, sha, state, target_url=None, description=None, context='default'): """Create a status object on a commit. :param str sha: (required), SHA of the commit to create the status on :param str state: (required), state of the test; only the following are accepted: 'pending', 'success', 'error', 'failure' :param str target_url: (optional), URL to associate with this status. :param str description: (optional), short description of the status :param str context: (optional), A string label to differentiate this status from the status of other systems :returns: the status created if successful :rtype: :class:`~github3.repos.status.Status` """ json = None if sha and state: data = {'state': state, 'target_url': target_url, 'description': description, 'context': context} url = self._build_url('statuses', sha, base_url=self._api) self._remove_none(data) json = self._json(self._post(url, data=data), 201) return Status(json) if json else None
python
def find_connected_atoms(struct, tolerance=0.45, ldict=JmolNN().el_radius): """ Finds bonded atoms and returns a adjacency matrix of bonded atoms. Author: "Gowoon Cheon" Email: "[email protected]" Args: struct (Structure): Input structure tolerance: length in angstroms used in finding bonded atoms. Two atoms are considered bonded if (radius of atom 1) + (radius of atom 2) + (tolerance) < (distance between atoms 1 and 2). Default value = 0.45, the value used by JMol and Cheon et al. ldict: dictionary of bond lengths used in finding bonded atoms. Values from JMol are used as default Returns: (np.ndarray): A numpy array of shape (number of atoms, number of atoms); If any image of atom j is bonded to atom i with periodic boundary conditions, the matrix element [atom i, atom j] is 1. """ n_atoms = len(struct.species) fc = np.array(struct.frac_coords) fc_copy = np.repeat(fc[:, :, np.newaxis], 27, axis=2) neighbors = np.array(list(itertools.product([0, 1, -1], [0, 1, -1], [0, 1, -1]))).T neighbors = np.repeat(neighbors[np.newaxis, :, :], 1, axis=0) fc_diff = fc_copy - neighbors species = list(map(str, struct.species)) # in case of charged species for i, item in enumerate(species): if not item in ldict.keys(): species[i] = str(Specie.from_string(item).element) latmat = struct.lattice.matrix connected_matrix = np.zeros((n_atoms,n_atoms)) for i in range(n_atoms): for j in range(i + 1, n_atoms): max_bond_length = ldict[species[i]] + ldict[species[j]] + tolerance frac_diff = fc_diff[j] - fc_copy[i] distance_ij = np.dot(latmat.T, frac_diff) # print(np.linalg.norm(distance_ij,axis=0)) if sum(np.linalg.norm(distance_ij, axis=0) < max_bond_length) > 0: connected_matrix[i, j] = 1 connected_matrix[j, i] = 1 return connected_matrix
java
protected String getToken() { return dataMgr.getSessionDAO().session() != null ? dataMgr.getSessionDAO().session().getAccessToken() : null; }
java
public boolean setPublicAddress(String host, int port) { try { // set 'sentBy' in the listening point for outbound messages parent.getSipProvider().getListeningPoints()[0].setSentBy(host + ":" + port); // update my contact info SipURI my_uri = (SipURI) contactInfo.getContactHeader().getAddress().getURI(); my_uri.setHost(host); my_uri.setPort(port); // update my via header ViaHeader my_via = (ViaHeader) viaHeaders.get(0); my_via.setHost(host); my_via.setPort(port); // update my host myhost = host; } catch (Exception ex) { setException(ex); setErrorMessage("Exception: " + ex.getClass().getName() + ": " + ex.getMessage()); setReturnCode(EXCEPTION_ENCOUNTERED); return false; } // LOG.info("my public IP {}", host); // LOG.info("my public port = {}", port); // LOG.info("my sentby = {}", // parent.getSipProvider().getListeningPoints()[0].getSentBy()); return true; }
java
public FessMessages addErrorsCouldNotOpenOnSystem(String property, String arg0) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_could_not_open_on_system, arg0)); return this; }
python
def mean_second_derivative_central(x): """ Returns the mean value of a central approximation of the second derivative .. math:: \\frac{1}{n} \\sum_{i=1,\ldots, n-1} \\frac{1}{2} (x_{i+2} - 2 \\cdot x_{i+1} + x_i) :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ diff = (_roll(x, 1) - 2 * np.array(x) + _roll(x, -1)) / 2.0 return np.mean(diff[1:-1])
java
private String getInjectionSetting(final String input, final char startDelim) { return input == null || input.equals("") ? null : StringUtilities.split(input, startDelim)[0].trim(); }
java
@Override public void registerMailboxProviderKeeper(final MailboxProviderKeeper keeper) { if (this.mailboxProviderKeeper != null) { this.mailboxProviderKeeper.close(); } this.mailboxProviderKeeper = keeper; }
python
def _send_byte(self,value): """ Convert a numerical value into an integer, then to a byte object. Check bounds for byte. """ # Coerce to int. This will throw a ValueError if the value can't # actually be converted. if type(value) != int: new_value = int(value) if self.give_warnings: w = "Coercing {} into int ({})".format(value,new_value) warnings.warn(w,Warning) value = new_value # Range check if value > 255 or value < 0: err = "Value {} exceeds the size of the board's byte.".format(value) raise OverflowError(err) return struct.pack("B",value)
python
def getBool(self, pchSection, pchSettingsKey): """ Users of the system need to provide a proper default in default.vrsettings in the resources/settings/ directory of either the runtime or the driver_xxx directory. Otherwise the default will be false, 0, 0.0 or "" """ fn = self.function_table.getBool peError = EVRSettingsError() result = fn(pchSection, pchSettingsKey, byref(peError)) return result, peError
java
private JTB newJTB () { final JTB jtb = new JTB (); jtb.setLog (getLog ()); jtb.setDescriptiveFieldNames (this.descriptiveFieldNames); jtb.setJavadocFriendlyComments (this.javadocFriendlyComments); jtb.setNodeParentClass (this.nodeParentClass); jtb.setParentPointers (this.parentPointers); jtb.setPrinter (this.printer); jtb.setScheme (this.scheme); jtb.setSpecialTokens (this.specialTokens); jtb.setSupressErrorChecking (this.supressErrorChecking); return jtb; }
python
def invoke(self, function_name, event, stdout=None, stderr=None): """ Find the Lambda function with given name and invoke it. Pass the given event to the function and return response through the given streams. This function will block until either the function completes or times out. Parameters ---------- function_name str Name of the Lambda function to invoke event str Event data passed to the function. Must be a valid JSON String. stdout samcli.lib.utils.stream_writer.StreamWriter Stream writer to write the output of the Lambda function to. stderr samcli.lib.utils.stream_writer.StreamWriter Stream writer to write the Lambda runtime logs to. Raises ------ FunctionNotfound When we cannot find a function with the given name """ # Generate the correct configuration based on given inputs function = self.provider.get(function_name) if not function: all_functions = [f.name for f in self.provider.get_all()] available_function_message = "{} not found. Possible options in your template: {}"\ .format(function_name, all_functions) LOG.info(available_function_message) raise FunctionNotFound("Unable to find a Function with name '%s'", function_name) LOG.debug("Found one Lambda function with name '%s'", function_name) LOG.info("Invoking %s (%s)", function.handler, function.runtime) config = self._get_invoke_config(function) # Invoke the function self.local_runtime.invoke(config, event, debug_context=self.debug_context, stdout=stdout, stderr=stderr)
java
@Override public GetDomainDetailResult getDomainDetail(GetDomainDetailRequest request) { request = beforeClientExecution(request); return executeGetDomainDetail(request); }
java
public static <T> Future<T> precomputed(final T value) { return new Future<T>() { public boolean cancel(boolean mayInterruptIfRunning) { return false; } public boolean isCancelled() { return false; } public boolean isDone() { return true; } public T get() { return value; } public T get(long timeout, TimeUnit unit) { return value; } }; }
java
public static long count(nitro_service service, String id) throws Exception{ linkset_interface_binding obj = new linkset_interface_binding(); obj.set_id(id); options option = new options(); option.set_count(true); linkset_interface_binding response[] = (linkset_interface_binding[]) obj.get_resources(service,option); if (response != null) { return response[0].__count; } return 0; }
java
public Result<String> extractRawText(InputStream stream) throws IOException { return new InternalDocumentConverter(options).extractRawText(stream).toResult(); }
java
public void setCustomAreaFillBottom(final Color CUSTOM_AREA_FILL_COLOR_BOTTOM) { customAreaFillBottom = CUSTOM_AREA_FILL_COLOR_BOTTOM; init(INNER_BOUNDS.width, INNER_BOUNDS.height); repaint(INNER_BOUNDS); }
java
private static Collection<Container> keepOnlyLastIndexedContainer(Collection<Container> existingContainers, final String partiallyApplied) { Collection<Container> result = new ArrayList<>(existingContainers); // No index place holder, so nothing to filters if (!partiallyApplied.contains(INDEX_PLACEHOLDER)) { return result; } Map<String,Container> containerMap = existingContainers.stream().collect(Collectors.toMap(Container::getName, Function.identity())); Container last = null; for (long i = 1; i < Long.MAX_VALUE; i++) { final String withIndexApplied = partiallyApplied.replaceAll(INDEX_PLACEHOLDER, String.valueOf(i)); Container mapped = containerMap.get(withIndexApplied); if (mapped != null) { result.remove(mapped); last = mapped; } else { // Readd last one removed (if any) if (last != null) { result.add(last); } return result; } } throw new IllegalStateException("Internal error: Cannot find a free container index slot in " + existingContainers); }
python
def _declareTimeoutExceeded(self, ev_data: RestartLogData): """ This function is called when time for restart is up """ logger.info("Timeout exceeded for {}".format(ev_data.when)) last = self._actionLog.last_event if (last and last.ev_type == RestartLog.Events.failed and last.data == ev_data): return None self._action_failed(ev_data, reason="exceeded restart timeout") self._unscheduleAction() self._actionFailedCallback()
java
public ArrayList<V> toArrayList (int maxElements) throws SQLException { ArrayList<V> al = new ArrayList<V>(Math.min(maxElements, 100)); V o; while (--maxElements >= 0 && (o = next()) != null) { al.add(o); } return al; }
java
public static List<Map<String, String>> multiple(Map<String, String> settings, final int taskCount) { Preconditions.checkNotNull(settings, "settings cannot be null."); Preconditions.checkState(taskCount > 0, "taskCount must be greater than 0."); final List<Map<String, String>> result = new ArrayList<>(taskCount); for (int i = 0; i < taskCount; i++) { result.add(settings); } return ImmutableList.copyOf(result); }
java
@Override public FacilityMessage createFAC() { FacilityMessage msg = new FacilityMessageImpl(_FAC_HOLDER.mandatoryCodes, _FAC_HOLDER.mandatoryVariableCodes, _FAC_HOLDER.optionalCodes, _FAC_HOLDER.mandatoryCodeToIndex, _FAC_HOLDER.mandatoryVariableCodeToIndex, _FAC_HOLDER.optionalCodeToIndex); return msg; }
python
def get_skill_data(self): """ generates tuples of name, path, url, sha """ path_to_sha = { folder: sha for folder, sha in self.get_shas() } modules = self.read_file('.gitmodules').split('[submodule "') for i, module in enumerate(modules): if not module: continue try: name = module.split('"]')[0].strip() path = module.split('path = ')[1].split('\n')[0].strip() url = module.split('url = ')[1].strip() sha = path_to_sha.get(path, '') yield name, path, url, sha except (ValueError, IndexError) as e: LOG.warning('Failed to parse submodule "{}" #{}:{}'.format( locals().get('name', ''), i, e ))
java
private void startScript(String line, DispatchCallback callback) { OutputFile outFile = sqlLine.getScriptOutputFile(); if (outFile != null) { callback.setToFailure(); sqlLine.error(sqlLine.loc("script-already-running", outFile)); return; } String filename; if (line.length() == "script".length() || (filename = sqlLine.dequote(line.substring("script".length() + 1))) == null) { sqlLine.error("Usage: script <file name>"); callback.setToFailure(); return; } try { outFile = new OutputFile(expand(filename)); sqlLine.setScriptOutputFile(outFile); sqlLine.output(sqlLine.loc("script-started", outFile)); callback.setToSuccess(); } catch (Exception e) { callback.setToFailure(); sqlLine.error(e); } }
python
def calc_acceleration_bca(jackknife_replicates): """ Calculate the acceleration constant for the Bias Corrected and Accelerated (BCa) bootstrap confidence intervals. Parameters ---------- jackknife_replicates : 2D ndarray. Each row should correspond to a different jackknife parameter sample, formed by deleting a particular observation and then re-estimating the desired model. Each column should correspond to an element of the parameter vector being estimated. Returns ------- acceleration : 1D ndarray. There will be one element for each element in `mle_estimate`. Elements denote the acceleration factors for each component of the parameter vector. References ---------- Efron, Bradley, and Robert J. Tibshirani. An Introduction to the Bootstrap. CRC press, 1994. Section 14.3, Equation 14.15. """ # Get the mean of the bootstrapped statistics. jackknife_mean = jackknife_replicates.mean(axis=0)[None, :] # Calculate the differences between the mean of the bootstrapped statistics differences = jackknife_mean - jackknife_replicates numerator = (differences**3).sum(axis=0) denominator = 6 * ((differences**2).sum(axis=0))**1.5 # guard against division by zero. Note that this guard shouldn't distort # the computational results since the numerator should be zero whenever the # denominator is zero. zero_denom = np.where(denominator == 0) denominator[zero_denom] = MIN_COMP_VALUE # Compute the acceleration. acceleration = numerator / denominator return acceleration
python
def _enforceDataType(self, data): """ Converts to int so that this CTI always stores that type. The data be set to a negative value, e.g. use -1 to select the last item by default. However, it will be converted to a positive by this method. """ idx = int(data) if idx < 0: idx += len(self._displayValues) assert 0 <= idx < len(self._displayValues), \ "Index should be >= 0 and < {}. Got {}".format(len(self._displayValues), idx) return idx
python
def process_text(self, text): """Splits a long text into words, eliminates the stopwords. Parameters ---------- text : string The text to be processed. Returns ------- words : dict (string, int) Word tokens with associated frequency. ..versionchanged:: 1.2.2 Changed return type from list of tuples to dict. Notes ----- There are better ways to do word tokenization, but I don't want to include all those things. """ stopwords = set([i.lower() for i in self.stopwords]) flags = (re.UNICODE if sys.version < '3' and type(text) is unicode # noqa: F821 else 0) regexp = self.regexp if self.regexp is not None else r"\w[\w']+" words = re.findall(regexp, text, flags) # remove stopwords words = [word for word in words if word.lower() not in stopwords] # remove 's words = [word[:-2] if word.lower().endswith("'s") else word for word in words] # remove numbers if not self.include_numbers: words = [word for word in words if not word.isdigit()] # remove short words if self.min_word_length: words = [word for word in words if len(word) >= self.min_word_length] if self.collocations: word_counts = unigrams_and_bigrams(words, self.normalize_plurals) else: word_counts, _ = process_tokens(words, self.normalize_plurals) return word_counts
java
@Override public void clearCache(CommerceShippingMethod commerceShippingMethod) { entityCache.removeResult(CommerceShippingMethodModelImpl.ENTITY_CACHE_ENABLED, CommerceShippingMethodImpl.class, commerceShippingMethod.getPrimaryKey()); finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION); finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION); clearUniqueFindersCache((CommerceShippingMethodModelImpl)commerceShippingMethod, true); }
python
def generate_ref(self): """ Ref can be link to remote or local definition. .. code-block:: python {'$ref': 'http://json-schema.org/draft-04/schema#'} { 'properties': { 'foo': {'type': 'integer'}, 'bar': {'$ref': '#/properties/foo'} } } """ with self._resolver.in_scope(self._definition['$ref']): name = self._resolver.get_scope_name() uri = self._resolver.get_uri() if uri not in self._validation_functions_done: self._needed_validation_functions[uri] = name # call validation function self.l('{}({variable})', name)
java
private Map<String, String> fillInitialVariables() { Map<String, TransitionTarget> targets = model.getChildren(); Set<String> variables = new HashSet<>(); for (TransitionTarget target : targets.values()) { OnEntry entry = target.getOnEntry(); List<Action> actions = entry.getActions(); for (Action action : actions) { if (action instanceof Assign) { String variable = ((Assign) action).getName(); variables.add(variable); } else if (action instanceof SetAssignExtension.SetAssignTag) { String variable = ((SetAssignExtension.SetAssignTag) action).getName(); variables.add(variable); } } } Map<String, String> result = new HashMap<>(); for (String variable : variables) { result.put(variable, ""); } return result; }
python
def scope_types(self, request, *args, **kwargs): """ Returns a list of scope types acceptable by events filter. """ return response.Response(utils.get_scope_types_mapping().keys())
java
String getStringByID(long stringID) { Long stringIDObj = new Long(stringID); String string = (String) stringCache.get(stringIDObj); if (string == null) { string = createStringByID(stringID); stringCache.put(stringIDObj,string); } return string; }
java
public void setDateReleased(CmsResource resource, long dateReleased, boolean recursive) throws CmsException { getResourceType(resource).setDateReleased(this, m_securityManager, resource, dateReleased, recursive); }
java
public String getString(Collection<ByteBuffer> names) { StringBuilder builder = new StringBuilder(); for (ByteBuffer name : names) { builder.append(getString(name)).append(","); } return builder.toString(); }
java
@Override public ResourceSet<AvailableAddOn> read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); }
python
async def cache_instruments(self, require: Dict[top_types.Mount, str] = None): """ - Get the attached instrument on each mount and - Cache their pipette configs from pipette-config.json If specified, the require element should be a dict of mounts to instrument models describing the instruments expected to be present. This can save a subsequent of :py:attr:`attached_instruments` and also serves as the hook for the hardware simulator to decide what is attached. """ checked_require = require or {} self._log.info("Updating instrument model cache") found = self._backend.get_attached_instruments(checked_require) for mount, instrument_data in found.items(): model = instrument_data.get('model') if model is not None: p = Pipette(model, self._config.instrument_offset[mount.name.lower()], instrument_data['id']) self._attached_instruments[mount] = p else: self._attached_instruments[mount] = None mod_log.info("Instruments found: {}".format( self._attached_instruments))
java
public <T> void includeClass(Class<T> includeClass) { Objects.requireNonNull(includeClass); validateIncludeClass(includeClass); if (includeClass.isAnnotationPresent(Service.class)) { serviceClass(includeClass); } if (! includeIsActive(includeClass)) { throw new IllegalArgumentException(L.l("include class '{0}' is invalid because it does not define any beans, services, or paths.", includeClass.getName())); } }
java
@Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); if (generateDoc) { try { docWriter = mFiler.createResource( StandardLocation.SOURCE_OUTPUT, PACKAGE_OF_GENERATE_DOCS, "arouter-map-of-" + moduleName + ".json" ).openWriter(); } catch (IOException e) { logger.error("Create doc writer failed, because " + e.getMessage()); } } iProvider = elementUtils.getTypeElement(Consts.IPROVIDER).asType(); logger.info(">>> RouteProcessor init. <<<"); }
python
def filter(self, *args): ''' Returns a filtered subset of this collection of signatures, based on a set of key/value tuples This is useful when you only want a subset of the signatures in a project. Example usage: :: pc = PerfherderClient() signatures = pc.get_signatures('mozilla-central') signatures = signatures.filter(('suite', 'tp5o'), ('machine_platform', 'windowsxp')) ''' filtered_signatures = {} for (signature, signature_value) in self.items(): skip = False for (key, val) in args: if signature_value.get(key) != val: skip = True break if not skip: filtered_signatures[signature] = signature_value return PerformanceSignatureCollection(filtered_signatures)
python
def get(self, block=True, timeout=None): """ Removes and returns an item from the queue. """ value = self._queue.get(block, timeout) if self._queue.empty(): self.clear() return value
python
def addresses(self): """ Return a new raw REST interface to address resources :rtype: :py:class:`ns1.rest.ipam.Adresses` """ import ns1.rest.ipam return ns1.rest.ipam.Addresses(self.config)
python
def QA_fetch_get_future_transaction_realtime(package, code): """ 期货实时tick """ Engine = use(package) if package in ['tdx', 'pytdx']: return Engine.QA_fetch_get_future_transaction_realtime(code) else: return 'Unsupport packages'
java
public static String toStr(Number number, String defaultValue) { return (null == number) ? defaultValue : toStr(number); }
python
def get_count(self, *args, **selectors): """ Return the count of UI object with *selectors* Example: | ${count} | Get Count | text=Accessibility | # Get the count of UI object text=Accessibility | | ${accessibility_text} | Get Object | text=Accessibility | # These two keywords combination | | ${count} | Get Count Of Object | ${accessibility_text} | # do the same thing. | """ obj = self.get_object(**selectors) return self.get_count_of_object(obj)
java
@Override public boolean isDisconnecting() { NetworkInfo networkInfo = isAvailable(); return (networkInfo == null)? false :(networkInfo.getState().equals(State.DISCONNECTING))? true :false; }
java
public void addValueToIn(Object value, String name, Map<String, Object> map) { Object val = getValue(map, name); if (val instanceof Collection) { Object cleanValue = getCleanValue(value); ((Collection) val).add(cleanValue); } else if (val == null) { setValueForIn(value, name + "[0]", map); } else { throw new SlimFixtureException(false, "name is not a list but: " + val.getClass().getSimpleName()); } }
python
def default_token_implementation(self, user_id): """ Default JWT token implementation This is used by default for generating user tokens if custom implementation was not configured. The token will contain user_id and expiration date. If you need more information added to the token, register your custom implementation. It will load a user to see if token is already on file. If it is, the existing token will be checked for expiration and returned if valid. Otherwise a new token will be generated and persisted. This can be used to perform token revocation. :param user_id: int, user id :return: string """ user = self.get(user_id) if not user: msg = 'No user with such id [{}]' raise x.JwtNoUser(msg.format(user_id)) # return token if exists and valid if user._token: try: self.decode_token(user._token) return user._token except jwt.exceptions.ExpiredSignatureError: pass from_now = datetime.timedelta(seconds=self.jwt_lifetime) expires = datetime.datetime.utcnow() + from_now issued = datetime.datetime.utcnow() not_before = datetime.datetime.utcnow() data = dict( exp=expires, nbf=not_before, iat=issued, user_id=user_id ) token = jwt.encode(data, self.jwt_secret, algorithm=self.jwt_algo) string_token = token.decode('utf-8') user._token = string_token self.save(user) return string_token
java
public void addErrorsProperties(Map<String,Object> properties, Object errorsType) { try { Method method = errorsType.getClass().getMethod("getErrors", EMPTY_PARAMS); if (method != null) { Object value = method.invoke(errorsType, EMPTY_DATA); if (value instanceof List<?>) { for (Object errorType : (List<?>)value) { method = errorType.getClass().getMethod("getShortText", EMPTY_PARAMS); if (method != null) { value = method.invoke(errorType, EMPTY_DATA); if (value instanceof String) properties.put("Error", value); } } } } } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
python
def proximal(self): """Proximal factory of the quadratically perturbed functional.""" if self.quadratic_coeff < 0: raise TypeError('`quadratic_coeff` {} must be non-negative' ''.format(self.quadratic_coeff)) return proximal_quadratic_perturbation( self.functional.proximal, a=self.quadratic_coeff, u=self.linear_term)
java
public static String format(String pattern, Map arguments) { MapFormat temp = new MapFormat(arguments); return temp.format(pattern); }
java
static void createFileFromResource(String resource, Resource file) throws IOException { createFileFromResource(resource, file, null); }
python
def _combine_args(self): """Sets protected data by combining raw data set from the constructor. If a ``_parent`` is set, updates the ``_flat_path`` and sets the ``_namespace`` and ``_project`` if not already set. :rtype: :class:`list` of :class:`dict` :returns: A list of key parts with kind and ID or name set. :raises: :class:`ValueError` if the parent key is not complete. """ child_path = self._parse_path(self._flat_path) if self._parent is not None: if self._parent.is_partial: raise ValueError("Parent key must be complete.") # We know that _parent.path() will return a copy. child_path = self._parent.path + child_path self._flat_path = self._parent.flat_path + self._flat_path if ( self._namespace is not None and self._namespace != self._parent.namespace ): raise ValueError("Child namespace must agree with parent's.") self._namespace = self._parent.namespace if self._project is not None and self._project != self._parent.project: raise ValueError("Child project must agree with parent's.") self._project = self._parent.project return child_path
java
static String[] getClasspathClassNames() throws ZipException, IOException { final String[] classes = getClasspathFileNamesWithExtension(".class"); for (int i = 0; i < classes.length; i++) { classes[i] = classes[i].substring(0, classes[i].length() - 6).replace("/", "."); } return classes; }
java
public void reset() { iZone = iDefaultZone; iOffset = null; iPivotYear = iDefaultPivotYear; iSavedFieldsCount = 0; iSavedFieldsShared = false; iSavedState = null; }
java
public static FileSystem newFileSystem(final Archive<?> archive) throws IllegalArgumentException, IOException { if (archive == null) { throw new IllegalArgumentException("Archive must be specified"); } final Map<String, Archive<?>> environment = new HashMap<>(); environment.put(FS_ENV_KEY_ARCHIVE, archive); final URI uri = getRootUri(archive); final FileSystem fs = FileSystems.newFileSystem(uri, environment); return fs; }
python
def com_google_fonts_check_fsselection(ttFont, style): """Checking OS/2 fsSelection value.""" from fontbakery.utils import check_bit_entry from fontbakery.constants import (STATIC_STYLE_NAMES, RIBBI_STYLE_NAMES, FsSelection) # Checking fsSelection REGULAR bit: expected = "Regular" in style or \ (style in STATIC_STYLE_NAMES and style not in RIBBI_STYLE_NAMES and "Italic" not in style) yield check_bit_entry(ttFont, "OS/2", "fsSelection", expected, bitmask=FsSelection.REGULAR, bitname="REGULAR") # Checking fsSelection ITALIC bit: expected = "Italic" in style yield check_bit_entry(ttFont, "OS/2", "fsSelection", expected, bitmask=FsSelection.ITALIC, bitname="ITALIC") # Checking fsSelection BOLD bit: expected = style in ["Bold", "BoldItalic"] yield check_bit_entry(ttFont, "OS/2", "fsSelection", expected, bitmask=FsSelection.BOLD, bitname="BOLD")
java
public static String interpolateString(String text, Properties properties) { if (null == text || null == properties) { return text; } final StringSubstitutor substitutor = new StringSubstitutor(new PropertyLookup(properties)); return substitutor.replace(text); }
python
def update_from_response(self, response): """ Update the state of the Table object based on the response data received from Amazon DynamoDB. """ if 'Table' in response: self._dict.update(response['Table']) elif 'TableDescription' in response: self._dict.update(response['TableDescription']) if 'KeySchema' in self._dict: self._schema = Schema(self._dict['KeySchema'])
python
def crop(im, r, c, sz_h, sz_w): ''' crop image into a square of size sz, ''' return im[r:r+sz_h, c:c+sz_w]
python
def rescale_gradients(model: Model, grad_norm: Optional[float] = None) -> Optional[float]: """ Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled. """ if grad_norm: parameters_to_clip = [p for p in model.parameters() if p.grad is not None] return sparse_clip_norm(parameters_to_clip, grad_norm) return None
python
def make_thread_suspend_str( self, thread_id, frame, stop_reason=None, message=None, suspend_type="trace", frame_id_to_lineno=None ): """ :return tuple(str,str): Returns tuple(thread_suspended_str, thread_stack_str). i.e.: ( ''' <xml> <thread id="id" stop_reason="reason"> <frame id="id" name="functionName " file="file" line="line"> </frame> </thread> </xml> ''' , ''' <frame id="id" name="functionName " file="file" line="line"> </frame> ''' ) """ make_valid_xml_value = pydevd_xml.make_valid_xml_value cmd_text_list = [] append = cmd_text_list.append cmd_text_list.append('<xml>') if message: message = make_valid_xml_value(message) append('<thread id="%s"' % (thread_id,)) if stop_reason is not None: append(' stop_reason="%s"' % (stop_reason,)) if message is not None: append(' message="%s"' % (message,)) if suspend_type is not None: append(' suspend_type="%s"' % (suspend_type,)) append('>') thread_stack_str = self.make_thread_stack_str(frame, frame_id_to_lineno) append(thread_stack_str) append("</thread></xml>") return ''.join(cmd_text_list), thread_stack_str
python
def _get_extended_metadata(h5group): """Extract the extended metadata for a PyCBC table in HDF5 This method packs non-table-column datasets in the given h5group into a metadata `dict` Returns ------- meta : `dict` the metadata dict """ meta = dict() # get PSD try: psd = h5group['psd'] except KeyError: pass else: from gwpy.frequencyseries import FrequencySeries meta['psd'] = FrequencySeries( psd[:], f0=0, df=psd.attrs['delta_f'], name='pycbc_live') # get everything else for key in META_COLUMNS - {'psd'}: try: value = h5group[key][:] except KeyError: pass else: meta[key] = value return meta
java
@Override public com.liferay.commerce.product.model.CPDisplayLayout getCPDisplayLayoutByUuidAndGroupId( String uuid, long groupId) throws com.liferay.portal.kernel.exception.PortalException { return _cpDisplayLayoutLocalService.getCPDisplayLayoutByUuidAndGroupId(uuid, groupId); }
python
def create_product_version(product_id, version, **kwargs): """ Create a new ProductVersion. Each ProductVersion represents a supported product release stream, which includes milestones and releases typically associated with a single major.minor version of a Product. Follows the Red Hat product support cycle, and typically includes Alpha, Beta, GA, and CP releases with the same major.minor version. Example: ProductVersion 1.0 includes the following releases: 1.0.Beta1, 1.0.GA, 1.0.1, etc. """ data = create_product_version_raw(product_id, version, **kwargs) if data: return utils.format_json(data)
java
public int read(char[] cbuf, int off, int len) throws IOException { int startPos = off; int currentlyRead; while (off - startPos < len && (currentlyRead = read()) != -1) { cbuf[off++] = (char) currentlyRead; } return off == startPos && len != 0 ? -1 : off - startPos; }
java
public void deleteFromConference(String connId, String dnToDrop) throws WorkspaceApiException { this.deleteFromConference(connId, dnToDrop, null, null); }
java
public DateTimeStamp setDateTimeStamp(Date dateTimeStamp) { DateTimeStamp prop = (dateTimeStamp == null) ? null : new DateTimeStamp(dateTimeStamp); setDateTimeStamp(prop); return prop; }