language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public Map<String, String> sign(String httpeMethod, String endpoint, String resourcePath, Map<String, String> headers, Map<String, String> params, InputStream entity, String accessKey, String secretKey) { Request<?> req = buildAWSRequest(httpeMethod, endpoint, resourcePath, headers, params, entity); sign(req...
python
def scenario_risk(riskinputs, riskmodel, param, monitor): """ Core function for a scenario computation. :param riskinput: a of :class:`openquake.risklib.riskinput.RiskInput` object :param riskmodel: a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance :param param: ...
python
def starts_with(self, prefix): """ Find all words starting with a prefix. Args: prefix: A prefix to be searched for. Returns: A list of all words found. """ prefix = prefix.lower() found_words = [] res = cgaddag.gdg_starts_with(s...
python
def get_links_of_type(self, s_type=''): """Return the `s_type` satellite list (eg. schedulers) If s_type is None, returns a dictionary of all satellites, else returns the dictionary of the s_type satellites The returned dict is indexed with the satellites uuid. :param s_type: ...
python
def to_latex(self, buf=None, columns=None, col_space=None, header=True, index=True, na_rep='NaN', formatters=None, float_format=None, sparsify=None, index_names=True, bold_rows=False, column_format=None, longtable=None, escape=None, encoding=None, deci...
java
Element evaluateXPathNode(Node contextNode, String expression, Object... args) { return evaluateXPathNodeNS(contextNode, null, expression, args); }
java
@Override public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { // if (useTokenServices && super.isApproved(authorizationRequest, userAuthentication)) { // return true; // } if (!userAuthentication.isAuthenticated()) { ...
java
public static AlipayFundTransOrderQueryResponse transferQueryToResponse(AlipayFundTransOrderQueryModel model) throws AlipayApiException { AlipayFundTransOrderQueryRequest request = new AlipayFundTransOrderQueryRequest(); request.setBizModel(model); return AliPayApiConfigKit.getAliPayApiConfig().getAlipayClient...
python
def _download_log(self, url, output_file): """Saves log returned by the message bus.""" logger.info("Saving log %s to %s", url, output_file) def _do_log_download(): try: return self.session.get(url) # pylint: disable=broad-except except Except...
python
def get_current_frame(): """ :return: current frame object (excluding this function call) :rtype: types.FrameType Uses sys._getframe if available, otherwise some trickery with sys.exc_info and a dummy exception. """ if hasattr(sys, "_getframe"): # noinspection PyProtectedMember ...
java
@InterfaceAudience.Public public void setContinuous(boolean isContinous) { if (isContinous) { this.lifecycle = Lifecycle.CONTINUOUS; replicationInternal.setLifecycle(Lifecycle.CONTINUOUS); } else { this.lifecycle = Lifecycle.ONESHOT; replicationInterna...
java
public void addMimeMapping(String extension, String type) { _mimeMap.put(StringUtils.asciiToLowerCase(extension), normalizeMimeType(type)); }
python
def add_group(self, L): """Add elements of L as descendants of the node. If there are several elements in L, group them in a P-node first """ if len(L) == 1: self.add(L[0]) elif len(L) >= 2: x = PQ_node(P_shape) x.add_all(L) self.ad...
python
def is_magic(line, language, global_escape_flag=True): """Is the current line a (possibly escaped) Jupyter magic, and should it be commented?""" if language in ['octave', 'matlab']: return False if _MAGIC_FORCE_ESC_RE.get(language, _MAGIC_FORCE_ESC_RE['python']).match(line): return True ...
python
def _onPaint(self, evt): """ Called when wxPaintEvt is generated """ DEBUG_MSG("_onPaint()", 1, self) drawDC = wx.PaintDC(self) if not self._isDrawn: self.draw(drawDC=drawDC) else: self.gui_repaint(drawDC=drawDC) evt.Skip()
java
private void scheduleOneTime(TaskScheduler scheduler) { scheduledFuture = scheduler.schedule(runnable, (int)delayTime, TimeUnit.MILLISECONDS); }
java
public void setActionFlags() { m_checkinBean.setFetchAndResetBeforeImport(m_fetchAndReset.getValue().booleanValue()); switch (m_mode) { case checkOut: m_checkinBean.setCheckout(true); m_checkinBean.setResetHead(false); m_checkinBean.setResetRe...
python
def _fullqualname_method_py3(obj): """Fully qualified name for 'method' objects in Python 3. """ if inspect.isclass(obj.__self__): cls = obj.__self__.__qualname__ else: cls = obj.__self__.__class__.__qualname__ return obj.__self__.__module__ + '.' + cls + '.' + obj.__name__
java
public void parse2DJSON(String str) { for (String latlon : str.split("\\[")) { if (latlon.trim().length() == 0) continue; String ll[] = latlon.split(","); String lat = ll[1].replace("]", "").trim(); add(Double.parseDouble(lat), Double.parseDouble(...
java
public final void doesNotContain(@NullableDecl Object element) { if (Iterables.contains(actual(), element)) { failWithActual("expected not to contain", element); } }
java
public static <T> T findBean(Class<T> type, ApplicationContext context) { Map m = context.getBeansOfType(type); switch(m.size()) { case 0: throw new IllegalArgumentException("No beans of "+type+" are defined"); case 1: return type.cast(m.values().iterator().next()...
python
def _GetRealImagArray(Array): """ Returns the real and imaginary components of each element in an array and returns them in 2 resulting arrays. Parameters ---------- Array : ndarray Input array Returns ------- RealArray : ndarray The real components of the input array ...
java
static Iterator getIterator(Object agg) throws JMFSchemaViolationException { if (agg instanceof Collection) { return ((Collection)agg).iterator(); } else if (agg.getClass().isArray()) { return new LiteIterator(agg); } else { throw new JMFSchemaViolationException(agg.getClass().getN...
python
def generate_sample_stacker_module(env_root, module_dir=None): """Generate skeleton Stacker sample module.""" if module_dir is None: module_dir = os.path.join(env_root, 'runway-sample-tfstate.cfn') generate_sample_module(module_dir) for i in ['stacks.yaml', 'dev...
java
public void doTag() throws JspException { JspTag parentTag = SimpleTagSupport.findAncestorWithClass(this, IFormattable.class); // if there are errors we need to either add these to the parent AbstractBastTag or report an error. if (hasErrors()) { if (parentTag instan...
python
def potential_purviews(self, direction, mechanism, purviews=False): """Override Subsystem implementation using Network-level indices.""" all_purviews = utils.powerset(self.node_indices) return irreducible_purviews( self.cm, direction, mechanism, all_purviews)
python
def _get_corpus_properties(self, corpus_name): """Check whether a corpus is available for import. :type corpus_name: str :param corpus_name: Name of available corpus. :rtype : str """ try: # corpora = LANGUAGE_CORPORA[self.language] corpora = self....
python
def clone(orig, n): """Construct `n` copies of a layer, with distinct weights. i.e. `clone(f, 3)(x)` computes `f(f'(f''(x)))`. """ if n == 0: return layerize(noop()) layers = [orig] for i in range(n - 1): layers.append(copy.deepcopy(orig)) layers[-1].set_id() return ...
java
protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { NodeCountry nodeCountry = (NodeCountry) samlObject; if (nodeCountry.getNodeCountry() != null) { ElementSupport.appendTextContent(domElement, nodeCountry.getNodeCountry()); } }
python
def calculate_lux(r, g, b): """Converts the raw R/G/B values to luminosity in lux.""" illuminance = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b) return int(illuminance)
python
def sync_with_s3(self): """ Walk through our self.local_files list, and match them with the list of keys in the S3 bucket. """ # Create a list to put all the files we're going to update self.update_list = [] # Figure out which files need to be updated and upload ...
python
def from_pystr_to_cstr(data): """Convert a list of Python str to C pointer Parameters ---------- data : list list of str """ if not isinstance(data, list): raise NotImplementedError pointers = (ctypes.c_char_p * len(data))() if PY3: data = [bytes(d, 'utf-8') for...
java
@Override public String debugPrint() { DebugPrintVisitor dpv = new DebugPrintVisitor(new StringBuilder(1000)); visitAll(dpv); return dpv.toString(); }
java
public void marshall(S3Target s3Target, ProtocolMarshaller protocolMarshaller) { if (s3Target == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(s3Target.getPath(), PATH_BINDING); protocol...
python
def enrich_sentences_with_NLP(self, all_sentences): """ Enrich a list of fonduer Sentence objects with NLP features. We merge and process the text of all Sentences for higher efficiency. :param all_sentences: List of fonduer Sentence objects for one document :return: """...
python
def _perform_request(self, request, parser=None, parser_args=None, operation_context=None): ''' Sends the request and return response. Catches HTTPError and hands it to error handler ''' operation_context = operation_context or _OperationContext() retry_context = RetryCon...
python
def DBundle_for_Ntubes_Phadkeb(Ntubes, Do, pitch, Ntp, angle=30): r'''Determine the bundle diameter required to fit a specified number of tubes in a heat exchanger. Uses the highly accurate method of [1]_, which takes into account pitch, number of tube passes, angle, and tube diameter. The method is an...
python
async def async_init(self): """ During async init we just need to create a HTTP session so we can keep outgoing connexions to the platform alive. """ self.session = aiohttp.ClientSession() asyncio.get_event_loop().create_task(self._deferred_init())
python
def _create_database(self): """ Set up database Creates tables required for the authentication module. """ self._logger.info('creating user database') sql = '''CREATE TABLE IF NOT EXISTS user ( username NOT NULL PRIMARY KEY, pwd_salt NOT NULL, ...
python
def _init_conn(self): """ This method will be called after `connect` is called. After this method finishes, the writer will be drained. Subclasses should make use of this if they need to send data to Telegram to indicate which connection mode will be used. """ ...
java
@Override public void write (@Nonnull final char [] aBuf, @Nonnegative final int nOfs, @Nonnegative final int nLen) { ValueEnforcer.isArrayOfsLen (aBuf, nOfs, nLen); if (nLen > 0) m_aSB.append (aBuf, nOfs, nLen); }
java
public void delete_device_property(String name, String[] propnames) throws DevFailed { databaseDAO.delete_device_property(this, name, propnames); }
java
private double getKJPolarizabilityFactor(IAtomContainer atomContainer, IAtom atom) { double polarizabilitiyFactor = 0; String AtomSymbol; AtomSymbol = atom.getSymbol(); switch (AtomSymbol) { case "H": polarizabilitiyFactor = 0.387; break; ...
python
def bg_phase_mask_from_sim(sim, radial_clearance=1.1): """Return the background phase mask of a qpsphere simulation Parameters ---------- sim: qpimage.QPImage Quantitative phase data simulated with qpsphere; The simulation keyword arguments "sim center", "sim radius", and "pixel...
python
def is_exchange(self, reaction_id): """Whether the given reaction is an exchange reaction.""" reaction = self.get_reaction(reaction_id) return (len(reaction.left) == 0) != (len(reaction.right) == 0)
python
def goal_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/goals#create-goal" api_path = "/api/v2/goals" return self.call(api_path, method="POST", data=data, **kwargs)
python
def _GetNetworkInfo(self, signatures_key): """Retrieves the network info within the signatures subkey. Args: signatures_key (dfwinreg.WinRegistryKey): a Windows Registry key. Returns: dict[str, tuple]: a tuple of default_gateway_mac and dns_suffix per profile identifier (GUID). "...
python
def extract_fragment(self, iri: str) -> str: ''' Pulls only for code/ID from the iri I only add the str() conversion for the iri because rdflib objects need to be converted. ''' fragment = str(iri).rsplit('/')[-1].split(':', 1)[-1].split('#', 1)[-1].split('_', 1)[-1] return frag...
java
private static void updateCountForINodeWithQuota(INodeDirectory dir, INode.DirCounts counts, ArrayList<INode> nodesInPath) { long parentNamespace = counts.nsCount; long parentDiskspace = counts.dsCount; counts.nsC...
java
public static boolean saveProperties(Properties inProperties, File saveFile, String comment) { try { if (!saveFile.exists()) JMFiles.createEmptyFile(saveFile); BufferedWriter writer = new BufferedWriter(new FileWriter(saveFile)); ...
java
private void addProjectProperties() throws MojoExecutionException { Properties projectProps = mavenProject.getProperties(); projectProps.setProperty( PROPERTY_NAME_COMPANY, versionInfo.getCompanyName() ); projectProps.setProperty( PROPERTY_NAME_COPYRIGHT, versionInfo.getCopyright() ...
python
def acquire(self, blocking=True): """acquire ownership of the lock if the lock is already owned by the calling greenlet, a counter simply gets incremented. if it is owned by a different greenlet then it will block until the lock becomes available. .. note:: this me...
java
@Given("^in less than '(\\d+?)' seconds, checking each '(\\d+?)' seconds, I send a '(.+?)' request to '(.+?)' so that the response( does not)? contains '(.+?)' based on '([^:]+?)'( as '(json|string|gov)')? with:$") public void sendRequestDataTableTimeout(Integer timeout, Integer wait, String requestType, String end...
python
def run(self, context: ActionContext): """ Run performs loop iterations. :param context: Action context. """ iterator = itertools.count(start=self.start, step=self.step) for i in iterator: self.with_iteration(i) if self.stop is not None and i ...
python
def copy_from(self, g): """Copy all nodes and edges from the given graph into this. Return myself. """ renamed = {} for k, v in g.node.items(): ok = k if k in self.place: n = 0 while k in self.place: k ...
java
public static String getSourceFolder(Resource resource, CopyResourcesMojo copyResourcesMojo, File workspacePlugin) throws ResourceExecutionException { String hostname = resource.getUri().getHost(); String username = resource.getUsername(); String password = resource.getPassword(); String remoteSource = r...
python
def floor(x): """ Floor function (round towards negative infinity) """ if isinstance(x, UncertainFunction): mcpts = np.floor(x._mcpts) return UncertainFunction(mcpts) else: return np.floor(x)
python
def _init_metadata(self): """stub""" self._min_decimal_value = None self._max_decimal_value = None self._decimal_values_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, ...
java
@Override public boolean isConnectedInDirection(N n1, E edgeValue, N n2) { return isConnectedInDirection(n1, Predicates.equalTo(edgeValue), n2); }
python
def print_nodes(nodes, detailed=False): """Prints all the given nodes""" found = 0 for node in nodes: found += 1 print_node(node, detailed=detailed) print("\nFound {0} node{1}".format(found, "s" if found != 1 else ""))
python
def update(gandi, resource, cmdline, kernel, name, size, snapshotprofile, delete_snapshotprofile, background): """ Update a disk. Resource can be a disk name, or ID """ if snapshotprofile and delete_snapshotprofile: raise UsageError('You must not set snapshotprofile and ' ...
python
def show_error(self, message): """ Send an error message to the active client. The new error will be displayed on any active GUI clients. Args: message (str): Plain-text message to display. Returns: None >>> s = _syncthing() ...
java
private Object writeOnly(CacheAopProxyChain pjp, Cache cache) throws Throwable { DataLoaderFactory factory = DataLoaderFactory.getInstance(); DataLoader dataLoader = factory.getDataLoader(); CacheWrapper<Object> cacheWrapper; try { cacheWrapper = dataLoader.init(pjp, cache, t...
java
public int clear() { int n = 0; for (GVRCursorController c : controllers) { c.stopDrag(); removeCursorController(c); ++n; } return n; }
java
public static void addVaryAcceptEncoding(final GZipServletResponseWrapper wrapper) { Collection<String> headers = wrapper.getHeaderNames(); String varyHeader = null; for (String header : headers) { if (header.equals("Vary")) { varyHeader = wrapper.getHeader(header); break; } } if (varyHeader =...
python
def measure_wf_coefficients(prep_program, coeff_list, reference_state, quantum_resource, variance_bound=1.0E-6): """ Measure a set of coefficients with a phase relative to the reference_state :param prep_program: pyQuil program to prepare the state :param coeff_list: list of...
java
public void setElbInfoList(java.util.Collection<ELBInfo> elbInfoList) { if (elbInfoList == null) { this.elbInfoList = null; return; } this.elbInfoList = new com.amazonaws.internal.SdkInternalList<ELBInfo>(elbInfoList); }
python
def guess_matches(video, guess, partial=False): """Get matches between a `video` and a `guess`. If a guess is `partial`, the absence information won't be counted as a match. :param video: the video. :type video: :class:`~subliminal.video.Video` :param guess: the guess. :type guess: dict :p...
java
public Dialect setKeepByteAndShort(boolean keepByteAndShort) { this.keepByteAndShort = keepByteAndShort; /** * 内部的 4 个 if 判断是为了避免替换掉用户通过 setModelBuilder(...) * setRecordBuilder(...) 配置的自定义 builder */ if (keepByteAndShort) { if (modelBuilder.getClass() == ModelBuilder.class) { modelBuilder ...
java
public Task<RemoteInsertOneResult> insertOne(final DocumentT document) { return dispatcher.dispatchTask(new Callable<RemoteInsertOneResult>() { @Override public RemoteInsertOneResult call() { return proxy.insertOne(document); } }); }
python
def load(cls, campaign_dir, ns_path=None, runner_type='Auto', optimized=True, check_repo=True): """ Load an existing simulation campaign. Note that specifying an ns-3 installation is not compulsory when using this method: existing results will be available, but in order to ...
java
public static LazyProxyFactory createDefaultProxyFactory() { if (testDependencyFullFilled()) { final String factoryClassName = "dev.morphia.mapping.lazy.CGLibLazyProxyFactory"; try { return (LazyProxyFactory) Class.forName(factoryClassName).newInstance(); } ca...
java
public static FilterParams fromTuples(Object... tuples) { StringValueMap map = StringValueMap.fromTuplesArray(tuples); return new FilterParams(map); }
java
@Override public CreateProjectResult createProject(CreateProjectRequest request) { request = beforeClientExecution(request); return executeCreateProject(request); }
java
public ProductionVariantSummary withDeployedImages(DeployedImage... deployedImages) { if (this.deployedImages == null) { setDeployedImages(new java.util.ArrayList<DeployedImage>(deployedImages.length)); } for (DeployedImage ele : deployedImages) { this.deployedImages.add(...
java
protected List<Map<String, ?>> generateStandardKeywords(Set<String> keywords) { final List<Map<String, ?>> list = new ArrayList<>(); if (!keywords.isEmpty()) { list.add(pattern(it -> { it.matches(keywordRegex(keywords)); it.style(KEYWORD_STYLE); it.comment("Standard Keywords"); //$NON-NLS-1$ })); ...
java
@Override public void delete(Long configId) { Config config = configDao.get(configId); configHistoryMgr.createOne(configId, config.getValue(), ""); configDao.deleteItem(configId); }
java
public OvhOrder license_virtuozzo_serviceName_upgrade_duration_GET(String serviceName, String duration, OvhOrderableVirtuozzoContainerNumberEnum containerNumber) throws IOException { String qPath = "/order/license/virtuozzo/{serviceName}/upgrade/{duration}"; StringBuilder sb = path(qPath, serviceName, duration); ...
python
def read_without_mac(self, *blocks): """Read a number of data blocks without integrity check. This method accepts a variable number of integer arguments as the block numbers to read. The blocks are read with service code 0x000B (NDEF). Tag command errors raise :exc:`~nfc.tag.Ta...
java
public void error(XPathContext xctxt, String msg, Object[] args) throws javax.xml.transform.TransformerException { java.lang.String fmsg = XSLMessages.createXPATHMessage(msg, args); if (null != xctxt) { ErrorListener eh = xctxt.getErrorListener(); TransformerException te = new Tran...
java
private void setForceContextMenu() { suppressContextMenu(getElement()); addShowContextMenuHandler(new ShowContextMenuHandler() { @Override public void onShowContextMenu(ShowContextMenuEvent event) { getContextMenu().showContextMenu(); } }); addListener(new Listener() { @Overrid...
java
protected void unregisterAllTimeouts() { for (Timeout<K> timeout : timeouts.values()) { timeout.cancel(); } timeouts.clear(); }
java
@Override public ITextRegion getTextRegion(EObject object, EStructuralFeature feature, int indexInList, RegionDescription query) { switch(query) { // we delegate the implementation to the existing and potentially overridden methods case SIGNIFICANT: return getSignificantTextRegion(object, feature, indexInLi...
python
def subjects(self): """ Return identifiers for all the subjects that are in the cache. :return: list of subject identifiers """ subj = [i["subject_id"] for i in self._cache.find()] return list(set(subj))
python
def start (self): ''' Starts (Subscribes) the client. ''' self.sub = rospy.Subscriber(self.topic, BumperEvent, self.__callback)
java
public static <T extends Comparable<T>> T geq(T value) { reportMatcher(new GreaterOrEqual<T>(value)); return null; }
python
def generate_context(name='', argspec='', note='', math=False, collapse=False, img_path='', css_path=CSS_PATH): """ Generate the html_context dictionary for our Sphinx conf file. This is a set of variables to be passed to the Jinja template engine and that are used to control h...
java
public StateStream getStateStream() { if(TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.entry(this, tc, "getStateStream"); SibTr.exit(tc, "getStateStream", oststream); } return oststream; }
java
@Override public DeleteEventSubscriptionResult deleteEventSubscription(DeleteEventSubscriptionRequest request) { request = beforeClientExecution(request); return executeDeleteEventSubscription(request); }
java
public static ClassResolver softCachingConcurrentResolver(ClassLoader classLoader) { return new CachingClassResolver( new ClassLoaderClassResolver(defaultClassLoader(classLoader)), new SoftReferenceMap<String, Class<?>>( PlatformDependent.<String, Referenc...
python
def get_all_switch_ips(self): """Using reserved switch binding get all switch ips.""" switch_connections = [] try: bindings = nxos_db.get_reserved_switch_binding() except excep.NexusPortBindingNotFound: LOG.error("No switch bindings in the port data base") ...
java
static ConstantClassInfo make(ConstantPool cp, String className, int dim) { ConstantInfo ci = new ConstantClassInfo(cp, className, dim); return (ConstantClassInfo)cp.addConstant(ci); }
java
public static <T> Set<T> randomSetFrom(Iterable<T> elements, Range<Integer> attemptedSize) { return Sets.newHashSet(randomListFrom(elements, attemptedSize)); }
python
def usearch(query, db, type, out, threads = '6', evalue = '100', alignment = 'local', max_hits = 100, cluster = False): """ run usearch """ if 'usearch64' in os.environ: usearch_loc = os.environ['usearch64'] else: usearch_loc = 'usearch' if os.path.exists(out) is False: d...
python
def to_abivars(self): """Returns a dictionary with the abinit variables""" abivars = { "ecuteps" : self.ecuteps, "ecutwfn" : self.ecutwfn, "inclvkb" : self.inclvkb, "gwpara" : self.gwpara, "awtr" : self.awtr, "symchi" ...
python
def every(self, **kwargs): """ Specify the interval at which you want the job run. Takes exactly one keyword argument. That argument must be one named one of [second, minute, hour, day, week, month, year] or their plural equivalents. :param kwargs: Exactly one keyword argument ...
java
public boolean delete(String name, boolean bankAccount) { boolean result = false; if (exist(name, bankAccount)) { result = Common.getInstance().getStorageHandler().getStorageEngine().deleteAccount(name, bankAccount); if (bankAccount) { bankList.remove(name); ...
java
public ItemRule newAttributeItemRule(String attributeName) { ItemRule itemRule = new ItemRule(); itemRule.setName(attributeName); addAttributeItemRule(itemRule); return itemRule; }
java
static void make72Safe(StringBuffer line) { int length = line.length(); if (length > 72) { int index = 70; while (index < length - 2) { line.insert(index, "\r\n "); index += 72; length += 3; } } return; ...
java
Observable<ChatResult> synchroniseStore() { if (isSynchronising.getAndSet(true)) { log.i("Synchronisation in progress."); return Observable.fromCallable(() -> new ChatResult(true, null)); } log.i("Synchronising store."); return synchroniseConversations() ...