language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _put_many(self, items: Iterable[DtoObject], cls): """Puts many items into the database. Updates lastUpdate column for each of them""" if cls._dto_type in self._expirations and self._expirations[cls._dto_type] == 0: # The expiration time has been set to 0 -> shoud not be cached ...
java
boolean update(ServiceNamespace namespace, long[] newVersions, int replicaIndex) { return getFragmentVersions(namespace).update(newVersions, replicaIndex); }
python
def set_account_username(self, account, old_username, new_username): """ Account's username was changed. """ self._delete_account(account, old_username) self._save_account(account, new_username)
java
@Override public ContainerConfiguration createDeployableConfiguration() throws Exception { ContainerConfiguration config = SecurityActions.newInstance( deployableContainer.getConfigurationClass(), new Class<?>[0], new Object[0]); MapObject.populate(config, containerConfiguration.getConta...
python
def create_from_ll(cls, lls:LabelLists, bs:int=64, val_bs:int=None, ds_tfms:Optional[TfmList]=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collection[Callable]]=None, device:torch.device=None, test:Optional[PathOrStr]=None, collate_fn:Callable=data_collate, size:int=None, no_che...
python
def _get_unique(self, *args): """Generate a unique value using the assigned maker""" # Generate a unique values value = '' attempts = 0 while True: attempts += 1 value = self._maker(*args) if value not in self._used_values: bre...
python
def fit(self, X, y=None, **kwargs): """ Fits the corpus to the appropriate tag map. Text documents must be tokenized & tagged before passing to fit. Parameters ---------- X : list or generator Should be provided as a list of documents or a generator ...
python
def get_session_conf_dir(self, cleanup=False): """ Tries to find the session configuration directory by looking in ~/.dnanexus_config/sessions/<PID>, where <PID> is pid of the parent of this process, then its parent, and so on. If none of those exist, the path for the immediate parent is...
python
def hex2web(hex): """Converts HEX representation to WEB :param rgb: 3 hex char or 6 hex char string representation :rtype: web string representation (human readable if possible) WEB representation uses X11 rgb.txt to define conversion between RGB and english color names. Usage ===== ...
python
def codingthreads(self): """ Find CDS features in .gff files to filter out non-coding sequences from the analysis """ printtime('Extracting CDS features', self.start) # Create and start threads for i in range(self.cpus): # Send the threads to the appropriate d...
python
def _process(self, obj, key=None): """ Generates a categorical 2D aggregate by inserting NaNs at all cross-product locations that do not already have a value assigned. Returns a 2D gridded Dataset object. """ if isinstance(obj, Dataset) and obj.interface.gridded: ...
python
def transform(self, X): """ Args: X: DataFrame with NaN's Returns: Dictionary with one key - 'X' corresponding to given DataFrame but without nan's """ if self.fill_missing: X = self.filler.complete(X) return {'X': X}
java
public static PCM loadPCM(String filename) throws IOException { PCMContainer pcmContainer = loadPCMContainer(filename); // Get the PCM PCM pcm = pcmContainer.getPcm(); return pcm ; }
java
public long getLong(String propertyName, long defaultValue) { Object obj = get(propertyName); return obj != null ? ((Number) get(propertyName)).longValue() : defaultValue; }
python
def reverse_complement_sequences(records): """ Transform sequences into reverse complements. """ logging.info('Applying _reverse_complement_sequences generator: ' 'transforming sequences into reverse complements.') for record in records: rev_record = SeqRecord(record.seq.rev...
java
public static final Color hex2RGB(final String hex) { String r, g, b; final int len = hex.length(); if (len == 7) { r = hex.substring(1, 3); g = hex.substring(3, 5); b = hex.substring(5, 7); } else if (len == 4) { ...
java
public boolean isLoggable(Level level) { if (level == null) { throw new NullPointerException(); } // performance-sensitive method: use two monomorphic call-sites JavaLoggerProxy jlp = javaLoggerProxy; return jlp != null ? jlp.isLoggable(level) : loggerProxy.isLoggable...
python
def get_new_service_instance_stub(service_instance, path, ns=None, version=None): ''' Returns a stub that points to a different path, created from an existing connection. service_instance The Service Instance. path Path of the new stub. ns ...
java
private synchronized void getAndSetRESTHandlerContainer(HttpServletRequest request) throws ServletException { if (REST_HANDLER_CONTAINER == null) { //Get the bundle context HttpSession session = request.getSession(); ServletContext sc = session.getServletContext(); ...
python
def add_route_for(cls, _name, rule, **options): """ Add a route for an existing method or view. Useful for modifying routes that a subclass inherits from a base class:: class BaseView(ClassView): def latent_view(self): return 'latent-view' ...
python
def migrate_abci_chain(self): """Generate and record a new ABCI chain ID. New blocks are not accepted until we receive an InitChain ABCI request with the matching chain ID and validator set. Chain ID is generated based on the current chain and height. `chain-X` => `chain-X-migra...
python
def send(self, stat, value, rate=1): """Send message to backend.""" if rate < 1 and random() > rate: return message = self.build_message(stat, value) if not message: return if self.pipeline is None: return self._send(message) self.pi...
java
public void setExtractionCacheMaxAge(String extractionCacheMaxAge) { try { setExtractionCacheMaxAge(Float.parseFloat(extractionCacheMaxAge)); } catch (NumberFormatException e) { LOG.error( Messages.get().getBundle().key( Messages.LOG_PARSE_EXT...
java
public void update(Viewer viewer) { x = (int) viewer.getX(); y = (int) viewer.getY() - viewer.getViewY(); height = viewer.getHeight(); }
java
public TabShowingAction show(final Tab tabToShow, final LmlTabbedPaneListener listener) { this.tabToShow = tabToShow; this.listener = listener; shown = false; return this; }
python
def new_add_recovery_transaction(self, ont_id: str, pub_key: str or bytes, b58_recovery_address: str, b58_payer_address: str, gas_limit: int, gas_price: int): """ This interface is used to generate a Transaction object which is used to add the recovery. :par...
java
public void logMapTaskStarted(TaskAttemptID taskAttemptId, long startTime, String trackerName, int httpPort, String taskType) { if (disableHistory) { return; } JobID id = taskAttemptId.getJobID(); if (!this.jobId.equals(id)) { ...
python
def _build_session_groups(self): """Returns a list of SessionGroups protobuffers from the summary data.""" # Algorithm: We keep a dict 'groups_by_name' mapping a SessionGroup name # (str) to a SessionGroup protobuffer. We traverse the runs associated with # the plugin--each representing a single sessio...
java
public static double blackScholesOptionDelta( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionMaturity < 0) { return 0; } else if(initialStockValue < 0) { // We use Indicator(S>K) = 1 - Indicator(-S>-K) return 1 - bl...
java
private List<MatrixQueryData.QName> splitMatrixKeysFromRaw(String raw) { LinkedList<MatrixQueryData.QName> result = new LinkedList<>(); String[] split = raw.split(","); for (String s : split) { String[] nameSplit = s.trim().split(":", 2); MatrixQueryData.QName qname = new MatrixQueryData....
python
def cube(cls, center=[0,0,0], radius=[1,1,1]): """ Construct an axis-aligned solid cuboid. Optional parameters are `center` and `radius`, which default to `[0, 0, 0]` and `[1, 1, 1]`. The radius can be specified using a single number or a list of three numbers, one for each axis. ...
java
public int readRawVarint32() throws IOException { byte tmp = readRawByte(); if (tmp >= 0) { return tmp; } int result = tmp & 0x7f; if ((tmp = readRawByte()) >= 0) { result |= tmp << 7; } else { result |= (tmp & 0x7f) << 7; if ((tmp = readRawByte()) >= 0) { result ...
java
@Override public void init() { // init super super.init(); // check: at least one search added if (searches.isEmpty()) { throw new SearchException("Cannot initialize basic parallel search: " + "no subsearches added for concurrent execut...
java
public static void init(com.typesafe.config.Config conf) { try { config = ConfigFactory.load().getConfig(PARA); if (conf != null) { config = conf.withFallback(config); } configMap = new HashMap<>(); for (Map.Entry<String, ConfigValue> con : config.entrySet()) { if (con.getValue().valueType() ...
python
def get_comments_for_reference_on_date(self, reference_id, from_, to): """Gets a list of all comments corresponding to a reference ``Id`` and effective during the entire given date range inclusive but not confined to the date range. arg: reference_id (osid.id.Id): a reference ``Id`` arg: ...
java
public Serializer getSerializer(Class cl) throws HessianProtocolException { if (ObjectName.class.equals(cl)) { return new StringValueSerializer(); } return null; }
python
def receive(self, decode=True): """ Receive from socket, authenticate and decode payload """ payload = self.socket.recv() payload = self.verify(payload) if decode: payload = self.decode(payload) return payload
java
public DeleteLoadBalancerListenersRequest withLoadBalancerPorts(Integer... loadBalancerPorts) { if (this.loadBalancerPorts == null) { setLoadBalancerPorts(new com.amazonaws.internal.SdkInternalList<Integer>(loadBalancerPorts.length)); } for (Integer ele : loadBalancerPorts) { ...
python
def perform_authorization(self): """ Check if the request should be permitted. Raises an appropriate exception if the request is not permitted. """ for permission in self.permissions: if not permission.has_permission(): if request.user: ...
python
def prefix_dict_keys(d: Dict[str, Any], prefix: str) -> Dict[str, Any]: """ Returns a dictionary that's a copy of as ``d`` but with ``prefix`` prepended to its keys. """ result = {} # type: Dict[str, Any] for k, v in d.items(): result[prefix + k] = v return result
java
protected static DateWriter date(Date date) { return date((date == null) ? null : new ICalDate(date)); }
python
def run(): """ Start the BaseHTTPServer and serve requests forever. """ server_address = (args.listen_addr, args.listen_port) httpd = YHSM_VALServer(server_address, YHSM_VALRequestHandler) my_log_message(args, syslog.LOG_INFO, "Serving requests to 'http://%s:%s%s' (YubiHSM: '%s')" \ ...
java
@Override public EClass getIfcArcIndex() { if (ifcArcIndexEClass == null) { ifcArcIndexEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(1111); } return ifcArcIndexEClass; }
java
@Nonnull public ParametersAction merge(@CheckForNull ParametersAction overrides) { if (overrides == null) { return new ParametersAction(parameters, this.safeParameters); } ParametersAction parametersAction = createUpdated(overrides.parameters); Set<String> safe = new Tree...
java
public static QueryBasedHivePublishEntity deserializePublishCommands(State state) { QueryBasedHivePublishEntity queryBasedHivePublishEntity = GSON.fromJson(state.getProp(HiveAvroORCQueryGenerator.SERIALIZED_PUBLISH_TABLE_COMMANDS), QueryBasedHivePublishEntity.class); return queryBasedHivePub...
python
def _load_hooks(path): """Load hook module and register signals. :param path: Absolute or relative path to module. :return: module """ module = imp.load_source(os.path.splitext(os.path.basename(path))[0], path) if not check_hook_mechanism_is_intact(module): # no hooks - do nothing ...
python
def trunking(self): """ Access the Trunking Twilio Domain :returns: Trunking Twilio Domain :rtype: twilio.rest.trunking.Trunking """ if self._trunking is None: from twilio.rest.trunking import Trunking self._trunking = Trunking(self) retur...
java
public static String signHmacSHA1(final String source, final String secret) { try { final Mac mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA1")); final byte[] signData = mac.doFinal(source.getBytes("UTF-8")); retu...
python
def lookup_zone_exception(self, callsign, timestamp=datetime.utcnow().replace(tzinfo=UTC)): """ Returns a CQ Zone if an exception exists for the given callsign Args: callsign (string): Amateur radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) ...
python
def _list_merge(src, dest): """ Merge the contents coming from src into dest :param src: source dictionary :param dest: destination dictionary """ for k in src: if type(src[k]) != dict: dest[k] = src[k] else: # --- # src could have a key whose...
python
def add_derived_property(cls, getter_function, name=None): """ Register a user-defined derived property Parameters ---------- getter_function : function Function that fetches the result of the user-defined derived property name : str Derived prope...
java
public static InsertIntoTable newInstance(String databaseName, String tableName, HiveConf conf) { TableDataBuilder builder = new TableDataBuilder(getHCatTable(databaseName, tableName, conf)); TableDataInserter inserter = new TableDataInserter(databaseName, tableName, conf); return new InsertIntoTable(builde...
java
public void write(String outputLocation, String format) throws ReportException { Format reportFormat = null; try { reportFormat = Format.valueOf(format.toUpperCase()); } catch (IllegalArgumentException ex) { LOGGER.trace("ignore this exception", ex); } if...
python
def json_parse(self, response): """ Wraps and abstracts response validation and JSON parsing to make sure the user gets the correct response. :param response: The response returned to us from the request :returns: a dict of the json response """ try: ...
python
def save(self, model_filename, optimizer_filename): """ Save the state of the model & optimizer to disk """ serializers.save_hdf5(model_filename, self.model) serializers.save_hdf5(optimizer_filename, self.optimizer)
python
def load(filename, ureg='pimms'): ''' pimms.load(filename) loads a pimms-formatted save-file from the given filename, which may optionaly be a string. By default, this function forces all quantities (via the pint module) to be loaded using the pimms.units unit registry; the option ureg can change ...
java
@Override public void debug(String message, Throwable throwable) { if(this.logger.isDebugEnabled()) { this.logger.debug(buildMessage(message), throwable); } }
java
public boolean hasReplyCode() { return getHeader(FtpMessageHeaders.FTP_REPLY_CODE) != null || Optional.ofNullable(commandResult) .map(result -> StringUtils.hasText(result.getReplyCode())) .orElse(false); }
java
@GET public Response getResource(@PathParam(JaxRxConstants.SYSTEM) final String system, @PathParam(JaxRxConstants.RESOURCE) final String resource, @Context final UriInfo uri, @Context final HttpHeaders headers) { return getResource(system, uri, resource, headers); }
python
def to_native(self): """ Convert to a native Python `datetime.time` value. """ h, m, s = self.hour_minute_second s, ns = nano_divmod(s, 1) ms = int(nano_mul(ns, 1000000)) return time(h, m, s, ms)
java
public String createToken(String response) throws IllegalArgumentException, ProtocolVersionException { final Response decodedResponse; final Challenge challenge; decodedResponse = CrtAuthCodec.deserializeResponse(decode(response)); challenge = CrtAuthCodec.deserializeChallengeAuthenticated( ...
python
def walk(self, dispatcher, node): """ Walk through the node with a custom dispatcher for extraction of details that are required. """ deferrable_handlers = { Declare: self.declare, Resolve: self.register_reference, } layout_handlers = { ...
python
def query_feature_states_for_default_scope(self, query, user_scope): """QueryFeatureStatesForDefaultScope. [Preview API] Get the states of the specified features for the default scope :param :class:`<ContributedFeatureStateQuery> <azure.devops.v5_0.feature_management.models.ContributedFeatureSta...
java
protected void initialize(ClassTraversal traversal) { Listener listener; listener = new Listener(); traversal.traverse(listener); m_NameCache = listener.getNameCache(); }
python
def check_nocycles(Adj, verbosity=2): """\ Checks that there are no cycles in graph described by adjacancy matrix. Parameters ---------- Adj (np.array): adjancancy matrix of dimension (dim, dim) Returns ------- True if there is no cycle, False otherwise. """ dim = Adj.shape[0] ...
python
def UpsertPermission(self, user_link, permission, options=None): """Upserts a permission for a user. :param str user_link: The link to the user entity. :param dict permission: The Azure Cosmos user permission to upsert. :param dict options: The reques...
python
def char_conv(out): """ Convert integer vectors to character vectors for batch. """ out_conv = list() for i in range(out.shape[0]): tmp_str = '' for j in range(out.shape[1]): if int(out[i][j]) >= 0: tmp_char = int2char(int(out[i][j])) if in...
java
public Component unregister(Object providerHolder) throws ProviderMissingException { Method[] methods = providerHolder.getClass().getDeclaredMethods(); for (Method method : methods) { if (method.isAnnotationPresent(Provides.class)) { Class<?> returnType = method.getReturnType...
java
public static Object getDefaultValue(Class cl) { if (cl.isArray()) {// 处理数组 return Array.newInstance(cl.getComponentType(), 0); } else if (cl.isPrimitive() || primitiveValueMap.containsKey(cl)) { // 处理原型 return primitiveValueMap.get(cl); } else { return newIns...
python
def subtract_params(param_list_left, param_list_right): """Subtract two lists of parameters :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays """ res = [] for x, y in zip(param_list_left, param_list_right): res.a...
python
def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.op...
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "GeocentricCRS", substitutionHeadNamespace = "http://www.opengis.net/gml", substitutionHeadName = "_CoordinateReferenceSystem") public JAXBElement<GeocentricCRSType> createGeocentricCRS(GeocentricCRSType value) { return new JAXBElement<Geocent...
java
private Element getRootElement(String fileName) throws IOException, SAXException, ParserConfigurationException { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setIgnoringComments(true); DocumentBuilder builder = docBuilderFactory.newDocumentBu...
java
@Override public JsMessage receive(long originalTimeout, TransactionCommon transaction) throws SISessionUnavailableException, SIIncorrectCallException, SIResourceException, SINotPossibleInCurrentConfiguratio...
java
public static CommerceAccount fetchByU_T_First(long userId, int type, OrderByComparator<CommerceAccount> orderByComparator) { return getPersistence().fetchByU_T_First(userId, type, orderByComparator); }
java
public Optional<Long> getDuration(final String path, final TimeUnit unit) { return config.hasPath(requireNonNull(path, "A non-null path expected")) ? ofNullable(config.getDuration(path, requireNonNull(unit, "A non-null unit expected"))) : empty(); }
python
def list_keys(self): ''' Return a dict of managed keys and what the key status are ''' key_dirs = self._check_minions_directories() ret = {} for dir_ in key_dirs: if dir_ is None: continue ret[os.path.basename(dir_)] = [] ...
java
public static Object setProperty( String key, String value ) { return prp.setProperty( key, value ); }
java
public String getEstimatedTimeRemaining(double theCompleteToDate, double theTotal) { double millis = getMillis(); long millisRemaining = (long) (((theTotal / theCompleteToDate) * millis) - (millis)); return formatMillis(millisRemaining); }
java
public static void updateLog4jConfiguration(Class<?> targetClass, String log4jFileName) throws IOException { final Closer closer = Closer.create(); try { final InputStream inputStream = closer.register(targetClass.getResourceAsStream("/" + log4jFileName)); final Properties originalProperties =...
java
public CompletableFuture<BackupResponse> backup(BackupRequest request) { logRequest(request); return CompletableFuture.completedFuture(logResponse(BackupResponse.error())); }
python
def get_value(d, name, field): """Handle gets from 'multidicts' made of lists It handles cases: ``{"key": [value]}`` and ``{"key": value}`` """ multiple = core.is_multiple(field) value = d.get(name, core.missing) if value is core.missing: return core.missing if multiple and value is...
java
@BetaApi public final ListHealthChecksPagedResponse listHealthChecks(String project) { ListHealthChecksHttpRequest request = ListHealthChecksHttpRequest.newBuilder().setProject(project).build(); return listHealthChecks(request); }
java
void appendProperty( @Nonnull String name, @Nonnull Expression value ) { if( output == null ) { throw new LessException( "Properties must be inside selector blocks, they cannot be in the root." ); } insets(); name = SelectorUtils.replacePlaceHolder( this, name, value ); ...
python
def bind_unix_socket(file_, mode=0o600, backlog=_DEFAULT_BACKLOG): """Creates a listening unix socket. If a socket with the given name already exists, it will be deleted. If any other file with that name exists, an exception will be raised. Returns a socket object (not a list of socket objects lik...
java
public static RenameHandler create(boolean loadFromClasspath) { RenameHandler handler = new RenameHandler(); if (loadFromClasspath) { handler.loadFromClasspath(); } return handler; }
java
public void marshall(UpgradeAppliedSchemaRequest upgradeAppliedSchemaRequest, ProtocolMarshaller protocolMarshaller) { if (upgradeAppliedSchemaRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
python
def to_dense(self): """ Convert to dense DataFrame Returns ------- df : DataFrame """ data = {k: v.to_dense() for k, v in self.items()} return DataFrame(data, index=self.index, columns=self.columns)
java
public Observable<Page<SiteInner>> changeVnetNextAsync(final String nextPageLink) { return changeVnetNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<SiteInner>>, Page<SiteInner>>() { @Override public Page<SiteInner> call(ServiceResponse<...
java
@Override public void seek(long pos) throws IOException { int n = (int) (real_pos - pos); if (n >= 0 && n <= buf_end) { buf_pos = buf_end - n; } else { super.seek(pos); invalidate(); } }
java
public static void collect() { AsyncTask.execute(new Runnable() { @Override public void run() { devicePropertiesCollector.collect(); appStateCollector.collect(); } }); }
java
public static CmsExtractionResult extractXmlContent(CmsObject cms, CmsResource resource, I_CmsSearchIndex index) throws CmsException { return extractXmlContent(cms, resource, index, null); }
python
def grid(self, start=None, stop=None, St=None, **kwargs): """Grid-like representation of payoff & profit structure. Returns ------- tuple Tuple of `St` (price at expiry), `payoffs`, `profits`. """ lb = 0.75 rb = 1.25 if not any((st...
python
def smart_attributes(dev, attributes=None, values=None): ''' Fetch SMART attributes Providing attributes will deliver only requested attributes Providing values will deliver only requested values for attributes Default is the Backblaze recommended set (https://www.backblaze.com/blog/hard-drive-...
java
@Override public final boolean callProcedureWithTimeout( ProcedureCallback callback, int batchTimeout, String procName, Object... parameters) throws IOException, NoConnectionsException { //Time unit doesn't matter in this case since the...
java
@SuppressWarnings({ "unchecked", "rawtypes" }) private AvroRecordBuilderFactory<E> buildAvroRecordBuilderFactory( Schema schema) { if (specific) { Class<E> specificClass; String className = schema.getFullName(); try { specificClass = (Class<E>) Class.forName(className); } cat...
java
private static void addBaseFilepath(String baseFilePath) { FileManager fm = EldaFileManager.get(); for (Iterator<Locator> il = fm.locators(); il.hasNext(); ) { Locator l = il.next(); if (l instanceof LocatorFile) if (((LocatorFile) l).getName().equals(baseFilePath...
python
def batch_get_pay_giftcard(self, effective=True, offset=0, count=10): """ 批量查询支付后投放卡券的规则 详情请参见 https://mp.weixin.qq.com/wiki?id=mp1466494654_K9rNz :param effective: 是否仅查询生效的规则 :type effective: bool :param offset: 起始偏移量 :type offset: int :param co...
java
private void fireOnDeclareExchange(ChannelEvent e) { List<EventListener> listeners = changes.getListenerList(AMQP); for (EventListener listener : listeners) { ChannelListener amqpListener = (ChannelListener)listener; amqpListener.onDeclareExchange(e); } }
java
private void createLNode(VNode vNode, VNode parent) { LNode lNode = layout.newNode(vNode); lNode.type = vNode.glyph.getClazz(); lNode.label = vNode.glyph.getId(); LGraph rootLGraph = layout.getGraphManager().getRoot(); //Add corresponding nodes to corresponding maps ...