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 interpolat...
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 ...
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] = ...
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 instan...
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 -...
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]...
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 { ...
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(c...
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 ...
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_...
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().ge...
java
public DirectedGraph<ModuleId, DefaultEdge> getModuleNameGraph() { SimpleDirectedGraph<ModuleId, DefaultEdge> graph = new SimpleDirectedGraph<ModuleId, DefaultEdge>(DefaultEdge.class); Map<ModuleId, ModuleIdentifier> moduleIdentifiers = getLatestRevisionIds(); GraphUtils.addAllVertices(graph, mo...
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 ...
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]] ...
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 ...
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()...
java
public List<JAXBElement<Object>> get_GenericApplicationPropertyOfIntTunnelInstallation() { if (_GenericApplicationPropertyOfIntTunnelInstallation == null) { _GenericApplicationPropertyOfIntTunnelInstallation = new ArrayList<JAXBElement<Object>>(); } return this._GenericApplicationPro...
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._fi...
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.getM...
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: disa...
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 ...
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: "gcheon@stanford.edu" Args: struct (Structure): Input structure tolerance: length in angstroms used in fi...
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().getAddr...
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.ndarra...
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 = i...
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.f...
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); ...
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. ...
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 isD...
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,o...
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_...
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 ...
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<>(taskC...
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.opti...
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: ...
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() == "sc...
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 sa...
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...
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. ...
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); finder...
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': '#...
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 = ...
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 ...
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 IllegalArgumentExcept...
java
@Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); if (generateDoc) { try { docWriter = mFiler.createResource( StandardLocation.SOURCE_OUTPUT, PACKAGE_OF_GENERATE_DOCS,...
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() sign...
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=Ac...
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) { setVa...
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 toke...
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); ...
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( ...
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 pa...
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("/", "."); } ret...
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.p...
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 fsS...
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....
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] ...
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). ...
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: ...
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 c...
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; }