language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def reset(self, ms=0, halt=True): """Resets the target. This method resets the target, and by default toggles the RESET and TRST pins. Args: self (JLink): the ``JLink`` instance ms (int): Amount of milliseconds to delay after reset (default: 0) halt (bool)...
java
protected URI loadConfigUri() throws URISyntaxException, FileNotFoundException { Collection<String> configNames = getAggregator().getInitParams().getValues(InitParams.CONFIG_INITPARAM); if (configNames.size() != 1) { throw new IllegalArgumentException(InitParams.CONFIG_INITPARAM); } String configName = ...
java
public void stop(String resourceGroupName, String networkWatcherName, String connectionMonitorName) { stopWithServiceResponseAsync(resourceGroupName, networkWatcherName, connectionMonitorName).toBlocking().last().body(); }
python
def get_global_parameters(config_names=("core", "scheduler", "worker", "retcode")): """ Returns a list of global, luigi-internal configuration parameters. Each list item is a 4-tuple containing the configuration class, the parameter instance, the parameter name, and the full parameter name in the cli. W...
python
def extract_relationships(cls, fields, resource, resource_instance): """ Builds the relationships top level object based on related serializers. """ # Avoid circular deps from rest_framework_json_api.relations import ResourceRelatedField data = OrderedDict() # D...
python
def dragLeaveEvent(self, event): """Clears drop cursor line""" super(AbstractDragView, self).dragLeaveEvent(event) self.dragline = None self.viewport().update() event.accept()
java
protected void setURI() { if (_scheme != null) { if (_scheme.length == 4 && Arrays.equals(_scheme, HTTP_SCHEME)) { _scheme = HTTP_SCHEME; } else if (_scheme.length == 5 && Arrays.equals(_scheme, HTTPS_SCHEME)) { _scheme = HTTPS_SCHEME; ...
python
def close(self): """ Closes the database, releasing lock. """ super(LockingDatabase, self).close() if not self.readonly: self.release_lock()
python
def upload_by_twine(self): """ upload by twine :return: """ check_call_no_output([ '{}'.format(self.python), 'setup.py', 'sdist', ]) filename = self.get_package_filename() check_call_no_output([ 'twine', ...
python
def part_name(self, basename='/tmp/sitemap.xml', part_number=0): """Name (file or URI) for one component sitemap. Works for both filenames and URIs because manipulates only the end of the string. Abstracting this into a function that starts from the basename to get prefix and s...
java
public static MozuUrl getAccountNotesUrl(Integer accountId, String filter, Integer pageSize, String responseFields, String sortBy, Integer startIndex) { UrlFormatter formatter = new UrlFormatter("/api/commerce/customer/accounts/{accountId}/notes?startIndex={startIndex}&pageSize={pageSize}&sortBy={sortBy}&filter={f...
java
public final String getTypeSignature() { final StringBuffer sb = new StringBuffer(); sb.append(getName()); sb.append("("); for (int i = 0; i < getArguments().size(); i++) { if (i > 0) { sb.append(", "); } final SgArgument arg = ...
java
public static Period parsePeriod(String string) { string = string.trim(); if (string.startsWith("-P") || string.startsWith("P")) { return Period.parse(string); } int years = 0, months = 0, days = 0; Set<String> units = new HashSet<>(); Matcher matcher = PERIOD_PATTERN.matcher(string.trim().toLowerCase()...
java
@Override public void removeByUuid_C(String uuid, long companyId) { for (CPOption cpOption : findByUuid_C(uuid, companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpOption); } }
python
def full_name(first_name, last_name, username, **extra): """Return full name or username.""" name = " ".join(n for n in [first_name, last_name] if n) if not name: return username return name
java
public Policy listBucketIamMembers(String bucketName) { // [START view_bucket_iam_members] // Initialize a Cloud Storage client Storage storage = StorageOptions.getDefaultInstance().getService(); // Get IAM Policy for a bucket Policy policy = storage.getIamPolicy(bucketName); // Print Roles an...
python
def map_pol_to_crt(aryTht, aryRad): """Remap coordinates from polar to cartesian Parameters ---------- aryTht : 1D numpy array Angle of coordinates aryRad : 1D numpy array Radius of coordinates. Returns ------- aryXCrds : 1D numpy array Array with x coordinate v...
java
public static Assignments cluster(Matrix matrix, int numClusters, int numRepetitions, CriterionFunction criterion) { return cluster(matrix, numClusters, numRepetitions, new Ra...
java
protected void downloadFromMavenRepo(PluginCoordinates coordinates, URI mavenRepoUrl, IAsyncResultHandler<File> handler) { String artifactSubPath = PluginUtils.getMavenPath(coordinates); try { File tempArtifactFile = File.createTempFile("_plugin", "dwn"); //$NON-NLS-1$ //$NON-NLS-2$ ...
python
def Disjunction(expr1: Expression, expr2: Expression) -> Expression: """Return expression which is the disjunction of `expr1` and `expr2`.""" expr = Expression(ast.BoolOp(ast.Or(), [expr1.body, expr2.body])) return ast.fix_missing_locations(expr)
java
public void addRemoteAudioPayloadType(PayloadType.Audio pt) { if (pt != null) { synchronized (remoteAudioPts) { remoteAudioPts.add(pt); } } }
python
def cli(env, context_id, include): """List IPSEC VPN tunnel context details. Additional resources can be joined using multiple instances of the include option, for which the following choices are available. \b at: address translations is: internal subnets rs: remote subnets sr: statica...
java
public static String stripParentheses(final String filter) { if (filter == null || filter.isEmpty()) { throw new IllegalArgumentException("Filter string cannot be null or empty"); } if (filter.charAt(filter.length() - 1) != ')') { throw new IllegalArgumentException("Filter must end with a ')': "...
java
public static String[] trimArray(String[] strings) { for (int i = 0; i < strings.length; i++) { strings[i] = strings[i].trim(); } return strings; }
python
def list_paths(self): """Utility method to list all the paths in the jar.""" paths = [] for cookie in iter(self): if cookie.path not in paths: paths.append(cookie.path) return paths
java
public ClassNode annotatedWith(String name) { ClassNode anno = infoBase.node(name); this.annotations.add(anno); anno.annotated.add(this); return this; }
java
@Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { //build compiler options //create compiler object //compile, get result //write result to output stream HttpServletRequest rq = (HttpServletRequ...
python
def composed_deps(self): """Dependencies of this build target.""" if 'deps' in self.params: param_deps = self.params['deps'] or [] deps = [self.makeaddress(dep) for dep in param_deps] return deps else: return None
python
def _fake_modifyinstance(self, namespace, **params): """ Implements a server responder for :meth:`~pywbem.WBEMConnection.CreateInstance` Modify a CIM instance in the local repository. Raises: CIMError: CIM_ERR_ALREADY_EXISTS, CIM_ERR_INVALID_CLASS """ ...
java
@Deprecated public static PointsToPolyline splitMerge(@Nullable ConfigSplitMergeLineFit config ) { if( config == null ) config = new ConfigSplitMergeLineFit(); config.checkValidity(); return new SplitMergeLineRefine_to_PointsToPolyline(config); }
java
private String extractSQLForJavaDoc(final SQLiteModelMethod method) { final One<Boolean> usedInWhere = new One<>(false); String sqlForJavaDoc = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) { @Override public String onColumnNameToUpdate(String columnName) { retu...
java
public static boolean isDefinedNSDecl( SerializationHandler serializer, int attr, DTM dtm) { if (DTM.NAMESPACE_NODE == dtm.getNodeType(attr)) { // String prefix = dtm.getPrefix(attr); String prefix = dtm.getNodeNameX(attr); String uri = s...
java
public static base_response unset(nitro_service client, String network, String args[]) throws Exception { route6 unsetresource = new route6(); unsetresource.network = network; return unsetresource.unset_resource(client, args); }
python
def do_fake( formatter, *args, **kwargs ): """ call a faker format uses: {% fake "formatterName" *args **kwargs as myvar %} {{ myvar }} or: {% fake 'name' %} """ return Faker.getGenerator().format( formatter, *args, **kwargs )
java
public HttpResponseHandler<SdkBaseException> createErrorResponseHandler( JsonErrorResponseMetadata errorResponsMetadata) { return new ApiGatewayErrorResponseHandler( createErrorUnmarshallers(errorResponsMetadata.getErrorShapes().stream()), SdkStructuredPlainJsonFactor...
python
def fit(self, analysis, grid_priors): """ Fit an analysis with a set of grid priors. The grid priors are priors associated with the model mapper of this instance that are replaced by uniform priors for each step of the grid search. Parameters ---------- analysis: non_lin...
python
def analyze(self, text): """Return the sentiment as a tuple of the form: ``(polarity, subjectivity)`` :param str text: A string. .. todo:: Figure out best format to be passed to the analyzer. There might be a better format than a string of space separated ...
python
def softmax_cross_entropy_with_logits(logits, targets, vocab_dim, z_loss=0.0): """Per-example softmax loss. if z_loss is nonzero, we add a loss equal to z_loss*log(z)^2, where z is the partition function. Example value: z_loss=1e-4. Two uses of z_loss are: - To keep the logits from drifting too far from zero...
java
@Deprecated // use withIdStrategy public JsonSet applyIdStrategy(IdStrategy strategy) { JsonSet newSet = new JsonSet(); newSet.strategy = strategy; for (JsonElement e : this) { newSet.add(e); } return newSet; }
java
public Response delete(String topicId, String replyId) throws JinxException { JinxUtils.validateParams(topicId, replyId); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.groups.discuss.replies.delete"); params.put("topic_id", topicId); params.put("reply_id", replyId); ...
java
public ResourceHandle getParent(String resourceType) { ResourceHandle result = getResource(); while (result.isValid() && !result.isResourceType(resourceType)) { result = result.getParent(); } if (!result.isValid()) { result = getParent(resourceType, getPath()); //...
python
def community_user_comments(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/post_comments#list-comments" api_path = "/api/v2/community/users/{id}/comments.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
python
def patch_modules(): """Patch modules to work better with :meth:`ExampleRunner.invoke`. ``subprocess.call` output is redirected to ``click.echo`` so it shows up in the example output. """ old_call = subprocess.call def dummy_call(*args, **kwargs): with tempfile.TemporaryFile("wb+") as ...
python
def call(self, my_args=None): """ publish the message in the topic :param my_args: dict like {msg: 'msg'} :return: nothing """ LOGGER.debug("zeromq.Publisher.call") if my_args is None: raise exceptions.ArianeConfError("publisher call arguments") ...
java
private void onEvent(CounterManager.Event2C.OnCounterUpdated event) { getModel().count = String.valueOf(event.getCount()); if (view != null) { view.update(); } }
java
public String decryptMsg(String msgSignature, String timeStamp, String nonce, String postData) throws AesException { // 密钥,公众账号的app secret // 提取密文 Object[] encrypt = XMLParser.extract(postData); // 验证安全签名 String signature = SHA1.getSHA1(token, timeStamp, nonce, encr...
java
public void setCurrentValue(double curValue, boolean fireEvent) { // Confine the value to the range this.curValue = Math.max(minValue, Math.min(maxValue, curValue)); double remainder = (this.curValue - minValue) % stepSize; this.curValue -= remainder; // Go to next step if more than halfway there if...
java
public INDArray[] output(MultiDataSetIterator iterator){ List<INDArray[]> outputs = new ArrayList<>(); while(iterator.hasNext()){ MultiDataSet next = iterator.next(); INDArray[] out = output(false, next.getFeatures(), next.getFeaturesMaskArrays(), next.getLabelsMaskArrays()); ...
java
void cancel(AsyncChannelFuture future, Exception reason) throws ClosedChannelException, IOException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "cancel"); } if (!isOpen()) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnable...
python
def cmd(send, msg, args): """Pesters somebody. Syntax: {command} <nick> <message> """ if not msg or len(msg.split()) < 2: send("Pester needs at least two arguments.") return match = re.match('(%s+) (.*)' % args['config']['core']['nickregex'], msg) if match: message = ma...
java
public com.google.api.ads.admanager.axis.v201902.RateType getRateType() { return rateType; }
python
def _poll(self): """ Poll Trusted Advisor (Support) API for limit checks. Return a dict of service name (string) keys to nested dict vals, where each key is a limit name and each value the current numeric limit. e.g.: :: { 'EC2': { ...
python
def register_mark(key=None): """Returns a decorator registering a mark class in the mark type registry. If no key is provided, the class name is used as a key. A key is provided for each core bqplot mark so that the frontend can use this key regardless of the kernel language. """ def wrap(mark)...
python
def try_process_text(self, text): """ safe process text if error - return not modifyed text """ if not text: return text try: return self.process_text(text) except (socket.gaierror, socket.timeout, xml.parsers.expat.ExpatError): return text
python
def get_by_natural_key(self, *args): """ Return the object corresponding to the provided natural key. (This is a generic implementation of the standard Django function) """ kwargs = self.natural_key_kwargs(*args) # Since kwargs already has __ lookups in it, we could ju...
java
protected InstallRequest buildInstallRequest(RaftMemberContext member, Snapshot snapshot) { if (member.getNextSnapshotIndex() != snapshot.index()) { member.setNextSnapshotIndex(snapshot.index()); member.setNextSnapshotOffset(0); } InstallRequest request; synchronized (snapshot) { // O...
java
@Nullable public static String getFromFirstIncl (@Nullable final String sStr, final char cSearch) { return _getFromFirst (sStr, cSearch, true); }
java
@Override public List<BounceProxyRecord> getAssignableBounceProxies() { return directory.values() .stream() .filter(Objects::nonNull) .filter(r -> r.getStatus().isAssignable()) .collect(Collectors.toList()); ...
java
@Override public void execute() throws MojoExecutionException, MojoFailureException { if (!skip) { boolean ansiRestore = Ansi.isEnabled(); log = new AnsiLogger(getLog(), useColorForLogging(), verbose, !settings.getInteractiveMode(), getLogPrefix()); try { ...
java
@Indexable(type = IndexableType.REINDEX) @Override public CommerceDiscountRule addCommerceDiscountRule( CommerceDiscountRule commerceDiscountRule) { commerceDiscountRule.setNew(true); return commerceDiscountRulePersistence.update(commerceDiscountRule); }
python
def sampleCellsAcrossColumns(numCellPairs, cellsPerColumn, numColumns, seed=42): """ Generate indices of cell pairs, each pair of cells are from different column @return cellPairs (list) list of cell pairs """ np.random.seed(seed) cellPairs = [] for i in range(numCellPairs): randCols = np.random.choic...
java
@Override public void configure(SceneStructureMetric structure , SceneObservations observations ) { this.structure = structure; this.observations = observations; numObservations = observations.getObservationCount(); numParameters = structure.getParameterCount(); structure.assignIDsToRigidPoints(); ...
java
public TupleRefBuilder bindings( VarBinding... bindings) { for( VarBinding binding : bindings) { tupleRef_.addVarBinding( binding); } return this; }
python
def acquire_lock(self): """ Acquire the global lock for the root directory associated with this context. When a goal requires serialization, it will call this to acquire the lock. :API: public """ if self.options.for_global_scope().lock: if not self._lock.acquired: self._lock.acquire(...
python
def max_freq(self, tech_in_nm=130, ffoverhead=None): """ Estimates the max frequency of a block in MHz. :param tech_in_nm: the size of the circuit technology to be estimated (for example, 65 is 65nm and 250 is 0.25um) :param ffoverhead: setup and ff propagation delay in picoseconds ...
java
public Chunk setUnderline(Color color, float thickness, float thicknessMul, float yPosition, float yPositionMul, int cap) { if (attributes == null) attributes = new HashMap(); Object obj[] = { color, new float[] { thickness, thicknessMul, yPosition, yPositionMul, cap } }; Object unders[][] = Utiliti...
python
def _find_sock(): """ Create a UDP socket """ if socket.has_ipv6: try: return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) except socket.gaierror: pass # Platform lied about IPv6 support return socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
python
def import_lv_stations(self, session): """ Import lv_stations within the given load_area Parameters ---------- session : sqlalchemy.orm.session.Session Database session Returns ------- lv_stations: :pandas:`pandas.DataFrame<dataframe>` ...
java
public final void setVolumeByIncrement(float level) throws IOException { Volume volume = this.getStatus().volume; float total = volume.level; if (volume.increment <= 0f) { throw new ChromeCastException("Volume.increment is <= 0"); } // With floating points we always...
python
def cardinality_class(self): """ Group the cardinality of the dimension into one of four buckets, from very small (less than 5) to very large (more than 1000). """ if self.cardinality: if self.cardinality > 1000: return 'high' if self.cardinality > 50: ...
java
private void validate(float[] input, float[] output, Map<Integer, ? extends Object> args) throws SmoothingFilterException { if(input == null) throw new SmoothingFilterException(getClass(), "Input array is null.", new NullPointerException()); if(output == null) throw new SmoothingFilterException(getCl...
python
def show_run(): ''' Shortcut to run `show run` on switch .. code-block:: bash salt '*' onyx.cmd show_run ''' try: enable() configure_terminal() ret = sendline('show running-config') configure_terminal_exit() disable() except TerminalException as ...
java
public T withIncludedProperties(List<String> includedProperties) { Validate.argumentIsNotNull(includedProperties); if (ignoredProperties.size() > 0) { throw new JaversException(JaversExceptionCode.IGNORED_AND_INCLUDED_PROPERTIES_MIX, clazz.getSimpleName()); } this.includedPro...
python
def parse_sparse(filename, vocab_filename): """ Parse a file that's in libSVM format. In libSVM format each line of the text file represents a document in bag of words format: num_unique_words_in_doc word_id:count another_id:count The word_ids have 0-based indexing, i.e. 0 corresponds to the first...
python
def selected_mapping(self): """Obtain the value-to-class mapping set by user. :returns: The complete mapping as a dict of lists. :rtype: dict """ value_map = {} tree_clone = self.treeClasses.invisibleRootItem().clone() for tree_branch in tree_clone.takeChildren()...
python
def collection(data, bins=10, *args, **kwargs): """Create histogram collection with shared binnning.""" from physt.histogram_collection import HistogramCollection if hasattr(data, "columns"): data = {column: data[column] for column in data.columns} return HistogramCollection.multi_h1(data, bins,...
python
def results(self, trial_ids): """ Accepts a sequence of trial ids and returns a pandas dataframe with the schema trial_id, iteration?, *metric_schema_union where iteration is an optional column that specifies the iteration when a user logged a metric, if the user suppli...
python
def value(self, units=None): """Return the pressure in the specified units.""" if units is None: return self._value if not units.upper() in CustomPressure.legal_units: raise UnitsError("unrecognized pressure unit: '" + units + "'") units = units.upper() i...
java
@Override public void scrollToPosition(int position) { mPendingScrollPosition = position; mPendingScrollPositionOffset = INVALID_OFFSET; if (mPendingSavedState != null) { mPendingSavedState.invalidateAnchor(); } requestLayout(); }
python
def iterkeys(obj): "Get key iterator from dictionary for Python 2 and 3" return iter(obj.keys()) if sys.version_info.major == 3 else obj.iterkeys()
python
def parse(self, commands): """ Parse a list of commands. """ # Get rid of dummy objects that represented deleted objects in # the last parsing round. to_delete = [] for id_, val in self._objects.items(): if val == JUST_DELETED: to_delete.appen...
python
def get_intersection(self, range_): """Get a list of variants that intersect with the given range. Args: range_ (`VersionRange`): Package version range. Returns: List of `_PackageEntry` objects. """ result = [] for entry in self.entries: ...
python
def get_sleep_timer(self): """Retrieves remaining sleep time, if any Returns: int or NoneType: Number of seconds left in timer. If there is no sleep timer currently set it will return None. """ resp = self.avTransport.GetRemainingSleepTimerDuration([ ...
java
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed // TODO add your handling code here: OkapiUI.compositeInputField.setText(compositeText.getText()); dispose(); }
python
def free_sources_by_name(self, names, free=True, pars=None, **kwargs): """Free all sources with names matching ``names``. Parameters ---------- names : list List of source names. free : bool Choose whether to free (free=True)...
python
def install(self, ref, table_name=None, index_columns=None,logger=None): """ Finds partition by reference and installs it to warehouse db. Args: ref (str): id, vid (versioned id), name or vname (versioned name) of the partition. """ try: obj_number = ObjectNum...
java
@Override public void load(final InputStream inStream) throws IOException { lock.writeLock().lock(); try { properties.load(inStream); } finally { lock.writeLock().unlock(); } }
java
public Object eval(String source, int lineNo, int columnNo, Object script) throws BSFException { try { Class scriptClass = evalScripts.get(script); if (scriptClass == null) { scriptClass = loader.parseClass(script.toString(), source); evalScripts.put(scrip...
java
@Check public void checkFieldNameShadowing(SarlField field) { if (!isIgnored(VARIABLE_NAME_SHADOWING) && !Utils.isHiddenMember(field.getName())) { final JvmField inferredField = this.associations.getJvmField(field); final Map<String, JvmField> inheritedFields = new TreeMap<>(); Utils.populateInheritance...
python
def set_up_log(filename, verbose=True): """Set up log This method sets up a basic log. Parameters ---------- filename : str Log file name Returns ------- logging.Logger instance """ # Add file extension. filename += '.log' if verbose: print('Preparin...
python
def _slice_cov(self, cov): """ Slice the correct dimensions for use in the kernel, as indicated by `self.active_dims` for covariance matrices. This requires slicing the rows *and* columns. This will also turn flattened diagonal matrices into a tensor of full diagonal matrices. ...
java
private String getSupportedResolutions() { final StringBuilder builder = new StringBuilder(Constant.HUNDRED); int i = 0; for (final DisplayMode display : dev.getDisplayModes()) { final StringBuilder widthSpace = new StringBuilder(); final int width = display.g...
python
def smart_reroot(treefile, outgroupfile, outfile, format=0): """ simple function to reroot Newick format tree using ete2 Tree reading format options see here: http://packages.python.org/ete2/tutorial/tutorial_trees.html#reading-newick-trees """ tree = Tree(treefile, format=format) leaves = ...
java
public void addItem (int index, T item) { if (_items == null) { return; } _items.add(index, item); }
java
private boolean computeCameraMatrix(View seed, Motion edge, FastQueue<Point2D_F64> featsB, DMatrixRMaj cameraMatrix ) { boolean seedSrc = edge.src == seed; int matched = 0; for (int i = 0; i < edge.inliers.size; i++) { // need to go from i to index of detected features in view 'seed' to index index of feature...
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public TagContext tagContextCreation(Data data) { return TagsBenchmarksUtil.createTagContext(data.tagger.emptyBuilder(), data.numTags); }
java
public static Call create(final BandwidthClient client, final Map <String, Object>params) throws Exception { assert (client != null && params != null); final String callUri = client.getUserResourceUri(BandwidthConstants.CALLS_URI_PATH); final RestResponse response = client.post(callUri, p...
java
public static byte[] calculateHMAC(byte[] message, byte[] keyBytes, String algorithm) throws NoSuchAlgorithmException, InvalidKeyException { if (keyBytes == null) { throw new IllegalArgumentException("Invalid HMAC key: null"); } String hmacAlgorithmName = "Hmac" + algorithm.toUpperCa...
python
def attribute( self, attr_type, attr_value, displayed=False, source=None, unique=True, formatter=None ): """Return instance of Attribute unique: * False - Attribute type:value can be duplicated. * Type - Attribute type has to be unique (e.g., only 1 Description Attri...
java
public static void scanForLeaves(List<RPNode> nodes,RPNode current) { if(current.getLeft() == null && current.getRight() == null) nodes.add(current); if(current.getLeft() != null) scanForLeaves(nodes,current.getLeft()); if(current.getRight() != null) scanForLe...