language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Trivial private IdentifierType createIdentiferFromLdapEntry(LdapEntry ldapEntry) throws WIMException { IdentifierType outId = new IdentifierType(); outId.setUniqueName(ldapEntry.getUniqueName()); outId.setExternalId(ldapEntry.getExtId()); outId.setExternalName(ldapEntry.getDN()); ...
java
public void updateString(int columnIndex, String x) throws SQLException { startUpdate(columnIndex); preparedStatement.setParameter(columnIndex, x); }
java
private void readNameToNode(CoronaSerializer coronaSerializer) throws IOException { coronaSerializer.readField("nameToNode"); // Expecting the START_OBJECT token for nameToNode coronaSerializer.readStartObjectToken("nameToNode"); JsonToken current = coronaSerializer.nextToken(); while (current !...
python
def resolve_image_id(name): ''' .. versionadded:: 2018.3.0 Given an image name (or partial image ID), return the full image ID. If no match is found among the locally-pulled images, then ``False`` will be returned. CLI Examples: .. code-block:: bash salt myminion docker.resolve_i...
python
def get_free_energy(self, temperature, pressure = 'Default', electronic_energy = 'Default', overbinding = True): """Returns the internal energy of an adsorbed molecule. Parameters ---------- temperature : numeric temperature in K electronic_energy : numeric ...
java
public LimitedOutputStream createFile() throws IOException { if (bytesUsed.get() >= maxBytesUsed) { throw new TemporaryStorageFullException(maxBytesUsed); } synchronized (files) { if (closed) { throw new ISE("Closed"); } FileUtils.forceMkdir(storageDirectory); if (!...
java
public static String getPrefixedUri(String prefix, String uri) { String localURI = uri; if (localURI.length() > 0) { // Put a / between the prefix and the tail only if: // the prefix does not ends with a / // the tail does not start with a / // the tail st...
java
public static ContentType create( final String mimeType, final String charset) throws UnsupportedCharsetException { return create(mimeType, charset != null ? Charset.forName(charset) : null); }
python
def align_dna(job, fastqs, sample_type, univ_options, bwa_options): """ A wrapper for the entire dna alignment subgraph. :param list fastqs: The input fastqs for alignment :param str sample_type: Description of the sample to inject into the filename :param dict univ_options: Dict of universal optio...
java
public static void readLine(final String format, final String line, final Map<String, Map<String, Double>> mapMetricUserValue, final Set<String> usersToAvoid) { String[] toks = line.split("\t"); // default (also trec_eval) format: metric \t user|all \t value if (format.equals("default")) { ...
python
def publishChatroom(self, fromUserId, toChatroomId, objectName, content): """ 发送聊天室消息方法(一个用户向聊天室发送消息,单条消息最大 128k。每秒钟限 100 次。) 方法 @param fromUserId:发送人用户 Id。(必传) @param toChatroomId:接收聊天室Id,提供多个本参数可以实现向多个聊天室发送消息。(必传) @param txtMessage:发送消息内容(必传) @return code:返回码,200 ...
java
public EClass getGCLINE() { if (gclineEClass == null) { gclineEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(455); } return gclineEClass; }
java
public static void write(final Hml data, final Writer writer) throws IOException { checkNotNull(data); checkNotNull(writer); try { JAXBContext context = JAXBContext.newInstance(Hml.class); Marshaller marshaller = context.createMarshaller(); SchemaFactory sche...
java
public final ProtoParser.option_entry_return option_entry(Proto proto, HasOptions ho) throws RecognitionException { ProtoParser.option_entry_return retval = new ProtoParser.option_entry_return(); retval.start = input.LT(1); Object root_0 = null; Token id=null; Token fid=null; ...
java
public double[] get(T object) { double[] v = map.get(object); if(v == null) { return null; } return v.clone(); }
python
def p_scalar__folded(self, p): """ scalar : B_FOLD_START scalar_group B_FOLD_END """ scalar_group = ''.join(p[2]) folded_scalar = fold(dedent(scalar_group)).rstrip() p[0] = ScalarDispatch('%s\n' % folded_scalar, cast='str')
python
def addPriority(self, objectName): """ 添加聊天室消息优先级方法 方法 @param objectName:低优先级的消息类型,每次最多提交 5 个,设置的消息类型最多不超过 20 个。(必传) @return code:返回码,200 为正常。 @return errorMessage:错误信息。 """ desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", ...
python
def restart(self): """ Restart all the processes """ Global.LOGGER.info("restarting the flow manager") self._stop_actions() # stop the old actions self.actions = [] # clear the action list self._start_actions() # start the configured actions Glo...
java
public boolean validOptions(List<String[]> optlist) { Object retVal; String options[][] = optlist.toArray(new String[optlist.length()][]); String methodName = "validOptions"; DocErrorReporter reporter = messager; Class<?>[] paramTypes = { String[][].class, DocErrorReporter.class ...
python
def _init(self): """ Finalize the initialization of the RlzsAssoc object by setting the (reduced) weights of the realizations. """ if self.num_samples: assert len(self.realizations) == self.num_samples, ( len(self.realizations), self.num_samples) ...
java
private static <T> T unmarshalBaseEntity(BaseEntity<?> nativeEntity, Class<T> entityClass) { if (nativeEntity == null) { return null; } Unmarshaller unmarshaller = new Unmarshaller(nativeEntity, entityClass); return unmarshaller.unmarshal(); }
python
def multiple_replace(text: str, rep: Dict[str, str]) -> str: """ Returns a version of ``text`` in which the keys of ``rep`` (a dict) have been replaced by their values. As per http://stackoverflow.com/questions/6116978/python-replace-multiple-strings. """ rep = dict((re.escape(k), v) for k,...
python
def find_route_by_view_name(self, view_name, name=None): """Find a route in the router based on the specified view name. :param view_name: string of view name to search by :param kwargs: additional params, usually for static files :return: tuple containing (uri, Route) """ ...
java
public OvhOrder license_plesk_serviceName_upgrade_duration_POST(String serviceName, String duration, OvhOrderableAntispamEnum antispam, OvhOrderableAntivirusEnum antivirus, OvhPleskApplicationSetEnum applicationSet, OvhOrderablePleskDomainNumberEnum domainNumber, OvhOrderablePleskLanguagePackEnum languagePackNumber, Bo...
python
def get_timerange_formatted(self, now): """ Return two ISO8601 formatted date strings, one for timeMin, the other for timeMax (to be consumed by get_events) """ later = now + datetime.timedelta(days=self.days) return now.isoformat(), later.isoformat()
java
public void showSuggest() { assert(getText() != null); lastWord = getText().trim(); //autoSuggestProvider.getSuggestion(lastWord); if (!getText().toLowerCase().contains(lastWord.toLowerCase())) { suggestions.clear(); } if (matcher != null) { matcher.setStop(); } matcher = new SuggestionFetch...
python
def highlightSubsequence(sequence, x1, x2, start=' [', stop = '] ') : """returns a sequence where the subsequence in [x1, x2[ is placed in bewteen 'start' and 'stop'""" seq = list(sequence) print x1, x2-1, len(seq) seq[x1] = start + seq[x1] seq[x2-1] = seq[x2-1] + stop return ''.join(seq)
java
@SuppressWarnings("unchecked") public <T> T getSet(Object key, Object value) { Jedis jedis = getJedis(); try { return (T)valueFromBytes(jedis.getSet(keyToBytes(key), valueToBytes(value))); } finally {close(jedis);} }
python
def export_avg_losses(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ dskey = ekey[0] oq = dstore['oqparam'] dt = oq.loss_dt() name, value, tags = _get_data(dstore, dskey, oq.hazard_stats().items()) writer = writers.Csv...
python
def locateConvergencePoint(stats): """ Walk backwards through stats until you locate the first point that diverges from target overlap values. We need this to handle cases where it might get to target values, diverge, and then get back again. We want the last convergence point. """ n = len(stats) for ...
python
def from_node(index, name, session, data): """ >>> Member.from_node(-1, '', '', '{"conn_url": "postgres://foo@bar/postgres"}') is not None True >>> Member.from_node(-1, '', '', '{') Member(index=-1, name='', session='', data={}) """ if data.startswith('postgres'):...
python
def fit_naa(self, reject_outliers=3.0, fit_lb=1.8, fit_ub=2.4, phase_correct=True): """ Fit a Lorentzian function to the NAA peak at ~ 2 ppm. Example of fitting inverted peak: Foerster et al. 2013, An imbalance between excitatory and inhibitory neurotransmitters in amyo...
java
public boolean isAurora() { if (haMode == HaMode.AURORA) { return true; } if (addresses != null) { for (HostAddress hostAddress : addresses) { Matcher matcher = AWS_PATTERN.matcher(hostAddress.host); if (matcher.find()) { return true; } } } return ...
python
def get_normal_image(self, page=1): """ Downloads and returns the normal sized image of a single page. The page kwarg specifies which page to return. One is the default. """ url = self.get_normal_image_url(page=page) return self._get_url(url)
python
def create_new_csv(samples, args): """create csv file that can be use with bcbio -w template""" out_fn = os.path.splitext(args.csv)[0] + "-merged.csv" logger.info("Preparing new csv: %s" % out_fn) with file_transaction(out_fn) as tx_out: with open(tx_out, 'w') as handle: handle.write...
java
public /*@Nullable*/String createCopyRef(String path) throws DbxException { DbxPathV1.checkArgNonRoot("path", path); String apiPath = "1/copy_ref/auto" + path; return doPost(host.getApi(), apiPath, null, null, new DbxRequestUtil.ResponseHandler</*@Nullable*/String>() { ...
python
def get_host_and_url(properties, cloud_token): """ Helper method to get host and url that can be used in HTTPSConnection. :param properties: Client config properties. :param cloud_token: Cloud discovery token. :return: Host and URL pair """ host = properties.get(...
java
public void setReturnValue(MethodDescriptor methodDesc, TypeQualifierValue<?> tqv, TypeQualifierAnnotation tqa) { Map<TypeQualifierValue<?>, TypeQualifierAnnotation> map = returnValueMap.get(methodDesc); if (map == null) { map = new HashMap<>(); returnValueMap.put(methodDesc, map...
java
public ArrayList<OvhBootOptionEnum> serviceName_boot_bootId_option_GET(String serviceName, Long bootId) throws IOException { String qPath = "/dedicated/server/{serviceName}/boot/{bootId}/option"; StringBuilder sb = path(qPath, serviceName, bootId); String resp = exec(qPath, "GET", sb.toString(), null); return c...
java
public ProtectionIntentResourceInner createOrUpdate(String vaultName, String resourceGroupName, String fabricName, String intentObjectName, ProtectionIntentResourceInner parameters) { return createOrUpdateWithServiceResponseAsync(vaultName, resourceGroupName, fabricName, intentObjectName, parameters).toBlocking...
python
def google_storage_url(self, sat): """ Returns a google storage url the contains the scene provided. :param sat: Expects an object created by scene_interpreter method :type sat: dict :returns: (String) The URL to a google storage file ...
python
def clone_repo(self): """Clone a repository containing the dotfiles source.""" tempdir_path = tempfile.mkdtemp() if self.args.git: self.log.debug('Cloning git source repository from %s to %s', self.source, tempdir_path) self.sh('git clone', sel...
java
private static int getScaleFactor(ImageMetadata metadata, int minW, int minH) { int scale = 1; int scaledW = metadata.getW(); int scaledH = metadata.getH(); while (scaledW / 2 > minW && scaledH / 2 > minH) { scale *= 2; scaledH /= 2; scaledW /= 2; ...
java
@Override public HttpFilterBuilder addFilter(RequestFilter<HttpRequest> filter) { requestFilter = new ChainHttpRequestFilter(filter, requestFilter); return this; }
java
protected void readDatabaseConfig() { m_databaseKeys = new ArrayList<String>(); m_databaseProperties = new HashMap<String, Properties>(); FileInputStream input = null; File childResource = null; List<String> databaseKeys = new ArrayList<String>(); Map<String, Propertie...
python
def get(self, key, default=None): """Return a value from this :class:`.Context`.""" return self._data.get(key, compat_builtins.__dict__.get(key, default))
python
def _is_valid_file(self, path): """Simple check to see if file path exists. Does not check for valid YAML format.""" return isinstance(path, basestring) and os.path.isfile(path)
python
def _build_data_block(self, lexer): """Build the data block of :class:`~ctfile.ctfile.SDfile` instance. :return: Data block. :rtype: :py:class:`collections.OrderedDict`. """ data_block = OrderedDict() header = '' while True: token = next(lexer) ...
python
def _check_rest_version(self, version): """Validate a REST API version is supported by the library and target array.""" version = str(version) if version not in self.supported_rest_versions: msg = "Library is incompatible with REST API version {0}" raise ValueError(msg.f...
python
def _print_dict(elem_dict): """ Print a dict in a readable way """ for key, value in sorted(elem_dict.iteritems()): if isinstance(value, collections.Iterable): print(key, len(value)) else: print(key, value)
python
def _format_coordinate(self, ax, m): ''' Format the basemap plot to show lat/long properly ''' lon_m, lon_M, lat_m, lat_M = self.window xlocs = np.linspace(lon_m, lon_M, 5) ylocs = np.linspace(lat_m, lat_M, 5) xlocs = map(lambda x: float('%1.2f' % (x)), xlocs) ylocs = map...
java
int getTrailCCFromCompYesAndZeroCC(CharSequence s, int cpStart, int cpLimit) { int c; if(cpStart==(cpLimit-1)) { c=s.charAt(cpStart); } else { c=Character.codePointAt(s, cpStart); } int prevNorm16=getNorm16(c); if(prevNorm16<=minYesNo) { ...
java
@Override public void parse(String contents) throws SourceMapParseException { SourceMapObject sourceMapObject = SourceMapObjectParser.parse(contents); parse(sourceMapObject, null); }
python
def p_expression_minus(self, p): 'expression : expression MINUS expression' p[0] = Minus(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
python
def canBeAromatic(cycle, pyroleLike): """(cycle)-> returns AROMATIC if a ring is conjugatable and passes the simple tests for aromaticity returns MAYBE if the ring in its present form can be aromatic but is not currently ...
python
def _disk(self): """Record Disk usage.""" mountpoints = [ p.mountpoint for p in psutil.disk_partitions() if p.device.endswith(self.device) ] if len(mountpoints) != 1: raise CommandError("Unknown device: {0}".format(self.device)) value = int(ps...
python
def liked(self): """ :returns: Whether or not the logged in user liked this profile """ if self.is_logged_in_user: return False classes = self._liked_xpb.one_(self.profile_tree).attrib['class'].split() return 'liked' in classes
python
def build_list(self, manifests): """ Builds a manifest list or OCI image out of the given manifests """ media_type = manifests[0]['media_type'] if (not all(m['media_type'] == media_type for m in manifests)): raise PluginFailedException('worker manifests have inconsis...
python
def execute(self, dataman): ''' run the task :type dataman: :class:`~kitty.data.data_manager.DataManager` :param dataman: the executing data manager ''' self._event.clear() try: self._result = self._task(dataman, *self._args) # # We ar...
python
def _ClearScreen(self): """Clears the terminal/console screen.""" if self._have_ansi_support: # ANSI escape sequence to clear screen. self._output_writer.Write('\033[2J') # ANSI escape sequence to move cursor to top left. self._output_writer.Write('\033[H') elif win32console: ...
python
def initialize(self): """ Initializes self.dweight and self.wed to zero matrices. """ self.randomize() self.dweight = Numeric.zeros((self.fromLayer.size, \ self.toLayer.size), 'f') self.wed = Numeric.zeros((self.fromLayer.size, \ ...
java
public static boolean isChar(char c) { return Character.isDigit(c)||Character.isLowerCase(c)||Character.isUpperCase(c); }
python
def _fix_genotypes_object(self, genotypes, variant_info): """Fixes a genotypes object (variant name, multi-allelic value.""" # Checking the name (if there were duplications) if self.has_index and variant_info.name != genotypes.variant.name: if not variant_info.name.startswith(genotyp...
python
def collapsesum(data_frame, by = None, var = None): ''' Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe. ''' assert by is not None assert var is not None grouped = data_frame.groupby([by]) return grouped.apply(lambda x: weighted_sum(groupe = x, var =var))
java
public OvhOrder vps_serviceName_plesk_duration_GET(String serviceName, String duration, OvhPleskLicenseDomainNumberEnum domainNumber) throws IOException { String qPath = "/order/vps/{serviceName}/plesk/{duration}"; StringBuilder sb = path(qPath, serviceName, duration); query(sb, "domainNumber", domainNumber); S...
python
def set_context(self, cell_type): """Set protein expression amounts from CCLE as initial conditions. This method uses :py:mod:`indra.databases.context_client` to get protein expression levels for a given cell type and set initial conditions for Monomers in the model accordingly. ...
python
def capture(rect=None, filepath='', prompt=True, hideWindow=None): """ Prompts the user to capture the screen. :param rect | <QRect> filepath | <str> prompt | <bool> :return (<str> filepath, <bool> accepted)...
java
public void restartWebApplication(DeployedModule webModuleConfig) throws WebAppNotLoadedException { try { removeWebApplication(webModuleConfig); } catch (Exception e) { String groupName = webModuleConfig.getName(); //Translated to SRVE0314E: Failed to remove web modul...
java
public void reset() { final int ceilingLgK = Util.toLog2(Util.ceilingPowerOf2(k_), "VarOptItemsSketch"); final int initialLgSize = SamplingUtil.startingSubMultiple(ceilingLgK, rf_.lg(), MIN_LG_ARR_ITEMS); currItemsAlloc_ = SamplingUtil.getAdjustedSize(k_, 1 << initialLgSize); data_ = new...
java
@Override public void started(ServiceBroker broker) throws Exception { super.started(broker); // Local nodeID this.nodeID = broker.getNodeID(); // Set components ServiceBrokerConfig cfg = broker.getConfig(); this.executor = cfg.getExecutor(); this.scheduler = cfg.getScheduler(); this.strategyFactory ...
java
@Override public java.util.concurrent.Future<DescribeReservedInstancesListingsResult> describeReservedInstancesListingsAsync( com.amazonaws.handlers.AsyncHandler<DescribeReservedInstancesListingsRequest, DescribeReservedInstancesListingsResult> asyncHandler) { return describeReservedInstancesLi...
java
private static String checkORBgiopMaxMsgSize() { /* * JacORB definition (see jacorb.properties file): * * This is NOT the maximum buffer size that can be used, but just the * largest size of buffers that will be kept and managed. This value * will be added to an inte...
java
final byte[] cryptoAsym(final byte[] input, final int offset, final int len, final boolean decrypt) throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { rsaCipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, decrypt ? rsaKeyForDecrypt ...
python
def send_mail(subject, message, from_email, recipient_emails, files=None, html=False, reply_to=None, bcc=None, cc=None, files_manually=None): """ Sends email with advanced optional parameters To attach non-file content (e.g. content not saved on disk), use files_manually parameter and pro...
python
def create_app(name, site, sourcepath, apppool=None): ''' Create an IIS application. .. note:: This function only validates against the application name, and will return True even if the application already exists with a different configuration. It will not modify the configuration...
python
def hms2dec(hms): """ Convert longitude from hours,minutes,seconds in string or 3-array format to decimal degrees. ADW: This really should be replaced by astropy """ DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. if isstring(hms): hour,minute,second = np.array(re....
java
public static void buildRegionsMonotone(Context ctx, CompactHeightfield chf, int borderSize, int minRegionArea, int mergeRegionArea) { ctx.startTimer("BUILD_REGIONS"); int w = chf.width; int h = chf.height; int id = 1; int[] srcReg = new int[chf.spanCount]; ...
java
private long addDigest(long digest, Class<?> cl) throws Exception { if (_cl == null) return digest; digest = addDigest(digest, cl.getName()); digest = addDigest(digest, cl.getModifiers()); Class<?> superClass = cl.getSuperclass(); if (superClass != null && superClass.getName()...
python
def RequestPacket(self): """Create a ready-to-transmit authentication request packet. Return a RADIUS packet which can be directly transmitted to a RADIUS server. :return: raw packet :rtype: string """ attr = self._PktEncodeAttributes() if self.authenti...
python
def delegated_login(self, login, admin_zc, duration=0): """Use another client to get logged in via delegated_auth mechanism by an already logged in admin. :param admin_zc: An already logged-in admin client :type admin_zc: ZimbraAdminClient :param login: the user login (or email)...
python
def create_invoices(account_id: str, due_date: date) -> Sequence[Invoice]: """ Creates the invoices for any due positive charges in the account. If there are due positive charges in different currencies, one invoice is created for each currency. :param account_id: The account to invoice. :param due...
java
protected int getOffset(long dt) { int ret = 0; TimeZone tz = DateUtilities.getCurrentTimeZone(); if(tz != null) ret = tz.getOffset(dt); return ret; }
java
public Map<String, INDArray> rnnActivateUsingStoredState(INDArray[] inputs, boolean training, boolean storeLastForTBPTT) { return ffToLayerActivationsDetached(training, FwdPassType.RNN_ACTIVATE_WITH_STORED_STATE, storeLastForTBPTT, vertices.length-1, ...
python
def pygame_image_loader(filename, colorkey, **kwargs): """ pytmx image loader for pygame :param filename: :param colorkey: :param kwargs: :return: """ if colorkey: colorkey = pygame.Color('#{0}'.format(colorkey)) pixelalpha = kwargs.get('pixelalpha', True) image = pygame.im...
python
def identify_datafiles(root, extensions_to_ignore=None, directories_to_ignore=None, files_to_ignore=None): """ Identify files that might contain data See function IP_verified() for details about optinoal parmeters """ for dirpath, di...
java
@Override public boolean isCancelled() { boolean canceled = false; for (Future<FUTURE_TYPE> future : futureList) { if (!future.isDone()) { return false; } canceled |= future.isCancelled(); } return canceled; }
python
def run(self, **kwargs): """Execute the worker thread. Returns: `None` """ super().run(**kwargs) scheduler = self.scheduler_plugins[self.active_scheduler]() if not kwargs['no_daemon']: self.log.info('Starting {} worker with {} threads checking fo...
java
@Override public Multimap<String, NotificationChannel> findSubscribedRecipientsForDispatcher(NotificationDispatcher dispatcher, String projectKey, SubscriberPermissionsOnProject subscriberPermissionsOnProject) { verifyProjectKey(projectKey); String dispatcherKey = dispatcher.getKey(); Set<SubscriberA...
python
def simple_srcflux(env, infile=None, psfmethod='arfcorr', conf=0.68, verbose=0, **kwargs): """Run the CIAO "srcflux" script and retrieve its results. *infile* The input events file; must be specified. The computation is done in a temporary directory, so this path — and all others...
java
@Override public EClass getIfcStyledItem() { if (ifcStyledItemEClass == null) { ifcStyledItemEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(666); } return ifcStyledItemEClass; }
python
def create(self, create_missing=None): """Do extra work to fetch a complete set of attributes for this entity. For more information, see `Bugzilla #1230873 <https://bugzilla.redhat.com/show_bug.cgi?id=1230873>`_. """ return Organization( self._server_config, ...
python
def encode(obj, outtype='json', raise_error=False): """ encode objects, via encoder plugins, to new types Parameters ---------- outtype: str use encoder method to_<outtype> to encode raise_error : bool if True, raise ValueError if no suitable plugin found Examples -------- ...
java
public void set(long value) throws MemcachedException, InterruptedException, TimeoutException { this.memcachedClient.set(this.key, 0, String.valueOf(value)); }
python
def unblockshaped(arr, h, w): """ Return an new array of shape (h, w) where h * w = arr.size If arr is of shape (n, nrows, ncols), n sublocks of shape (nrows, ncols), then the returned array preserves the "physical" layout of the sublocks. """ n, nrows, ncols = arr.shape return (arr.res...
python
def get_last_doc(self): """Returns the last document stored in the Solr engine. """ #search everything, sort by descending timestamp, return 1 row try: result = self.solr.search('*:*', sort='_ts desc', rows=1) except ValueError: return None for r ...
python
def delete(self, creative_id, nick=None): '''xxxxx.xxxxx.creative.delete =================================== 删除一个创意''' request = TOPRequest('xxxxx.xxxxx.creative.delete') request['creative_id'] = creative_id if nick!=None: request['nick'] = nick self.create(self.e...
python
def get_query_result(self, selector, fields=None, raw_result=False, **kwargs): """ Retrieves the query result from the specified database based on the query parameters provided. By default the result is returned as a :class:`~cloudant.result.QueryResult` which u...
java
public static java.sql.Timestamp convertSqlDate(Date dt) { if (dt == null) { return new java.sql.Timestamp(0); } return new java.sql.Timestamp(dt.getTime()); }
python
def fill_profile(profile, array, weights=None, return_indices=False): """Fill a ROOT profile with a NumPy array. Parameters ---------- profile : ROOT TProfile, TProfile2D, or TProfile3D The ROOT profile to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fi...
python
def apply_exclusions(self,exclusions): """ Trim sky catalog to remove any sources within regions specified by exclusions file. """ # parse exclusion file into list of positions and distances exclusion_coords = tweakutils.parse_exclusions(exclusions) if exclusion_coord...