language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public String nextUID() { StringBuilder tmp = new StringBuilder(prefix.length + 16); tmp.append(prefix); tmp.append(counter.incrementAndGet()); return tmp.toString(); }
java
public static FixedStringSearchInterpolator createInterpolator(MojoParameters params, String filter) { String[] delimiters = extractDelimiters(filter); if (delimiters == null) { // Don't interpolate anything return FixedStringSearchInterpolator.create(); } Docker...
java
public static String simplifyPath(String pathname) { if (N.isNullOrEmpty(pathname)) { return "."; } pathname = pathname.replace('\\', '/'); // split the path apart String[] components = pathSplitter.splitToArray(pathname); List<String> path = new Ar...
java
public Observable<Page<IntegrationAccountInner>> listNextAsync(final String nextPageLink) { return listNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<IntegrationAccountInner>>, Page<IntegrationAccountInner>>() { @Override public Page<In...
java
public void setServerCustomizers( Collection<? extends JettyServerCustomizer> customizers) { Assert.notNull(customizers, "Customizers must not be null"); this.jettyServerCustomizers = new ArrayList<>(customizers); }
python
def update_task_ids(self, encoder_vocab_size): """Generate task_ids for each problem. These ids correspond to the index of the task in the task_list. Args: encoder_vocab_size: the size of the vocab which is used to compute the index offset. """ for idx, task in enumerate(self.task_li...
python
def value(self): """returns object as dictionary""" return { "type" : "uniqueValue", "field1" : self._field1, "field2" : self._field2, "field3" : self._field3, "fieldDelimiter" : self._fieldDelimiter, "defaultSymbol" : self._defaul...
java
private void duplicateProperties(final String spaceId, final String contentId, final Map<String, String> sourceProperties) throws TaskExecutionFailedException { log.info("Duplicating properties for " + contentId + " in space " + spaceId + " in accoun...
python
def _upload_image(registry, docker_tag, image_id) -> None: """ Upload the passed image by id, tag it with docker tag and upload to S3 bucket :param registry: Docker registry name :param docker_tag: Docker tag :param image_id: Image id :return: None """ # We don't have to retag the image ...
java
public static void setLearningRate(MultiLayerNetwork net, int layerNumber, double newLr) { setLearningRate(net, layerNumber, newLr, null, true); }
python
def __init_yaml(): """Lazy init yaml because canmatrix might not be fully loaded when loading this format.""" global _yaml_initialized if not _yaml_initialized: _yaml_initialized = True yaml.add_constructor(u'tag:yaml.org,2002:Frame', _frame_constructor) yaml.add_constructor(u'tag:ya...
python
def stop(self, measurementId, failureReason=None): """ informs the target the named measurement has completed :param measurementId: the measurement that has completed. :return: """ if failureReason is None: self.endResponseCode = self._doPut(self.sendURL + "/c...
python
def get_agents_by_ids(self, agent_ids): """Gets an ``AgentList`` corresponding to the given ``IdList``. In plenary mode, the returned list contains all of the agents specified in the ``Id`` list, in the order of the list, including duplicates, or an error results if an ``Id`` in the ...
python
def Transit(time, t0=0., dur=0.1, per=3.56789, depth=0.001, **kwargs): ''' A `Mandel-Agol <http://adsabs.harvard.edu/abs/2002ApJ...580L.171M>`_ transit model, but with the depth and the duration as primary input variables. :param numpy.ndarray time: The time array :param float t0: The time of f...
python
async def list_networks(request: web.Request) -> web.Response: """ Get request will return a list of discovered ssids: GET /wifi/list 200 OK { "list": [ { ssid: string // e.g. "linksys", name to connect to signal: int // e.g. 100; arbitrary signal strength, more is be...
python
def infer_transportation_modes(self, dt_threshold=10): """In-place transportation inferring of segments Returns: This track """ self.segments = [ segment.infer_transportation_mode(dt_threshold=dt_threshold) for segment in self.segments ] ...
java
private long timeOfBeat(BeatGrid beatGrid, int beatNumber, DeviceUpdate update) { if (beatNumber <= beatGrid.beatCount) { return beatGrid.getTimeWithinTrack(beatNumber); } logger.warn("Received beat number " + beatNumber + " from " + update.getDeviceName() + " " + upd...
java
protected List<AbstractClassTypeDeclarationDescr> sortByHierarchy(Collection<AbstractClassTypeDeclarationDescr> unsortedDescrs, KnowledgeBuilderImpl kbuilder) { taxonomy = new HashMap<QualifiedName, Collection<QualifiedName>>(); Map<QualifiedName, AbstractClassTypeDeclarationDescr> cache = new HashMap<...
java
private static Identity parse(final JsonObject json) { final Map<String, String> props = new HashMap<>(json.size()); // @checkstyle MultipleStringLiteralsCheck (1 line) props.put(PsGithub.LOGIN, json.getString(PsGithub.LOGIN, "unknown")); props.put("avatar", json.getString("avatar_url", ...
python
def _handle_func_def(self, node, scope, ctxt, stream): """Handle FuncDef nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling function definition") func = self._handle_node(node.decl, scope, ctxt, strea...
java
static public Angle difference(Angle angle1, Angle angle2) { return new Angle(angle1.value - angle2.value); }
python
def get_user_contact_list(self, id, contact_list_id, **data): """ GET /users/:id/contact_lists/:contact_list_id/ Gets a user's :format:`contact_list` by ID as ``contact_list``. """ return self.get("/users/{0}/contact_lists/{0}/".format(id,contact_list_id), data=data)
java
public List<Project> getAllProjects() { try { sessionService.startSession(); List<Project> projects = projectDao.getAll(); log.debug("Retrieved All Projects number: " + projects.size()); return projects; } finally { sessionService.closeSessio...
java
public Instances samoaInstancesInformation(weka.core.Instances instances) { Instances samoaInstances; List<Attribute> attInfo = new ArrayList<Attribute>(); for (int i = 0; i < instances.numAttributes(); i++) { attInfo.add(samoaAttribute(i, instances.attribute(i))); } ...
java
public static void main(String[] args) throws NoSuchAlgorithmException, IOException, InvalidKeyException, XmlPullParserException { try { /* play.min.io for test and development. */ MinioClient minioClient = new MinioClient("https://play.min.io:9000", "Q3AM3UQ867SPQQA43P2F", ...
java
public Set<String> selectOrganizationPermissions(DbSession dbSession, String organizationUuid, int userId) { return mapper(dbSession).selectOrganizationPermissions(organizationUuid, userId); }
python
def asynchronous(func): """Return `func` in a "smart" asynchronous-aware wrapper. If `func` is called within the event-loop — i.e. when it is running — this returns the result of `func` without alteration. However, when called from outside of the event-loop, and the result is awaitable, the result will...
python
def intersperse(iterable, element): """Generator yielding all elements of `iterable`, but with `element` inserted between each two consecutive elements""" iterable = iter(iterable) yield next(iterable) while True: next_from_iterable = next(iterable) yield element yield next_f...
python
def remove(args): """ Remove the feed given in <args> """ session = c.Session(args) if not args["name"] in session.feeds: sys.exit("You don't have a feed with that name.") inputtext = ("Are you sure you want to remove the {} " " feed? (y/N) ").format(args["name"]) re...
java
public static String delFirst(Pattern pattern, CharSequence content) { if (null == pattern || StrUtil.isBlank(content)) { return StrUtil.str(content); } return pattern.matcher(content).replaceFirst(StrUtil.EMPTY); }
python
def extract_declarations(map_el, dirs, scale=1, user_styles=[]): """ Given a Map element and directories object, remove and return a complete list of style declarations from any Stylesheet elements found within. """ styles = [] # # First, look at all the stylesheets defined in the map i...
python
def get_post(post_id, username, password): """ metaWeblog.getPost(post_id, username, password) => post structure """ user = authenticate(username, password) site = Site.objects.get_current() return post_structure(Entry.objects.get(id=post_id, authors=user), site)
python
def dag(self) -> Tuple[Dict, Dict]: """Construct the DAG of this pipeline based on the its operations and their downstream.""" from pipelines import dags operations = self.operations.all().prefetch_related('downstream_operations') def get_downstream(op): return op.downstrea...
python
def main_callback(self, *args, **kwargs): """ Main callback called when an event is received from an entry point. :returns: The entry point's callback. :rtype: function :raises NotImplementedError: When the entrypoint doesn't have the required attributes. """ if ...
python
def DeleteAllFlowRequestsAndResponses(self, client_id, flow_id): """Deletes all requests and responses for a given flow from the database.""" flow_key = (client_id, flow_id) try: self.flows[flow_key] except KeyError: raise db.UnknownFlowError(client_id, flow_id) try: del self.flow...
java
public static void writeRecords(final List<VcfSample> samples, final List<VcfRecord> records, final PrintWriter writer) { checkNotNull(samples); checkNotNull(records); checkNotNull(writer); for (VcfRecord record : r...
java
public void putBooleanMapping(String property, Object trueValue, Object falseValue) { Map<String, Object> mapping = new HashMap<>(2); mapping.put(TRUE, trueValue); mapping.put(FALSE, falseValue); this.getBooleanMapping().put(property, mapping); }
python
def valueAt(self, percent): """ Returns the value the percent represents between the minimum and maximum for this axis. :param value | <int> || <float> :return <float> """ min_val = self.minimum() max_val = self.maximum...
java
@Override public synchronized void registerObserver(SubjectObserver<Settings> settingsObserver) { if (settingsObserver == null) throw new IllegalArgumentException("settingsObserver is required"); if(file != null) { if(fileMonitor == null) fileMonitor = new FileMonitor(); fileMonitor.moni...
java
public Server jdkSsl() throws SSLException, CertificateException { SelfSignedCertificate cert = new SelfSignedCertificate(); sslContext = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()) .sslProvider(SslProvider.JDK) .build(); return this; }
java
public synchronized List<TaskStatus> getNonRunningTasks() { List<TaskStatus> result = new ArrayList<TaskStatus>(tasks.size()); for(Map.Entry<TaskAttemptID, TaskInProgress> task: tasks.entrySet()) { if (!runningTasks.containsKey(task.getKey())) { result.add(task.getValue().getStatus()); } ...
java
public List<CmsListItem> getSelectedItems() { Iterator<String> it = CmsStringUtil.splitAsList( getParamSelItems(), CmsHtmlList.ITEM_SEPARATOR, true).iterator(); List<CmsListItem> items = new ArrayList<CmsListItem>(); while (it.hasNext()) { String ...
python
def to_dict(self, img_sets): """Create a dictionary serialization for a prediction image set handle. Parameters ---------- img_sets : PredictionImageSetHandle Returns ------- dict Dictionary serialization of the resource """ # Get the...
java
private void checkInlineParams(NodeTraversal t, Node function) { Node paramList = NodeUtil.getFunctionParameters(function); for (Node param : paramList.children()) { JSDocInfo jsDoc = param.getJSDocInfo(); if (jsDoc == null) { t.report(param, MISSING_PARAMETER_JSDOC); return; ...
python
def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or qu...
python
def find_or_build_all(cls, list_of_kwargs): """Similar to `find_or_create_all`. But transaction is not committed. """ return cls.add_all([cls.first(**kwargs) or cls.new(**kwargs) for kwargs in list_of_kwargs], commit=False)
java
public static Object instantiate(String type, ClassLoader classLoader) { try { return ClassUtils.forName(type, classLoader) .flatMap(InstantiationUtils::tryInstantiate) .orElseThrow(() -> new InstantiationException("No class found for name: " + type)); } catch...
python
def protect_libraries_from_patching(): """ In this function we delete some modules from `sys.modules` dictionary and import them again inside `_pydev_saved_modules` in order to save their original copies there. After that we can use these saved modules within the debugger to protect them from patchi...
java
void setArrayExpression(BSHArrayInitializer init) { this.isArrayExpression = true; if (parent instanceof BSHAssignment) { BSHAssignment ass = (BSHAssignment) parent; if ( null != ass.operator && ass.operator == ParserConstants.ASSIGN ) this.isM...
python
def atan2(y, x, context=None): """ Return ``atan(y / x)`` with the appropriate choice of function branch. If ``x > 0``, then ``atan2(y, x)`` is mathematically equivalent to ``atan(y / x)``. If ``x < 0`` and ``y > 0``, ``atan(y, x)`` is equivalent to ``π + atan(y, x)``. If ``x < 0`` and ``y < 0``,...
java
public synchronized void registerNewConf(Address address, List<ConfigProperty> configList) { Preconditions.checkNotNull(address, "address should not be null"); Preconditions.checkNotNull(configList, "configuration list should not be null"); // Instead of recording property name, we record property key. ...
java
public static String clean(String path) { path = path.replaceAll("//", "/"); return StringUtils.trimToNull(path); }
python
def get_bucket(self, bucket, marker=None, max_keys=None, prefix=None): """ Get a list of all the objects in a bucket. @param bucket: The name of the bucket from which to retrieve objects. @type bucket: L{unicode} @param marker: If given, indicate a position in the overall ...
java
@Execute public HtmlResponse create(final CreateForm form) { verifyCrudMode(form.crudMode, CrudMode.CREATE); validate(form, messages -> {}, () -> asEditHtml()); verifyToken(() -> asEditHtml()); getBadWord(form).ifPresent( entity -> { try { ...
python
def _escape_token(token, alphabet): r"""Replace characters that aren't in the alphabet and append "_" to token. Apply three transformations to the token: 1. Replace underline character "_" with "\u", and backslash "\" with "\\". 2. Replace characters outside of the alphabet with "\###;", where ### is the ...
java
public static Context pushContext(Map<String, Object> current) { Context context = new Context(getContext(), current); LOCAL.set(context); return context; }
java
public boolean isReadOnly(ELContext context, Object base, Object property) { context.setPropertyResolved(false); boolean readOnly; for (int i = 0; i < size; i++) { readOnly = elResolvers[i].isReadOnly(context, base, proper...
java
public void startWithoutExecuting(Map<String, Object> variables) { initialize(); initializeTimerDeclarations(); fireHistoricProcessStartEvent(); performOperation(PvmAtomicOperation.FIRE_PROCESS_START); setActivity(null); setActivityInstanceId(getId()); // set variables setVariables(var...
python
def debug(self, group, message): '''Maybe write a debug-level log message. In particular, this gets written if the hidden `debug_worker` option contains `group`. ''' if group in self.debug_worker: if 'stdout' in self.debug_worker: print message ...
java
public static DocPath forName(Utils utils, TypeElement typeElement) { return (typeElement == null) ? empty : new DocPath(utils.getSimpleName(typeElement) + ".html"); }
java
@SuppressWarnings("rawtypes") public static boolean isBesicType(Class cls){ if (cls == null) return false; String type = cls.getName(); return isBasicType(type); }
python
def polarity_scores(self, text): """ Return a float for sentiment strength based on the input text. Positive values are positive valence, negative value are negative valence. """ # convert emojis to their textual descriptions text_token_list = text.split() ...
python
def run_query(ont, aset, args): """ Basic querying by positive/negative class lists """ subjects = aset.query(args.query, args.negative) for s in subjects: print("{} {}".format(s, str(aset.label(s)))) if args.plot: import plotly.plotly as py import plotly.graph_objs as g...
java
protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port, int timeoutMS) throws IOException { try { Socket socket = new Socket(iaddr, port); socket.setSoTimeout(timeoutMS); socket.setTcpNoDelay(true); ret...
python
def _remove_duplicates(self, items): """ Remove duplicates, while keeping the order. (Sometimes we have duplicates, because the there several matches of the same grammar, each yielding similar completions.) """ result = [] for i in items: if i not in r...
java
public void marshall(DisassociateDomainRequest disassociateDomainRequest, ProtocolMarshaller protocolMarshaller) { if (disassociateDomainRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(disa...
java
public static AVIMMessageIntervalBound createBound(String messageId, long timestamp, boolean closed) { return new AVIMMessageIntervalBound(messageId, timestamp, closed); }
python
def qmed(self, method='best', **method_options): """ Return QMED estimate using best available methodology depending on what catchment attributes are available. The preferred/best order of methods is defined by :attr:`qmed_methods`. Alternatively, a method can be supplied e.g. `method='...
python
def create_order(email, request, addresses=None, shipping_address=None, billing_address=None, shipping_option=None, capture_payment=False): """ Create an order from a basket and customer infomation """ ...
java
public void setProductCodes(java.util.Collection<ProductCode> productCodes) { if (productCodes == null) { this.productCodes = null; return; } this.productCodes = new com.amazonaws.internal.SdkInternalList<ProductCode>(productCodes); }
java
@Override public java.util.concurrent.Future<GetShardIteratorResult> getShardIteratorAsync(String streamName, String shardId, String shardIteratorType, String startingSequenceNumber) { return getShardIteratorAsync(new GetShardIteratorRequest().withStreamName(streamName).withShardId(shardId).wit...
java
public String convertIfcCoilTypeEnumToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
python
def wrap_content(content, settings, hard_breaks=False): """ Returns *content* wrapped in a HTML structure. If *hard_breaks* is set, line breaks are converted to `<br />` tags. """ settings.context['content'] = wrap_paragraphs(content, hard_breaks) template = Template(settings.template) try: return t...
python
def _prepare_deprecation_data(self): """ Cycles through the list of AppSettingDeprecation instances set on ``self.deprecations`` and prepulates two new dictionary attributes: ``self._deprecated_settings``: Uses the deprecated setting names themselves as the keys. Used to ...
java
private int unFilledSpacesInHeaderGroup(int header) { //If mNumColumns is equal to zero we will have a divide by 0 exception if(mNumColumns == 0){ return 0; } int remainder = mDelegate.getCountForHeader(header) % mNumColumns; return remainder == 0 ? 0 : mNumColumns -...
python
def __delete_internal_blob(self, key): ''' This method will insert blob data to blob table ''' with self.get_conn() as conn: conn.isolation_level = None try: c = conn.cursor() c.execute("BEGIN") if key is None: ...
java
public static boolean handleIfMatch(final String ifMatch, final List<ETag> etags, boolean allowWeak) { if (ifMatch == null) { return true; } if (ifMatch.equals("*")) { return true; //todo: how to tell if there is a current entity for the request } List<ETa...
python
def create(obj: PersistedObject, obj_type: Type[Any], arg_name: str): """ Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests https://github.com/nose-devs/nose/issues/725 :param obj: :param obj_type: :param arg_nam...
python
def _get_environs(self, prefix: str = None) -> dict: """ Fetches set environment variables if such exist, via the :func:`~notifiers.utils.helpers.dict_from_environs` Searches for `[PREFIX_NAME]_[PROVIDER_NAME]_[ARGUMENT]` for each of the arguments defined in the schema :param prefix: Th...
java
public static UIResults extractException(HttpServletRequest httpRequest) throws ServletException { UIResults results = (UIResults) httpRequest.getAttribute(FERRET_NAME); if (results == null) { throw new ServletException("No attribute.."); } if (results.exception == null) { throw new ServletException(...
java
public static boolean in( char c, String str ) { return Chr.in ( c, FastStringUtils.toCharArray(str) ); }
java
@Override public synchronized Task take() throws TimeoutException { try { Task task = queue.remove(); inprocess.add(task); return task; } catch (NoSuchElementException ex) { throw new TimeoutException(ex); } }
java
public static CredentialDeleter deleter(final String pathAccountSid, final String pathCredentialListSid, final String pathSid) { return new CredentialDeleter(pathAccountSid, pathCredentialListSid, pathSid); }
python
def _ttv_compute(self, v, dims, vidx, remdims): """ Tensor times vector product Parameter --------- """ if not isinstance(v, tuple): raise ValueError('v must be a tuple of vectors') ndim = self.ndim order = list(remdims) + list(dims) i...
python
def Concat(*args: Union[BitVec, List[BitVec]]) -> BitVec: """Create a concatenation expression. :param args: :return: """ # The following statement is used if a list is provided as an argument to concat if len(args) == 1 and isinstance(args[0], list): bvs = args[0] # type: List[BitVec]...
python
def _mod_aggregate(self, low, running, chunks): ''' Execute the aggregation systems to runtime modify the low chunk ''' agg_opt = self.functions['config.option']('state_aggregate') if 'aggregate' in low: agg_opt = low['aggregate'] if agg_opt is True: ...
python
def bulk_get(cls, imports, api=None): """ Retrieve imports in bulk :param imports: Imports to be retrieved. :param api: Api instance. :return: List of ImportBulkRecord objects. """ api = api or cls._API import_ids = [Transform.to_import(import_) for import...
java
public void setAlternateHandlingShifted(boolean shifted) { checkNotFrozen(); if(shifted == isAlternateHandlingShifted()) { return; } CollationSettings ownedSettings = getOwnedSettings(); ownedSettings.setAlternateHandlingShifted(shifted); setFastLatinOptions(ownedSettings); }
java
@Override public NodeSet<OWLObjectPropertyExpression> getDisjointObjectProperties( OWLObjectPropertyExpression pe) throws InconsistentOntologyException, FreshEntitiesException, ReasonerInterruptedException, TimeOutException { throw new ReasonerInternalException( ...
python
def verify_arguments(target, method_name, args, kwargs): """Verifies that the provided arguments match the signature of the provided method. :param Target target: A ``Target`` object containing the object with the method to double. :param str method_name: The name of the method to double. :param tuple ...
java
@SuppressWarnings("unused") // called through reflection by RequestServer public GridsV99 list(int version, GridsV99 s) { final Key[] gridKeys = KeySnapshot.globalSnapshot().filter(new KeySnapshot.KVFilter() { @Override public boolean filter(KeySnapshot.KeyInfo k) { return Value.isSubclassOf(k...
java
public static ISonarConverter getConverterInstance() { if (converterInstance == null) { synchronized (DefaultSonarConverter.class) { if (converterInstance == null) converterInstance = new DefaultSonarConverter(); } } return converte...
java
public void setLcHeight(Integer newLcHeight) { Integer oldLcHeight = lcHeight; lcHeight = newLcHeight; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.FNPRG__LC_HEIGHT, oldLcHeight, lcHeight)); }
java
public Object getJsonPath(String json, String jsonPath) { if (!JsonPath.isPathDefinite(jsonPath)) { throw new RuntimeException(jsonPath + " returns a list of results, not a single."); } return parseJson(json).read(jsonPath); }
python
def save_picture(self, outfolder, filename): """Saves a picture""" self.set_fancy_ray() self.png_workaround("/".join([outfolder, filename]))
python
def register_config_changes(self, configs, meta_changes): """ Persist config changes to the JSON state file. When a config changes, a process manager may perform certain actions based on these changes. This method can be called once the actions are complete. """ for config_file i...
python
def ConvertValues(default_metadata, values, token=None, options=None): """Converts a set of RDFValues into a set of export-friendly RDFValues. Args: default_metadata: export.ExportedMetadata instance with basic information about where the values come from. This metadata will be passed to exporters....
python
def ascii_mode(enabled=True): """ Disables color and switches to an ASCII character set if True. """ global _backups, _chars, _primary_style, _secondary_style, _ascii_mode if not (enabled or _backups) or (enabled and _ascii_mode): return if enabled: _backups = _chars.copy(), _primary...
python
def node_number(self, *, count_pnode=True) -> int: """Return the number of node""" return (sum(1 for n in self.nodes()) + (sum(1 for n in self.powernodes()) if count_pnode else 0))
java
private Observable<ProposedBucketConfigContext> buildRefreshFallbackSequence(List<NodeInfo> nodeInfos, String bucketName) { Observable<ProposedBucketConfigContext> failbackSequence = null; for (final NodeInfo nodeInfo : nodeInfos) { if (!isValidCarrierNode(environment.sslEnabled(), nodeInfo)...