language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public InetAddress addressRemote() { if (_remoteAddr == null) { try { _remoteAddr = InetAddress.getByName(getRemoteHost()); } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } return _remoteAddr; }
java
public static final void verify(byte[] Y, byte[] v, byte[] h, byte[] P) { /* Y = v abs(P) + h G */ byte[] d=new byte[32]; long10[] p=new long10[]{new long10(),new long10()}, s=new long10[]{new long10(),new long10()}, yx=new long10[]{new long10(),new long10(),new long10()}, yz=new l...
java
public String print( ChronoPrinter<T> printer, String intervalPattern ) { AttributeQuery attrs = printer.getAttributes(); StringBuilder sb = new StringBuilder(32); int i = 0; int n = intervalPattern.length(); while (i < n) { char c = intervalPatt...
python
def iuptri(items, diago=True, with_inds=False): """ A generator that yields the upper triangle of the matrix (items x items) Args: items: Iterable object with elements [e0, e1, ...] diago: False if diagonal matrix elements should be excluded with_inds: If True, (i,j) (e_i, e_j) is r...
python
def _fd_matrix(step_ratio, parity, nterms): """ Return matrix for finite difference and complex step derivation. Parameters ---------- step_ratio : real scalar ratio between steps in unequally spaced difference rule. parity : scalar, integer 0 (on...
java
protected int persistHydrant( FireHydrant indexToPersist, DataSchema schema, Interval interval, Map<String, Object> metadataElems ) { synchronized (indexToPersist) { if (indexToPersist.hasSwapped()) { log.info( "DataSource[%s], Interval[%s], Hydrant[%s] already ...
java
public double d(double x){ int intervalNumber =getIntervalNumber(x); if (intervalNumber==0 || intervalNumber==points.length) { return x; } return getIntervalReferencePoint(intervalNumber-1); }
java
public static <T extends Comparable<? super T>> void sort (T[] a) { sort(a, 0, a.length - 1); }
python
def respond_webhook(self, environ): """ Passes the request onto a bot with a webhook if the webhook path is requested. """ request = FieldStorage(fp=environ["wsgi.input"], environ=environ) url = environ["PATH_INFO"] params = dict([(k, request[k].value) for k in re...
python
def download(sid, credentials=None, subjects_path=None, overwrite=False, release='HCP_1200', database='hcp-openaccess', file_list=None): ''' download(sid) downloads the data for subject with the given subject id. By default, the subject will be placed in the first HCP subject directory in the...
python
def __get_default_currency(self): """Read the default currency from GnuCash preferences""" # If we are on Windows, read from registry. if sys.platform == "win32": # read from registry def_curr = self.book["default-currency"] = self.__get_default_currency_windows() ...
java
@Deprecated public boolean matches(Object actual, Object expected) { return comparator.equal(actual, expected); }
python
def parse_flags(headers): """Copied from https://github.com/girishramnani/gmail/blob/master/gmail/message.py""" if len(headers) == 0: return [] if sys.version_info[0] == 3: headers = bytes(headers, "ascii") return list(imaplib.ParseFlags(headers))
python
def decoratornames(self): """Get the qualified names of each of the decorators on this function. :returns: The names of the decorators. :rtype: set(str) """ result = set() decoratornodes = [] if self.decorators is not None: decoratornodes += self.deco...
java
public RoundingParams setCornersRadii(float[] radii) { Preconditions.checkNotNull(radii); Preconditions.checkArgument(radii.length == 8, "radii should have exactly 8 values"); System.arraycopy(radii, 0, getOrCreateRoundedCornersRadii(), 0, 8); return this; }
java
static void main(String[] args, PrintStream out) throws IOException { try { Main main = null; Option[] options = Option.parseCLArgs(args, TEMPLATES); Option helpOption = (options == null) ? null : findOption(HELP_OPTION.getName(), options); Option installOption = ...
java
@Override public void setDefaultPrefix(final String prefixString) { lock.writeLock().lock(); try { if (prefixString == null || StringUtils.isBlank(prefixString)) { defaultPrefix = null; } else { if (prefixes != null) { if (!prefixes.contains(prefixString)) { throw new IllegalArgumentExcept...
java
@Override public boolean contains(final int x) { final short hb = Util.highbits(x); final Container c = highLowContainer.getContainer(hb); return c != null && c.contains(Util.lowbits(x)); }
java
public Subscription get( Subscription subscription ) { return RestfulUtils.show( SubscriptionService.PATH, subscription, Subscription.class, super.httpClient ); }
java
private static double ar(AssociativeArray2D survivalFunction, int r) { if(survivalFunction.isEmpty()) { throw new IllegalArgumentException("The provided collection can't be empty."); } AssociativeArray2D survivalFunctionCopy = survivalFunction; //check if la...
java
private void addEntriesFromTag(List<Entry> entries, RekordboxAnlz.CueTag tag) { for (RekordboxAnlz.CueEntry cueEntry : tag.cues()) { // TODO: Need to figure out how to identify deleted entries to ignore. if (cueEntry.type() == RekordboxAnlz.CueEntryType.LOOP) { entries.add(new Entry...
java
private List<PostConstructInfo> processPostConstruct(TypeElement type) { List<PostConstructInfo> postConstructs = new ArrayList<>(); ElementFilter.methodsIn(type.getEnclosedElements()).stream() .filter(method -> MoreElements.isAnnotationPresent(method, PostConstruct.class)) ...
java
public void config(String msg) { if (Level.CONFIG.intValue() < levelValue) { return; } log(Level.CONFIG, msg); }
java
public static boolean isRoundingAvailable(RoundingQuery roundingQuery) { return Optional.ofNullable(monetaryRoundingsSingletonSpi()).orElseThrow( () -> new MonetaryException("No MonetaryRoundingsSpi loaded, query functionality is not available.")) .isRoundingAvailable(roundingQue...
python
def get_params(self): """Gets current parameters. Returns ------- `(arg_params, aux_params)` A pair of dictionaries each mapping parameter names to NDArray values. """ assert self.binded and self.params_initialized self._curr_module._params_dirty = se...
java
public static void addColTimes(Matrix matrix, long diag, long fromRow, long col, double factor) { long rows = matrix.getRowCount(); for (long row = fromRow; row < rows; row++) { matrix.setAsDouble( matrix.getAsDouble(row, col) - factor * matrix.getAsDouble(row, diag), row, col); } }
python
def get_user_groups(self, user): """Returns a ``list`` with the user's groups or ``None`` if unsuccessful. :param str user: User we want groups for. """ conn = self.bind try: if current_app.config['LDAP_OPENLDAP']: fields = \ ...
java
private void readRecurringData(ProjectCalendarException bce, Project.Calendars.Calendar.Exceptions.Exception exception) { RecurrenceType rt = getRecurrenceType(NumberHelper.getInt(exception.getType())); if (rt != null) { RecurringData rd = new RecurringData(); rd.setStartDate(bce....
python
def save_cards(cards, filename=None): """ Save the given cards, in plain text, to a txt file. :arg cards: The cards to save. Can be a ``Stack``, ``Deck``, or ``list``. :arg str filename: The filename to use for the cards file. If no filename given, defaults to "cards-YYYYMMDD.tx...
java
@Override void createEntry(int hash, K key, V value, int bucketIndex) { HashMapPro.Entry<K, V> old = table[bucketIndex]; Entry<K, V> e = new Entry<K, V>(hash, key, value, old); table[bucketIndex] = e; e.addBefore(header); size++; }
python
def generate_thumbnail(self, ratio=None, width=None, height=None, filter='undefined', store=current_store, _preprocess_image=None, _postprocess_image=None): """Resizes the :attr:`original` (scales up or down) and then store the resized thumbnail into...
java
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception { pq_stats[] resources = new pq_stats[1]; pq_response result = (pq_response) service.get_payload_formatter().string_to_resource(pq_response.class, response); if(result.errorcode != 0) { if (result.errorcode ==...
java
@SuppressWarnings("unchecked") public static <T, C extends Collection<T>> C convert(Object object, Class<?> collectionClass, Class<T> componentClass) { if (collectionClass == null || !Collection.class.isAssignableFrom(collectionClass)) { log.fine("{0} does not extend collection.", collectionClass); ...
java
public void setTerminationPolicies(java.util.Collection<String> terminationPolicies) { if (terminationPolicies == null) { this.terminationPolicies = null; return; } this.terminationPolicies = new com.amazonaws.internal.SdkInternalList<String>(terminationPolicies); }
java
public String senSegment(String text){ String ret = text; //Segment sentences if (vnSenSegmenter != null){ ret = vnSenSegmenter.senSegment(text); } return ret.trim(); }
python
def all_pkgs(self): """ Return a list of all packages. """ if not self.packages: self.packages = self.get_pkg_list() return self.packages
python
def FromBinary(cls, record_data, record_count=1): """Create an UpdateRecord subclass from binary record data. This should be called with a binary record blob (including the record type header) and it will return the best record class match that it can find for that record. Args...
python
def get_page_object(objects, sid): """ **Arguments** ``objects`` all objects ``sid` symbolic id for object selection :return selected object """ selected_object = None for obj in objects: if obj.sid == sid: selected_object = obj break ...
java
public static Writable newInstance(Class<? extends Writable> c, Configuration conf, boolean supportJobConf) { WritableFactory factory = WritableFactories.getFactory(c); if (factory != null) { Writable result = factory.newInstance(); if (result instanceof Configurable) { ((Configurable)...
python
def parse_list_objects_v2(data, bucket_name): """ Parser for list objects version 2 response. :param data: Response data for list objects. :param bucket_name: Response for the bucket. :return: Returns three distinct components: - List of :class:`Object <Object>` - True if list is trun...
python
def encrypt_cbc(self, data, init_vector): """ Return an iterator that encrypts `data` using the Cipher-Block Chaining (CBC) mode of operation. CBC mode can only operate on `data` that is a multiple of the block-size in length. Each iteration returns a block-sized :obj:`bytes` object (i...
java
public static double elementMaxAbs( DMatrix2 a ) { double max = Math.abs(a.a1); double tmp = Math.abs(a.a2); if( tmp > max ) max = tmp; tmp = Math.abs(a.a2); if( tmp > max ) max = tmp; return max; }
java
@Override public void xmlWriteOn(FormattedWriter writer) throws IOException { // Restore an un-cached message to we can dump its state if (msg == null) getJSMessage(true); try { if (msg != null) { writer.newLine(); ...
java
public StartPullSessionResponse startPullSession(String sessionId) { StartPullSessionRequest request = new StartPullSessionRequest().withSessionId(sessionId); return startPullSession(request); }
python
def authenticate_user(self): """Confirm user authentication Make sure the user has provided all of the authentication info we need. """ cloud_config = os_client_config.OpenStackConfig().get_one_cloud( cloud=self.options.os_cloud, argparse=self.options, ne...
java
public Expression<Integer> gte(int value) { String valueString = "'" + value + "'"; return new Expression<Integer>(this, Operation.gte, valueString); }
python
def hdfoutput(outname, frames, dozip=False): '''Outputs the frames to an hdf file.''' with h5.File(outname,'a') as f: for frame in frames: group=str(frame['step']); h5w(f, frame, group=group, compression='lzf' if dozip else None);
java
private void addMonth(int i) { Calendar cal = Calendar.getInstance(); cal.set(getDisplayYear(), getDisplayMonth() - 1, 1); int month = cal.get(Calendar.MONTH) + 1; if (i > 0 && month == 12) { addYear(1); } if (i < 0 && month == 1) { addYear(-1); ...
java
public final Tuple5<T7, T8, T9, T10, T11> skip6() { return new Tuple5<>(v7, v8, v9, v10, v11); }
python
def package_removed(name, image=None, restart=False): ''' Uninstall a package Args: name (str): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. This can also be the n...
java
public void remove_logging_target(String target_type, String target_name) throws DevFailed { deviceProxyDAO.remove_logging_target(this, target_type, target_name); }
java
@Override public void endElement(String uri, String name, String qName) { setContent(content.toString().trim()); content = new StringBuffer(); inside = ""; /* * if(tag!=null && tag.getName().equalsIgnoreCase("input")) { * print.ln(tag.getName()+"-"+att.getName()+":"+inside+"-"+insideTag+"-"+insideAtt); * ...
python
def _z2deriv(self,R,z,phi=0.,t=0.): """ NAME: _z2deriv PURPOSE: evaluate the second vertical derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t- time OUTP...
python
def _authenticate(self): """Authenticates to the api and sets up client information.""" data = {'username': self.username, 'password': self.password} url = '{base}/client/login'.format(base=self.base_url) response = self._session.get(url, params=data) print(respon...
java
public static void ioprioSetIfPossible(int ioprio_value) throws IOException { if (nativeLoaded && ioprioPossible) { try { ioprio_set(ioprio_value); } catch (UnsupportedOperationException uoe) { LOG.warn("ioprioSetIfPossible() failed", uoe); ioprioPossible = false; } catch (...
python
def get_buffers_of_type(self, t): """ returns currently open buffers for a given subclass of :class:`~alot.buffers.Buffer`. :param t: Buffer class :type t: alot.buffers.Buffer :rtype: list """ return [x for x in self.buffers if isinstance(x, t)]
python
def new(cls, ver_key: VerKey, sign_key: SignKey) -> 'ProofOfPossession': """ Creates and returns BLS proof of possession that corresponds to the given ver key and sign key. :param: ver_key - Ver Key :param: sign_key - Sign Key :return: BLS proof of possession """ ...
java
@Override public void addChild(Object identifier, TreeNode<T> child) { child.setParent(this); childrenMap.put(identifier, child); }
python
def verify_permitted_to_read(gs_path): """Check if the user has permissions to read from the given path. Args: gs_path: the GCS path to check if user is permitted to read. Raises: Exception if user has no permissions to read. """ # TODO(qimingj): Storage APIs need to be modified to allo...
python
def exists(self, filename): """Determines whether a path exists or not.""" client = boto3.client("s3") bucket, path = self.bucket_and_path(filename) r = client.list_objects(Bucket=bucket, Prefix=path, Delimiter="/") if r.get("Contents") or r.get("CommonPrefixes"): ret...
java
protected final void addPropertyAlias(String alias, Class<?> type, String name) { Map<String, Property> typeMap = properties.get(type); if (typeMap == null) { typeMap = new HashMap<String, Property>(); properties.put(type, typeMap); } try { typeMap.p...
java
Constraint getLimitConstraint() { Constraint result = null; for (Constraint constraint : getConstraints()) { if (constraint.getConstraintType() == Constraint.LIMIT) { // We're assuming only one LIMIT constraint at the moment result = constraint; ...
java
public Configuration fromFile(String path) throws ConfigurationLoadException { PropertiesConfiguration propertiesConfiguration = setupConfiguration(new PropertiesConfiguration()); propertiesConfiguration.setFileName(path); try { propertiesConfiguration.load(); } catch (ConfigurationExcepti...
python
def _optimize_voltage_based_curtailment(feedin, voltage_pu, total_curtailment, voltage_threshold, timeindex, solver): """ Formulates and solves linear problem to find linear relation between curtailment and node voltage. Parameters ------------ feedin : :...
java
public AuthenticatedUser authenticateUser(Credentials credentials) throws GuacamoleException { // Pull CAS ticket from request if present HttpServletRequest request = credentials.getRequest(); if (request != null) { String ticket = request.getParameter(CASTicketField.PAR...
java
public ListChildrenResult withChildren(Child... children) { if (this.children == null) { setChildren(new java.util.ArrayList<Child>(children.length)); } for (Child ele : children) { this.children.add(ele); } return this; }
python
def get_session_value(self, name, default=None): """Get value from session""" session_name = 'list_{}_{}_{}'.format(self.kwargs.get('app'), self.kwargs.get('model'), name) return self.request.session.get(session_name, default)
python
def pull_image(self, image, progress_callback=None): """ Pull image from docker repository :params image: Image name :params progress_callback: A function that receive a log message about image download progress """ try: yield from self.query("GET", "images/...
python
def isBusy(self): """ Returns true if the underlying engine is doing an async operation. """ # return self._impl.isBusy() if self._lock.acquire(False): self._lock.release() return False else: return True
java
private ProjectFile handleFileInDirectory(File directory) throws Exception { List<File> directories = new ArrayList<File>(); File[] files = directory.listFiles(); if (files != null) { // Try files first for (File file : files) { if (file.isDirectory()) ...
python
def copy_tree_and_replace_vars(self, src, dst): """ Если передается директория в качестве аргумента, то будет рассматриваться как шаблон именно её содержимое!! Оно же и будет копироваться """ if os.path.isdir(src): copy_tree(src, self.temp_dir) elif os...
python
def predict(self, X): """Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters -------...
python
def _get_uncolored_output(self, script, value): """ Creates an uncolored output. :param bytes script: The output script. :param int value: The satoshi value of the output. :return: An object representing the uncolored output. :rtype: TransactionOutput """ ...
java
public void write(int ch) throws IOException { OutputStream os = getOutputStream(); os.write('D'); os.write(0); os.write(1); os.write(ch); }
java
private MapCollections<K, V> getCollection() { @WeakOuter class InteropMapCollections extends MapCollections<K, V> { @Override protected int colGetSize() { return mSize; } @Override protected Object colGetEntry(int index, int o...
python
def find_external_metabolites(model): """Return all metabolites in the external compartment.""" ex_comp = find_external_compartment(model) return [met for met in model.metabolites if met.compartment == ex_comp]
python
def in_domain(self, points): """ Returns ``True`` if all of the given points are in the domain, ``False`` otherwise. :param np.ndarray points: An `np.ndarray` of type `self.dtype`. :rtype: `bool` """ array_view = self.to_regular_array(points) non_negativ...
python
def route(self, request, service): """ :meth:`.WWebRouteMapProto.route` method implementation """ for route in self.__routes: result = route.match(request, service) if result is not None: if self.target_route_valid(result) is True: return result
python
def bounds(filename, start_re, end_re, encoding='utf8'): """ Compute chunk bounds from text file according to start_re and end_re: yields (start_match, Bounds) tuples. """ start_re, end_re = re.compile(start_re), re.compile(end_re) mo, line_start, line_end, byte_start, byte_end = [None]*5 of...
java
public String serialize() { JaxbJsonSerializer<CreateSnapshotBridgeParameters> serializer = new JaxbJsonSerializer<>(CreateSnapshotBridgeParameters.class); try { return serializer.serialize(this); } catch (IOException e) { throw new SnapshotDataException( ...
python
def intercalate(elems, list_): """Insert given elements between existing elements of a list. :param elems: List of elements to insert between elements of ``list_` :param list_: List to insert the elements to :return: A new list where items from ``elems`` are inserted between every two ele...
java
public static void calculate(LPC lpc, long[] R) { int coeffCount = lpc.order; //calculate first iteration directly double[] A = lpc.rawCoefficients; for(int i = 0; i < coeffCount+1; i++) A[i] = 0.0; A[0] = 1; double E = R[0]; //calculate remaining iterations if(R[0] == 0) { for(...
java
public static <E1> ConcurrentConveyorSingleQueue<E1> concurrentConveyorSingleQueue( E1 submitterGoneItem, QueuedPipe<E1> queue ) { return new ConcurrentConveyorSingleQueue<E1>(submitterGoneItem, queue); }
java
protected final void beginOfMonth(final Calendar c) { c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH)); }
java
public static String getPropertyNameForBranch(String key, int numBranches, int branchId) { Preconditions.checkArgument(numBranches >= 0, "The number of branches is expected to be non-negative"); Preconditions.checkArgument(branchId >= 0, "The branchId is expected to be non-negative"); return numBranches > 1...
java
public static TableId of(String project, String dataset, String table) { return new TableId(checkNotNull(project), checkNotNull(dataset), checkNotNull(table)); }
python
def _indexed_ifilter(self, recursive=True, matches=None, flags=FLAGS, forcetype=None): """Iterate over nodes and their corresponding indices in the node list. The arguments are interpreted as for :meth:`ifilter`. For each tuple ``(i, node)`` yielded by this method, ``se...
java
@Override protected void delete(Object entity, Object pKey) { EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass()); r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName()).get(pKey).delete().run(connection); }
java
public void reloadPartitions() { if (partitions == null) { initializePartitions(); partitions.updateCache(); } else { Partitions loadedPartitions = loadPartitions(); if (TopologyComparators.isChanged(getPartitions(), loadedPartitions)) { ...
java
public LazyType getType(int index) throws LazyException{ LazyNode token=getValueToken(index); switch(token.type){ case LazyNode.OBJECT: return LazyType.OBJECT; case LazyNode.ARRAY: return LazyType.ARRAY; case LazyNode.VALUE_TRUE: return LazyType.BOOLEAN; case LazyNode.VALUE_FALSE: return LazyType.BOOLEA...
java
private void createForeignKeys(Set<ForeignKey> allForeignKeys, Map<Column, ColumnDescriptor> allColumns, Store store) { // Foreign keys for (ForeignKey foreignKey : allForeignKeys) { ForeignKeyDescriptor foreignKeyDescriptor = store.create(ForeignKeyDescriptor.class); foreignKeyD...
java
private BufferedImage downloadImage() throws Exception { BufferedImage image = null; InputStream in = null; try { // first try reading with the default class URL url = new URL(imageUrl); HttpURLConnection conn = null; boolean success = false; try...
java
@Override public final void cleanup(Context context) throws IOException, InterruptedException { cleanup(this.context, collector); collector.close(); super.cleanup(context); }
python
def send_msg_to_webhook(self, message): """separated Requests logic for easier testing Args: message (str): actual logging string to be passed to REST endpoint Todo: * Requests.text/json return for better testing options """ payload = { 'cont...
java
private void addAdjacentSiblingElements() { for (Node node : nodes) { Node n = helper.getNextSibling(node); if (n != null) if (matchTag(n)) result.add(n); } }
python
def getAverageBuildDuration(self, package, **kwargs): """ Return a timedelta that Koji considers to be average for this package. Calls "getAverageBuildDuration" XML-RPC. :param package: ``str``, for example "ceph" :returns: deferred that when fired returns a datetime object for...
python
def ssml_break(self, strength=None, time=None, **kwargs): """ Create a <Break> element :param strength: Set a pause based on strength :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms :param kwargs: addition...
python
def _parse_state_file(state_file_path='terraform.tfstate'): ''' Parses the terraform state file passing different resource types to the right handler ''' ret = {} with salt.utils.files.fopen(state_file_path, 'r') as fh_: tfstate = salt.utils.json.load(fh_) modules = tfstate.get('modules...
java
public void setFieldConversionClassName(String fieldConversionClassName) { try { this.fieldConversion = (FieldConversion) ClassHelper.newInstance(fieldConversionClassName); } catch (Exception e) { throw new MetadataException( ...
java
public void put(int key, E value) { int i = ContainerHelpers.binarySearch(mKeys, mSize, key); if (i >= 0) { mValues[i] = value; } else { i = ~i; if (i < mSize && mValues[i] == DELETED) { mKeys[i] = key; mValues[i] = value; ...