language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void putBoolean(String key, boolean value) { sharedPreferences.edit().putBoolean(key, value).commit(); }
python
def files_changed(): """ Return the list of file changed in the current branch compared to `master` """ with chdir(get_root()): result = run_command('git diff --name-only master...', capture='out') changed_files = result.stdout.splitlines() # Remove empty lines return [f for f in ch...
python
def stop(self, unique_id, configs=None): """Stop the service. If the deployer has not started a service with`unique_id` the deployer will raise an Exception There are two configs that will be considered: 'terminate_only': if this config is passed in then this method is the same as terminate(unique_id) (thi...
java
private void unregisterQuickStartSecurityRegistryConfiguration() { if (urConfigReg != null) { urConfigReg.unregister(); urConfigReg = null; quickStartRegistry = null; } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { ...
python
def init(self, n=0, ftype="real", colfac=1.0e-8, lmfac=1.0e-3, fid=0): """Set selected properties of the fitserver instance. Like in the constructor, the number of unknowns to be solved for; the number of simultaneous solutions; the ftype and the collinearity and Levenberg-Marquardt fac...
python
def fetch_all(self, credentials, regions = [], partition_name = 'aws', targets = None): """ Generic fetching function that iterates through all of the service's targets :param credentials: F :param service: Name of the service :param regions: ...
java
public void createNewSecureIdentitySecurityDomain72(String securityDomainName, String username, String password) throws Exception { Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_SECURITY, SECURITY_DOMAIN, securityDomainName); ModelNode addTopNode = createRequest(ADD, addr); ...
java
public static Builder newConvertBuilder(String input, String output) { return new Builder(input, output, TaskGroupActivity.CONVERT); }
java
@XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "logo", scope = FeedType.class) public JAXBElement<LogoType> createFeedTypeLogo(LogoType value) { return new JAXBElement<LogoType>(FEED_TYPE_LOGO_QNAME, LogoType.class, FeedType.class, value); }
python
def log_stack(self, signal, frame): """Signal handler to log the stack trace of the current thread. For use with `set_blocking_signal_threshold`. """ gen_log.warning('IOLoop blocked for %f seconds in\n%s', self._blocking_signal_threshold, ...
java
public ReturnValue execute(final String[] argsAry) throws BadThresholdException { // CommandLineParser clp = new PosixParser(); try { HelpFormatter hf = new HelpFormatter(); // configure a parser Parser cliParser = new Parser(); cliParser.setGroup(mainOpti...
java
public int writeCacheEntry(CacheEntry ce) { // @A5C int returnCode = htod.writeCacheEntry(ce); if (returnCode == HTODDynacache.DISK_EXCEPTION) { stopOnError(this.htod.diskCacheException); } return returnCode; }
java
@Nonnull public final XMLWriterSettings setSerializeComments (@Nonnull final EXMLSerializeComments eSerializeComments) { m_eSerializeComments = ValueEnforcer.notNull (eSerializeComments, "SerializeComments"); return this; }
java
public void run() { final Scanner scanner = getScanner(); // start the process by loading all of the trees in the system final List<Tree> trees; try { trees = Tree.fetchAllTrees(tsdb).joinUninterruptibly(); LOG.info("[" + thread_id + "] Complete"); } catch (Exception e) { LOG.erro...
python
async def get_permitted(request, permission, context): """Returns true if the one of the groups in the request has the requested permission. The function takes a request, a permission to check for and a context. A context is a sequence of ACL tuples which consist of a Allow/Deny action, a group, an...
java
public UnsignedInteger32 postWriteRequest(byte[] handle, long position, byte[] data, int off, int len) throws SftpStatusException, SshException { if ((data.length - off) < len) { throw new IndexOutOfBoundsException("Incorrect data array size!"); } try { UnsignedInteger32 requestId = nextRequestId();...
python
def _objective_bestscore(self, old, new): """An objective function that returns True if new has a better score than old, and ``False`` otherwise. INPUTS: old (tuple): a tuple (score, embedding) new (tuple): a tuple (score, embedding) """ (oldscore, oldt...
java
public static Date getTransactionTime() { final Stack<Date> stack = threadLocal.get(); return stack != null ? stack.peek() : null; }
python
def generate_query_key(self, serializer): """Get the key that can be passed to Django's filter method. To account for serialier field name rewrites, this method translates serializer field names to model field names by inspecting `serializer`. For example, a query like `filter{...
python
def parse_raw_token(self, raw_token): """Parse token and secret from raw token response.""" if raw_token is None: return (None, None, None) qs = parse_qs(raw_token) token = qs.get('oauth_token', [None])[0] token_secret = qs.get('oauth_token_secret', [None])[0] ...
java
@Override public RecordWriter<NullWritable, WARCWritable> getRecordWriter(TaskAttemptContext context) throws IOException, InterruptedException { return new WARCWriter(context); }
python
def send_message(self, message, mention_id=None, mentions=[]): """ Send the specified message to twitter, with appropriate mentions, tokenized as necessary :param message: Message to be sent :param mention_id: In-reply-to mention_id (to link messages to a previous message) :param...
java
public String waitTextToRender(int seconds, String excludeText) { String text = null; if (seconds == 0 && ((text = getText(true)) != null && text.length() > 0 && !text.equals(excludeText))) { return text; } for (int i = 0, count = 5 * seconds; i < count; i++) { te...
java
private void addKeyboardListener(KeyboardAwt keyboard) { componentForKeyboard.addKeyListener(keyboard); componentForKeyboard.requestFocus(); componentForKeyboard.setFocusTraversalKeysEnabled(false); }
java
public static Divider getDivider(@ColorInt int color) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return new Api21ItemDivider(color); } return new Api20ItemDivider(color); }
java
public static <T> T[] offerArray(T[] prepend, T[] tail) { if (prepend == null || prepend.length < 1) { return tail; } else if (tail == null || tail.length < 1) { return prepend; } else { T[] result = newArrayInstance(tail, prepend.length + tail.length); ...
java
public void put_class_property(String name, DbDatum[] properties) throws DevFailed { databaseDAO.put_class_property(this, name, properties); }
python
def times(p, mint, maxt=None): '''Repeat a parser between `mint` and `maxt` times. DO AS MUCH MATCH AS IT CAN. Return a list of values.''' maxt = maxt if maxt else mint @Parser def times_parser(text, index): cnt, values, res = 0, Value.success(index, []), None while cnt < maxt: ...
python
def _serve_experiment_runs(self, request): """Serve a JSON runs of an experiment, specified with query param `experiment`, with their nested data, tag, populated. Runs returned are ordered by started time (aka first event time) with empty times sorted last, and then ties are broken by sorting on the run...
python
def unmarshal(pkg_reader, package, part_factory): """ Construct graph of parts and realized relationships based on the contents of *pkg_reader*, delegating construction of each part to *part_factory*. Package relationships are added to *pkg*. """ parts = Unmarshaller._unm...
python
def _check_boundaries(self, fragment): """ Check that the interval of the given fragment is within the boundaries of the list. Raises an error if not OK. """ if not isinstance(fragment, SyncMapFragment): raise TypeError(u"fragment is not an instance of SyncMap...
java
public static <T extends Case1<A>, A> DecomposableMatchBuilder0<T> case1( Class<T> clazz, MatchesExact<A> a) { List<Matcher<Object>> matchers = Lists.of(ArgumentMatchers.eq(a.t)); return new DecomposableMatchBuilder0<T>(matchers, new Case1FieldExtractor<>(clazz)); }
java
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception { Reference ref = (Reference) obj; String api = null; String url = null; for (int i = 0; i < ref.size(); i++) { ...
java
public static void loadUserConfigProps() { userProps = new Properties(); try { LOG.info("Loading the properties as proj root /src:"); loadProps(userProps, mRunPropertiesFile); } catch (IOException e) { LOG.info("context", e); try { ...
java
public static LongIteratorEx of(final Supplier<? extends LongIterator> iteratorSupplier) { N.checkArgNotNull(iteratorSupplier, "iteratorSupplier"); return new LongIteratorEx() { private LongIterator iter = null; private LongIteratorEx iterEx = null; private boo...
java
public DescribeWorkingStorageResult withDiskIds(String... diskIds) { if (this.diskIds == null) { setDiskIds(new com.amazonaws.internal.SdkInternalList<String>(diskIds.length)); } for (String ele : diskIds) { this.diskIds.add(ele); } return this; }
java
@Deprecated public static Map<String, String> refundByMap(Map<String, String> reqData) { return SDKUtil.convertResultStringToMap(refund(reqData)); }
java
private boolean doUpdateConversationFromEvent(ChatStore store, String conversationId, Long eventId, Long updatedOn) { ChatConversationBase conversation = store.getConversation(conversationId); if (conversation != null) { ChatConversationBase.Builder builder = ChatConversationBase.baseBuil...
java
public void concatInternal(String target, String [] srcs) throws IOException { // actual move waitForReady(); long now = FSNamesystem.now(); unprotectedConcat(target, srcs, now); fsImage.getEditLog().logConcat(target, srcs, now); }
java
public EClass getIfcPreDefinedSymbol() { if (ifcPreDefinedSymbolEClass == null) { ifcPreDefinedSymbolEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(377); } return ifcPreDefinedSymbolEClass; }
python
def random_from_alphabet(size, alphabet): """ Takes *size* random elements from provided alphabet :param size: :param alphabet: """ import random return list(random.choice(alphabet) for _ in range(size))
java
public void shutDown() { synchronized (channels) { isCurrentlyShutingDown = true; for (final SynchronizeFXWebsocketChannel server : channels.values()) { server.shutdown(); } servers.clear(); channels.clear(); clients.clear()...
java
public void undeploy(final DeploymentUnit deploymentUnit) { final ExtensionInfo extensionInfo = deploymentUnit.getAttachment(Attachments.EXTENSION_INFORMATION); if (extensionInfo == null) { return; } // we need to remove the extension on undeploy final ServiceControll...
python
def copy(string, **kwargs): """Copy given string into system clipboard.""" clip.OpenClipboard() clip.EmptyClipboard() clip.SetClipboardData(win32con.CF_UNICODETEXT, string) clip.CloseClipboard() return
python
def set_chebyshev_approximators(self, deg_forward=50, deg_backwards=200): r'''Method to derive and set coefficients for chebyshev polynomial function approximation of the height-volume and volume-height relationship. A single set of chebyshev coefficients is used for t...
python
def number_letters(block_or_record, key=None): """Return a dict of {posn: restype} for each letter in the sequence.""" if key: logging.warn("DEPRECATED: Pass a record instead") assert 'sequences' in block_or_record, "Expected a block and a key" record = find_seq_rec(block_or_record, key)...
java
public void load(RulesDefinition.NewRepository repo) { for (RulesDefinition.NewRule rule : repo.rules()) { String name = i18n.getName(repo.key(), rule.key()); if (StringUtils.isNotBlank(name)) { rule.setName(name); } String desc = i18n.getDescription(repo.key(), rule.key()); i...
python
def cluster_number(self, data, maxgap): '''General function that clusters numbers. Args data (list): list of integers. maxgap (int): max gap between numbers in the cluster. ''' data.sort() groups = [[data[0]]] for x in data[1:]: if ...
python
def killall(self, wait = None): """ Kill all active workers. @wait: Seconds to wait until last worker ends. If None it waits forever. """ self.queue.close() self.count_lock.acquire() self.kill(self.shared['workers']) self.count_lock.release(...
python
def array(arr, *args, **kwargs): ''' Wrapper around weldarray - first create np.array and then convert to weldarray. ''' return weldarray(np.array(arr, *args, **kwargs))
java
protected ResourceBundle getResourceBundle(final String rbBaseName, final Locale resourceBundleLocale, final boolean loop) { ResourceBundle rb = null; if (rbBaseName == null) { return null; } try { if (resourceBundleLocale != null) { r...
python
def async_call(func, *args, callback=None): '''Call `func` in background thread, and then call `callback` in Gtk main thread. If error occurs in `func`, error will keep the traceback and passed to `callback` as second parameter. Always check `error` is not None. ''' def do_call(): result = ...
python
def _close_and_clean(self, cleanup): """ Closes the project, and cleanup the disk if cleanup is True :param cleanup: Whether to delete the project directory """ tasks = [] for node in self._nodes: tasks.append(asyncio.async(node.manager.close_node(node.id)))...
python
def unpad_aes256(s): """ Removes padding from an input string based on a given block size. :param s: string :returns: The unpadded string. """ if not s: return s try: return Padding.removePadding(s, blocksize=AES.block_size) except AssertionError: # if there's an...
java
public static <S> com.bazaarvoice.ostrich.ServicePool<S> getPool(S dynamicProxy) { checkNotNull(dynamicProxy); checkArgument(isProxy(dynamicProxy)); @SuppressWarnings("unchecked") ServicePoolProxy<S> poolProxy = (ServicePoolProxy<S>) Proxy.getInvocationHandler(dynamicProxy); ...
java
@Override public void prepare(FeatureProvider provider) { transformable = provider.getFeature(Transformable.class); if (provider instanceof TileCollidableListener) { addListener((TileCollidableListener) provider); } }
python
def from_ast_file(cls, filename, index=None): """Create a TranslationUnit instance from a saved AST file. A previously-saved AST file (provided with -emit-ast or TranslationUnit.save()) is loaded from the filename specified. If the file cannot be loaded, a TranslationUnitLoadError will...
python
def _get_preprocessed(self, data): """ Returns: (DeveloperPackage, new_data) 2-tuple IFF the preprocess function changed the package; otherwise None. """ from rez.serialise import process_python_objects from rez.utils.data_utils import get_dict_diff_str ...
python
def cache_node(node, provider, opts): ''' Cache node individually .. versionadded:: 2014.7.0 ''' if isinstance(opts, dict): __opts__.update(opts) if 'update_cachedir' not in __opts__ or not __opts__['update_cachedir']: return if not os.path.exists(os.path.join(__opts__['ca...
java
public void normalize() { for (int i = 0; i < size; i++) { keys[i] = lowerCase(keys[i]); } }
java
public static void handleCacheableResponse(HttpServletRequest request, HttpServletResponse response, byte[] data, String contentType) throws IOException { String ifNoneMatch = request.getHeader("If-None-Match"); String etag = "\"0" + DigestUtils.md5DigestAsHex(data) + "\""; addCacheHeaders(response, etag, ...
python
def reset(self): """factory reset""" print '%s call reset' % self.port try: self._sendline('factoryreset') self._read() except Exception, e: ModuleHelper.WriteIntoDebugLogger("reset() Error: " + str(e))
python
def _detab(self, text): r"""Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") ' foo' >>> m._detab(" \tfoo") ' foo' >>> m._detab("\t foo") ' foo' >>> m._detab(" foo") ...
java
@Override public List<CommercePriceList> findByCommerceCurrencyId( long commerceCurrencyId) { return findByCommerceCurrencyId(commerceCurrencyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
python
def handle(cls, value, provider, **kwargs): """Fetch the most recent AMI Id using a filter For example: ${ami [<region>@]owners:self,account,amazon name_regex:serverX-[0-9]+ architecture:x64,i386} The above fetches the most recent AMI where owner is self ...
java
@Override public String describe(Session session) { try { return describeImpl(session); } catch (Exception e) { e.printStackTrace(); return e.toString(); } }
python
def plot3d(points, color=(0.5, 0.5, 0.5), tube_radius=0.005, n_components=30, name=None): """Plot a 3d curve through a set of points using tubes. Parameters ---------- points : (n,3) float A series of 3D points that define a curve in space. color : (3,) float ...
python
def find_biconnected_components(graph): """Finds all the biconnected components in a graph. Returns a list of lists, each containing the edges that form a biconnected component. Returns an empty list for an empty graph. """ list_of_components = [] # Run the algorithm on each of the connected c...
java
public static Multimap<String, String> getParameters(final String rawQuery) { Multimap<String, String> result = HashMultimap.create(); if (rawQuery == null) { return result; } StringTokenizer tokens = new StringTokenizer(rawQuery, "&"); while (tokens.hasMoreTokens())...
python
def badge(self, *args, **kwargs): """ Latest Build Status Badge Checks the status of the latest build of a given branch and returns corresponding badge svg. This method is ``experimental`` """ return self._makeApiCall(self.funcinfo["badge"], *args, **kwargs)
java
public static ConnectionHandler unregister(final String id) { if (id == null || id.length() == 0) { return null; // Not possible } // end of if return handlers.remove(id); }
java
protected Scheme getScheme() { String scheme; try { URI uri = new URI(this.apiUrl); scheme = uri.getScheme(); } catch (URISyntaxException e) { scheme = "http"; } if (scheme.equals("https")) { return new Scheme(scheme, DEFAULT_HTTPS_...
python
def _IsCronJobFailing(self, cron_job): """Returns True if the last run failed.""" status = cron_job.Get(cron_job.Schema.LAST_RUN_STATUS) if status is None: return False return status.status != rdf_cronjobs.CronJobRunStatus.Status.OK
java
@Override public SqlEntityQuery<E> limit(final long limit) { if (!agent().getSqlConfig().getDialect().supportsLimitClause()) { throw new UroborosqlRuntimeException("Unsupported limit clause."); } this.limit = limit; return this; }
java
public Setting getSetting(String group) { final Setting setting = new Setting(); setting.putAll(this.getMap(group)); return setting; }
java
String compact(final String json) throws IOException { final StringWriter output = new StringWriter(json.length()); final JsonFactory factory = mapper.getFactory(); final JsonParser parser = factory.createParser(json); final JsonGenerator generator = factory.createGenerator(output); ...
java
public Chronology getChronology(Object object, DateTimeZone zone) { Chronology chrono = ((ReadableInstant) object).getChronology(); if (chrono == null) { return ISOChronology.getInstance(zone); } DateTimeZone chronoZone = chrono.getZone(); if (chronoZone != zone) { ...
java
public List<JoinableResourceBundle> getResourceBundles(Properties properties) { PropertiesConfigHelper props = new PropertiesConfigHelper(properties, resourceType); String fileExtension = "." + resourceType; // Initialize custom bundles List<JoinableResourceBundle> customBundles = new ArrayList<>(); // Chec...
java
private void ensureMinimum() { int belowMin = minEndpoints - endpoints.size(); if (belowMin > 0) { LOGGER.debug(logIdent(hostname, this) + "Service is {} below minimum, filling up.", belowMin); synchronized (epMutex) { for (int i = 0; i < belowMin; i++) { ...
java
@Override public IMetaEntry deserializeEntry(DataInput pData) throws TTIOException { try { final int kind = pData.readInt(); switch (kind) { case KEY: return new DumbKey(pData.readLong()); case VALUE: return new DumbValue(pData....
java
public static Exception resolveRSBException(final RSBException rsbException) { Exception exception = null; // build stacktrace array where each line is stored as entry. entry is extract each line stacktrace into arr final String[] stacktrace = ("Caused by: " + rsbException.getMessage()).split("...
python
def build_area_source_node(area_source): """ Parses an area source to a Node class :param area_source: Area source as instance of :class: `openquake.hazardlib.source.area.AreaSource` :returns: Instance of :class:`openquake.baselib.node.Node` """ # parse geometry sour...
python
def cache(cls, key_attrs, expires=None): """Decorates a method to provide cached-memoization using a combination of the positional arguments, keyword argments, and whitelisted instance attributes. """ def decorator(func): @functools.wraps(func) def wrapp...
java
public static int cuMemsetD16(CUdeviceptr dstDevice, short us, long N) { return checkResult(cuMemsetD16Native(dstDevice, us, N)); }
python
def open_ring(mol_graph, bond, opt_steps): """ Function to actually open a ring using OpenBabel's local opt. Given a molecule graph and a bond, convert the molecule graph into an OpenBabel molecule, remove the given bond, perform the local opt with the number of steps determined by self.steps, and t...
java
@Nonnull public static CachingXmlDataStore createCachingXmlDataStore(@Nonnull final URL dataUrl, @Nonnull final URL versionURL, @Nonnull final DataStore fallback) { return createCachingXmlDataStore(findOrCreateCacheFile(), dataUrl, versionURL, DEFAULT_CHARSET, fallback); }
python
def humanize(self): """ Humanize relative to now: .. testsetup:: from datetime import timedelta from delorean import Delorean .. doctest:: >>> past = Delorean.utcnow() - timedelta(hours=1) >>> past.humanize() 'an hour ago' ...
python
def daily(location='Fresno, CA', years=1, use_cache=True, verbosity=1): """Retrieve weather for the indicated airport code or 'City, ST' string. >>> df = daily('Camas, WA', verbosity=-1) >>> 365 <= len(df) <= 365 * 2 + 1 True Sacramento data has gaps (airport KMCC): 8/21/2013 is missing fr...
python
def _move_data_entries(destination_eggdir, dist_data): """Move data entries to their correct location.""" dist_data = os.path.join(destination_eggdir, dist_data) dist_data_scripts = os.path.join(dist_data, 'scripts') if os.path.exists(dist_data_scripts): egg_info_scripts = os...
java
public RateBasedRule withMatchPredicates(Predicate... matchPredicates) { if (this.matchPredicates == null) { setMatchPredicates(new java.util.ArrayList<Predicate>(matchPredicates.length)); } for (Predicate ele : matchPredicates) { this.matchPredicates.add(ele); } ...
java
private Map<String, String> getDependenciesFromJson(JSONObject json, String keyJson) { Map<String, String> nameVersionMap = new HashMap<>(); if (json.has(keyJson)) { JSONObject optionals = json.getJSONObject(keyJson); Iterator<String> keys = optionals.keys(); while (k...
python
def user_default_add_related_pks(self, obj): """Add related primary keys to a User instance.""" if not hasattr(obj, '_votes_pks'): obj._votes_pks = list(obj.votes.values_list('pk', flat=True))
java
public void checkHttpURL(String document, String userAgent, ErrorHandler errorHandler) throws IOException, SAXException { CookieHandler.setDefault( new CookieManager(null, CookiePolicy.ACCEPT_ALL)); validator.reset(); httpRes = new PrudentHttpEntityResolve...
java
public void setLineThickness(@FloatRange(from = 1) final float lineThickness) { queueEvent(new Runnable() { @Override public void run() { scene.setLineThickness(lineThickness); } }); }
python
def replace_lines(html_file, transformed): """Replace lines in the old file with the transformed lines.""" result = [] with codecs.open(html_file, 'r', 'utf-8') as input_file: for line in input_file: # replace all single quotes with double quotes line = re.sub(r'\'', '"', lin...
java
public static Object instantiate( TypeDefinition type, SerializationContext context, List<SerializationRule> rules, boolean forceType ) throws Exception { Object instance = null; for (SerializationRule rule : rules) if (rule.canInstantiate(type, context)) { instance = rule.instantiate(type, context)...
java
public static Map<String, List<String>> decodeParams(String paramsStr, String charset) { if (StrUtil.isBlank(paramsStr)) { return Collections.emptyMap(); } // 去掉Path部分 int pathEndPos = paramsStr.indexOf('?'); if (pathEndPos > -1) { paramsStr = StrUtil.subSuf(paramsStr, pathEndPos + 1); } ...
python
def find_indices(lst, element): """ Returns the indices for all occurrences of 'element' in 'lst'. Args: lst (list): List to search. element: Element to find. Returns: list: List of indices or values """ result = [] offset = -1 while True: try: ...
python
def set_temperature(self, temp: float, hold_time: float = None, ramp_rate: float = None): """ Set the target temperature, in C. Valid operational range yet to be determined. :param temp: The target temperature, in degrees C...
python
def airplane(self, model_mask: str = '###') -> str: """Generate a dummy airplane model. :param model_mask: Mask of truck model. Here '@' is a placeholder of characters and '#' is a placeholder of digits. :return: Airplane model. :Example: Boeing 727. """...