language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def generated_key(key): """Create the proper generated key value""" key_name = key['name'] if key['method'] == 'uuid': LOG.debug("Setting %s to a uuid", key_name) return str(uuid4()) elif key['method'] == 'words': LOG.debug("Setting %s to random words", key_name) return r...
python
def loadAnns(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :return: anns (object array) : loaded ann objects """ if type(ids) == list: return [self.anns[id] for id in ids] elif type(ids)...
java
public CloudJob get(String jobId, JobGetOptions jobGetOptions) { return getWithServiceResponseAsync(jobId, jobGetOptions).toBlocking().single().body(); }
java
@SneakyThrows protected Pair<String, String> generateCertificateAndKey() { try (val certWriter = new StringWriter(); val keyWriter = new StringWriter()) { samlIdPMetadataGeneratorConfigurationContext.getSamlIdPCertificateAndKeyWriter().writeCertificateAndKey(keyWriter, certWriter); v...
java
public static CharBuffer clearAndEnsureCapacity(CharBuffer buffer, int elements) { if (buffer == null || buffer.capacity() < elements) { buffer = CharBuffer.allocate(elements); } else { buffer.clear(); } return buffer; }
python
def DyJsonData(cls,name, sequence): ''' set dynamic value from the json data of response @param name: glob parameter name @param sequence: sequence for the json e.g. result={"a":1, "b":[1,2,3,4], "c":{"d":5,"e":6}, "f...
python
def latex(source: str): """ Add a mathematical equation in latex math-mode syntax to the display. Instead of the traditional backslash escape character, the @ character is used instead to prevent backslash conflicts with Python strings. For example, \\delta would be @delta. :param source: ...
python
def to_bytes(value, encoding='utf-8'): """Converts a string value to bytes, if necessary. Unfortunately, ``six.b`` is insufficient for this task since in Python 2 because it does not modify ``unicode`` objects. Args: value (Union[str, bytes]): The value to be converted. encoding (str):...
java
public Object eval(Selector sel) { try { return eval(sel, MatchSpaceKey.DUMMY, EvalCache.DUMMY, null, false); } catch (BadMessageFormatMatchingException e) { // No FFDC Code Needed. // FFDC driven by wrapper class. FFDC.processException(this, cclass, "co...
java
@Override public String startRestoreFromSnapshot(String snapshotName) { String jobID = consNextJobID(); String jobName = consJobName("restoreBackup", snapshotName); LongJob job = getNode().consRestoreFromSnapshotJob(jobID, jobName, snapshotName); startJob(job); return jobID; }
java
public void addAnnotationDetailsTreeHeader(ClassDoc classDoc, Content memberDetailsTree) { if (!writer.printedAnnotationHeading) { memberDetailsTree.addContent(writer.getMarkerAnchor( SectionName.ANNOTATION_TYPE_ELEMENT_DETAIL)); Content heading = HtmlTree...
java
public static base_response update(nitro_service client, authenticationauthnprofile resource) throws Exception { authenticationauthnprofile updateresource = new authenticationauthnprofile(); updateresource.name = resource.name; updateresource.authnvsname = resource.authnvsname; updateresource.authenticationhost...
java
public void addToolBarComponent(Component component) { validateComponentNonNull(component); if (component instanceof JButton) { addButton((JButton) component); } else if (component instanceof JToggleButton) { addButton((JToggleButton) component); } else { getToolbar().add(component); } }
python
def get_local_uri(m, file_names, _): """ populates file_names list with urls that matched the regex match object returns the total filesize of all the files matched """ path = m.group(2) result = 0 for root, _, files in os.walk(path): for file_name in files: absolute_path...
python
def create(self, weight, priority, enabled, friendly_name, sip_url): """ Create a new OriginationUrlInstance :param unicode weight: The value that determines the relative load the URI should receive compared to others with the same priority :param unicode priority: The relative importan...
python
def get_data_from_buffer(self, filter_func=None, converter_func=None): '''Reads local data buffer and returns data and meta data list. Returns ------- data : list List of data and meta data dicts. ''' if self._is_running: raise RuntimeErr...
python
def parse(self,fileName,offset): '''Parses synset from file <fileName> from offset <offset> ''' p = Parser() p.file = open(fileName, 'rb') a = p.parse_synset(offset=offset) p.file.close() self.__dict__.update(a.__dict__)
python
def is_full(self): """ :return: """ if self.cache.currsize == self.cache.maxsize: return True return False
java
public static boolean cs_usolve(Scs U, float[] x) { int p, j, n, Up[], Ui[]; float Ux[]; if (!Scs_util.CS_CSC(U) || x == null) return (false); /* check inputs */ n = U.n; Up = U.p; Ui = U.i; Ux = U.x; for (j = n - 1; j >= 0; j--) { ...
java
public void updateUsableScales() { Bbox bgBounds = backgroundPart.getBounds(); /* * First move background a little bit to right based on difference in width with the sliderUnit. */ int internalHorMargin = (int) (sliderUnit.getBounds().getWidth() - backgroundPart.getBounds().getWidth()) / 2; bgBounds.setX(...
java
private ClassLoader makeGlobalClassLoader(ModuleLoader moduleLoader, ModuleIdentifier cacheContainerModule, List<ModuleIdentifier> additionalModules) throws ModuleLoadException { Set<ClassLoader> classLoaders = new LinkedHashSet<>(); // use an ordered set to deduplicate possible duplicates! if (cacheCo...
python
def admin_tagify(short_description=None, allow_tags=True): """ Decorator that add short_description and allow_tags to ModelAdmin list_display function. Example: class AlbumAdmin(admin.ModelAdmin): ...
java
public void checkDirectory(InodeDirectory inode, AlluxioURI alluxioUri) throws FileDoesNotExistException, InvalidPathException, IOException { Preconditions.checkArgument(inode.isPersisted()); UfsStatus[] ufsChildren = getChildrenInUFS(alluxioUri); // Filter out temporary files ufsChildren = Arrays...
python
def minion_process(): ''' Start a minion process ''' import salt.utils.platform import salt.utils.process import salt.cli.daemons # salt_minion spawns this function in a new process salt.utils.process.appendproctitle('KeepAlive') def handle_hup(manager, sig, frame): manage...
python
def set_instance(self, thing: type, value, overwrite=False): """ Set an instance of a thing. """ if thing in self.instances and not overwrite: raise DiayException('instance for %r already exists' % thing) self.instances[thing] = value
java
public final TcpServer doOnBound(Consumer<? super DisposableServer> doOnBound) { Objects.requireNonNull(doOnBound, "doOnBound"); return new TcpServerDoOn(this, null, doOnBound, null); }
java
public Observable<ServiceResponse<OperationBatchStatusResponseInner>> getOperationBatchStatusWithServiceResponseAsync(String userName, List<String> urls) { if (userName == null) { throw new IllegalArgumentException("Parameter userName is required and cannot be null."); } if (this.cli...
java
public boolean checkModuleGroups(String groupname, String moduleNameFormList) { String[] mdlPatterns = moduleNameFormList.split(":"); if (groupList.contains(groupname)) { initMessages(); messages.warning("doclet.Groupname_already_used", groupname); return false; ...
java
public static ValueType fromConfig(String property) { //If the property is valid and we cannot find a "property.type" then the value of the property represents its simple type. if (Config.hasProperty(property) && !Config.hasProperty(property, TYPE_PROPERTY)) { return new SimpleValueType(Config.get(...
java
public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException { return new XNumber(getArg0AsString(xctxt).length()); }
java
public void andWith(OrCondition other) { //Because Titan does not natively support Or conditions in Graph Queries, //we need to expand out the condition so it is in the form of a single OrCondition //that contains only AndConditions. We do this by following the rules of boolean //algeb...
python
def post(self): """Create a new user""" self.reqparse.add_argument('username', type=str, required=True) self.reqparse.add_argument('authSystem', type=str, required=True) self.reqparse.add_argument('password', type=str, required=False, default=None) self.reqparse.add_argument('rol...
python
def _legacy_handle_unregistration(config, pconn): """ returns (bool): True success, False failure """ check = get_registration_status(config, pconn) for m in check['messages']: logger.debug(m) if check['unreachable']: # Run connection test and exit return None ...
python
def get_unset_inputs(self): """ Return a set of unset inputs """ return set([k for k, v in self._inputs.items() if v.is_empty(False)])
python
def sample(problem, N, calc_second_order=True, seed=None): """Generates model inputs using Saltelli's extension of the Sobol sequence. Returns a NumPy matrix containing the model inputs using Saltelli's sampling scheme. Saltelli's scheme extends the Sobol sequence in a way to reduce the error rat...
java
@XmlElementDecl(namespace = "http://www.w3.org/1998/Math/MathML", name = "tendsto") public JAXBElement<TendstoType> createTendsto(TendstoType value) { return new JAXBElement<TendstoType>(_Tendsto_QNAME, TendstoType.class, null, value); }
python
def get_event(self, timeout=None, block=True): """ Fetch the next available :class:`Event` from any source, or raise :class:`mitogen.core.TimeoutError` if no value is available within `timeout` seconds. On success, the message's :attr:`receiver <mitogen.core.Message.rece...
java
public ClassInfoList getClassesWithAnnotation() { if (!scanResult.scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()"); } if (!isAnnotation) { throw new IllegalArgumentException("Class is not a...
java
public static SparseDoubleVector immutable(SparseDoubleVector vector) { if (vector == null) throw new NullPointerException("Cannot create an immutable " + "null vector"); return new ViewDoubleAsDoubleSparseVector(vector, true); }
python
def _load_text(handle, split=False, encoding="utf-8"): """Load and decode a string.""" string = handle.read().decode(encoding) return string.splitlines() if split else string
python
def distribute(self, func, partitioned_chunks, kwargs): """ Calculates the features in a sequential fashion by pythons map command :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - each element is again ...
java
public CmsLogFilter filterFrom(long from) { CmsLogFilter filter = (CmsLogFilter)clone(); filter.m_dateFrom = from; return filter; }
java
public void deleteServerRegistrationHTTP(RESTRequest request, int clientID, ServerNotificationRegistration serverNotificationRegistration, String registrationID, ...
java
@Override public EClass getIfcFurniture() { if (ifcFurnitureEClass == null) { ifcFurnitureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(298); } return ifcFurnitureEClass; }
python
def get_filename4code(module, content, ext=None): """Generate filename based on content The function ensures that the (temporary) directory exists, so that the file can be written. Example: filename = get_filename4code("myfilter", code) """ imagedir = module + "-images" fn = hashli...
java
@Deprecated public void connect(Object from, String from_out, Object to, String to_in) { controller.connect(from, from_out, to, to_in); }
java
public void onSearchBoxTextChanged(String searchText, boolean forceReloadEventIfSameText) { if (!forceReloadEventIfSameText && Utility.stringsEqualOrEmpty(this.searchText, searchText)) { return; } if (TextUtils.isEmpty(searchText)) { searchText = null; } ...
java
public void initialize(ControlBean bean, Object target) { initServices(bean, target); initControls(bean, target); initEventProxies(bean, target); }
java
public static <T> Option<T> of(T t) { return t == null ? Option.<T>none() : some(t); }
python
def list_plugins(path, user): ''' List plugins in an installed wordpress path path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.list_plugins /var/www/html apache ''' ret = [] resp ...
java
public Future<CreateTableResult> createTableAsync(final CreateTableRequest createTableRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateTableResult>() { public CreateTableResult call() throws Exception { retu...
java
protected Long addLongValue(Object name, long inc) { Long val = this.longCounters.get(name); Long retv = null; if (val == null) { retv = new Long(inc); } else { retv = new Long(val.longValue() + inc); } this.longCounters.put(name, retv); return retv; }
python
def get_result(self): """Perform the call and return the peak date and how many users""" result = get_json_from_remote_server(self.call) if result: date, value = max(result.iteritems(), key=itemgetter(1)) return {'date': date, 'users': value} else: ret...
python
def parse_username_password_hostname(remote_url): """ Parse a command line string and return username, password, remote hostname and remote path. :param remote_url: A command line string. :return: A tuple, containing username, password, remote hostname and remote path. """ assert remote_url ...
java
private Map<String, Snapshot> getSnapshots() { /* * Use the individual snapshot directories instead of voltroot, because * they can be set individually */ Map<String, SnapshotPathType> paths = new HashMap<String, SnapshotPathType>(); if (VoltDB.instance().getConfig().m...
python
def get_package_dir_name(self, nb): """This is the name of the package we will be creating. """ package_dir = self.package_dir if not package_dir: package_dir = getcwd() package_name = self.package_name if not package_name: doc = ExtractInlineMetatabDo...
python
def create(ctx, data): """Create a new SWAG item.""" swag = create_swag_from_ctx(ctx) data = json.loads(data.read()) for account in data: swag.create(account, dry_run=ctx.dry_run)
java
private void classify() { // Classify monitor.taskStarted("Classifying"); monitor.taskBusy(); reasoner = reasoner.classify(); monitor.taskEnded(); monitor.taskStarted("Building taxonomy"); monitor.taskBusy(); taxonomy = reasoner.getClassifiedOntolo...
java
protected void handleCitationAnnotations(ProtoNetwork protoNetwork, Citation citation, Map<String, Annotation> annotationMap) { AnnotationDefinitionTable adt = protoNetwork .getAnnotationDefinitionTable(); final CommonModelFactory af = CommonModelFactory.getInstance(); ...
python
def minify_ring(mol, verbose=False): """ Minify ring set (similar to SSSR) Limitation: this can not correctly recognize minimum rings in the case of non-outerplanar graph. Note: concept of SSSR is controversial. Roughly reduce the size of cycle basis can help some scaffold-based analysis """ ...
java
public static <T extends Throwable> Try<T, Unit> trying(CheckedRunnable<T> runnable) { return trying(() -> { runnable.run(); return UNIT; }); }
java
public String resolve(String label, int type) throws DNSSECException { // Setup Resolver try { this.validatingResolver.loadTrustAnchors(new ByteArrayInputStream(ROOT.getBytes("ASCII"))); } catch (UnknownHostException e) { throw new DNSSECException("Unknown DNS Host: " + ...
java
public Observable<JobScheduleInner> getAsync(String resourceGroupName, String automationAccountName, UUID jobScheduleId) { return getWithServiceResponseAsync(resourceGroupName, automationAccountName, jobScheduleId).map(new Func1<ServiceResponse<JobScheduleInner>, JobScheduleInner>() { @Override ...
java
public static UaiRoute findValidRoute(final HttpServerExchange httpServerExchange) { final List<UaiRoute> orderedList = getSortedRouteByKey(httpServerExchange); if (orderedList.isEmpty()) { final String errorText = String.format( URI_NOT_FOUND_MESSAGE, httpSe...
python
def tail(self, line_by_line=True, move_end=True): """Read line-by-line and run callback on each line. line_by_line: yield each time a callback has returned True move_end: start from the last line of the log""" try: self._open_file(move_end=move_end) while True: ...
java
private <T,S> void upgradeWebSocket(ServiceWebSocket<T,S> service) { /* try { _service.open((WebRequest) request); } catch (Exception e) { log.log(Level.WARNING, e.toString(), e); } */ TypeRef type = TypeRef.of(service.getClass()).to(ServiceWebSocket.class).param(0); ServiceRe...
java
public boolean seek(KafkaTopicPartitionOffset tpo) { KafkaConsumer<String, byte[]> consumer = _getConsumer(tpo.topic); return KafkaHelper.seek(consumer, tpo); }
python
def browse_morelikethis_preview(self, seed): """Fetch More Like This preview result for a seed deviation :param seed: The deviationid to fetch more like """ response = self._req('/browse/morelikethis/preview', { "seed":seed }) returned_seed = response['see...
python
def _HuntOutputPluginStateFromRow(self, row): """Builds OutputPluginState object from a DB row.""" plugin_name, plugin_args_bytes, plugin_state_bytes = row plugin_descriptor = rdf_output_plugin.OutputPluginDescriptor( plugin_name=plugin_name) if plugin_args_bytes is not None: plugin_args_...
python
def install(): """Manual install main script. """ # check installed package print("Compare to '%s' ..." % _DST) need_install_flag = check_need_install() if not need_install_flag: print("\tpackage is up-to-date, no need to install.") return print("Difference been found, start ...
python
def _who_when(self, s, cmd, section, accept_just_who=False): """Parse who and when information from a string. :return: a tuple of (name,email,timestamp,timezone). name may be the empty string if only an email address was given. """ match = _WHO_AND_WHEN_RE.search(s) ...
python
def _expand_subsystems(self, scope_infos): """Add all subsystems tied to a scope, right after that scope.""" # Get non-global subsystem dependencies of the specified subsystem client. def subsys_deps(subsystem_client_cls): for dep in subsystem_client_cls.subsystem_dependencies_iter(): if dep....
java
public ClientBootstrap bootStrapTcpClient() throws HttpRequestCreateException { ClientBootstrap tcpClient = null; try { // Configure the client. tcpClient = new ClientBootstrap(tcpMeta.getChannelFactory()); // Configure the pipeline factory. ...
java
@GwtIncompatible("incompatible method") public static boolean isAssignable(final Class<?> cls, final Class<?> toClass) { return isAssignable(cls, toClass, SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5)); }
java
private String generateKey(String key, HashMap<String, String[]>[] queryVariables) { StringBuilder newKey = new StringBuilder(key); newKey.append(" -"); for (int q = 0; q < queryVariables.length; q++) { if (queryVariables[q] != null && queryVariables[q].size() > 0) { for (String name : q...
java
public EClass getExternalAlgorithm() { if (externalAlgorithmEClass == null) { externalAlgorithmEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(393); } return externalAlgorithmEClass; }
java
private Writer doWrite(Writer writer, int indentFactor, int indent) throws IOException { writer.write(CharUtil.DELIM_START); boolean isFirst = true; final boolean isIgnoreNullValue = this.config.isIgnoreNullValue(); final int newIndent = indent + indentFactor; for (Entry<String, Object> entry : this.entr...
python
def compute_gas_limit(parent_header: BlockHeader, gas_limit_floor: int) -> int: """ A simple strategy for adjusting the gas limit. For each block: - decrease by 1/1024th of the gas limit from the previous block - increase by 50% of the total gas used by the previous block If the value is less...
java
@Then("^we are in page '(.+?)'$") public void checkURL(String url) throws Exception { if (commonspec.getWebHost() == null) { throw new Exception("Web host has not been set"); } if (commonspec.getWebPort() == null) { throw new Exception("Web port has not been set"); ...
java
private boolean symmetryBreakingForStayingVMs(ReconfigurationProblem rp) { for (VM vm : rp.getFutureRunningVMs()) { VMTransition a = rp.getVMAction(vm); Slice dSlice = a.getDSlice(); Slice cSlice = a.getCSlice(); if (dSlice != null && cSlice != null) { ...
java
public void onDestroy(Activity activity) { if (sameActivity(activity)) { hideCurrentScreen(); this.activity = null; container = null; menu = null; } }
java
static void int2bin( int value, /* input : decimal value */ int no_of_bits, /* input : number of bits to use */ short[] bitstream, int bitstreams /* output: bitstream */ ) { int pt_bitstream; short i, bit; pt_bitstream = bitstreams + no_of_bits; for (i = 0; i < no_o...
python
def acquaint_insides(swap_gate: ops.Gate, acquaintance_gate: ops.Operation, qubits: Sequence[ops.Qid], before: bool, layers: Layers, mapping: Dict[ops.Qid, int] ) -> None: """Acquaints each ...
java
public static void toDNF(LogicClause topNode) { while(makeDNF(topNode) == false) { // do nothing, just repeat } cleanEmptyLeafs(topNode); flattenDNF(topNode); }
python
def sparse_reindex(self, new_index): """ Conform sparse values to new SparseIndex Parameters ---------- new_index : {BlockIndex, IntIndex} Returns ------- reindexed : SparseSeries """ if not isinstance(new_index, splib.SparseIndex): ...
python
def partial_predict(self, X, y=None): """Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters...
python
def _build_type(type_, value, property_path=None): """ Builds the schema definition based on the given type for the given value. :param type_: The type of the value :param value: The value to build the schema definition for :param List[str] property_path: The property path of the current type, ...
python
def consume_input(self, inp): """ Return True/False if the machine accepts/reject the input. Args: inp (str): input string to be consumed Returns: bool: A true or false value depending on if the DFA accepts the provided input """ cu...
java
public void execute() throws IOException { try { prepare(); boolean commitResult = commit(); if (commitResult == false) { throw PatchLogger.ROOT_LOGGER.failedToDeleteBackup(); } } catch (PrepareException pe){ rollback(); ...
java
public CredentialsProvider createFor(String uri, String username, String password, String passphrase, boolean skipSslValidation) { CredentialsProvider provider = null; if (awsAvailable() && AwsCodeCommitCredentialProvider.canHandle(uri)) { this.logger .debug("Constructing AwsCodeCommitCredentialProvider ...
java
public StringGrabber removeHeadConsecutiveChars(char charToRemove) { boolean loop = true; if (sb.length() > 0) { while (loop) { if (sb.charAt(0) == charToRemove) { removeHead(1); } else { loop = false; } } } return StringGrabber.this; }
java
public String getCmdOut() { return debug.transform(new Function<Debug, String>() { @Override public String apply(Debug input) { return input.getCmdout(); } }).or(""); }
python
def control_valve_noise_g_2011(m, P1, P2, T1, rho, gamma, MW, Kv, d, Di, t_pipe, Fd, FL, FLP=None, FP=None, rho_pipe=7800.0, c_pipe=5000.0, P_air=101325.0, rho_air=1.2, c_air=343.0, An=-3.8, St...
java
@Override public Collection<String> getHeaders(String name) { return (headers != null ? headers.get(name) : null); }
python
def lrem(self, key, value, count=0): """Emulate lrem.""" value = self._encode(value) redis_list = self._get_list(key, 'LREM') removed_count = 0 if self._encode(key) in self.redis: if count == 0: # Remove all ocurrences while redis_list....
python
def define_operators(cls, operators): """Bind operators to specified functions for the scope of the context: Example ------- model = Model() other = Model() with Model.define_operators({"+": lambda self, other: "plus"}): print(model + other) ...
python
def random_redshift_array( log, sampleNumber, lowerRedshiftLimit, upperRedshiftLimit, redshiftResolution, pathToOutputPlotDirectory, plot=False): """ *Generate a NumPy array of random distances given a sample number and distance limit* **Key Arguments...
python
def _process_plugin(self, plugin): ''' Logic to handle each plugin that is active @param plugin: a plugin dict object ''' instance = plugin['instance'] regex = plugin['regex'] for key in self.redis_conn.scan_iter(match=regex): # acquire lock ...
java
public PropertyNameProcessor findJavaPropertyNameProcessor( Class beanClass ) { if( !javaPropertyNameProcessorMap.isEmpty() ) { Object key = javaPropertyNameProcessorMatcher.getMatch( beanClass, javaPropertyNameProcessorMap.keySet() ); return (PropertyNameProcessor) javaPropertyNameProcessorMap....
java
@SuppressWarnings("unchecked") private void setValue(List<Element> elements, String attrName, Object pojo, CustomPropertyDescriptor field) { XmlNode attrXmlNode = field.getAnnotation(XmlNode.class); log.debug("要赋值的fieldName为{}", field.getName()); final XmlTypeConver...