language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def alter_function(self, dbName, funcName, newFunc): """ Parameters: - dbName - funcName - newFunc """ self.send_alter_function(dbName, funcName, newFunc) self.recv_alter_function()
java
public ListenableFuture<Map<JobId, Job>> jobs(@Nullable final String jobQuery) { return jobs(jobQuery, null); }
java
public List<Entity> query(Transaction transaction, Query query) { return query(transaction, query, FetchOptions.Builder.withOffset(0)); }
python
def create_request_url(self, profile_type, steamID): """Create the url to submit to the Steam Community XML feed.""" regex = re.compile('^\d{17,}$') if regex.match(steamID): if profile_type == self.USER: url = "http://steamcommunity.com/profiles/%s/?xml=1" % (steamID)...
java
private int getDataMemberListIndex(Member member) { final Collection<Member> dataMembers = nodeEngine.getClusterService().getMembers(DATA_MEMBER_SELECTOR); int index = -1; for (Member dataMember : dataMembers) { index++; if (dataMember.equals(member)) { re...
python
def intersection(self, other): ''' :param: other - Line subclass :return: Point subclass Returns a Point object with the coordinates of the intersection between the current line and the other line. Will raise Parallel() if the two lines are parallel. Will raise ...
java
private void init(ResourceLoader resourceLoader) throws IOException { if (config == null && configs == null) { if (resourceLoader == null) { return; } else if (configFileArgument == null && configArgument == null && analyzerArgument==null) { throw new IOException("no configuration"); ...
java
public List<ClasspathResourceVersion> getResourceVersions() throws URISyntaxException, IOException { if (!lazyLoadDone) { if (isClassFolder()) { logger.debug("\nScanning class folder: " + getUrl()); URI uri = new URI(getUrl()); Path start = Paths.get(...
java
public static DispatchRule newInstance(String name, String dispatcherName, String contentType, String encoding, Boolean defaultResponse) { DispatchRule dr = new DispatchRule(); dr.setName(name); dr.setDispatcherName(dispatcherName); dr.setConten...
java
public void restartDyno(String appName, String dynoId) { connection.execute(new DynoRestart(appName, dynoId), apiKey); }
python
def load(path, service=None, hostport=None, module_name=None): """Loads the Thrift file at the specified path. The file is compiled in-memory and a Python module containing the result is returned. It may be used with ``TChannel.thrift``. For example, .. code-block:: python from tchannel impor...
python
def get_font(self, weight='medium', slant='upright', width='normal'): """Return the font matching or closest to the given style If a font with the given weight, slant and width is available, return it. Otherwise, return the font that is closest in style. Args: weight (FontW...
python
def regenerate_models(self, propnames=None, exclude=[], deep=False): r""" Re-runs the specified model or models. Parameters ---------- propnames : string or list of strings The list of property names to be regenerated. If None are given then ALL models a...
python
def get_string(self, key): """Get a string from all_options""" # Massive hack, lol if key.startswith("lambda."): key = "lambda.items.{0}".format(key[7:]) if key.startswith("apigateway."): key = "apigateway.items.{0}".format(key[11:]) # Make sure key is i...
java
public PagedList<ApplicationGatewaySslPredefinedPolicyInner> listAvailableSslPredefinedPoliciesNext(final String nextPageLink) { ServiceResponse<Page<ApplicationGatewaySslPredefinedPolicyInner>> response = listAvailableSslPredefinedPoliciesNextSinglePageAsync(nextPageLink).toBlocking().single(); return ...
java
public static void main(String[] args) throws Throwable { CliArguments arguments = CliArguments.parse(args); if (arguments.isSet() && !arguments.isUsageMode()) { CliRunner runner = new CliRunner(arguments); try { runner.run(); } finally { runner.close(); } } else { PrintWriter out = new Pri...
java
@Override public CPRuleAssetCategoryRel fetchByAssetCategoryId_Last( long assetCategoryId, OrderByComparator<CPRuleAssetCategoryRel> orderByComparator) { int count = countByAssetCategoryId(assetCategoryId); if (count == 0) { return null; } List<CPRuleAssetCategoryRel> list = findByAssetCategoryId(asse...
python
def drop_temporary(pr: PullRequestDetails, problem: Optional[CannotAutomergeError], prev_seen_times: Dict[int, datetime.datetime], next_seen_times: Dict[int, datetime.datetime], ) -> Optional[CannotAutomergeError]: """Filters out problems t...
java
public static Integer readInteger(String value, Integer defaultValue) { if (!StringUtils.hasText(value)) return defaultValue; return Integer.valueOf(value); }
python
def _compile_to_sklearn(self, expr): """Compile a DEAP pipeline into a sklearn pipeline. Parameters ---------- expr: DEAP individual The DEAP pipeline to be compiled Returns ------- sklearn_pipeline: sklearn.pipeline.Pipeline """ skle...
java
protected void decodeOptionalBody(ISUPParameterFactory parameterFactory, byte[] parameterBody, byte parameterCode) throws ParameterException { switch (parameterCode & 0xFF) { case CallReference._PARAMETER_CODE: CallReference RS = parameterFactory.createCallReference(); ...
java
private int findAvailablePortNumber( Integer portNumberStartingPoint, List<Integer> reservedPorts ) { assert portNumberStartingPoint != null; int candidate = portNumberStartingPoint; while ( reservedPorts.contains( candidate ) ) { candidate++; } return can...
java
public void push(CollectorRegistry registry, String job) throws IOException { doRequest(registry, job, null, "PUT"); }
java
@SuppressWarnings("unused") public void setAppInfo(String name, String version) { if (name == null || version == null) { // nothing to do return; } this.userAgent = DEFAULT_USER_AGENT + " " + name.trim() + "/" + version.trim(); }
java
public long set(long instant, int value) { FieldUtils.verifyValueBounds(this, value, iMin, iMax); return super.set(instant, value - iOffset); }
python
def assignment(self, index): """ Returns a list of assignments for the corresponding index. Parameters ---------- index: list, array-like List of indices whose assignment is to be computed Returns ------- list: Returns a list of full assignme...
java
private void parseUsersAuthentication(final XMLExtendedStreamReader reader, final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException { final ModelNode usersAddress = realmAddress.clone().add(AUTHENTICATION, USERS); list.add...
python
def defaultCrawlId(): """ Provide a reasonable default crawl name using the user name and date """ timestamp = datetime.now().isoformat().replace(':', '_') user = getuser() return '_'.join(('crawl', user, timestamp))
java
public static Schema schema(int version, Iced impl) { if (version == -1) version = getLatestVersion(); return schema(version, impl.getClass().getSimpleName()); }
python
def get_map_data(self): """ Returns a serializable data set describing the map location """ return { 'containerSelector': '#' + self.get_map_element_id(), 'center': self.map_center_description, 'marker': self.map_marker_description or self.map_center_...
python
def kill(self, task_id): """Kills the specified task. Note that attempting to kill a task is currently not reliable. If, for example, a scheduler fails over while it was attempting to kill a task it will need to retry in the future. Likewise, if unregistered / disconnected, the ...
java
public boolean onButtonPress(MouseButton button) { if (!isEnabled()) return false; return parent != null ? parent.onButtonPress(button) : false; }
java
public void toDBObject(final Object containingObject, final MappedField mf, final DBObject dbObj, final MapperOptions opts) { final Object fieldValue = mf.getFieldValue(containingObject); final TypeConverter enc = getEncoder(fieldValue, mf); final Object encoded = enc.encode(fieldValue, mf); ...
python
def attach(func, params): """ Given a function and a namespace of possible parameters, bind any params matching the signature of the function to that function. """ sig = inspect.signature(func) params = Projection(sig.parameters.keys(), params) return functools.partial(func, **params)
python
def populate(self, **values): """Populate values to fields. Skip non-existing.""" values = values.copy() fields = list(self.iterate_with_name()) for _, structure_name, field in fields: if structure_name in values: field.__set__(self, values.pop(structure_name)...
java
public static Endpoint update(final String domainId, final String endpointId, final String endpointPassword) throws AppPlatformException, ParseException, Exception { return update(domainId, endpointId, endpointPassword, null, false); }
java
protected String getString(Exchange exchange, Message message, String name) { Object value = getObject(exchange, message, name); if (value instanceof String) { return (String)value; } else if (value != null) { return String.valueOf(value); } return null; ...
python
def add_string_pairs_from_attributed_ui_element(results, ui_element, comment_prefix): """ Adds string pairs from a UI element with attributed text Args: results (list): The list to add the results to. attributed_element (element): The element from the xib that contains, to extract the fragments...
python
def load_process_algorithm(algo_defs, env): """ Load an algorithm into a module. The algorithm is an instance of ``AlgorithmDef`` class. :param algo_defs: algorithm definitions :type algo_defs: AlgorithmDef | list[AlgorithmDef] :param env: environment :Example: >>> import sys >>> from ...
java
public void deserialize(InputStream in, DigitalObject out, String format, String encoding, int transContext) throws ObjectIntegrityException, StreamIOException, UnsupportedTranslationException, Se...
java
private ImmutableSet<Class<? super T>> getImmediateRawTypes() { // Cast from ImmutableSet<Class<?>> to ImmutableSet<Class<? super T>> @SuppressWarnings({"unchecked", "rawtypes"}) ImmutableSet<Class<? super T>> result = (ImmutableSet) getRawTypes(runtimeType); return result; }
python
def STRUCT_DECL(self, cursor, num=None): """ Handles Structure declaration. Its a wrapper to _record_decl. """ return self._record_decl(cursor, typedesc.Structure, num)
java
public void setYoaOrent(Integer newYoaOrent) { Integer oldYoaOrent = yoaOrent; yoaOrent = newYoaOrent; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.IOC__YOA_ORENT, oldYoaOrent, yoaOrent)); }
python
def system(self): """ Creates a reference to the System operations for Portal """ url = self._url + "/system" return _System(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=...
python
def reset_consumer_group_metadata(self, *groups): """Reset cache of what broker manages the offset for specified groups Remove the cache of what Kafka broker should be contacted when fetching or updating the committed offsets for a given consumer group or groups. NOTE: Does not...
python
def _compute_full_path(self, fn_parent_ref, fn_parent_seq): '''Based on the parent reference and sequence, computes the full path. The majority of the files in a filesystem has a very small amount of parent directories. By definition, a filesystem is expected to have much smaller amount...
java
public JenkinsServer updateView(String viewName, String viewXml) throws IOException { return this.updateView(viewName, viewXml, true); }
python
def set_data(self, data): ''' Sending data to via TCP. Parameters ---------- data : array Array of unsigned integers (32 bit). ''' data = array.array('B', struct.unpack("{}B".format(len(data) * 4), struct.pack("{}I".format(len(data)), *data))) self._i...
python
def get(self, **params): ''' Returns details for a specific offer. .. code-block:: python amadeus.shopping.hotel_offer('XXX').get :rtype: amadeus.Response :raises amadeus.ResponseError: if the request could not be completed ''' return self.client.ge...
java
public synchronized ProgressBar setMin(int min) { if(min > max) { setMax(min); } if(min > value) { setValue(min); } if(this.min != min) { this.min = min; invalidate(); } return this; }
python
def translate_to_ascii(values): r"""Transliterate the string into ascii representation. Transliterate the string contents of the given sequence into ascii representation. Returns a sequence with the modified values if the module 'unidecode' is available. Otherwise it will fall back to the inferior ...
java
protected void error(String msg) { System.err.println(CSLToolContext.current().getToolName() + ": " + msg); }
java
private void assignUserFileOwnership(final String effectiveUser, final String fileName) throws Exception { final ExecuteAsUser executeAsUser = new ExecuteAsUser( this.getSysProps().getString(AZKABAN_SERVER_NATIVE_LIB_FOLDER)); final String groupName = this.getSysProps().getString(AZKABAN_SERVER_GR...
python
def watch(key, recurse=False, profile=None, timeout=0, index=None, **kwargs): ''' .. versionadded:: 2016.3.0 Makes a best effort to watch for a key or tree change in etcd. Returns a dict containing the new key value ( or None if the key was deleted ), the modifiedIndex of the key, whether the key c...
java
public Map<String, EntityDocument> wbGetEntities(String ids, String sites, String titles, String props, String languages, String sitefilter) throws MediaWikiApiErrorException, IOException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put(ApiConnection.PARAM_ACTION, "wbgetentiti...
java
@Override public CPOptionValue fetchCPOptionValueByUuidAndGroupId(String uuid, long groupId) { return cpOptionValuePersistence.fetchByUUID_G(uuid, groupId); }
python
def kube_node_status_ready(self, metric, scraper_config): """ The ready status of a cluster node (legacy)""" service_check_name = scraper_config['namespace'] + '.node.ready' for sample in metric.samples: node_tag = self._label_to_tag("node", sample[self.SAMPLE_LABELS], scraper_config...
python
def sentinels(self, name): """Returns a list of sentinels for ``name``.""" fut = self.execute(b'SENTINELS', name, encoding='utf-8') return wait_convert(fut, parse_sentinel_slaves_and_sentinels)
python
def rad_latitude(self): """ Lazy conversion degrees latitude to radians. """ if self._rad_latitude is None: self._rad_latitude = math.radians(self.latitude) return self._rad_latitude
python
def set_years(self, startyear=1765, endyear=2100): """ Set the start and end dates of the simulations. Parameters ---------- startyear : int Start year of the simulation endyear : int End year of the simulation Returns ------- ...
java
@Nonnull public static <T1, T2, R> LBiObjLongFunctionBuilder<T1, T2, R> biObjLongFunction() { return new LBiObjLongFunctionBuilder(); }
java
@SuppressWarnings({"checkstyle:parametername", "checkstyle:localfinalvariablename"}) private static Point2d NTFLambert_NTFLambdaPhi(double x, double y, double n, double c, double Xs, double Ys) { // Several constants from the IGN specifications //Longitude in radians of Paris (2°20'14.025" E) from Greenwich fina...
java
protected void reportWarning(ValidationResult result, String messageKey, Object... params) { reportMessage(result, Severity.WARNING, messageKey, params); }
java
public ManagementEdge getBackwardEdge(final int index) { if (index < this.backwardEdges.size()) { return this.backwardEdges.get(index); } return null; }
python
def authorize_url(self, state=None): ''' Generate authorize_url. >>> GitHub(client_id='3ebf94c5776d565bcf75').authorize_url() 'https://github.com/login/oauth/authorize?client_id=3ebf94c5776d565bcf75' ''' if not self._client_id: raise ApiAuthError('No client i...
python
def _float(text): """Fonction to convert the 'decimal point assumed' format of TLE to actual float >>> _float('0000+0') 0.0 >>> _float('+0000+0') 0.0 >>> _float('34473-3') 0.00034473 >>> _float('-60129-4') -6.0129e-05 >>> _float('+45871-4') 4.5871e-05 """ text ...
python
def process(self): """ This method handles the actual processing of Modules and Transforms """ self.modules.sort(key=lambda x: x.priority) for module in self.modules: transforms = module.transform(self.data) transforms.sort(key=lambda x: x.linenum, revers...
python
def run(self, processes=4): """TODO""" if processes == 1: self.pool = MockTub(init_worker, (self.inpaths, self.global_args)) else: self.pool = Pool(processes, init_worker, (self.inpaths, self.global_args)) self.options["transform"] = guard_transform(self.options[...
python
def status(self): """ Get the :py:class:`~user_tasks.models.UserTaskStatus` model instance for this UserTaskMixin. """ task_id = self.request.id try: # Most calls are for existing objects, don't waste time # preparing creation arguments unless necessary ...
java
public void register(final GVRSceneObject sceneObject, final Focusable focusable) { Log.d(Log.SUBSYSTEM.FOCUS, TAG, "register sceneObject %s , focusable = %s", sceneObject.getName(), focusable); mFocusableMap.put(sceneObject, new WeakReference<>(focusable)); }
java
public List<StreamObjectV2> getAppStream(int appId, Integer limit, Integer offset) { return getStreamV2("/stream/app/" + appId + "/", limit, offset, null, null); }
java
public static int unmarshallSize(ObjectInput in) throws IOException { byte b = in.readByte(); if ((b & 0x80) != 0) { return NULL_VALUE; //negative value } int i = b & 0x3F; if ((b & 0x40) == 0) { return i; } int shift = 6; do { b = in.readByte()...
java
public static void safeIncr(String counterName) { org.apache.heron.api.metric.GlobalMetrics.safeIncr(counterName); }
java
@Override public void closeLog(byte[] serviceData) throws InternalLogException { if (tc.isEntryEnabled()) Tr.entry(tc, "closeLog", new java.lang.Object[] { RLSUtils.toHexString(serviceData, RLSUtils.MAX_DISPLAY_BYTES), this }); if (_logHandle != null) { try ...
python
def _container_registration(self, alias): """ Check for an available name and return that to the caller. """ containers = Container.find_by_name(self._client_session, alias) def validate_name(name): valid = True if name in containers: vali...
python
def migrateUp(self): """ Recreate the hooks in the site store to trigger this SubScheduler. """ te = self.store.findFirst(TimedEvent, sort=TimedEvent.time.descending) if te is not None: self._transientSchedule(te.time, None)
java
public void truncate(int offset) throws IOException { if ((offset < 0)||(offset > _write_pos)) throw new IOException("bad truncate offset"); if (_read_pos > offset) _read_pos = offset; if (_mark_pos > offset) _mark_pos = offset; _write_pos = offset; if (_file_high > offset) _file...
java
public Future<SummonerSpell> getSummonerSpell(int id, SpellData data) { return new DummyFuture<>(handler.getSummonerSpell(id, data)); }
java
public void marshall(CreateListenerRequest createListenerRequest, ProtocolMarshaller protocolMarshaller) { if (createListenerRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createListenerRe...
python
def evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, output_file, debug=False): """Evaluate parser on a data set Parameters ---------- parser : BiaffineParser biaffine parser vocab : ParserVocabulary vocabulary built ...
java
@Override public void makeSensitiveBuildVariables(AbstractBuild build, Set<String> sensitiveVariables) { super.makeSensitiveBuildVariables(build, sensitiveVariables); // TODO determine if there is a meaningful way to generalize this; perhaps as a new [Run]Action recording sensitiveVariables? // ...
python
def print_progress_bar(text, done, total, width): """ Print progress bar. """ if total > 0: n = int(float(width) * float(done) / float(total)) sys.stdout.write("\r{0} [{1}{2}] ({3}/{4})".format(text, '#' * n, ' ' * (width - n), done, total)) sys.stdout.flush()
java
public static Path appendLinesAndClose(String filePath, Charset charset, String... lines) { return appendLineStreamAndClose(filePath, charset, Arrays.stream(lines)); }
java
public static long scalarProduct(final Modulo2Equation e, long[] solution) { long sum = 0; for(final IntListIterator iterator = e.variables.iterator(); iterator.hasNext();) sum ^= solution[iterator.nextInt()]; return sum; }
python
def flatten_list(l): """ Nested lists to single-level list, does not split strings""" return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l))
java
public void setHtml5Asset(com.google.api.ads.admanager.axis.v201811.CreativeAsset html5Asset) { this.html5Asset = html5Asset; }
java
Object insertByLeftShift( int ix, Object new1) { Object old1 = leftMostKey(); leftShift(ix); _nodeKey[ix] = new1; if (midPoint() > rightMostIndex()) _nodeKey[midPoint()] = rightMostKey(); return old1; }
python
def do_fake_filter( formatter, arg=None ): """ call a faker format uses: {{ 'randomElement'|fake:mylist }} {% if 'boolean'|fake:30 %} .. {% endif %} {% for word in 'words'|fake:times %}{{ word }}\n{% endfor %} """ args = [] if not arg is None: args.append(arg) retur...
java
private void collectModifications(NameAwareAttribute changedAttr, List<ModificationItem> modificationList) throws NamingException { NameAwareAttribute currentAttribute = originalAttrs.get(changedAttr.getID()); if(currentAttribute != null && changedAttr.hasValuesAsNames()) { try { ...
java
public ApplicationDefinition getApplication(Tenant tenant, String appName) { checkServiceState(); return getApplicationDefinition(tenant, appName); }
java
public static void saveFile(final File file, final String contents, final String encoding) throws IOException { saveFile(file, contents.getBytes(encoding)); }
java
public static void getOrdering(int p, int n, List<String> list, int[] gt, int pos, int[] map) { for (int a = 0; a <= n; a++) { if (map == null) { gt[pos] = a; } else { // Remap allele gt[pos] = remapAllele(map, a); } ...
java
protected void doSetAllValues( Document values ) { if (values != null) { values = Utility.unwrap(values); document.putAll(values); } }
java
@Override public EClass getIfcSoundPowerLevelMeasure() { if (ifcSoundPowerLevelMeasureEClass == null) { ifcSoundPowerLevelMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(865); } return ifcSoundPowerLevelMeasureEClass; }
python
def _format_table(fmt, headers, rows, colwidths, colaligns, is_multiline): """Produce a plain-text representation of the table.""" lines = [] hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else [] pad = fmt.padding headerrow = fmt.headerrow padded_widths = [(w + 2 * pad) fo...
python
def close(self): """ Close the connection to the AMQP compliant broker. """ if self.channel is not None: self.channel.close() if self.__connection is not None: self.__connection.close()
java
protected void addNodeToItsParent(CmsAppCategoryNode node) { String parentId = node.getCategory().getParentId(); if (CmsStringUtil.isEmptyOrWhitespaceOnly(parentId)) { parentId = null; } CmsAppCategoryNode parentNode = m_nodes.get(parentId); if (parentNode == null) {...
java
protected void addToNonSingletonListeners(final Object bean) { if( logger.isDebugEnabled() ) logger.debug( "Adding Authentication/LoginAware bean to list of non-singleton listeners: bean='" + bean ); nonSingletonListeners.add( new WeakReference( bean ) ); }
python
def _FormatNotes(self, event): """Formats the notes. Args: event (EventObject): event. Returns: str: formatted notes field. """ inode = event.inode if inode is None: inode = '-' notes = getattr(event, 'notes', '') if not notes: display_name = getattr(event, '...
python
def keyphrases_table(keyphrases, texts, similarity_measure=None, synonimizer=None, language=consts.Language.ENGLISH): """ Constructs the keyphrases table, containing their matching scores in a set of texts. The resulting table is stored as a dictionary of dictionaries, where the en...