language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static Map<String, Object> toNullableMap(String value) { if (value == null) return null; try { Map<String, Object> map = _mapper.readValue((String) value, typeRef); return RecursiveMapConverter.toNullableMap(map); } catch (Exception ex) { return null; } }
java
@Override public Session get(String id) throws Exception { Session session; Exception ex = null; while (true) { session = doGet(id); if (sessionDataStore == null) { break; // can't load any session data so just return null or the session object ...
python
def save(self): """ Writes current changes to disk and flushes modified objects in the AAFObjectManager """ if self.mode in ("wb+", 'rb+'): if not self.is_open: raise IOError("file closed") self.write_reference_properties() self...
python
def _logfile_sigterm_handler(*_): # type: (...) -> None """Handle exit signals and write out a log file. Raises: SystemExit: Contains the signal as the return code. """ logging.error('Received SIGTERM.') write_logfile() print('Received signal. Please see the log file for more inform...
java
public static void sendMessage (DObject speakObj, ChatMessage msg) { if (speakObj == null) { log.warning("Dropping speak message, no speak obj '" + msg + "'.", new Exception()); return; } // post the message to the relevant object speakObj.postMessage(ChatCod...
python
def develop_link(options, info): ''' Prepare development environment. Perform the following steps: - Uninstall ``dmf_control_board_firmware`` if installed as Conda package. - Install build and run-time Conda dependencies. - Link working ``.pioenvs`` directory into Conda ``Library`` director...
python
def distributions_for_instances(self, data): """ Peforms predictions, returning the class distributions. :param data: the Instances to get the class distributions for :type data: Instances :return: the class distribution matrix, None if not a batch predictor :rtype: ndar...
java
boolean containsInstallOrOpen() { synchronized (reqQueueLockObject) { for (ServerRequest req : queue) { if (req != null && ((req instanceof ServerRequestRegisterInstall) || req instanceof ServerRequestRegisterOpen)) { return true; ...
java
protected void convertToHours(LinkedList<TimephasedWork> list) { for (TimephasedWork assignment : list) { Duration totalWork = assignment.getTotalAmount(); Duration workPerDay = assignment.getAmountPerDay(); totalWork = Duration.getInstance(totalWork.getDuration() / 60, TimeUni...
java
public Traverson follow(final List<String> rels, final Predicate<Link> predicate) { return follow(rels, predicate, emptyMap()); }
python
def textslice(self, start, end): """ Return a chunk referencing a slice of a scalar text value. """ return self._select(self._pointer.textslice(start, end))
java
public ServiceFuture<Void> beginExportDataAsync(String resourceGroupName, String name, ExportRDBParameters parameters, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(beginExportDataWithServiceResponseAsync(resourceGroupName, name, parameters), serviceCallback); }
python
def _partial_corr(self, x=None, y=None, covar=None, x_covar=None, y_covar=None, tail='two-sided', method='pearson'): """Partial and semi-partial correlation.""" stats = partial_corr(data=self, x=x, y=y, covar=covar, x_covar=x_covar, y_covar=y_covar, tail=tail, method=m...
python
def get(self, tag, default=None): """Get a metadata value. Each metadata value is referenced by a ``tag`` -- a short string such as ``'xlen'`` or ``'audit'``. In the sidecar file these tag names are prepended with ``'Xmp.pyctools.'``, which corresponds to a custom namespace in t...
python
def __supplement_lemma_frequency_lexicon(self, docs, hiddenWords, lexicon, amb_lexicon): """ Täiendab etteantud sagedusleksikone antud korpuse (docs) põhjal: *) yldist sagedusleksikoni, kus on k6ik lemmad, v.a. lemmad, mis kuuluvad nn peidetud sõnade hulka (hiddenWords); ...
java
protected static final String parseString(Source src) { char c = src.chars[src.idx]; if (src.idx <= src.last && c == '"') { src.idx++; } final int start = src.idx; loop: for (; src.idx <= src.last; src.idx++) { c = src.chars[src.idx]; if (c == '"') { break; } if (c == '\\') { ...
java
public static String getJavaCommand(final Path javaHome) { final Path resolvedJavaHome = javaHome == null ? findJavaHome() : javaHome; final String exe; if (resolvedJavaHome == null) { exe = "java"; } else { exe = resolvedJavaHome.resolve("bin").resolve("java").to...
java
private void fireOnDeclareQueue(ChannelEvent e) { List<EventListener> listeners = changes.getListenerList(AMQP); for (EventListener listener : listeners) { ChannelListener amqpListener = (ChannelListener)listener; amqpListener.onDeclareQueue(e); } }
java
public static aaauser_vpnintranetapplication_binding[] get(nitro_service service, String username) throws Exception{ aaauser_vpnintranetapplication_binding obj = new aaauser_vpnintranetapplication_binding(); obj.set_username(username); aaauser_vpnintranetapplication_binding response[] = (aaauser_vpnintranetapplic...
java
public static CommerceCountry fetchByG_A_First(long groupId, boolean active, OrderByComparator<CommerceCountry> orderByComparator) { return getPersistence() .fetchByG_A_First(groupId, active, orderByComparator); }
python
def check_zip(self, token): """ Returns true if token is matches a zip code (5 numbers). Zip code must be the last token in an address (minus anything removed during preprocessing such as --2 units. """ if self.zip is None: # print "last matched", self.last_matched ...
java
public static <T extends ViewTraverse<T>> Map<String, Object> replaceDataReferences( final Map<String, Object> input, final T currentContext, final BiFunction<Integer, String, T> viewMap, final Converter<String, String> converter, final MultiDataContext<T, Dat...
python
def fetchvalue(self, sql: str, *args) -> Optional[Any]: """Executes SQL; returns the first value of the first row, or None.""" row = self.fetchone(sql, *args) if row is None: return None return row[0]
python
def site_analysis(self, folder_name, site_install_mapping, end_date): """ Summarize site data into a single table. folder_name : str Folder where all site data resides. site_event_mapping : dic Dictionary of site name to date of installation. end_date ...
java
protected final int getIndex(long stamp) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getIndex", Long.valueOf(stamp)); int first = 0; int last = blockVector.size(); int index = linearSearch(stamp, first, last - 1); if (TraceComponent.isAnyT...
java
public static String schedule(String schedulingPattern, Runnable task) { return scheduler.schedule(schedulingPattern, task); }
java
protected void adjustIndexMap(Iterable<? extends Element> elements) { for (Element element : elements) { if (shouldAddToIndexMap(element)) { String name = utils.isPackage(element) ? utils.getPackageName((PackageElement)element) : utils....
python
def arches(self): """ Return a list of architectures for this task. :returns: a list of arch strings (eg ["ppc64le", "x86_64"]). The list is empty if this task has no arches associated with it. """ if self.method == 'image': return self.params[2] ...
java
public static void mkdirs(File f) { try { Files.createDirectories(f.toPath()); } catch (IOException e) { throw new RuntimeException("Could not create directory: " + e.getMessage(), e); } }
python
def get_resource_value(self, device_id, _resource_path, **kwargs): # noqa: E501 """Read from a resource # noqa: E501 Requests the resource value and when the response is available, an `AsyncIDResponse` json object is received in the notification channel. The preferred way to get resource values is to...
python
def read(self, size=None): """Read data from the file. """ if size is None: size = self.size - self.position else: size = min(size, self.size - self.position) buf = b"" while size > 0: while True: data, start, stop, off...
python
def update_custom_field_options(self, custom_field_key, new_options, keep_existing_options): """Updates the options of a multi-optioned custom field on this list.""" custom_field_key = quote(custom_field_key, '') body = { "Options": new_options, ...
python
def relation_operation(self): """ Returns the relation operation from the last node visited on the path, or `None`, if no node has been visited yet. """ if len(self.nodes) > 0: rel_op = self.nodes[-1].relation_operation else: rel_op = None ...
python
def _connect_db(self): """ Open database connection """ # Get database configuration db_args = {} db_args['host'] = self._cfg.get('nipapd', 'db_host') db_args['database'] = self._cfg.get('nipapd', 'db_name') db_args['user'] = self._cfg.get('nipapd', 'db_user') ...
java
public static void escapeHtml4(final char[] text, final int offset, final int len, final Writer writer) throws IOException { escapeHtml(text, offset, len, writer, HtmlEscapeType.HTML4_NAMED_REFERENCES_DEFAULT_TO_DECIMAL, HtmlEscapeLevel.LEVEL_2_ALL_NON_ASCII_PL...
java
public OvhFrontendTcp serviceName_tcp_frontend_POST(String serviceName, String[] allowedSource, String[] dedicatedIpfo, Long defaultFarmId, Long defaultSslId, Boolean disabled, String displayName, String port, Boolean ssl, String zone) throws IOException { String qPath = "/ipLoadbalancing/{serviceName}/tcp/frontend";...
java
public void divide(PairDblInt[] cols, double val) { for (int i = 0; i < numLabels; i++) { cols[i].first /= val; } }
python
def sign(self, message): """ >>> authlen = OmapiHMACMD5Authenticator.authlen >>> len(OmapiHMACMD5Authenticator(b"foo", 16*b"x").sign(b"baz")) == authlen True @type message: bytes @rtype: bytes @returns: a signature of length self.authlen """ return hmac.HMAC(self.key, message, digestmod=hashlib.md5)....
java
public synchronized static void read(int fd, ByteBuffer buffer) throws IOException{ byte[] data = read(fd); buffer.put(data); }
python
def Nishino_Yamazaki(x, rhol, rhog): r'''Calculates void fraction in two-phase flow according to the model presented in [1]_ as shown in [2]_. .. math:: \alpha = 1 - \left(\frac{1-x}{x}\frac{\rho_g}{\rho_l}\right)^{0.5} \alpha_h^{0.5} Parameters ---------- x : float ...
python
def validate(): """Validate metadata content. --- tags: - ddo consumes: - application/json parameters: - in: body name: body required: true description: Asset metadata. schema: type: object responses: 200: description: suc...
python
def check_user(user, password): """check the auth for user and password.""" return ((user == attowiki.user or attowiki.user is None) and (password == attowiki.password or attowiki.password is None))
java
@SuppressWarnings({"unchecked"}) public <T> T read(File jsonFile, Configuration configuration) throws IOException { notNull(jsonFile, "json file can not be null"); isTrue(jsonFile.exists(), "json file does not exist"); notNull(configuration, "jsonProvider can not be null"); FileInpu...
python
def auto_slug_on_insert(mapper, connection, target): """Generate a slug from :prop:`Entity.auto_slug` for new entities, unless slug is already set.""" if target.slug is None and target.name: target.slug = target.auto_slug
python
def set_peer_address(self, value=None, default=False, disable=False): """Configures the mlag peer-address value Args: value (str): The value to configure the peer-address default (bool): Configures the peer-address using the default keyword disable (b...
python
def _os_dispatch(func, *args, **kwargs): ''' Internal, dispatches functions by operating system ''' if __grains__['kernel'] in SUPPORTED_BSD_LIKE: kernel = 'bsd' else: kernel = __grains__['kernel'].lower() _os_func = getattr(sys.modules[__name__], '_{0}_{1}'.format(kernel, func)...
java
public void marshall(DeploymentOverview deploymentOverview, ProtocolMarshaller protocolMarshaller) { if (deploymentOverview == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deploymentOverview.getPen...
java
@Pure @Inline(value = "TextUtil.join($1, null, null, $2)", imported = {TextUtil.class}) public static String join(String joinText, Iterable<?> elements) { return join(joinText, null, null, elements); }
java
@Override public EnableLoggingResult enableLogging(EnableLoggingRequest request) { request = beforeClientExecution(request); return executeEnableLogging(request); }
python
def pretty_print_schedule(self, hyperband_schedule, describe_hyperband=True): """ Prints scheduler for user to read. """ print("=========================================") print("| Hyperband Schedule |") print("========================================="...
java
private static String guessDumpDate(String fileName) { Pattern p = Pattern.compile("([0-9]{8})"); Matcher m = p.matcher(fileName); if (m.find()) { return m.group(1); } else { logger.info("Could not guess date of the dump file \"" + fileName + "\". Defaulting to YYYYMMDD."); return "YYYYMMDD"; }...
python
def _fill_lookup_prop(self, requirements_properties): """Fills the polarion-lookup-method property.""" if not self._lookup_prop: raise Dump2PolarionException("Failed to set the 'polarion-lookup-method' property") etree.SubElement( requirements_properties, "pr...
python
def lsr_pairwise(n_items, data, alpha=0.0, initial_params=None): """Compute the LSR estimate of model parameters. This function implements the Luce Spectral Ranking inference algorithm [MG15]_ for pairwise-comparison data (see :ref:`data-pairwise`). The argument ``initial_params`` can be used to itera...
python
def is_in_expr(expr, find): """Returns True if `find` is a subtree of `expr`.""" return expr == find or (isinstance(expr, ExprNode) and expr.is_in(find))
java
static FirestoreException serverRejected(Status status, String message, Object... params) { return new FirestoreException(String.format(message, params), status); }
python
def annual_event_counts(kind='all'): """ Returns a QuerySet of dicts, each one with these keys: * year - a date object representing the year * total - the number of events of `kind` that year kind - The Event `kind`, or 'all' for all kinds (default). """ qs = Event.objects if ...
python
def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders data to HTML, using Django's standard template rendering. The template name is determined by (in order of preference): 1. An explicit .template_name set on the response. 2. An explicit .templat...
java
@Override public void removeAdapterItemAt(int index) { if(index == getSelectedItemPosition()) { Calendar time = getSelectedTime(); selectTemporary(new TimeItem(formatTime(time.get(Calendar.HOUR_OF_DAY), time.get(Calendar.MINUTE)), time, NO_ID)); } super.removeAdapterI...
python
def metadata_path(self, m_path): """Provide pointers to the paths of the metadata file Args: m_path: Path to metadata file """ if not m_path: self.metadata_dir = None self.metadata_file = None else: if not op.exists(m_path): ...
java
@Override public CommercePriceEntry fetchCommercePriceEntryByUuidAndGroupId( String uuid, long groupId) { return commercePriceEntryPersistence.fetchByUUID_G(uuid, groupId); }
python
def delete_consumer(self, consumer=None): """ Remove a specific consumer from a consumer group. :consumer: name of consumer to delete. If not provided, will be the default consumer for this stream. :returns: number of pending messages that the consumer had before ...
python
def styled_plot(*style_sheets): """Return a decorator that will apply matplotlib style sheets to a plot. ``style_sheets`` is a base set of styles, which will be ignored if ``no_base_style`` is set in the decorated function arguments. The style will further be overwritten by any styles in the ``style``...
python
def write_bytes(self, data): """ Open the file in bytes mode, write to it, and close the file. """ if not isinstance(data, six.binary_type): raise TypeError( 'data must be %s, not %s' % (six.binary_type.__class__.__name__, data.__class__.__name...
python
def prepare(self, node): """ Initialise values to prepare typing computation. Reorder functions to avoid dependencies issues and prepare typing computation setting typing values for Pythonic functions. """ def register(name, module): """ Recursively save fun...
python
def checker_for_type(t): """ Return "checker" function for the given type `t`. This checker function will accept a single argument (of any type), and return True if the argument matches type `t`, or False otherwise. For example: chkr = checker_for_type(int) assert chkr.check(123) i...
java
private static boolean isLearnerAndEvaluatorCompatible(Learner learner, PerformanceEvaluator evaluator) { return (learner instanceof RegressionLearner && evaluator instanceof RegressionPerformanceEvaluator) || (learner instanceof ClassificationLearner && evaluator instanceof ClassificationPerformanc...
java
public ServiceFuture<List<CloudJob>> listNextAsync(final String nextPageLink, final JobListNextOptions jobListNextOptions, final ServiceFuture<List<CloudJob>> serviceFuture, final ListOperationCallback<CloudJob> serviceCallback) { return AzureServiceFuture.fromHeaderPageResponse( listNextSinglePageA...
python
def save(self, path_info, checksum): """Save checksum for the specified path info. Args: path_info (dict): path_info to save checksum for. checksum (str): checksum to save. """ assert path_info["scheme"] == "local" assert checksum is not None pat...
java
public I_CmsListDirectAction getDirectAction(String actionId) { Iterator<I_CmsListDirectAction> it = m_directActions.iterator(); while (it.hasNext()) { I_CmsListDirectAction action = it.next(); if (action.getId().equals(actionId)) { return action; } ...
java
public void splitSpan(int n) { int x = (xKnots[n] + xKnots[n+1])/2; addKnot(x, getColor(x/256.0f), knotTypes[n]); rebuildGradient(); }
java
@JsonIgnore public String getErrorMessage(){ StringBuilder sb = new StringBuilder(); sb.append(exceptionCode.getCode()).append(":").append(exceptionCode.getMessage()); if(this.message != null && ! this.message.isEmpty()){ sb.append(" - ").append(message); } return...
python
def to_native_units(self, motor): """ Return the native speed measurement required to achieve desired rotations-per-second """ assert abs(self.rotations_per_second) <= motor.max_rps,\ "invalid rotations-per-second: {} max RPS is {}, {} was requested".format( motor...
python
def midnight(arg=None): """ convert date to datetime as midnight or get current day's midnight :param arg: string or date/datetime :return: datetime at 00:00:00 """ if arg: _arg = parse(arg) if isinstance(_arg, datetime.date): return datetime.datetime.combine(_arg, da...
python
def get(self, statediag): """ Args: statediag (list): The states of the PDA Returns: list: A reduced list of states using BFS """ if len(statediag) < 1: print 'PDA is empty and can not be reduced' return statediag newstatedi...
python
def simplex_averaging_matrix(simplices, weight=None, inverse=False): ''' Simplex_averaging_matrix(mtx) is equivalent to simplex_simmation_matrix, except that each row of the matrix is subsequently normalized such that all rows sum to 1. The optional argument inverse=True may be passed to indicate...
python
async def revoke(self, user_id, *permissions): " 取消用户(user_id)的权限(permission) " prefix = f"{self._prefix_perm}/{user_id}/" perm_names = [str(p) for p in permissions] checkings = [ KV.delete.txn(prefix + p, b'\0', prev_kv=True) for p in perm_names ] s...
java
public static Object invokeMethod(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (InvocationTargetException | IllegalAccessException e) { throw new IllegalStateException("Could not access method: " + method, ExceptionUtils.getRoo...
java
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { // Get the ReportService. ReportServiceInterface reportService = adManagerServices.get(session, ReportServiceInterface.class); // Create report query. ReportQuery reportQu...
java
@Override public EnableDirectoryResult enableDirectory(EnableDirectoryRequest request) { request = beforeClientExecution(request); return executeEnableDirectory(request); }
java
protected void setForm(final T bean, final AjaxRequestTarget target) { LOG.debug("Setting form to {}", bean); // update the model with the new bean formModel.setObject(bean); // add the form to the target target.add(form); // update the button updateSaveButton....
python
def check(self): """ Logic extracted from: http://developer.oanda.com/rest-live/orders/#createNewOrder """ for k in iter(self.__dict__.keys()): if k not in self.__allowed: raise TypeError("Parameter not allowed {}".format(k)) for k in self.__r...
java
public static String parseRevIDSuffix(String rev) { String result = null; int dashPos = rev.indexOf('-'); if (dashPos >= 0) { result = rev.substring(dashPos + 1); } return result; }
java
public Postcard withByteArray(@Nullable String key, @Nullable byte[] value) { mBundle.putByteArray(key, value); return this; }
python
def get_dict_from_response(response): """Check for errors in the response and return the resulting JSON.""" if getattr(response, '_resp') and response._resp.code > 400: raise OAuthResponseError( 'Application mis-configuration in Globus', None, response ) return response....
java
@Override public List<RevisionInternal> getRevisionHistory(RevisionInternal rev) { Document doc = getDocument(rev.getDocID()); if (doc == null) return null; try { try { if (!doc.selectRevID(rev.getRevID(), false)) return null; ...
java
@NonNull @Override public MutableDictionary setLong(@NonNull String key, long value) { return setValue(key, value); }
python
def mset(m_dict, keys, value, delimiter=':'): """ :param m_dict: A dictionary to set the value inside of :type m_dict: dict :param keys: A list of keys :type keys: str :param value: The value to set inside of the dictionary :param delimiter: The delimiter used in the keys list :type deli...
python
def find_input(self, stream): """Find the input that responds to this stream. Args: stream (DataStream): The stream to find Returns: (index, None): The index if found or None """ for i, input_x in enumerate(self.inputs): if input_x[0].matche...
java
public void incrementCount(List<K> l, K o, double count) { if (l.size() != depth - 1) { wrongDepth(); } GeneralizedCounter<K> next = this; for (K o2: l) { next.addToTotal(count); next = next.conditionalizeHelper(o2); } next.addToTotal(count); next.incrementCou...
python
def exp_rmspe(pred:Tensor, targ:Tensor)->Rank0Tensor: "Exp RMSE between `pred` and `targ`." pred,targ = flatten_check(pred,targ) pred, targ = torch.exp(pred), torch.exp(targ) pct_var = (targ - pred)/targ return torch.sqrt((pct_var**2).mean())
python
def _clean_data(api_response): ''' Returns the DATA response from a Linode API query as a single pre-formatted dictionary api_response The query to be cleaned. ''' data = {} data.update(api_response['DATA']) if not data: response_data = api_response['DATA'] data.upd...
python
def get_highest_values(self, count): """Get a list of the the x highest values of the Data Collection and their indices. This is useful for situations where one needs to know the times of the year when the largest values of a data collection occur. For example, there is a European dayi...
java
private static void loadLibraryResource( String resourceSubdirectoryName, String libraryName, String tempSubdirectoryName, String ... dependentLibraryNames) throws Throwable { // First try to load all dependent libraries, recursively for (String dependentLibrar...
python
def to_power_basis(nodes1, nodes2): """Compute the coefficients of an **intersection polynomial**. .. note:: This assumes that the degree of the curve given by ``nodes1`` is less than or equal to the degree of that given by ``nodes2``. Args: nodes1 (numpy.ndarray): The nodes in the ...
python
def getrawtransaction(self, txid: str, decrypt: int=0) -> dict: '''Returns raw transaction representation for given transaction id. decrypt can be set to 0(false) or 1(true).''' q = 'getrawtransaction?txid={txid}&decrypt={decrypt}'.format(txid=txid, decrypt=decrypt) return cast(dict, s...
python
def parent(self): """Document that owns the current collection. Returns: Optional[~.firestore_v1beta1.document.DocumentReference]: The parent document, if the current collection is not a top-level collection. """ if len(self._path) == 1: r...
java
public final int addChild (Task<E> child) { int index = addChildToTask(child); if (tree != null && tree.listeners != null) tree.notifyChildAdded(this, index); return index; }
java
@Override public int mbcCaseFold(int flag, byte[]bytes, IntHolder pp, int end, byte[]fold) { int p = pp.value; int foldP = 0; int code = mbcToCode(bytes, p, end); int len = length(bytes, p, end); pp.value += len; if (Config.USE_UNICODE_CASE_FOLD_TURKISH_AZERI) { ...
python
def getAllNodes(self): ''' getAllNodes - Get every element @return TagCollection<AdvancedTag> ''' ret = TagCollection() for rootNode in self.getRootNodes(): ret.append(rootNode) ret += rootNode.getAllChildNodes() return ret
java
public static Properties readTDConf() { Properties p = new Properties(); File file = new File(System.getProperty("user.home", "./"), String.format(".td/td.conf")); if (!file.exists()) { logger.warn(String.format("config file %s is not found", file)); return p; ...