language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public Object fromStream(final byte[] iStream) throws IOException { if (iStream == null || iStream.length == 0) // NULL VALUE return null; final int classNameSize = OBinaryProtocol.bytes2int(iStream); if (classNameSize <= 0) OLogManager.instance().error(this, "Class signature not found in ANY ele...
python
def install_requirements(self, requires): """ Install the listed requirements """ # Temporarily install dependencies required by setup.py before trying to import them. sys.path[0:0] = ['setup-requires'] pkg_resources.working_set.add_entry('setup-requires') to_install = l...
java
private IntIntPair totalPivotSearch(int k) { double max = 0; int i, j, pivotRow = k, pivotCol = k; double absValue; for(i = k; i < coeff.length; i++) { for(j = k; j < coeff[0].length; j++) { // compute absolute value of // current entry in absValue absValue = Math.abs(coeff...
java
@Override public void mapTileRequestExpiredTile(MapTileRequestState pState, Drawable pDrawable) { putTileIntoCache(pState.getMapTile(), pDrawable, ExpirableBitmapDrawable.getState(pDrawable)); // tell our caller we've finished and it should update its view for (final Handler handler : mTileRequestCompleteHandle...
java
public java.util.List<NodeGroupConfiguration> getNodeGroupConfiguration() { if (nodeGroupConfiguration == null) { nodeGroupConfiguration = new com.amazonaws.internal.SdkInternalList<NodeGroupConfiguration>(); } return nodeGroupConfiguration; }
java
public static boolean parseBoolean(String value, boolean defaultValue) { if (value == null) return defaultValue; value = value.trim(); // any of the following will final String[] acceptedTrue = new String[]{ "yes", "true", "t", "y", "1" }; final String[] acceptedFalse = new String[]{ "no", "false", "f"...
python
def is_prime( n ): """Return True if x is prime, False otherwise. We use the Miller-Rabin test, as given in Menezes et al. p. 138. This test is not exact: there are composite values n for which it returns True. In testing the odd numbers from 10000001 to 19999999, about 66 composites got past the first te...
java
private static BigInteger divideAndRound(BigInteger bdividend, long ldivisor, int roundingMode) { boolean isRemainderZero; // record remainder is zero or not int qsign; // quotient sign long r = 0; // store quotient & remainder in long MutableBigInteger mq = null; // store quotient ...
java
public EventJournalConfig findCacheEventJournalConfig(String name) { name = getBaseName(name); final EventJournalConfig config = lookupByPattern(configPatternMatcher, cacheEventJournalConfigs, name); if (config != null) { return config.getAsReadOnly(); } return getCac...
java
public static boolean validateTokenRequest(TokenRequestDto tokenRequestDto, OAuthApplicationDto oAuthApplicationDto) { // basic check try { String decodedRedirectUri = java.net.URLDecoder.decode(tokenRequestDto.getRedirectUri(), "UTF-8"); if (StringUtils.isNotBlank(oAuthApplicati...
java
public static ObjectName makeObjectName(String domainName, String beanName, String[] folderNameStrings) { return makeObjectName(domainName, beanName, null, folderNameStrings); }
java
public static Map<String, String> parseUrl(String url) { Map<String, String> result = new HashMap<>(8); result.put(PROTOCOL_KEY, ValueConsts.EMPTY_STRING); result.put(HOST_KEY, ValueConsts.EMPTY_STRING); result.put(PATH_KEY, ValueConsts.EMPTY_STRING); if (Checker.isNotEmpty(url))...
java
public int doEndTag() throws JspException { ServletRequest req = pageContext.getRequest(); String fmtErrors = null; if (_formatterError) { fmtErrors = getErrorsFromBody(); } if (hasErrors()) return reportAndExit(EVAL_PAGE); _state.disabled = ...
java
protected String[] prepareStringArray(Object value, String propertyName, Class<?> proeprtyType, FormMappingOption option) { // not null (empty if null) final String[] result; if (value != null && value instanceof String[]) { result = (String[]) value; } else { result = va...
python
def datetime_parsing(text, base_date=datetime.now()): """ Extract datetime objects from a string of text. """ matches = [] found_array = [] # Find the position in the string for expression, function in regex: for match in expression.finditer(text): matches.append((match....
java
@Override public ModelMapper getObject() throws Exception { // instantiates new instance of mapper final ModelMapper modelMapper = new ModelMapper(); // configures the mapper configure(modelMapper); // returns the mapper return modelMapper; }
java
@GET @Produces(MediaType.APPLICATION_JSON) @Path("/metrics/schemarecords") @Description("Discover metric schema records. If type is specified, then records of that particular type are returned.") public List<? extends Object> getRecords(@Context HttpServletRequest req, @DefaultValue("*") @QueryP...
java
@Override public void messageReceived(NextFilter nextFilter, S session, AmqpSecureMessage message) throws Exception { nextFilter.messageReceived(session, message); }
java
public Parameters append(String key, String value) { if (nameValuePairs == null) { nameValuePairs = new ArrayList<NameValuePair>(); } nameValuePairs.add(new BasicNameValuePair(key, value)); return this; }
java
public EnquireLinkResp enquireLinkResp(byte[] b) { EnquireLinkResp resp = new EnquireLinkResp(); assignHeader(resp, b); return resp; }
java
@Override public DeleteLogSubscriptionResult deleteLogSubscription(DeleteLogSubscriptionRequest request) { request = beforeClientExecution(request); return executeDeleteLogSubscription(request); }
java
public static CouchbaseCluster create(final List<String> nodes) { return new CouchbaseCluster( DefaultCouchbaseEnvironment.create(), ConnectionString.fromHostnames(nodes), false ); }
python
def not_right(self, num): """ WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE LEFT [:-num:] """ if num == None: return FlatList([_get_list(self)[:-1:]]) if num <= 0: return FlatList.EMPTY return FlatList(_get_list(self)[:-num:])
python
def compute(self, inputVector, learn, activeArray, burstingColumns, predictedCells): """ This is the primary public method of the class. This function takes an input vector and outputs the indices of the active columns. New parameters defined here: ---------------------------- @pa...
python
def bind(self, instance, auto=False): """ Bind deps to instance :param instance: :param auto: follow update of DI and refresh binds once we will get something new :return: """ methods = [ (m, cls.__dict__[m]) for cls in inspect.getmro(type...
java
public static HashedWheelTimer newTimer(final int ticks, final int ticks_per_wheel, final String name) { class TimerThreadNamer implements ThreadNameDeterminer { @Override public String determineThreadName(String currentThreadName, String proposedThreadName) throws Exception { r...
java
public Collection<Retrospective> getRetrospectives( RetrospectiveFilter filter) { filter = (filter == null) ? new RetrospectiveFilter() : filter; filter.team.clear(); filter.team.add(this); return getInstance().get().retrospectives(filter); }
java
private void activityResumed(Activity activity) { getConfigLogger().verbose(getAccountId(), "App in foreground"); checkTimeoutSession(); if(!isAppLaunchPushed()) { pushAppLaunchedEvent(); onTokenRefresh(); } if (!inCurrentSession()) { //onToken...
python
def timeid(self, data: ['SASdata', str] = None, by: str = None, id: str = None, out: [str, 'SASdata'] = None, procopts: str = None, stmtpassthrough: str = None, **kwargs: dict) -> 'SASresults': """ Python method to...
python
def train_model(params: Params, serialization_dir: str, file_friendly_logging: bool = False, recover: bool = False, force: bool = False, cache_directory: str = None, cache_prefix: str = None) -> Model: """ Trains the...
python
def loadd(self, ava): """ expects a special set of keys """ if "attributes" in ava: for key, val in ava["attributes"].items(): self.attributes[key] = val try: self.tag = ava["tag"] except KeyError: if not self.tag: rai...
python
def get_cv_idxs(n, cv_idx=0, val_pct=0.2, seed=42): """ Get a list of index values for Validation set from a dataset Arguments: n : int, Total number of elements in the data set. cv_idx : int, starting index [idx_start = cv_idx*int(val_pct*n)] val_pct : (int, float), validation set...
python
def calc_sun_times(self): """ Computes the times of sunrise, solar noon, and sunset for each day. """ self.sun_times = melodist.util.get_sun_times(self.data_daily.index, self.lon, self.lat, self.timezone)
python
def reboot(self): """Reboots the device. Generally one should use this method to reboot the device instead of directly calling `adb.reboot`. Because this method gracefully handles the teardown and restoration of running services. This method is blocking and only returns when th...
python
def job_disable(self, job_id): """ Disable a job. Disabled jobs will not be executed. :param job_id: Job identifier to disable. :type job_id: :py:class:`uuid.UUID` """ job_id = normalize_job_id(job_id) with self._job_lock: job_desc = self._jobs[job_id] job_desc['enabled'] = False
java
@SafeVarargs private final <T> Set<T> join(Set<T>... sets) { Set<T> result = new HashSet<>(); if (sets == null) return result; for (Set<T> set : sets) { if (set != null) result.addAll(set); } return result; }
python
def get_resource_relationships_for_source_resource_on_date(self, source_resource_id, from_, to): """Pass through to provider ResourceRelationshipLookupSession.get_resource_relationships_for_source_resource_on_date""" # Implemented from azosid template for - # osid.relationship.RelationshipLookup...
java
public <D, S> ForkedStream<D, S> forkStream(RecordStreamWithMetadata<D, S> inputStream, ForkOperator<S, D> forkOperator, WorkUnitState workUnitState) throws Exception { int branches = forkOperator.getBranches(workUnitState); // Set fork.branches explicitly here so the rest task flow can pick it up ...
python
def _get_connect_kwargs(self, host, port, user, password, database_url): """ Get the params to pass to psycopg2.connect() based on passed-in vals from yaml settings file """ if database_url: return {'dsn': database_url} if not host: raise CheckExc...
java
private EvaluationResult callHelper(URI type, URI id, URI issuer, URI category, int adType) { if (finder != null) { return finder.findAttribute(type, id, issuer, category, this, adType); } else { logg...
java
public static <I, D> List<Word<I>> suffixesForLocalOutput(Query<I, D> ceQuery, int localSuffixIdx, boolean allSuffixes) { if (localSuffixIdx == -1) { return Collections.emptyL...
java
@Override protected void updateStackingContexts() { super.updateStackingContexts(); if (stackingParent != null) { if (formsStackingContext()) //all the positioned boxes are considered as separate stacking contexts { stackingParent.getStackingContex...
python
def create(self, unique_name, domain_suffix=values.unset): """ Create a new EnvironmentInstance :param unicode unique_name: The unique_name :param unicode domain_suffix: The domain_suffix :returns: Newly created EnvironmentInstance :rtype: twilio.rest.serverless.v1.serv...
java
public Collection<Plugin> removeUncheckedPlugins( Collection<String> uncheckedPlugins, Collection<Plugin> plugins ) throws MojoExecutionException { if ( uncheckedPlugins != null && !uncheckedPlugins.isEmpty() ) { for ( String pluginKey : uncheckedPlugins ) { ...
java
public BaseMessageFilter setupRecordListener(JMessageListener listener, boolean bTrackMultipleRecords, boolean bAllowEchos, boolean bReceiveAllAdds) { BaseMessageFilter filter = null; MessageManager messageManager = null; if (listener == null) listener = this.getRecordOwner(); ...
java
@NullSafe public static boolean createFile(File path) { try { return (path != null && !path.isDirectory() && (path.isFile() || path.createNewFile())); } catch (IOException ignore) { return false; } }
java
private static void validate(String name, Collection<Geometry> geometries, int extent) { if (name == null) { throw new IllegalArgumentException("layer name is null"); } if (geometries == null) { throw new IllegalArgumentException("geometry collection is null"); } ...
java
protected boolean jobTooOld(final JobInfo jobInfo, final JobDefinition jobDefinition) { final Optional<OffsetDateTime> stopped = jobInfo.getStopped(); if (stopped.isPresent() && jobDefinition.maxAge().isPresent()) { final OffsetDateTime deadlineToRerun = stopped.get().plus(jobDefinition.maxA...
java
public final SortedSet<T> toSortedSet(final Comparator<? super T> comparator) { return ImmutableSortedSet.copyOf(comparator, toCollection(Lists.<T>newArrayListWithCapacity(256))); }
java
private void updateFailedLoginAttempts(int numberOfAttempts) { UserSecret userSecret = getSecret(); userSecret.setFailedLoginAttempts(numberOfAttempts); if (userSecret.getFailedLoginAttempts() >= MAX_FAILED_LOGIN_ATTEMPTS) { if (!(userSecret.getLastFailedAuthentication() != null && (Instant....
java
private StringBuffer toQueryPrefix(String t) { StringBuffer sb = new StringBuffer(255); return sb.append(selstar).append(t).append(whereTrue); }
java
public boolean isSameNode(Node other) { return (other instanceof NodeImpl) && (((NodeImpl) other).tree == tree) && (((NodeImpl) other).node == node); }
python
def _graph_add_edge(self, src_block_id, dst_block_id, **kwargs): """ Add an edge onto the graph. :param BlockID src_block_id: The block ID for source node. :param BlockID dst_block_id: The block Id for destination node. :param str jumpkind: The jumpkind of the edge. ...
java
private void checkC() throws DatatypeException, IOException { if (context.length() == 0) { appendToContext(current); } current = reader.read(); appendToContext(current); skipSpaces(); boolean expectNumber = true; for (;;) { switch (current...
java
public static DocLink fragment(String fragment) { return new DocLink((String) null, (String) null, fragment); }
python
def index(args): """ %prog index database.fasta ` Wrapper for `gmap_build`. Same interface. """ p = OptionParser(index.__doc__) p.add_option("--supercat", default=False, action="store_true", help="Concatenate reference to speed up alignment") opts, args = p.parse_args(args) ...
python
def _receive(self): """Receive any incoming socket data. If an error is thrown, handle it and return an empty string. :return: data_in :rtype: bytes """ data_in = EMPTY_BUFFER try: data_in = self._read_from_socket() except socket.timeout:...
python
def __try_instantiate(self, component_context, instance): # type: (ComponentContext, object) -> bool """ Instantiates a component, if all of its handlers are there. Returns False if a handler is missing. :param component_context: A ComponentContext bean :param instance: ...
python
def command(self, name, *args): """Execute a raw command.""" args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8')) for arg in args if arg is not None ] + [None] _mpv_command(self.handle, (c_char_p*len(args))(*args))
python
def translation(language): """ Return a translation object in the default 'django' domain. """ global _translations if language not in _translations: _translations[language] = Translations(language) return _translations[language]
java
public synchronized GoogleCloudStorageItemInfo putItem(GoogleCloudStorageItemInfo item) { StorageResourceId id = item.getResourceId(); PrefixKey key = new PrefixKey(id.getBucketName(), id.getObjectName()); CacheValue<GoogleCloudStorageItemInfo> value = new CacheValue<GoogleCloudStorageItemInfo>(item...
python
def submit_bsub_job(command, job_id=None, dependent_id=None, memory=None, requeue_code=None, logfile=None): """ construct a bsub job submission command Args: command: list of strings that forma unix command job_id: string for job ID for submission dependent_id: job ID, or list of jo...
java
public void marshall(DescribeActivationsRequest describeActivationsRequest, ProtocolMarshaller protocolMarshaller) { if (describeActivationsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(d...
java
public static void main (String[] args) { try { h2omapper m = new h2omapper(); m.run(null); } catch (Exception e) { System.out.println (e); } }
java
public Set<Key> keySet(int access) { Set<Key> set = new LinkedHashSet<Key>(); Map.Entry<Key, Member> entry; Iterator<Entry<Key, Member>> it = _data.entrySet().iterator(); while (it.hasNext()) { entry = it.next(); if (entry.getValue().getAccess() <= access) set.add(entry.getKey()); } return set; }
python
def get_stats(self, nid=None): """Get statistics for class :type nid: str :param nid: This is the ID of the network to get stats from. This is optional and only to override the existing `network_id` entered when created the class """ r = self.request( ...
python
def channel_to_id(slack, channel): """ Surely there's a better way to do this... """ channels = slack.api_call('channels.list').get('channels') or [] groups = slack.api_call('groups.list').get('groups') or [] if not channels and not groups: raise RuntimeError("Couldn't get channels and groups."...
java
public static boolean copyFile(final File source, final File destination, final Charset sourceEncoding, final Charset destinationEncoding, final boolean lastModified) throws IOException { if (source.isDirectory()) { throw new IllegalArgumentException("The source File " + destination.getName() + " should...
java
public static dnsview_gslbservice_binding[] get(nitro_service service, String viewname) throws Exception{ dnsview_gslbservice_binding obj = new dnsview_gslbservice_binding(); obj.set_viewname(viewname); dnsview_gslbservice_binding response[] = (dnsview_gslbservice_binding[]) obj.get_resources(service); return r...
java
public static <T extends TypeDefinition> ElementMatcher.Junction<T> noneOf(Type... value) { return noneOf(new TypeList.Generic.ForLoadedTypes(value)); }
python
def stratHeun(f, G, y0, tspan, dW=None): """Use the Stratonovich Heun algorithm to integrate Stratonovich equation dy = f(y,t)dt + G(y,t) \circ dW(t) where y is the d-dimensional state vector, f is a vector-valued function, G is an d x m matrix-valued function giving the noise coefficients and dW(t...
java
protected static List<SpecNode> getAllSpecNodes(final ContentSpec contentSpec) { final List<SpecNode> specNodes = new ArrayList<SpecNode>(); for (final Node childNode : contentSpec.getNodes()) { if (childNode instanceof SpecNode) { specNodes.add((SpecNode) childNode); ...
java
@Override public PackingPlan repack(PackingPlan currentPackingPlan, Map<String, Integer> componentChanges) throws PackingException { int initialNumContainer = TopologyUtils.getNumContainers(topology); int initialNumInstance = TopologyUtils.getTotalInstance(topology); double initialNumInstancePerCont...
java
@Override public MapReadResult readLabels(Tile upperLeft, Tile lowerRight) { return readMapData(upperLeft, lowerRight, Selector.LABELS); }
java
public void setOptions(String[][] options) throws Fault { LinkedHashSet<String[]> customTagStrs = new LinkedHashSet<>(); // Some options, specifically -link and -linkoffline, require that // the output directory has already been created: so do that first. for (String[] os : options) { ...
python
def get_tokens(self, auth, username=None): """ Returns the tokens owned by the specified user. If no user is specified, uses the user authenticated by ``auth``. :param auth.Authentication auth: authentication for user to retrieve. Must be a usern...
java
public void parse(final InsertStatement insertStatement) { if (!lexerEngine.skipIfEqual(getCustomizedInsertKeywords())) { return; } lexerEngine.accept(DefaultKeyword.DUPLICATE); lexerEngine.accept(DefaultKeyword.KEY); lexerEngine.accept(DefaultKeyword.UPDATE); ...
python
def parse(datetime_str, timezone=None, isofirst=True, dayfirst=True, yearfirst=True): """ Parses a datetime string and returns a `Delorean` object. :param datetime_str: The string to be interpreted into a `Delorean` object. :param timezone: Pass this parameter and the returned Delorean object will be n...
java
public Event withAttributes(java.util.Map<String, String> attributes) { setAttributes(attributes); return this; }
java
public List<Integer> locationsToReadForDecode(List<Integer> erasedLocations) throws TooManyErasedLocations { List<Integer> locationsToRead = new ArrayList<Integer>(stripeSize()); int limit = stripeSize() + paritySize(); // Loop through all possible locations in the stripe. for (int loc = limit - 1...
java
@GET @Path(WEBUI_CONFIG) @ReturnType("alluxio.wire.MasterWebUIConfiguration") public Response getWebUIConfiguration() { return RestUtils.call(() -> { MasterWebUIConfiguration response = new MasterWebUIConfiguration(); response.setWhitelist(mFileSystemMaster.getWhiteList()); TreeSet<Triple<...
python
def _cnf(lexer, varname): """Return a DIMACS CNF.""" _expect_token(lexer, {KW_p}) _expect_token(lexer, {KW_cnf}) nvars = _expect_token(lexer, {IntegerToken}).value nclauses = _expect_token(lexer, {IntegerToken}).value return _cnf_formula(lexer, varname, nvars, nclauses)
python
def directory(self, query, **kwargs): """Search by users or channels on all server.""" if isinstance(query, dict): query = str(query).replace("'", '"') return self.__call_api_get('directory', query=query, kwargs=kwargs)
python
def render_sparkline(self, **kwargs): """Render a sparkline""" spark_options = dict( width=200, height=50, show_dots=False, show_legend=False, show_x_labels=False, show_y_labels=False, spacing=0, margin=5, ...
python
def list_changes(self): """ Return a list of modified records. This is only applicable for attached tables. Returns: A list of `(row_index, record)` tuples of modified records Raises: :class:`delphin.exceptions.ItsdbError`: when called on a ...
python
def move_folder(self, to_folder, *, update_parent_if_changed=True): """ Move this folder to another folder :param to_folder: the destination Folder/folder_id to move into :type to_folder: mailbox.Folder or str :param bool update_parent_if_changed: updates self.parent with the n...
java
public static String getWebViewLink(Drive drive, String fileId) { try { return getWebViewLink(getFile(drive, fileId)); } catch (IOException e) { logger.log(Level.SEVERE, String.format( "Failed to build Google Drive URL for file %s", fileId), e); } return null; }
python
def get_keys(self): ''' 获取配置并检查是否更改 ''' if not os.path.exists(PATH_CONFIG): with open(PATH_CONFIG, 'w') as F: F.write(CONFIG) else: config = ConfigParser.ConfigParser() with open(PATH_CONFIG, 'r') as cfgfile: con...
java
public synchronized void setInetAddrPort(InetAddrPort address) { if (_address != null && _address.equals(address)) return; if (isStarted()) log.warn(this + " is started"); _address = address; }
python
def add_edges_from(self, ebunch, attr_dict=None, **attr): """Add all the edges in ebunch. Parameters ---------- ebunch : container of edges Each edge given in the container will be added to the graph. The edges can be: - 3-tuples (u,v,d) for an e...
python
def run_prepare(*data): """ Run seqcluster prepare to merge all samples in one file """ out_dir = os.path.join(dd.get_work_dir(data[0][0]), "seqcluster", "prepare") out_dir = os.path.abspath(safe_makedir(out_dir)) prepare_dir = os.path.join(out_dir, "prepare") tools = dd.get_expression_calle...
python
def save_and_close_enable(self): """Handle the data change event to enable the save and close button.""" if self.btn_save_and_close: self.btn_save_and_close.setEnabled(True) self.btn_save_and_close.setAutoDefault(True) self.btn_save_and_close.setDefault(True)
java
public ComputeNodeUpdateUserHeaders withLastModified(DateTime lastModified) { if (lastModified == null) { this.lastModified = null; } else { this.lastModified = new DateTimeRfc1123(lastModified); } return this; }
java
public synchronized void getUpdatedData() { if (!isUpdateDataNeeded()) { return; } this._projectResult = new ProjectLrResults(); _workedBuilds = new ArrayList<Integer>(); RunList<? extends Run> projectBuilds = currentProject.getBuilds(); // updateLastBuild...
python
def _collapse_fastq(in_fn): """ collapse reads into unique sequences """ args = argparse.Namespace() args.fastq = in_fn args.minimum = 1 args.out = op.dirname(in_fn) return collapse_fastq(args)
java
private ProcessingItem createPi(Processor processor, int parallelism) { ProcessingItem pi = this.componentFactory.createPi(processor, parallelism); this.topology.addProcessingItem(pi, parallelism); return pi; }
java
public String getHostAndPort() { if (enablePlaintextPort) { if (plaintextPort < 0) { return HostAndPort.fromString(host).toString(); } else { return HostAndPort.fromParts(host, plaintextPort).toString(); } } return null; }
java
@Override protected String newAlgorithm() { if (getModel().getAlgorithm() == null) { getModel().setAlgorithm(AesAlgorithm.AES); } return getModel().getAlgorithm().getAlgorithm(); }
java
public void checkAuthentication() throws ConnectionException { IServices services = new Services(createMetaModel(), populateHeaders(new V1APIConnector(getApplicationURL() + "rest-1.v1/", username, password, ApiClientInternals.getProxyProvider(proxySettings)))); Oid logge...
java
private static void processBiGram() { //移除二元模型出现频率为1的情况 Iterator<String> iter = BIGRAM.keySet().iterator(); while(iter.hasNext()){ String key = iter.next(); if(BIGRAM.get(key) < 2){ iter.remove(); } } try(BufferedWriter writer =...