language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static Bip39Wallet generateBip39Wallet(String password, File destinationDirectory) throws CipherException, IOException { byte[] initialEntropy = new byte[16]; secureRandom.nextBytes(initialEntropy); String mnemonic = MnemonicUtils.generateMnemonic(initialEntropy); byte[] seed = MnemonicUtils.generateSeed(mnemonic, password); ECKeyPair privateKey = ECKeyPair.create(sha256(seed)); String walletFile = generateWalletFile(password, privateKey, destinationDirectory, false); return new Bip39Wallet(walletFile, mnemonic); }
java
private void checkIfUpdateIsNeeded(CmsUUID structureId, String rootPath, int typeId) { try { I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(typeId); if ((resType instanceof CmsResourceTypeXmlContent) && !OpenCms.getResourceManager().matchResourceType( CmsResourceTypeXmlContainerPage.RESOURCE_TYPE_NAME, typeId)) { markForUpdate(structureId); } } catch (CmsLoaderException e) { // resource type not found, just log an error LOG.error(e.getLocalizedMessage(), e); } }
python
def request_hc_path_corresponds(self): """ Tells if the hc path of the request corresponds to that specified by the admin :return: a boolean that says if it corresponds or not """ uri_path = self.path.split(COAP_PREFACE) request_hc_path = uri_path[0] logger.debug("HCPATH: %s", hc_path) # print HC_PATH logger.debug("URI: %s", request_hc_path) if hc_path != request_hc_path: return False else: return True
python
def absolute_redirect_n_times(n): """Absolutely 302 Redirects n times. --- tags: - Redirects parameters: - in: path name: n type: int produces: - text/html responses: 302: description: A redirection. """ assert n > 0 if n == 1: return redirect(url_for("view_get", _external=True)) return _redirect("absolute", n, True)
java
public DbHistory[] get_device_attribute_property_history(String devname, String attname, String propname) throws DevFailed { return databaseDAO.get_device_attribute_property_history(this, devname, attname, propname); }
java
public static base_response add(nitro_service client, dnssoarec resource) throws Exception { dnssoarec addresource = new dnssoarec(); addresource.domain = resource.domain; addresource.originserver = resource.originserver; addresource.contact = resource.contact; addresource.serial = resource.serial; addresource.refresh = resource.refresh; addresource.retry = resource.retry; addresource.expire = resource.expire; addresource.minimum = resource.minimum; addresource.ttl = resource.ttl; return addresource.add_resource(client); }
java
public static ArrayList<VictimsRecord> getRecords(InputStream in, String filename) throws IOException { ArrayList<VictimsRecord> records = new ArrayList<VictimsRecord>(); Artifact artifact = Processor.process(in, filename); scanArtifact(artifact, new ArrayOutputStream(records)); return records; }
python
def confirm_register_form_factory(Form): """Factory for creating a confirm register form.""" class CsrfDisabledProfileForm(ProfileForm): """Subclass of ProfileForm to disable CSRF token in the inner form. This class will always be a inner form field of the parent class `Form`. The parent will add/remove the CSRF token in the form. """ def __init__(self, *args, **kwargs): """Initialize the object by hardcoding CSRF token to false.""" kwargs = _update_with_csrf_disabled(kwargs) super(CsrfDisabledProfileForm, self).__init__(*args, **kwargs) class ConfirmRegisterForm(Form): """RegisterForm extended with UserProfile details.""" profile = FormField(CsrfDisabledProfileForm, separator='.') return ConfirmRegisterForm
java
public DecoderResult decode(BitMatrix bits) throws FormatException, ChecksumException { // Construct a parser and read version, error-correction level BitMatrixParser parser = new BitMatrixParser(bits); Version version = parser.getVersion(); // Read codewords byte[] codewords = parser.readCodewords(); // Separate into data blocks DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version); // Count total number of data bytes int totalBytes = 0; for (DataBlock db : dataBlocks) { totalBytes += db.getNumDataCodewords(); } byte[] resultBytes = new byte[totalBytes]; int dataBlocksCount = dataBlocks.length; // Error-correct and copy data blocks together into a stream of bytes for (int j = 0; j < dataBlocksCount; j++) { DataBlock dataBlock = dataBlocks[j]; byte[] codewordBytes = dataBlock.getCodewords(); int numDataCodewords = dataBlock.getNumDataCodewords(); correctErrors(codewordBytes, numDataCodewords); for (int i = 0; i < numDataCodewords; i++) { // De-interlace data blocks. resultBytes[i * dataBlocksCount + j] = codewordBytes[i]; } } // Decode the contents of that stream of bytes return DecodedBitStreamParser.decode(resultBytes); }
java
public MaterialStep getCurrentStep() { if (currentStepIndex > getWidgetCount() - 1 || currentStepIndex < 0) { return null; } Widget w = getWidget(currentStepIndex); if (w instanceof MaterialStep) { return (MaterialStep) w; } return null; }
java
public void setParamTabEdDirectEditButtonStyle(String value) { try { m_userSettings.setDirectEditButtonStyle(Integer.parseInt(value)); } catch (Throwable t) { // should usually never happen } }
java
public EClass getIDEStructure() { if (ideStructureEClass == null) { ideStructureEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(392); } return ideStructureEClass; }
java
@Nonnull public static BootstrapButtonGroup createButtonAsDropDownMenuWithSeparateCaret (@Nonnull final BootstrapButton aButton, @Nonnull final Consumer <? super BootstrapDropdownMenu> aMenuItemProvider) { final BootstrapButtonGroup aBG = new BootstrapButtonGroup (); aBG.addChild (aButton); final BootstrapButton aCaret = new BootstrapButton (aButton.getButtonType (), aButton.getButtonSize ()); BootstrapDropdown.makeDropdownToggle (aCaret); aBG.addChild (aCaret); final BootstrapDropdownMenu aMenu = aBG.addDropDownMenu (); aMenuItemProvider.accept (aMenu); return aBG; }
java
@Override public <T> List<T> dynamicQuery(DynamicQuery dynamicQuery) { return cpRuleUserSegmentRelPersistence.findWithDynamicQuery(dynamicQuery); }
java
public Deployment deploy(URL url, Context context, ClassLoader parent) throws DeployException { FileInputStream fis = null; try { File dashRaXml = new File(url.toURI()); ResourceAdapterParser parser = new ResourceAdapterParser(); fis = new FileInputStream(dashRaXml); XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(fis); Activations activations = parser.parse(xsr); Merger merger = new Merger(); ClassLoaderDeployer classLoaderDeployer = context.getKernel().getBean("ClassLoaderDeployer", ClassLoaderDeployer.class); List<org.ironjacamar.core.api.deploymentrepository.Deployment> deployments = new ArrayList<org.ironjacamar.core.api.deploymentrepository.Deployment>(); for (Activation activation : activations.getActivations()) { Metadata metadata = metadataRepository.findByName(activation.getArchive()); if (metadata == null) throw new DeployException("Deployment " + activation.getArchive() + " not found"); Connector c = metadata.getMetadata(); File archive = metadata.getArchive(); Connector actC = merger.merge(c.copy(), activation); // Create a class loader for the archive context.put(Constants.ATTACHMENT_ARCHIVE, archive); classLoaderDeployer.clone().deploy(url, context, parent); KernelClassLoader cl = (KernelClassLoader)context.get(Constants.ATTACHMENT_CLASSLOADER); deployments.add(activate(actC, activation, activation.getArchive(), archive, cl)); } return new ActivationDeployment(url, deployments, deploymentRepository, deployments.get(0).getClassLoader()); } catch (DeployException de) { log.error(de.getMessage(), de); throw de; } catch (Throwable t) { log.error(t.getMessage(), t); throw new DeployException("Deployment " + url.toExternalForm() + " failed", t); } finally { if (fis != null) { try { fis.close(); } catch (IOException ignore) { // Ignore } } } }
python
def write_uint16(self, word): """Write 2 bytes.""" self.write_byte(nyamuk_net.MOSQ_MSB(word)) self.write_byte(nyamuk_net.MOSQ_LSB(word))
java
public R performActionAndWaitForEvent(K eventKey, long timeout, Callback<E> action) throws InterruptedException, E { final Reference<R> reference = new Reference<>(); events.put(eventKey, reference); try { synchronized (reference) { action.action(); reference.wait(timeout); } return reference.eventResult; } finally { events.remove(eventKey); } }
java
public void evaluate(DoubleSolution solution){ double aux, xi, xj; double[] fx = new double[getNumberOfObjectives()]; double[] x = new double[getNumberOfVariables()]; for (int i = 0; i < solution.getNumberOfVariables(); i++) { x[i] = solution.getVariableValue(i) ; } fx[0] = 0.0; for (int var = 0; var < solution.getNumberOfVariables() - 1; var++) { xi = x[var] * x[var]; xj = x[var + 1] * x[var + 1]; aux = (-0.2) * Math.sqrt(xi + xj); fx[0] += (-10.0) * Math.exp(aux); } fx[1] = 0.0; for (int var = 0; var < solution.getNumberOfVariables(); var++) { fx[1] += Math.pow(Math.abs(x[var]), 0.8) + 5.0 * Math.sin(Math.pow(x[var], 3.0)); } solution.setObjective(0, fx[0]); solution.setObjective(1, fx[1]); }
java
public boolean remove(URI uri, HttpCookie ck) { // argument can't be null if (ck == null) { throw new NullPointerException("cookie is null"); } lock.lock(); try { uri = getEffectiveURI(uri); if (uriIndex.get(uri) == null) { return false; } else { List<HttpCookie> cookies = uriIndex.get(uri); if (cookies != null) { return cookies.remove(ck); } else { return false; } } } finally { lock.unlock(); } }
java
public HttpClientResponseBuilder doThrowException(IOException exception) { newRule.addAction(new ExceptionAction(exception)); return new HttpClientResponseBuilder(newRule); }
java
private void nnChainCore(MatrixParadigm mat, DBIDArrayMIter prots, DistanceQuery<O> dq, PointerHierarchyRepresentationBuilder builder, Int2ObjectOpenHashMap<ModifiableDBIDs> clusters) { final DBIDArrayIter ix = mat.ix; final double[] distances = mat.matrix; final int size = mat.size; // The maximum chain size = number of ids + 1 IntegerArray chain = new IntegerArray(size + 1); FiniteProgress progress = LOG.isVerbose() ? new FiniteProgress("Running MiniMax-NNChain", size - 1, LOG) : null; for(int k = 1, end = size; k < size; k++) { int a = -1, b = -1; if(chain.size() <= 3) { // Accessing two arbitrary not yet merged elements could be optimized to // work in O(1) like in Müllner; // however this usually does not have a huge impact (empirically just // about 1/5000 of total performance) a = NNChain.findUnlinked(0, end, ix, builder); b = NNChain.findUnlinked(a + 1, end, ix, builder); chain.clear(); chain.add(a); } else { // Chain is expected to look like (.... a, b, c, b) with b and c merged. int lastIndex = chain.size; int c = chain.get(lastIndex - 2); b = chain.get(lastIndex - 3); a = chain.get(lastIndex - 4); // Ensure we had a loop at the end: assert (chain.get(lastIndex - 1) == c || chain.get(lastIndex - 1) == b); // if c < b, then we merged b -> c, otherwise c -> b b = c < b ? c : b; // Cut the tail: chain.size -= 3; } // For ties, always prefer the second-last element b: double minDist = mat.get(a, b); do { int c = b; final int ta = MatrixParadigm.triangleSize(a); for(int i = 0; i < a; i++) { if(i != b && !builder.isLinked(ix.seek(i))) { double dist = distances[ta + i]; if(dist < minDist) { minDist = dist; c = i; } } } for(int i = a + 1; i < size; i++) { if(i != b && !builder.isLinked(ix.seek(i))) { double dist = distances[MatrixParadigm.triangleSize(i) + a]; if(dist < minDist) { minDist = dist; c = i; } } } b = a; a = c; chain.add(a); } while(chain.size() < 3 || a != chain.get(chain.size - 1 - 2)); // We always merge the larger into the smaller index: if(a < b) { int tmp = a; a = b; b = tmp; } assert (minDist == mat.get(a, b)); assert (b < a); MiniMax.merge(size, mat, prots, builder, clusters, dq, a, b); end = AGNES.shrinkActiveSet(ix, builder, end, a); // Shrink working set LOG.incrementProcessed(progress); } LOG.ensureCompleted(progress); }
python
def _errstr(value): """Returns the value str, truncated to MAX_ERROR_STR_LEN characters. If it's truncated, the returned value will have '...' on the end. """ value = str(value) # We won't make the caller convert value to a string each time. if len(value) > MAX_ERROR_STR_LEN: return value[:MAX_ERROR_STR_LEN] + '...' else: return value
python
def _search(self, which, term): """ The real search method. :param which: 1 for anime, 2 for manga :param term: What to search for :rtype: list :return: list of :class:`Pymoe.Mal.Objects.Manga` or :class:`Pymoe.Mal.Objects.Anime` objects as per the type param. """ url = self.apiurl + "{}/search.xml".format('anime' if which == 1 else 'manga') r = requests.get(url, params={'q': term}, auth=HTTPBasicAuth(self._username, self._password), headers=self.header) if r.status_code != 200: return [] data = ET.fromstring(r.text) final_list = [] if which == 1: for item in data.findall('entry'): syn = item.find('synonyms').text.split(';') if item.find('synonyms').text else [] final_list.append(Anime( item.find('id').text, title=item.find('title').text, synonyms=syn.append(item.find('english').text), episodes=item.find('episodes').text, average=item.find('score').text, anime_start=item.find('start_date').text, anime_end=item.find('end_date').text, synopsis=html.unescape(item.find('synopsis').text.replace('<br />', '')) if item.find( 'synopsis').text else None, image=item.find('image').text, status_anime=item.find('status').text, type=item.find('type').text )) return NT_SEARCH_ANIME( airing=[x for x in final_list if x.status.series == "Currently Airing"], finished=[x for x in final_list if x.status.series == "Finished Airing"], unaired=[x for x in final_list if x.status.series == "Not Yet Aired"], dropped=[x for x in final_list if x.status.series == "Dropped"], planned=[x for x in final_list if x.status.series == "Plan to Watch"] ) else: for item in data.findall('entry'): syn = item.find('synonyms').text.split(';') if item.find('synonyms').text else [] final_list.append(Manga( item.find('id').text, title=item.find('title').text, synonyms=syn.append(item.find('english').text), chapters=item.find('chapters').text, volumes=item.find('volumes').text, average=item.find('score').text, manga_start=item.find('start_date').text, manga_end=item.find('end_date').text, synopsis=html.unescape(item.find('synopsis').text.replace('<br />', '')) if item.find( 'synopsis').text else None, image=item.find('image').text, status_manga=item.find('status').text, type=item.find('type').text )) return NT_SEARCH_MANGA( publishing=[x for x in final_list if x.status.series == "Publishing"], finished=[x for x in final_list if x.status.series == "Finished"], unpublished=[x for x in final_list if x.status.series == "Not Yet Published"], dropped=[x for x in final_list if x.status.series == "Dropped"], planned=[x for x in final_list if x.status.series == "Plan to Read"] )
java
@Override public EClass getIfcSlab() { if (ifcSlabEClass == null) { ifcSlabEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(602); } return ifcSlabEClass; }
java
@Override public void traverse(TraversalListener listener) { for (String classname: m_Classnames) listener.traversing(classname, null); }
java
public void setAttributeValues(java.util.Collection<String> attributeValues) { if (attributeValues == null) { this.attributeValues = null; return; } this.attributeValues = new com.amazonaws.internal.SdkInternalList<String>(attributeValues); }
java
public void marshall(BonusPayment bonusPayment, ProtocolMarshaller protocolMarshaller) { if (bonusPayment == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(bonusPayment.getWorkerId(), WORKERID_BINDING); protocolMarshaller.marshall(bonusPayment.getBonusAmount(), BONUSAMOUNT_BINDING); protocolMarshaller.marshall(bonusPayment.getAssignmentId(), ASSIGNMENTID_BINDING); protocolMarshaller.marshall(bonusPayment.getReason(), REASON_BINDING); protocolMarshaller.marshall(bonusPayment.getGrantTime(), GRANTTIME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
python
def mux(index, *mux_ins, **kwargs): """ Multiplexer returning the value of the wire in . :param WireVector index: used as the select input to the multiplexer :param WireVector mux_ins: additional WireVector arguments selected when select>1 :param WireVector kwargs: additional WireVectors, keyword arg "default" If you are selecting between less items than your index can address, you can use the "default" keyword argument to auto-expand those terms. For example, if you have a 3-bit index but are selecting between 6 options, you need to specify a value for those other 2 possible values of index (0b110 and 0b111). :return: WireVector of length of the longest input (not including select) To avoid confusion, if you are using the mux where the select is a "predicate" (meaning something that you are checking the truth value of rather than using it as a number) it is recommended that you use the select function instead as named arguments because the ordering is different from the classic ternary operator of some languages. Example of mux as "selector" to pick between a0 and a1: :: index = WireVector(1) mux( index, a0, a1 ) Example of mux as "selector" to pick between a0 ... a3: :: index = WireVector(2) mux( index, a0, a1, a2, a3 ) Example of "default" to specify additional arguments: :: index = WireVector(3) mux( index, a0, a1, a2, a3, a4, a5, default=0 ) """ if kwargs: # only "default" is allowed as kwarg. if len(kwargs) != 1 or 'default' not in kwargs: try: result = select(index, **kwargs) import warnings warnings.warn("Predicates are being deprecated in Mux. " "Use the select operator instead.", stacklevel=2) return result except Exception: bad_args = [k for k in kwargs.keys() if k != 'default'] raise PyrtlError('unknown keywords %s applied to mux' % str(bad_args)) default = kwargs['default'] else: default = None # find the diff between the addressable range and number of inputs given short_by = 2**len(index) - len(mux_ins) if short_by > 0: if default is not None: # extend the list to appropriate size mux_ins = list(mux_ins) extention = [default] * short_by mux_ins.extend(extention) if 2 ** len(index) != len(mux_ins): raise PyrtlError( 'Mux select line is %d bits, but selecting from %d inputs. ' % (len(index), len(mux_ins))) if len(index) == 1: return select(index, falsecase=mux_ins[0], truecase=mux_ins[1]) half = len(mux_ins) // 2 return select(index[-1], falsecase=mux(index[0:-1], *mux_ins[:half]), truecase=mux(index[0:-1], *mux_ins[half:]))
java
public <R> StreamEx<R> flatMapKeyValue(BiFunction<? super K, ? super V, ? extends Stream<? extends R>> mapper) { return this.<R> flatMap(toFunction(mapper)); }
python
def skip_signatures_and_duplicates_concat_well_known_metadata(cls, default_dup_action=None, additional_rules=None): """Produces a rule set useful in many deploy jar creation contexts. The rule set skips duplicate entries by default, retaining the 1st encountered. In addition it has the following special handling: - jar signature metadata is dropped - jar indexing files INDEX.LIST are dropped - ``java.util.ServiceLoader`` provider-configuration files are concatenated in the order encountered :param default_dup_action: An optional default action to take for duplicates. Defaults to `Duplicate.SKIP` if not specified. :param additional_rules: Optionally one or more jar rules to add to those described above. :returns: JarRules """ default_dup_action = Duplicate.validate_action(default_dup_action or Duplicate.SKIP) additional_rules = assert_list(additional_rules, expected_type=(Duplicate, Skip)) rules = [Skip(r'^META-INF/[^/]+\.SF$'), # signature file Skip(r'^META-INF/[^/]+\.DSA$'), # default signature alg. file Skip(r'^META-INF/[^/]+\.RSA$'), # default signature alg. file Skip(r'^META-INF/INDEX.LIST$'), # interferes with Class-Path: see man jar for i option Duplicate(r'^META-INF/services/', Duplicate.CONCAT_TEXT)] # 1 svc fqcn per line return JarRules(rules=rules + additional_rules, default_dup_action=default_dup_action)
java
public final ListAlertPoliciesPagedResponse listAlertPolicies(ProjectName name) { ListAlertPoliciesRequest request = ListAlertPoliciesRequest.newBuilder() .setName(name == null ? null : name.toString()) .build(); return listAlertPolicies(request); }
java
public int getNumberOfColumns() { List<WebElement> cells; String xPath = getXPathBase() + "tr"; List<WebElement> elements = HtmlElementUtils.locateElements(xPath); if (elements.size() > 0 && getDataStartIndex() - 1 < elements.size()) { cells = elements.get(getDataStartIndex() - 1).findElements(By.xpath("td")); return cells.size(); } return 0; }
python
def is_ignored(mod_or_pkg, ignored_package): """Test, if this :class:`docfly.pkg.picage.Module` or :class:`docfly.pkg.picage.Package` should be included to generate API reference document. :param mod_or_pkg: module or package :param ignored_package: ignored package **中文文档** 根据全名判断一个包或者模块是否要被包含到自动生成的API文档中。 """ ignored_pattern = list() for pkg_fullname in ignored_package: if pkg_fullname.endswith(".py"): pkg_fullname = pkg_fullname[:-3] ignored_pattern.append(pkg_fullname) else: ignored_pattern.append(pkg_fullname) for pattern in ignored_pattern: if mod_or_pkg.fullname.startswith(pattern): return True return False
java
public void append(DigitBuffer other) { check(other.size); System.arraycopy(other.buf, 0, buf, size, other.size); size += other.size; }
java
public static List<Boolean> unmodifiableView(boolean[] array, int length) { return Collections.unmodifiableList(view(array, length)); }
java
public ArrayList<File> scanAllFiles(File directoryToScan) { CumulativeFileScannerObserver fileScanner = new CumulativeFileScannerObserver(); DirectoryScanner directoryScanner = new DirectoryScanner(fileScanner); for (FileScannerObserver fileScannerObserver : fileScanners) { directoryScanner.addFileScanner(fileScannerObserver); } directoryScanner.setFileFilter(this.fileFilter); directoryScanner.scanDirectory(directoryToScan); return fileScanner.getResults(); }
python
def timer(): """ Timer used for calculate time elapsed """ if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time return default_timer()
python
def _find_files(self, entries, root, relative_path, file_name_regex): """ Return the elements in entries that 1. are in ``root/relative_path``, and 2. match ``file_name_regex``. :param list entries: the list of entries (file paths) in the container :param string root: the root directory of the container :param string relative_path: the relative path in which we must search :param regex file_name_regex: the regex matching the desired file names :rtype: list of strings (path) """ self.log([u"Finding files within root: '%s'", root]) target = root if relative_path is not None: self.log([u"Joining relative path: '%s'", relative_path]) target = gf.norm_join(root, relative_path) self.log([u"Finding files within target: '%s'", target]) files = [] target_len = len(target) for entry in entries: if entry.startswith(target): self.log([u"Examining entry: '%s'", entry]) entry_suffix = entry[target_len + 1:] self.log([u"Examining entry suffix: '%s'", entry_suffix]) if re.search(file_name_regex, entry_suffix) is not None: self.log([u"Match: '%s'", entry]) files.append(entry) else: self.log([u"No match: '%s'", entry]) return sorted(files)
java
@Override public void reset(IoSession session) { synchronized (lock) { if (!ready && this.session != null) { throw new IllegalStateException("Cannot reset a future that has not yet completed"); } this.session = session; this.firstListener = null; this.otherListeners = null; this.result = null; this.ready = false; this.waiters = 0; } }
java
public static String charToEscape(char ch) { String hexValue = Integer.toHexString(ch); if (hexValue.length() == 1) { return "\\u000" + hexValue; } if (hexValue.length() == 2) { return "\\u00" + hexValue; } if (hexValue.length() == 3) { return "\\u0" + hexValue; } return "\\u" + hexValue; }
java
private static boolean polylineContainsPoint_(Polyline polyline_a, Point point_b, double tolerance, ProgressTracker progress_tracker) { // Quick rasterize test to see whether the the geometries are disjoint. if (tryRasterizedContainsOrDisjoint_(polyline_a, point_b, tolerance, false) == Relation.disjoint) return false; Point2D pt_b = point_b.getXY(); return linearPathContainsPoint_(polyline_a, pt_b, tolerance); }
python
def _get_package_data(): """Iterate over the `init` dir for directories and returns all files within them. Only files within `binaries` and `templates` will be added. """ from os import listdir as ls from os.path import join as jn x = 'init' b = jn('serv', x) dr = ['binaries', 'templates'] return [jn(x, d, f) for d in ls(b) if d in dr for f in ls(jn(b, d))]
java
public ArrayList<net.minidev.ovh.api.me.consumption.OvhTransaction> consumption_usage_forecast_GET() throws IOException { String qPath = "/me/consumption/usage/forecast"; StringBuilder sb = path(qPath); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t7); }
java
public static String serviceName(Class<?> serviceInterface) { // Service name Service serviceAnnotation = serviceInterface.getAnnotation(Service.class); if (serviceAnnotation == null) { throw new IllegalArgumentException( String.format("Not a service interface: %s", serviceInterface)); } return serviceAnnotation.value().length() > 0 ? serviceAnnotation.value() : serviceInterface.getName(); }
java
public static String getFieldNameWithJavaCase(final String name) { return name==null?null:Character.toLowerCase(name.charAt(0))+name.substring(1); }
python
def get_conn(host='', username=None, password=None, port=445): ''' Get an SMB connection ''' if HAS_IMPACKET and not HAS_SMBPROTOCOL: salt.utils.versions.warn_until( 'Sodium', 'Support of impacket has been depricated and will be ' 'removed in Sodium. Please install smbprotocol instead.' ) if HAS_SMBPROTOCOL: log.info('Get connection smbprotocol') return _get_conn_smbprotocol(host, username, password, port=port) elif HAS_IMPACKET: log.info('Get connection impacket') return _get_conn_impacket(host, username, password, port=port) return False
java
private static boolean disjoint_(String scl) { if (scl.charAt(0) == 'F' && scl.charAt(1) == 'F' && scl.charAt(2) == '*' && scl.charAt(3) == 'F' && scl.charAt(4) == 'F' && scl.charAt(5) == '*' && scl.charAt(6) == '*' && scl.charAt(7) == '*' && scl.charAt(8) == '*') return true; return false; }
java
public static RgbaColor fromHsla(String hsl) { String[] parts = getHslaParts(hsl).split(","); if (parts.length == 4) { float[] HSL = new float[] { parseInt(parts[0]), parseInt(parts[1]), parseInt(parts[2]) }; RgbaColor ret = fromHsl(HSL); if (ret != null) { ret.a = parseFloat(parts[3]); } return ret; } else { return getDefaultColor(); } }
java
public static int toInteger(final Boolean bool, final int trueValue, final int falseValue, final int nullValue) { if (bool == null) { return nullValue; } return bool.booleanValue() ? trueValue : falseValue; }
java
@Override public final StringBuilder renderAsListItem(final StringBuilder builder, final boolean newLine, final int pad) { GedRenderer.renderPad(builder, pad, newLine); builder.append(getListItemContents()); return builder; }
python
def rss_parse(self, response): """ Extracts all article links and initiates crawling them. :param obj response: The scrapy response """ for item in response.xpath('//item'): for url in item.xpath('link/text()').extract(): yield scrapy.Request(url, lambda resp: self.article_parse( resp, item.xpath('title/text()').extract()[0]))
java
@Override public void searchMCS(boolean bondTypeMatch) { setBondMatchFlag(bondTypeMatch); searchVFMCSMappings(); boolean flag = mcgregorFlag(); if (flag && !vfLibSolutions.isEmpty()) { try { searchMcGregorMapping(); } catch (CDKException ex) { LOGGER.error(Level.SEVERE, null, ex); } catch (IOException ex) { LOGGER.error(Level.SEVERE, null, ex); } } else if (!allAtomMCSCopy.isEmpty()) { allAtomMCS.addAll(allAtomMCSCopy); allMCS.addAll(allMCSCopy); } setFirstMappings(); }
java
public void holdCall( String connId, KeyValueCollection reasons, KeyValueCollection extensions ) throws WorkspaceApiException { try { VoicecallsidanswerData holdData = new VoicecallsidanswerData(); holdData.setReasons(Util.toKVList(reasons)); holdData.setExtensions(Util.toKVList(extensions)); HoldData data = new HoldData(); data.data(holdData); ApiSuccessResponse response = this.voiceApi.hold(connId, data); throwIfNotOk("holdCall", response); } catch (ApiException e) { throw new WorkspaceApiException("holdCall failed.", e); } }
java
@Override public int compareTo(LocationWhereValueBecomesNull o) { int cmp = this.location.compareTo(o.location); if (cmp != 0) { return cmp; } cmp = this.valueNumber.compareTo(o.valueNumber); return cmp; }
java
public static <T> Optional<T> tryFind(Iterator<T> iterator, Predicate<? super T> predicate) { UnmodifiableIterator<T> filteredIterator = filter(iterator, predicate); return filteredIterator.hasNext() ? Optional.of(filteredIterator.next()) : Optional.<T>absent(); }
java
public static void main(String[] args) { Tree t; try { t = Tree.valueOf("(S (NP (NNP Sam)) (VP (VBD died) (NP-TMP (NN today))))"); } catch (Exception e) { System.err.println("Horrible error: " + e); e.printStackTrace(); return; } t.pennPrint(); System.out.println("----------------------------"); TreeGraph tg = new TreeGraph(t); System.out.println(tg); tg.root.percolateHeads(new SemanticHeadFinder()); System.out.println("----------------------------"); System.out.println(tg); // TreeGraphNode node1 = tg.getNodeByIndex(1); // TreeGraphNode node4 = tg.getNodeByIndex(4); // node1.addArc("1to4", node4); // node1.addArc("1TO4", node4); // node4.addArc("4to1", node1); // System.out.println("----------------------------"); // System.out.println("arcs from 1 to 4: " + node1.arcLabelsToNode(node4)); // System.out.println("arcs from 4 to 1: " + node4.arcLabelsToNode(node1)); // System.out.println("arcs from 0 to 4: " + tg.root.arcLabelsToNode(node4)); // for (int i = 0; i <= 9; i++) { // System.out.println("parent of " + i + ": " + tg.getNodeByIndex(i).parent()); // System.out.println("highest node with same head as " + i + ": " + tg.getNodeByIndex(i).highestNodeWithSameHead()); // } }
python
def sdb_get_or_set_hash(uri, opts, length=8, chars='abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)', utils=None): ''' Check if value exists in sdb. If it does, return, otherwise generate a random string and store it. This can be used for storing secrets in a centralized place. ''' if not isinstance(uri, string_types) or not uri.startswith('sdb://'): return False if utils is None: utils = salt.loader.utils(opts) ret = sdb_get(uri, opts, utils=utils) if ret is None: val = ''.join([random.SystemRandom().choice(chars) for _ in range(length)]) sdb_set(uri, val, opts, utils) return ret or val
python
def execute(self): """ Entry point to the execution of the program. """ # Ensure that we have commands registered if not self.commands or self._parser is None: raise NotImplementedError( "No commands registered with this program!" ) # Handle input from the command line args = self.parser.parse_args() # Parse the arguments try: handle_default_args(args) # Handle the default args if not hasattr(args, 'func'): # Handle no subcommands self.parser.print_help() self.exit(0) msg = args.func(args) # Call the default function msg = "{}\n".format(msg) if msg else '' # Format the message self.exit(0, msg) # Exit cleanly with message except Exception as e: if hasattr(args, 'traceback') and args.traceback: traceback.print_exc() msg = color.format(str(e), color.RED) self.exit(1, msg)
python
def toNumber (str, default=None): """toNumber(str[, default]) -> integer | float | default Converts the given string to a numeric value. The string may be a hexadecimal, integer, or floating number. If string could not be converted, default (None) is returned. Examples: >>> n = toNumber("0x2A") >>> assert type(n) is int and n == 42 >>> n = toNumber("42") >>> assert type(n) is int and n == 42 >>> n = toNumber("42.0") >>> assert type(n) is float and n == 42.0 >>> n = toNumber("Foo", 42) >>> assert type(n) is int and n == 42 >>> n = toNumber("Foo") >>> assert n is None """ value = default try: if str.startswith("0x"): value = int(str, 16) else: try: value = int(str) except ValueError: value = float(str) except ValueError: pass return value
python
def separate_camel_case(word, first_cap_re, all_cap_re): """ What it says on the tin. Input: - word: A string that may be in camelCase. Output: - separated_word: A list of strings with camel case separated. """ s1 = first_cap_re.sub(r'\1 \2', word) separated_word = all_cap_re.sub(r'\1 \2', s1) return separated_word
python
def changebase(string, frm, to, minlen=0): """ Change a string's characters from one base to another. Return the re-encoded string """ if frm == to: return lpad(string, get_code_string(frm)[0], minlen) return encode(decode(string, frm), to, minlen)
java
public static List<CPRule> filterFindByGroupId(long groupId, int start, int end) { return getPersistence().filterFindByGroupId(groupId, start, end); }
python
def get_driver_payments(self, offset=None, limit=None, from_time=None, to_time=None ): """Get payments about the authorized Uber driver. Parameters offset (int) The integer offset for activity results. Offset the list of returned results by this amount. Default is zero. limit (int) Integer amount of results to return. Number of items to retrieve per page. Default is 10, maximum is 50. from_time (int) Unix timestamp of the start time to query. Queries starting from the first trip if omitted. to_time (int) Unix timestamp of the end time to query. Queries starting from the last trip if omitted. Returns (Response) A Response object containing trip information. """ args = { 'offset': offset, 'limit': limit, 'from_time': from_time, 'to_time': to_time, } return self._api_call('GET', 'v1/partners/payments', args=args)
java
private static void init() { if (alFirstConsonants == null) { alFirstConsonants = new ArrayList(); alLastConsonants = new ArrayList(); alMainVowels = new ArrayList(); alSecondaryVowels = new ArrayList(); initArrayList(alFirstConsonants, vnFirstConsonants); initArrayList(alLastConsonants, vnLastConsonants); initArrayList(alMainVowels, vnMainVowels); initArrayList(alSecondaryVowels, vnSecondaryVowels); } }
python
def compare(args): """ Compare the extant river with the given name to the passed JSON. The command will exit with a return code of 0 if the named river is configured as specified, and 1 otherwise. """ data = json.load(sys.stdin) m = RiverManager(args.hosts) if m.compare(args.name, data): sys.exit(0) else: sys.exit(1)
python
def write_separated_lines(path, values, separator=' ', sort_by_column=0): """ Writes list or dict to file line by line. Dict can have list as value then they written separated on the line. Parameters: path (str): Path to write file to. values (dict, list): A dictionary or a list to write to the file. separator (str): Separator to use between columns. sort_by_column (int): if >= 0, sorts the list by the given index, if its 0 or 1 and its a dictionary it sorts it by either the key (0) or value (1). By default 0, meaning sorted by the first column or the key. """ f = open(path, 'w', encoding='utf-8') if type(values) is dict: if sort_by_column in [0, 1]: items = sorted(values.items(), key=lambda t: t[sort_by_column]) else: items = values.items() for key, value in items: if type(value) in [list, set]: value = separator.join([str(x) for x in value]) f.write('{}{}{}\n'.format(key, separator, value)) elif type(values) is list or type(values) is set: if 0 <= sort_by_column < len(values): items = sorted(values) else: items = values for record in items: str_values = [str(value) for value in record] f.write('{}\n'.format(separator.join(str_values))) f.close()
python
def next_occurrences(self, n=None, since=None): """Yield the next planned occurrences after the date "since" The `since` argument can be either a date or datetime onject. If not given, it defaults to the date of the last event that's already planned. If `n` is given, the result is limited to that many dates; otherwise, infinite results may be generated. Note that less than `n` results may be yielded. """ scheme = self.recurrence_scheme if scheme is None: return () db = Session.object_session(self) query = db.query(Event) query = query.filter(Event.series_slug == self.slug) query = query.order_by(desc(Event.date)) query = query.limit(1) last_planned_event = query.one_or_none() if since is None: last_planned_event = query.one() since = last_planned_event.date elif since < last_planned_event.date: since = last_planned_event.date start = getattr(since, 'date', since) start += relativedelta.relativedelta(days=+1) if (scheme == 'monthly' and last_planned_event and last_planned_event.date.year == start.year and last_planned_event.date.month == start.month): # Monthly events try to have one event per month, so exclude # the current month if there was already a meetup start += relativedelta.relativedelta(months=+1) start = start.replace(day=1) start = datetime.datetime.combine(start, datetime.time(tzinfo=CET)) result = rrule.rrulestr(self.recurrence_rule, dtstart=start) if n is not None: result = itertools.islice(result, n) return result
java
public ApiResponse<DeviceTaskUpdateResponse> updateTaskForDeviceWithHttpInfo(String tid, String did, DeviceTaskUpdateRequest deviceTaskUpdateRequest) throws ApiException { com.squareup.okhttp.Call call = updateTaskForDeviceValidateBeforeCall(tid, did, deviceTaskUpdateRequest, null, null); Type localVarReturnType = new TypeToken<DeviceTaskUpdateResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
java
protected String getMessageInternal(Locale locale, String code, Object[] args) { if(code == null) { return null; } if(locale == null) { locale = I18nUtils.getLocale(); } final MessageFormat messageFormat = resolveMessageFormat(locale, code); if(messageFormat != null) { synchronized(messageFormat) { return messageFormat.format(args); } } return null; }
python
def t_seg(p1, p2, t, align=0): """ trim segment Args: p1, p2: point(x, y) t: scaling factor (1 - trimed segment / original segment) align: 1: trim p2, 2: trim p1, 0: both side Return: trimmed segment(p1, p2) """ v = vector(p1, p2) result = { 1: lambda a, b: (a, translate(b, scale(v, -t))), 2: lambda a, b: (translate(a, scale(v, t)), b), 0: lambda a, b: (translate(a, scale(v, t / 2)), translate(b, scale(v, -t / 2))) } return result[align](p1, p2)
java
@Override public void connectionRecovered(IManagedConnectionEvent<C> event) { // physical connection is already set free if (!event.getManagedConnection().hasCoreConnection()) { return; } IPhynixxConnection con = event.getManagedConnection() .getCoreConnection(); if (con == null || !(con instanceof IXADataRecorderAware)) { return; } IXADataRecorderAware messageAwareConnection = (IXADataRecorderAware) con; // Transaction is close and the logger is destroyed ... IXADataRecorder xaDataRecorder = messageAwareConnection .getXADataRecorder(); if (xaDataRecorder == null) { return; } // it's my logger .... // the logger has to be destroyed ... else { xaDataRecorder.destroy(); messageAwareConnection.setXADataRecorder(null); } }
java
public boolean isCompatibleWith(DataType other) { // A type is compatible with a choice type if it is a subtype of one of the choice types if (other instanceof ChoiceType) { for (DataType choice : ((ChoiceType)other).getTypes()) { if (this.isSubTypeOf(choice)) { return true; } } } return this.equals(other); // Any data type is compatible with itself }
python
def integral(requestContext, seriesList): """ This will show the sum over time, sort of like a continuous addition function. Useful for finding totals or trends in metrics that are collected per minute. Example:: &target=integral(company.sales.perMinute) This would start at zero on the left side of the graph, adding the sales each minute, and show the total sales for the time period selected at the right side, (time now, or the time specified by '&until='). """ results = [] for series in seriesList: newValues = [] current = 0.0 for val in series: if val is None: newValues.append(None) else: current += val newValues.append(current) newName = "integral(%s)" % series.name newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues) newSeries.pathExpression = newName results.append(newSeries) return results
python
def load(input_stream=None): """ Load JSON-encoded document and return a :class:`.Doc` element. The JSON input will be read from :data:`sys.stdin` unless an alternative text stream is given (a file handle). To load from a file, you can do: >>> import panflute as pf >>> with open('some-document.json', encoding='utf-8') as f: >>> doc = pf.load(f) To load from a string, you can do: >>> import io >>> raw = '[{"unMeta":{}}, [{"t":"Para","c":[{"t":"Str","c":"Hello!"}]}]]' >>> f = io.StringIO(raw) >>> doc = pf.load(f) :param input_stream: text stream used as input (default is :data:`sys.stdin`) :rtype: :class:`.Doc` """ if input_stream is None: input_stream = io.open(sys.stdin.fileno()) if py2 else io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8') # Load JSON and validate it doc = json.load(input_stream, object_pairs_hook=from_json) # Notes: # - We use 'object_pairs_hook' instead of 'object_hook' to preserve the # order of the metadata. # - The hook gets called for dicts (not lists), and the deepest dicts # get called first (so you can ensure that when you receive a dict, # its contents have already been fed to the hook). # Compatibility: # - Before Pandoc 1.8 (1.7 or earlier, AKA "Pandoc Legacy"), # the JSON is a list: # [{"unMeta":{META}},[BLOCKS]] # - Afterwards, it's a dict: # {"pandoc-api-version" : [MAJ, MIN, REV], # "meta" : META, "blocks": BLOCKS} # - This means that on legacy, the hook WILL NOT get called on the entire # document and we need to create the Doc() element by hand # Corner cases: # - If META is missing, 'object_pairs_hook' will receive an empty list # Output format format = sys.argv[1] if len(sys.argv) > 1 else 'html' # API Version if isinstance(doc, Doc): # Modern Pandoc doc.format = format pass else: # Legacy Pandoc metadata, items = doc assert type(items) == list assert len(doc) == 2, 'json.load returned list with unexpected size:' doc = Doc(*items, metadata=metadata, format=format) return doc
java
public EList<Boolean> getValues() { if (values == null) { values = new EDataTypeEList<Boolean>(Boolean.class, this, TypesPackage.JVM_BOOLEAN_ANNOTATION_VALUE__VALUES); } return values; }
java
public void setContentAddStyleNames(String value) { if (value == null || value.isEmpty()) return; JQMCommon.addStyleNames(content, value); }
python
def flush(self): """Ensure contents are written to file.""" for name in self.item_names: item = self[name] item.flush() self.file.flush()
java
public XAttributeTimestamp createAttributeTimestamp(String key, Date value, XExtension extension) { return new XAttributeTimestampImpl(intern(key), value, extension); }
python
def forward_backward(self, x): """Perform forward and backward computation for a batch of src seq and dst seq""" (src_seq, tgt_seq, src_valid_length, tgt_valid_length), batch_size = x with mx.autograd.record(): out, _ = self._model(src_seq, tgt_seq[:, :-1], src_valid_length, tgt_valid_length - 1) smoothed_label = self._label_smoothing(tgt_seq[:, 1:]) ls = self._loss(out, smoothed_label, tgt_valid_length - 1).sum() ls = (ls * (tgt_seq.shape[1] - 1)) / batch_size / self._rescale_loss ls.backward() return ls
python
def create_future(loop): # pragma: no cover """Compatibility wrapper for the loop.create_future() call introduced in 3.5.2.""" if hasattr(loop, 'create_future'): return loop.create_future() return asyncio.Future(loop=loop)
python
def get_usage_string(self): """Returns usage representation string (as embedded in HID device if available) """ if self.string_index: usage_string_type = c_wchar * MAX_HID_STRING_LENGTH # 128 max string length abuffer = usage_string_type() hid_dll.HidD_GetIndexedString( self.hid_report.get_hid_object().hid_handle, self.string_index, byref(abuffer), MAX_HID_STRING_LENGTH-1 ) return abuffer.value return ""
java
void preBackout(Transaction transaction) throws ObjectManagerException { throw new InvalidStateException(this, InternalTransaction.stateTerminated, InternalTransaction.stateNames[InternalTransaction.stateTerminated]); }
java
private static String getKey(Object... objects) { Object[] args = new Object[objects.length + 1]; args[0] = LineageEventBuilder.LIENAGE_EVENT_NAMESPACE; System.arraycopy(objects, 0, args, 1, objects.length); return LineageEventBuilder.getKey(args); }
java
public static boolean[] removeAllOccurrences(final boolean[] a, final boolean element) { if (N.isNullOrEmpty(a)) { return N.EMPTY_BOOLEAN_ARRAY; } final boolean[] copy = a.clone(); int idx = 0; for (int i = 0, len = a.length; i < len; i++) { if (a[i] == element) { continue; } copy[idx++] = a[i]; } return idx == copy.length ? copy : N.copyOfRange(copy, 0, idx); }
java
public static String escapeShell(final String s) { if(null==s){ return s; } if (s.startsWith("'") && s.endsWith("'")) { return s; } else if (s.startsWith("\"") && s.endsWith("\"")) { return s.replaceAll("([\\\\`])", "\\\\$1"); } return s.replaceAll("([&><|;\\\\`])", "\\\\$1"); }
java
public static String getParameter(final PageParameters parameters, final String name) { return getString(parameters.get(name)); }
python
def select_one_album(albums): """Display the albums returned by search api. :params albums: API['result']['albums'] :return: a Album object. """ if len(albums) == 1: select_i = 0 else: table = PrettyTable(['Sequence', 'Album Name', 'Artist Name']) for i, album in enumerate(albums, 1): table.add_row([i, album['name'], album['artist']['name']]) click.echo(table) select_i = click.prompt('Select one album', type=int, default=1) while select_i < 1 or select_i > len(albums): select_i = click.prompt('Error Select! Select Again', type=int) album_id = albums[select_i-1]['id'] album_name = albums[select_i-1]['name'] album = Album(album_id, album_name) return album
java
public final void add(ByteBuf buf, ChannelFutureListener listener) { // buffers are added before promises so that we naturally 'consume' the entire buffer during removal // before we complete it's promise. bufAndListenerPairs.add(buf); if (listener != null) { bufAndListenerPairs.add(listener); } incrementReadableBytes(buf.readableBytes()); }
java
@SuppressWarnings("unchecked") public static <T extends Executable> T getRootExecutable(T m) { return (T) EXECUTABLE_GET_ROOT.apply(m); }
java
public static <T> T[] validIndex(final T[] array, final int index, final String message, final Object... values) { Validate.notNull(array); if (index < 0 || index >= array.length) { throw new IndexOutOfBoundsException(StringUtils.simpleFormat(message, values)); } return array; }
python
def add_colorbar(self, **kwargs): """Draw a colorbar """ kwargs = kwargs.copy() if self._cmap_extend is not None: kwargs.setdefault('extend', self._cmap_extend) if 'label' not in kwargs: kwargs.setdefault('label', label_from_attrs(self.data)) self.cbar = self.fig.colorbar(self._mappables[-1], ax=list(self.axes.flat), **kwargs) return self
python
def _get_atomic_dtype(data_type): """Retrieve the NumPy's `dtype` for a given atomic data type.""" atomic_type = getattr(data_type, 'type', None) if atomic_type is not None: return atomic_type return _PREDEFINED_ATOMIC_NUMPY_TYPES[_find_base_type(data_type)]
java
public String getTableNames(boolean bAddQuotes) { return (m_tableName == null) ? Record.formatTableNames(ANALYSIS_LOG_FILE, bAddQuotes) : super.getTableNames(bAddQuotes); }
java
public PooledConnection getPooledConnection(String user, String password) throws SQLException { return new MariaDbPooledConnection((MariaDbConnection) getConnection(user, password)); }
java
@Override public void snapshot(String snapshotName, TableName tableName, SnapshotType arg2) throws IOException, SnapshotCreationException, IllegalArgumentException { snapshot(snapshotName, tableName); }
java
public static Result run(String inPaths, String pkgName, String outPath, boolean dbg, boolean vbs) throws IOException, ClassHierarchyException, IllegalArgumentException { DEBUG = dbg; VERBOSE = vbs; long start = System.currentTimeMillis(); Set<String> setInPaths = new HashSet<>(Arrays.asList(inPaths.split(","))); for (String inPath : setInPaths) { InputStream jarIS = null; if (inPath.endsWith(".jar") || inPath.endsWith(".aar")) { jarIS = getInputStream(inPath); if (jarIS == null) { continue; } } else if (!new File(inPath).exists()) { continue; } AnalysisScope scope = AnalysisScopeReader.makePrimordialScope(null); scope.setExclusions( new FileOfClasses( new ByteArrayInputStream(DEFAULT_EXCLUSIONS.getBytes(StandardCharsets.UTF_8)))); if (jarIS != null) scope.addInputStreamForJarToScope(ClassLoaderReference.Application, jarIS); else AnalysisScopeReader.addClassPathToScope(inPath, scope, ClassLoaderReference.Application); AnalysisOptions options = new AnalysisOptions(scope, null); AnalysisCache cache = new AnalysisCacheImpl(); IClassHierarchy cha = ClassHierarchyFactory.makeWithPhantom(scope); Warnings.clear(); // Iterate over all classes:methods in the 'Application' and 'Extension' class loaders for (IClassLoader cldr : cha.getLoaders()) { if (!cldr.getName().toString().equals("Primordial")) { for (IClass cls : Iterator2Iterable.make(cldr.iterateAllClasses())) { if (cls instanceof PhantomClass) continue; // Only process classes in specified classpath and not its dependencies. // TODO: figure the right way to do this if (!pkgName.isEmpty() && !cls.getName().toString().startsWith(pkgName)) continue; LOG(DEBUG, "DEBUG", "analyzing class: " + cls.getName().toString()); for (IMethod mtd : Iterator2Iterable.make(cls.getDeclaredMethods().iterator())) { // Skip methods without parameters, abstract methods, native methods // some Application classes are Primordial (why?) if (!mtd.isPrivate() && !mtd.isAbstract() && !mtd.isNative() && !isAllPrimitiveTypes(mtd) && !mtd.getDeclaringClass() .getClassLoader() .getName() .toString() .equals("Primordial")) { Preconditions.checkNotNull(mtd, "method not found"); DefinitelyDerefedParams analysisDriver = null; String sign = ""; // Parameter analysis if (mtd.getNumberOfParameters() > (mtd.isStatic() ? 0 : 1)) { // Skip methods by looking at bytecode try { if (!CodeScanner.getFieldsRead(mtd).isEmpty() || !CodeScanner.getFieldsWritten(mtd).isEmpty() || !CodeScanner.getCallSites(mtd).isEmpty()) { if (analysisDriver == null) { analysisDriver = getAnalysisDriver(mtd, options, cache, cha); } Set<Integer> result = analysisDriver.analyze(); sign = getSignature(mtd); LOG(DEBUG, "DEBUG", "analyzed method: " + sign); if (!result.isEmpty() || DEBUG) { map_result.put(sign, result); LOG( DEBUG, "DEBUG", "Inferred Nonnull param for method: " + sign + " = " + result.toString()); } } } catch (Exception e) { LOG( DEBUG, "DEBUG", "Exception while scanning bytecodes for " + mtd + " " + e.getMessage()); } } // Return value analysis if (!mtd.getReturnType().isPrimitiveType()) { if (analysisDriver == null) { analysisDriver = getAnalysisDriver(mtd, options, cache, cha); } if (analysisDriver.analyzeReturnType() == DefinitelyDerefedParams.NullnessHint.NULLABLE) { if (sign.isEmpty()) { sign = getSignature(mtd); } nullableReturns.add(sign); LOG(DEBUG, "DEBUG", "Inferred Nullable method return: " + sign); } } } } } } } long end = System.currentTimeMillis(); LOG( VERBOSE, "Stats", inPath + " >> time(ms): " + (end - start) + ", bytecode size: " + analyzedBytes + ", rate (ms/KB): " + (analyzedBytes > 0 ? (((end - start) * 1000) / analyzedBytes) : 0)); } new File(outPath).getParentFile().mkdirs(); if (outPath.endsWith(".astubx")) { writeModel(new DataOutputStream(new FileOutputStream(outPath))); } else { writeModelJAR(outPath); } lastOutPath = outPath; return map_result; }
java
private void printText(PrintWriter pw, String key, String defaultText) { String text = null; if (key != null) { ResourceBundle bundle = null; // retrieve the resource bundle try { bundle = ResourceBundle.getBundle(DIST_EX_RESOURCE_BUNDLE_NAME); } catch (MissingResourceException e) { text = defaultText; } // if the resource bundle was successfully retrieved, get the specific text based // on the resource key if (bundle != null) { try { text = bundle.getString(key); } catch (MissingResourceException e) { text = defaultText; } } } else { // no key was provided text = defaultText; } pw.println(text); }
java
public void marshall(ResourceQuery resourceQuery, ProtocolMarshaller protocolMarshaller) { if (resourceQuery == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(resourceQuery.getType(), TYPE_BINDING); protocolMarshaller.marshall(resourceQuery.getQuery(), QUERY_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
python
def ngram_counts(args, parser): """Outputs the results of performing a counts query.""" store = utils.get_data_store(args) corpus = utils.get_corpus(args) catalogue = utils.get_catalogue(args) store.validate(corpus, catalogue) store.counts(catalogue, sys.stdout)
java
protected Boolean _hasSideEffects(XReturnExpression expression, ISideEffectContext context) { return hasSideEffects(expression.getExpression(), context); }