language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def assignrepr_values(values, prefix, width=None, _fakeend=0): """Return a prefixed, wrapped and properly aligned string representation of the given values using function |repr|. >>> from hydpy.core.objecttools import assignrepr_values >>> print(assignrepr_values(range(1, 13), 'test(', 20) + ')') t...
python
def import_header(self, header: BlockHeader ) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]: """ Direct passthrough to `headerdb` Also updates the local `header` property to be the latest canonical head. Returns an iterable of he...
python
def make_energies_hdu(self, extname="ENERGIES"): """ Builds and returns a FITs HDU with the energy bin boundries extname : The HDU extension name """ if self._evals is None: return None cols = [fits.Column("ENERGY", "1E", unit='MeV', ...
java
protected void skipBytes(int amount) throws IOException { ensureAvailableBytes(amount); this.buffer.position(this.buffer.position() + amount); }
python
def rate(s=switchpoint, e=early_mean, l=late_mean): ''' Concatenate Poisson means ''' out = empty(len(disasters_array)) out[:s] = e out[s:] = l return out
java
@Override public void handleRequest(final Request request) { super.handleRequest(request); WComponent visibleDialog = getVisible(); if (visibleDialog != null) { visibleDialog.serviceRequest(request); } }
java
public static <T> OptionalValue<T> ofNullable(T value) { return new GenericOptionalValue<T>(RUNTIME_SOURCE, DEFAULT_KEY, value); }
java
static public Probability and(Probability probability1, Probability probability2) { double p1 = probability1.value; double p2 = probability2.value; return new Probability(p1 * p2); }
java
@Override public List<String> getFeatureTables() { List<String> tableNames = getTables(ContentsDataType.FEATURES); return tableNames; }
java
public synchronized long readFromEnd(final long datalen, final ByteBuffer buf) { if (!validState) { throw new InvalidStateException(); } final long size = size(); final long offset = (size - HEADER_LEN - datalen - FOOTER_LEN); return read(offset, buf); }
java
public static int cuGraphicsGLRegisterImage(CUgraphicsResource pCudaResource, int image, int target, int Flags ) { return checkResult(cuGraphicsGLRegisterImageNative(pCudaResource, image, target, Flags)); }
python
def _create_post_table(self): """ Creates the table to store the blog posts. :return: """ with self._engine.begin() as conn: post_table_name = self._table_name("post") if not conn.dialect.has_table(conn, post_table_name): self._post_table ...
python
def _solve(self, A=None, b=None): r""" Sends the A and b matrices to the specified solver, and solves for *x* given the boundary conditions, and source terms based on the present value of *x*. This method does NOT iterate to solve for non-linear source terms or march time steps....
python
def fetch_credential(self, credential=None, profile=None): """Fetch credential from credentials file. Args: credential (str): Credential to fetch. profile (str): Credentials profile. Defaults to ``'default'``. Returns: str, None: Fetched credential or ``None...
java
protected int getRequestTypeFromString(String requestType) { if ("GET".equals(requestType)) { return REQUEST_TYPE_GET; } if ("POST".equals(requestType)) { return REQUEST_TYPE_POST; } if ("PUT".equals(requestType)) { return REQUEST_TYPE_PUT; ...
python
def get_tim(_, data): """http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n874. Positional arguments: data -- bytearray data to read. Returns: Dict. """ answers = { 'DTIM Count': data[0], 'DTIM Period': data[1], 'Bitmap Control': data[2]...
python
def reserve_udp_port(self, port, project): """ Reserve a specific UDP port number :param port: UDP port number :param project: Project instance """ if port in self._used_udp_ports: raise HTTPConflict(text="UDP port {} already in use on host {}".format(port, ...
python
def create_product (self, name, location='GLO', unit='kg', **kwargs): """ Create a new product in the model database """ new_product = item_factory(name=name, location=location, unit=unit, type='product', **kwargs) if not self.exists_in_database(new_product['code']): ...
java
public static <K, V> Multimap<K, V> constrainedMultimap( Multimap<K, V> multimap, MapConstraint<? super K, ? super V> constraint) { return new ConstrainedMultimap<K, V>(multimap, constraint); }
python
def _on_stackexchange_request(self, future, response): """Invoked as a response to the StackExchange API request. Will decode the response and set the result for the future to return the callback or raise an exception """ content = escape.json_decode(response.body) if 'e...
java
private void fillItem(final CmsResource resource, final CmsListItem item, final int id) { CmsObject cms = getCms(); CmsXmlContent xmlContent; I_CmsResourceType type; String iconPath; // fill path column: String sitePath = cms.getSitePath(resource); item.set(LIS...
java
private boolean isShortOption(String token) { // short options (-S, -SV, -S=V, -SV1=V2, -S1S2) return token.startsWith("-") && token.length() >= 2 && options.hasShortOption(token.substring(1, 2)); }
python
def fit_shifts(xy, uv): """ Performs a simple fit for the shift only between matched lists of positions 'xy' and 'uv'. Output: (same as for fit_arrays) ================================= DEVELOPMENT NOTE: Checks need to be put in place to verify that enough ob...
java
public static void scanPath(String path) { log.debug("Scanning classpath for JSONObjects under path '{}'", path); final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.addIncludeFilter(new AssignableTypeFilter(JSONObject.class)); /...
python
def manage_recurring_payments_profile_status(self, profileid, action, note=None): """Shortcut to the ManageRecurringPaymentsProfileStatus method. ``profileid`` is the same profile id used for getting profile details. ``action`` should be either '...
java
public static String verifyCertificate(X509Certificate cert, Collection crls, Calendar calendar) { if (calendar == null) calendar = new GregorianCalendar(); if (cert.hasUnsupportedCriticalExtension()) return "Has unsupported critical extension"; try { cert.che...
java
public ExchangeRateBuilder setRateChain(ExchangeRate... exchangeRates) { this.rateChain.clear(); if (Objects.nonNull(exchangeRates)) { this.rateChain.addAll(Arrays.asList(exchangeRates.clone())); } return this; }
java
private List<Certificate> convertToBouncyCastleCertificate( X509Certificate[] chain) { final List<Certificate> bcChain = new ArrayList<>(); for (X509Certificate cert : chain) { try { bcChain.add(Certificate.getInstance(cert.getEncoded())); } catch (CertificateEncoding...
java
private void preLoadBeanPool() { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.debug(tc, "preLoadBeanPool: " + j2eeName); synchronized (beanPool) { Object oldClassLoader = ThreadContextAccessor.UNCHANGED; ...
java
private void multipleNodeDeletion(final double[][] mat, final BiclusterCandidate cand) { cand.updateRowAndColumnMeans(mat, false); cand.computeMeanSquaredDeviation(mat); // Note: assumes that cand.residue = H(I,J) while(cand.residue > delta) { final boolean[] modified = { false, false }; /...
python
def unregister(model_or_iterable, fail_silently=False): ''' Remove one or more models from the autofixture registry. ''' from django.db import models from .compat import get_model if issubclass(model_or_iterable, models.Model): model_or_iterable = [model_or_iterable] for model in mo...
java
public Javalin get(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) { return addHandler(HandlerType.GET, path, handler, permittedRoles); }
java
protected void onUp(Event event) { m_clientX = event.getClientX(); m_clientY = event.getClientY(); m_modifierCTRL = event.getCtrlKey() || event.getMetaKey(); if ((m_currentTarget == null) || (m_currentTarget.getPlaceholderIndex() < 0)) { cancel(); } else { ...
java
public Object doSetHandle(Object bookmark, int iOpenMode, String strFields, int iHandleType) throws DBException, RemoteException { BaseTransport transport = this.createProxyTransport(DO_SET_HANDLE); transport.addParam(BOOKMARK, bookmark); transport.addParam(OPEN_MODE, iOpenMode); tra...
python
def send_verification_mail(request, user, verification_type): """ Sends an email with a verification link to users when ``ACCOUNTS_VERIFICATION_REQUIRED`` is ```True`` and they're signing up, or when they reset a lost password. The ``verification_type`` arg is both the name of the urlpattern for ...
python
def CrowdsaleRegister(self, wallet, register_addresses, from_addr=None): """ Register for a crowd sale. Args: wallet (neo.Wallets.Wallet): a wallet instance. register_addresses (list): list of public addresses to register for the sale. Returns: tuple...
java
public static boolean isSbeJavaName(final String value) { for (final String token : PATTERN.split(value, -1)) { if (isJavaIdentifier(token)) { if (isJavaKeyword(token)) { return false; } } ...
java
public static void unescapeUriFragmentId(final char[] text, final int offset, final int len, final Writer writer, final String encoding) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be n...
python
def update_webhook(self, webhook_url, webhook_id, events=None): """Register webhook (if it doesn't exit).""" hooks = self._request(MINUT_WEBHOOKS_URL, request_type='GET')['hooks'] try: self._webhook = next( hook for hook in hooks if hook['url'] == webhook_url) ...
java
public static String fileToString(File file) throws IOException { return IOUtils.toString(new BufferedReader(new FileReader(file))); }
java
void wipeDatanode(DatanodeID nodeID) throws IOException { String key = nodeID.getStorageID(); host2DataNodeMap.remove(datanodeMap.remove(key)); if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug( "BLOCK* NameSystem.wipeDatanode: " + nodeID.getName() + " sto...
python
def _translate_dst_register_oprnd(self, operand): """Translate destination register operand to SMT expr. """ reg_info = self._arch_alias_mapper.get(operand.name, None) parent_reg_constrs = [] if reg_info: var_base_name, offset = reg_info var_name_old = ...
python
def _call_brew(cmd, failhard=True): ''' Calls the brew command with the user account of brew ''' user = __salt__['file.get_user'](_homebrew_bin()) runas = user if user != __opts__['user'] else None cmd = '{} {}'.format(salt.utils.path.which('brew'), cmd) result = __salt__['cmd.run_all'](cmd,...
java
@Override public Object determineData(Object dataObject, DataConfig type) throws VectorPrintException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class dataClass = dataObject.getClass(); Method m = dataClass.getMethod(type.getValueasstringmethod()...
python
def getedges(fname, iddfile): """return the edges of the idf file fname""" data, commdct, _idd_index = readidf.readdatacommdct(fname, iddfile=iddfile) edges = makeairplantloop(data, commdct) return edges
java
private TypeDefinitionContainer getTypeDescendants( int depth, TypeDefinitionContainer tc, boolean includePropertyDefinitions) { TypeDefinitionContainerImpl result = new TypeDefinitionContainerImpl(); TypeDefinition type = copyTypeDefintion(tc.getTypeDefinition()); if (...
java
protected OptionalThing<Object> prepareDynamicData(Postcard postcard, String bodyFile, boolean filesystem, OptionalThing<Locale> receiverLocale) { if (dynamicTextAssist == null) { return OptionalThing.empty(); } final SMailDynamicDataResource resource = new SMailDynamicDa...
python
def arg_bool(name, default=False): """ Fetch a query argument, as a boolean. """ v = request.args.get(name, '') if not len(v): return default return v in BOOL_TRUISH
java
public CoverageDataResults getValues(BoundingBox requestBoundingBox) { CoverageDataRequest request = new CoverageDataRequest( requestBoundingBox); CoverageDataResults values = getValues(request); return values; }
python
def eventize(self, granularity): """ This splits the JSON information found at self.events into the several events. For this there are three different levels of time consuming actions: 1-soft, 2-medium and 3-hard. Level 1 provides events about commits Level 2 provides events abo...
python
def jitterplot(data, positions=None, ax=None, vert=True, scale=0.1, **scatter_kwargs): '''Plots jittered points as a distribution visualizer. Scatter plot arguments default to: marker='.', c='k', alpha=0.75 Also known as a stripplot. See also: boxplot, violinplot, beeswarm ''' if ax is None:...
java
protected void applyQueryFilter(Map<String, Object> params, QueryFilter queryFilter) { if (queryFilter != null) { applyQueryContext(params, queryFilter); if (queryFilter.getFilterParams() != null && !queryFilter.getFilterParams().isEmpty()) { params.put(FILTER, queryFilter.getFilterPara...
java
public void setTableVersions(java.util.Collection<TableVersion> tableVersions) { if (tableVersions == null) { this.tableVersions = null; return; } this.tableVersions = new java.util.ArrayList<TableVersion>(tableVersions); }
java
public static int[] sort(float[] c) { HashMap<Integer, Float> map = new HashMap<Integer, Float>(); for (int i = 0; i < c.length; i++) { if (c[i] != 0.0) { map.put(i, Math.abs(c[i])); } } ArrayList<Map.Entry<Integer, Float>> list = new ArrayList<Map.Entry<Integer, Float>>( map.entrySet(...
python
def get_queryset(self): """ Retrieve the category by his path and build a queryset of her published entries. """ self.category = get_category_or_404(self.kwargs['path']) return self.category.entries_published()
java
public static Mail buildHelloEmail() throws IOException { Email from = new Email("test@example.com"); String subject = "Hello World from the SendGrid Java Library"; Email to = new Email("test@example.com"); Content content = new Content("text/plain", "some text here"); // Note that when you use this...
java
public void extendedPut(String remoteFileName, long offset, DataSource source, MarkerListener mListener) throws IOException, ServerException, ClientException{ // servers support GridFTP? ...
java
public Map<String, EntityMetadata> getEntityMetadataMap() { if (entityMetadataMap == null) { entityMetadataMap = new HashMap<String, EntityMetadata>(); } return entityMetadataMap; }
java
public static String identityToString(Object pObject) { if (pObject == null) { return null; } else { return pObject.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(pObject)); } }
python
def decode_raw_stream(self, text, decode_raw, known_encoding, filename): """given string/unicode or bytes/string, determine encoding from magic encoding comment, return body as unicode or raw if decode_raw=False """ if isinstance(text, compat.text_type): m = se...
java
protected static Properties getComponentProperties(String componentPrefix, Properties properties) { Properties result = new Properties(); if (null != componentPrefix) { int componentPrefixLength = componentPrefix.length(); for (String propertyName : properties.stringPropertyN...
python
def append(self, term, type=None, value=None): """ Appends the given term to the taxonomy and tags it as the given type. Optionally, a disambiguation value can be supplied. For example: taxonomy.append("many", "quantity", "50-200") """ term = self._normalize(term) ...
java
public static <T, R> Consumer<T> consumer(Function<T, R> function) { dbc.precondition(function != null, "cannot adapt a null function"); return function::apply; }
java
@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") private List<Long> getOrCreateBucketsValues(final Stopwatch stopwatch) { synchronized (stopwatch) { List<Long> values = getBucketsValues(stopwatch); if (values == null) { values = new ArrayList<>((int) warmupCounter); stopwatch....
python
def set_domain(self, domain='https://api.anaconda.org'): """Reset current api domain.""" logger.debug(str((domain))) config = binstar_client.utils.get_config() config['url'] = domain binstar_client.utils.set_config(config) self._anaconda_client_api = binstar_client.utils...
java
protected void actionDropingOff(double extrp) { progress -= speed * extrp; final int curProgress = (int) Math.floor(progress); // Check ended if (curProgress <= 0) { for (final ExtractorListener listener : listeners) { listener.notifyD...
python
def remove(self, *l): '''remove inner from outer Args: *l element that is passes into Inner init ''' for a in flatten(l): self._remove([self.Inner(a)], self.l)
python
def get_clinical_summary(self, patient_id, section, encounter_id_identifer, verbose=''): """ invokes TouchWorksMagicConstants.ACTION_GET_CLINICAL_SUMMARY action :param patient_id: :param section - if o...
python
def _makeLocationElement(self, locationObject, name=None): """ Convert Location object to an locationElement.""" locElement = ET.Element("location") if name is not None: locElement.attrib['name'] = name for dimensionName, dimensionValue in locationObject.items(): d...
python
def get_ssh_to_node(self, ssh_to=None): """ Return target node for SSH/SFTP connections. The target node is the first node of the class specified in the configuration file as ``ssh_to`` (but argument ``ssh_to`` can override this choice). If not ``ssh_to`` has been speci...
python
def load_page_buffer(self, buffer_number, address, bytes): """! @brief Load data to a numbered page buffer. This method is used in conjunction with start_program_page_with_buffer() to implement double buffered programming. """ assert buffer_number < len(self.page...
python
def select_coins(target, fee, output_size, min_change, *, absolute_fee=False, consolidate=False, unspents): ''' Implementation of Branch-and-Bound coin selection defined in Erhart's Master's thesis An Evaluation of Coin Selection Strategies here: http://murch.one/wp-content/uploads/2016...
python
def delete_api_key(self, api_key, **kwargs): # noqa: E501 """Delete API key. # noqa: E501 An endpoint for deleting the API key. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/api-keys/{apikey-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501 This method makes ...
python
def _validate_value(self, value, field_spec, path, errors): """Validates that the given field value is valid given the associated field spec and path. Any validation failures are added to the given errors collection.""" # Check if the value is None and add an error if the field is not n...
python
def dsr_thurai_2007(D_eq): """ Drop shape relationship function from Thurai2007 (http://dx.doi.org/10.1175/JTECH2051.1) paper. Arguments: D_eq: Drop volume-equivalent diameter (mm) Returns: r: The vertical-to-horizontal drop axis ratio. Note: the Scatterer class expects hori...
python
def Smooth(x, window_len=100, window='hanning'): ''' Smooth data by convolving on a given timescale. :param ndarray x: The data array :param int window_len: The size of the smoothing window. Default `100` :param str window: The window type. Default `hanning` ''' if window_len == 0: ...
java
public Object extractObject(ObjectToJsonConverter pConverter, Object pValue, Stack<String> pPathParts,boolean jsonify) throws AttributeNotFoundException { List list = (List) pValue; int length = pConverter.getCollectionLength(list.size()); String pathPart = pPathParts.isEmpty() ? nul...
java
public EEnum getCFCRetired1() { if (cfcRetired1EEnum == null) { cfcRetired1EEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(11); } return cfcRetired1EEnum; }
java
public static boolean isAssignableFrom(ClassNode superClass, ClassNode childClass) { ClassNode currentSuper = childClass; while (currentSuper != null) { if (currentSuper.equals(superClass)) { return true; } currentSuper = currentSuper.getSuperClass()...
python
def postinit(self, type=None, name=None, body=None): """Do some setup after initialisation. :param type: The types that the block handles. :type type: Tuple or NodeNG or None :param name: The name that the caught exception is assigned to. :type name: AssignName or None ...
python
def intSize(self, obj): """Returns the number of bytes necessary to store the given integer.""" # SIGNED if obj < 0: # Signed integer, always 8 bytes return 8 # UNSIGNED elif obj <= 0xFF: # 1 byte return 1 elif obj <= 0xFFFF: # 2 bytes ...
java
public List<Filter<S>> conjunctiveNormalFormSplit() { final List<Filter<S>> list = new ArrayList<Filter<S>>(); conjunctiveNormalForm().accept(new Visitor<S, Object, Object>() { @Override public Object visit(OrFilter<S> filter, Object param) { list.add(filte...
python
def get_typelist(self): """ This collects all avaliable types and applies include/exclude filters """ typelist = [] # convert type list into arrays if strings if isinstance(self.config['type_include'], basestring): self.config['type_include'] = self.config['t...
python
def find_previous_word_beginning(self, count=1, WORD=False): """ Return an index relative to the cursor position pointing to the start of the previous word. Return `None` if nothing was found. """ if count < 0: return self.find_next_word_beginning(count=-count, WORD=W...
java
public void fastFlip(int index) { assert index >= 0 && index < numBits; int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] ^= bitmask; }
java
@RequestMapping(value = "/api/profile/{profileIdentifier}/clients/delete", method = RequestMethod.POST) public @ResponseBody HashMap<String, Object> deleteClient(Model model, @RequestParam("profileIdentifier") String profileIdentifier, ...
python
def from_pairs(cls, doc, pairs): """ Construct an enumeration from an iterable of pairs. :param doc: See `Enum.__init__`. :type pairs: ``Iterable[Tuple[unicode, unicode]]`` :param pairs: Iterable to construct the enumeration from. :rtype: Enum """ values ...
python
def unique_bits(flags_class): """ A decorator for flags classes to forbid declaring flags with overlapping bits. """ flags_class = unique(flags_class) other_bits = 0 for name, member in flags_class.__members_without_aliases__.items(): bits = int(member) if other_bits & bits: ...
java
public List<CmsResource> readAllSubscribedResources(CmsObject cms, CmsPrincipal principal) throws CmsException { return m_securityManager.readAllSubscribedResources(cms.getRequestContext(), getPoolName(), principal); }
java
public static <T, U> SameType<T> of(TreeNode<T> expected, TreeDef<U> treeDef, U actual, Function<? super U, ? extends T> mapper) { return of(TreeNode.treeDef(), expected, treeDef, actual).mapToSame(TreeNode::getContent, mapper); }
java
public static <T> T[] copyOfRange(final T[] original, final int from, final int to, final int step) { return copyOfRange(original, from, to, step, (Class<T[]>) original.getClass()); }
java
public void buildCluster(String secured) { if (secured == null) { this.cluster = Cluster.builder().addContactPoint(this.host).build(); this.cluster.getConfiguration().getQueryOptions() .setConsistencyLevel(ConsistencyLevel.ONE); } else { try { ...
python
def render(self, namespace): '''Render a 'true' or (if available) 'false' block based on a boolean.''' if (self._isbool and namespace[self._evaluate]) or \ (not self._isbool and namespace[self._evaluate](*[namespace[arg] ...
python
def wmom(arrin, weightsin, inputmean=None, calcerr=False, sdev=False): """ NAME: wmom() PURPOSE: Calculate the weighted mean, error, and optionally standard deviation of an input array. CALLING SEQUENCE: wmean,werr = wmom(arr, weights, inputmean=None, calcerr=Fal...
python
def X_less(self): """Zoom out on the x-axis.""" self.parent.value('window_length', self.parent.value('window_length') / 2) self.parent.overview.update_position()
java
public static <T>CompletableFuture<T> completedExceptionally(Throwable cause) { CompletableFuture<T> result = new CompletableFuture<>(); result.completeExceptionally(cause); return result; }
python
def apply(self, func, **kwargs): """Apply some callable function to the data in this partition. Note: It is up to the implementation how kwargs are handled. They are an important part of many implementations. As of right now, they are not serialized. Args: f...
python
async def main(): """ Main code (synchronous requests) """ # Create Client from endpoint string in Duniter format client = Client(ES_CORE_ENDPOINT) # Get the current node (direct REST GET request) print("\nGET g1-test/block/current/_source:") response = await client.get('g1-test/block/c...
java
public Trigger<? super S> getLoadTrigger() { ForLoad<S> forLoad = mForLoad; return forLoad.isEmpty() ? null : forLoad; }
python
def get_reminders_per_page(self, per_page=1000, page=1, params=None): """ Get reminders per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param params: Search parameters. Default: {} :return: list """ ...