language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@SuppressWarnings("unchecked") public void set(long sequenceId, T item) { final E rbItem = convertToRingbufferFormat(item); // first we write the dataItem in the ring. ringbuffer.set(sequenceId, rbItem); if (sequenceId > tailSequence()) { ringbuffer.setTailSequence(sequ...
python
def next_blob(self): """Get the next frame from file""" blob_file = self.blob_file try: preamble = DAQPreamble(file_obj=blob_file) except struct.error: raise StopIteration try: data_type = DATA_TYPES[preamble.data_type] except KeyError...
python
def simulate_experiment(self, modelparams, expparams, repeat=1, split_by_modelparams=True): """ Simulates the underlying (serial) model using the parallel engines. Returns what the serial model would return, see :attr:`~Simulatable.simulate_experiment` :param bool split_by_mode...
java
@Override public int run(String[] args) throws Exception { // When we started processing. This is also the upper limit of files we // accept, next run will pick up the new incoming files. long processingStartMillis = System.currentTimeMillis(); Configuration hbaseConf = HBaseConfiguration.create(get...
python
def produce_events(events, queue_url, batch_size=10, randomize_delay=0): """ Efficiently sends events to the SQS event queue. Note: SQS has a max size of 10 items. Please be aware that this can make the messages go past size -- even with shrinking messages! Events can get randomized delays, maxim...
java
public void setupFields() { FieldInfo field = null; field = new FieldInfo(this, ID, Constants.DEFAULT_FIELD_LENGTH, null, null); field.setDataClass(Integer.class); field.setHidden(true); field = new FieldInfo(this, LAST_CHANGED, Constants.DEFAULT_FIELD_LENGTH, null, null); ...
python
def _compute_focal_depth_term(self, C, rup): """ Computes the hypocentral depth scaling term - as indicated by equation (3) """ if rup.hypo_depth > 120.0: z_h = 120.0 else: z_h = rup.hypo_depth return C['theta11'] * (z_h - 60.)
java
public <T extends Post> T newPost(String blogName, Class<T> klass) throws IllegalAccessException, InstantiationException { T post = klass.newInstance(); post.setClient(this); post.setBlogName(blogName); return post; }
python
def _convert_value(self, value, model_instance, add): """ Converts the value to the appropriate timezone and time as declared by the `time_override` and `populate_from` attributes. """ if not value: return value # Retrieve the default timezone as the default...
java
@Override public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { Future<?> wrapped = (Future<?>) future.get(timeout, unit); return wrapped.get(timeout, unit); }
java
public Matrix3f rotate(float angle, Vector3fc axis) { return rotate(angle, axis.x(), axis.y(), axis.z()); }
java
public static List<Instance> findAllScopedInstances( AbstractApplication app ) { List<Instance> instanceList = new ArrayList<> (); List<Instance> todo = new ArrayList<> (); todo.addAll( app.getRootInstances()); while( ! todo.isEmpty()) { Instance current = todo.remove( 0 ); todo.addAll( current.getChild...
python
def cli(ctx, value, metadata=""): """Add a canned value Output: A dictionnary containing canned value description """ return ctx.gi.cannedvalues.add_value(value, metadata=metadata)
python
def cumulative_time_to(self, when: datetime.datetime) -> datetime.timedelta: """ Returns the cumulative time contained in our intervals up to the specified time point. """ assert self.no_overlap, self._ONLY_FOR_NO_INTERVAL cumulative = datetime....
python
def remove_core_element(self, model): """Remove respective core element of handed scoped variable model :param ScopedVariableModel model: Scoped variable model which core element should be removed :return: """ assert model.scoped_variable.parent is self.model.state gui_h...
python
def export_results(file_path, univ_options): """ Write out a file to a given location. The location can be either a directory on the local machine, or a folder with a bucket on AWS. TODO: Azure support :param file_path: The path to the file that neeeds to be transferred to the new location. :par...
python
def import_blogger(filepath): """Imports A Blogger export and converts it to a Blended site""" print("\nBlended: Static Website Generator -\n") checkConfig() print("Importing from Blogger...") blogger = parseXML(filepath) wname = blogger.feed.title.cdata aname = blogger.feed.author.name....
python
def execute(self, **minpack_options): """ :param \*\*minpack_options: Any named arguments to be passed to leastsqbound """ popt, pcov, infodic, mesg, ier = leastsqbound( self.objective, # Dfun=self.jacobian, x0=self.initial_guesses, bounds=...
python
def visit(self, node): """ See the ``NodeVisitor`` visit method. This just changes the order in which we visit nonterminals from right to left to left to right. """ method = getattr(self, 'visit_' + node.expr_name, self.generic_visit) # Call that method, and show where i...
java
public static Map<String, CFMetaData> deserializeColumnFamilies(Row row) { if (row.cf == null) return Collections.emptyMap(); Map<String, CFMetaData> cfms = new HashMap<>(); UntypedResultSet results = QueryProcessor.resultify("SELECT * FROM system.schema_columnfamilies", row); ...
python
def get_vault_nodes(self, vault_id, ancestor_levels, descendant_levels, include_siblings): """Gets a portion of the hierarchy for the given vault. arg: vault_id (osid.id.Id): the ``Id`` to query arg: ancestor_levels (cardinal): the maximum number of ancestor levels to incl...
python
def remove_images(self, images): """ Remove images from the album. :param images: A list of the images we want to remove from the album. Can be Image objects, ids or a combination of the two. Images that you cannot remove (non-existing, not owned by you or not part of ...
python
def produce(self, **kwargs): """ Asynchronously sends message to Kafka by encoding with specified or default avro schema. :param str topic: topic name :param object value: An object to serialize :param str value_schema: Avro schema for value :param ob...
python
def getChain(self) : "returns a list of keys representing the chain of documents" l = [] h = self.head while h : l.append(h._key) h = h.nextDoc return l
java
protected Rectangle pushScissorState (int x, int y, int width, int height) { // grow the scissors buffer if necessary if (scissorDepth == scissors.size()) { scissors.add(new Rectangle()); } Rectangle r = scissors.get(scissorDepth); if (scissorDepth == 0) { r.setBounds(x, y...
java
public static SAXSource newSAXSource(Reader reader, String systemId, JstlEntityResolver entityResolver) throws ParserConfigurationException, SAXException { SAXSource source = new SAXSource(newXMLReader(entityResolver), new InputSource(reader)); source.setSystemId(wrapSystemId(systemId)); ...
python
def save_all(self): """Save all opened files. Iterate through self.data and call save() on any modified files. """ for index in range(self.get_stack_count()): if self.data[index].editor.document().isModified(): self.save(index)
python
def check_name_collision( self, name, block_id, checked_ops ): """ Are there any colliding names in this block? Set the '__collided__' flag and related flags if so, so we don't commit them. Not called directly; called by the @state_create() decorator in blockstack.lib.operations...
java
public static EntityUnlinkOperation unlinkOptions(String contentKeyAuthorizationPolicyId, String contentKeyAuthorizationPolicyOptionId) { return new EntityUnlinkOperation(ENTITY_SET, contentKeyAuthorizationPolicyId, "Options", contentKeyAuthorizationPolicyOptionId); }
java
@Override public Set<RepositoryCapability> getCapabilities() { Set<RepositoryCapability> capabilities = new HashSet<>(); capabilities.addAll(delegate().getCapabilities()); capabilities.addAll(EnumSet.of(QUERYABLE, AGGREGATEABLE)); return unmodifiableSet(capabilities); }
python
def list(ctx, show_hidden, oath_type, period): """ List all credentials. List all credentials stored on your YubiKey. """ ensure_validated(ctx) controller = ctx.obj['controller'] creds = [cred for cred in controller.list() if show_hidden or not cred.is_hidden ...
java
@Override public ControlHandler getControlHandler( ProtocolType type, SIBUuid8 sourceMEUuid, ControlMessage msg) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEna...
python
def _alert(self, args): """ This method allows the server to send a non-fatal warning to the client. This is used for methods that are normally asynchronous and thus do not have confirmations, and for which the server may detect errors that need to be reported. Fatal er...
java
public Kind getKind() { Opcode opcode = getOpcode(); return (opcode != null ? opcode.kind : Kind.UNKNOWN); }
python
def GetParent(self): """Constructs a path info corresponding to the parent of current path. The root path (represented by an empty list of components, corresponds to `/` on Unix-like systems) does not have a parent. Returns: Instance of `rdf_objects.PathInfo` or `None` if parent does not exist. ...
python
def write_to_stream(self, stream_id, data, sandbox=None): """ Write to the stream :param stream_id: The stream identifier :param data: The stream instances :param sandbox: The sandbox for this stream :type stream_id: StreamId :return: None :raises: NotImp...
python
def encode(self, envelope, session, encoding=None, **kwargs): """ :meth:`.WMessengerOnionCoderLayerProto.encode` method implementation. :param envelope: original envelope :param session: original session :param encoding: encoding to use (default is 'utf-8') :param kwargs: additional arguments :return: WMe...
python
def DELETE(self, *args, **kwargs): """ DELETE request """ return self._handle_api(self.API_DELETE, args, kwargs)
java
public static YamlScalar asScalar(YamlNode node) { if (node != null && !(node instanceof YamlScalar)) { String nodeName = node.nodeName(); throw new YamlException(String.format("Child %s is not a scalar, it's actual type is %s", nodeName, node.getClass())); } return (Yam...
python
def _generate_sympify_namespace( independent_variables, dependent_variables, helper_functions ): """Generate the link between the symbols of the derivatives and the sympy Derivative operation. Parameters ---------- independent_variable : str name of the independant variable ("...
python
def backdate(res, date=None, as_datetime=False, fmt='%Y-%m-%d'): """ get past date based on currect date """ if res is None: return None if date is None: date = datetime.datetime.now() else: try: date = parse_date(date) except Exception as e: pass...
java
private static int headingIndex(Element element) { String tagName = element.tagName(); if (tagName.startsWith("h")) { try { return Integer.parseInt(tagName.substring(1)); } catch (Throwable ex) { throw new IllegalArgumentException("Must be a header tag: " + tagName, ex); ...
java
public Observable<ServiceResponseWithHeaders<TransformationInner, TransformationsCreateOrReplaceHeaders>> createOrReplaceWithServiceResponseAsync(String resourceGroupName, String jobName, String transformationName, TransformationInner transformation, String ifMatch, String ifNoneMatch) { if (this.client.subscri...
python
def pretty_date(time=False): """ Get a datetime object or a int() Epoch timestamp and return a pretty string like 'an hour ago', 'Yesterday', '3 months ago', 'just now', etc """ now = datetime.now(PST_TIMEZONE) if type(time) is int: diff = now - datetime.fromtimestamp(time) elif ...
python
def set(**kwargs): """Set configuration parameters. Pass keyword arguments for the parameters you would like to set. This function is particularly useful to call at the head of your script file to disable particular features. For example, >>> from paranoid.settings ...
java
public CmsGallerySearchResult searchByPath(String path, Locale locale) throws CmsException { I_CmsSearchDocument sDoc = m_index.getDocument(CmsSearchField.FIELD_PATH, path); CmsGallerySearchResult result = null; if ((sDoc != null) && (sDoc.getDocument() != null)) { result = new CmsG...
java
static Drawable maybeApplyLeafRounding( @Nullable Drawable drawable, @Nullable RoundingParams roundingParams, Resources resources) { try { if (FrescoSystrace.isTracing()) { FrescoSystrace.beginSection("WrappingUtils#maybeApplyLeafRounding"); } if (drawable == null ...
java
public static ResourceRecordSet<SPFData> spf(String name, String spfdata) { return new SPFBuilder().name(name).add(spfdata).build(); }
java
public void bind(String address, @Service FileServiceBind service) { _bindMap.put(address, service); }
python
def _any(self, memory, addr, **kwargs): """ Gets any solution of an address. """ return memory.state.solver.eval(addr, exact=kwargs.pop('exact', self._exact), **kwargs)
java
@Nonnull public IFileItemIterator getItemIterator (@Nonnull final HttpServletRequest aHttpRequest) throws FileUploadException, IOException { return super.getItemIterator (new ServletRequestContext (aHttpRequest)); }
java
public static final SQLException sqlException(String msg, String sqlstate, int code, Throwable cause) { if (sqlstate.startsWith("08")) { if (!sqlstate.endsWith("003")) { // then, e.g. - the database may spuriously cease to be "in use" // upo...
python
def run_action(self, unit_sentry, action, _check_output=subprocess.check_output, params=None): """Translate to amulet's built in run_action(). Deprecated. Run the named action on a given unit sentry. params a dict of parameters to use _check_output...
python
def Many2ManyThroughModel(field): '''Create a Many2Many through model with two foreign key fields and a CompositeFieldId depending on the two foreign keys.''' from stdnet.odm import ModelType, StdModel, ForeignKey, CompositeIdField name_model = field.model._meta.name name_relmodel = field.relmodel....
python
def _prepare_trans_tar(name, sls_opts, mods=None, pillar=None, extra_filerefs=''): ''' Prepares a self contained tarball that has the state to be applied in the container ''' chunks = _compile_state(sls_opts, mods) # reuse it from salt.ssh, however this function should ...
python
def rasm_mode(self, K, Y, likelihood, Ki_f_init, Y_metadata=None, *args, **kwargs): """ Rasmussen's numerically stable mode finding For nomenclature see Rasmussen & Williams 2006 Influenced by GPML (BSD) code, all errors are our own :param K: Covariance matrix evaluated at locat...
python
def exit_success(jid, ext_source=None): ''' Check if a job has been executed and exit successfully jid The jid to look up. ext_source The external job cache to use. Default: `None`. CLI Example: .. code-block:: bash salt-run jobs.exit_success 20160520145827701627 ...
java
private String addCacheBuster(String url, BinaryResourcesHandler binaryRsHandler) throws IOException { if (binaryRsHandler != null) { FilePathMappingUtils.buildFilePathMapping(bundle, url, binaryRsHandler.getRsReaderHandler()); } // Try to retrieve the cache busted URL from the bundle processing cache Stri...
python
def unique_id(self): """Creates a unique ID for the `Atom` based on its parents. Returns ------- unique_id : (str, str, str) (polymer.id, residue.id, atom.id) """ chain = self.parent.parent.id residue = self.parent.id return chain, residue, se...
python
def handle_job_and_work_save(self, sender, instance, **kwargs): """ Custom handler for job and work save """ self.handle_save(instance.project.__class__, instance.project)
java
private void run_implementation_(PushProcessor p) throws Exception { final Map<GroupName, Alert> alerts = registry_.getCollectionAlerts(); final TimeSeriesCollection tsdata = registry_.getCollectionData(); p.accept(tsdata, unmodifiableMap(alerts), registry_.getFailedCollections()); }
java
void addTransition(CharRange condition, DFAState<T> to) { Transition<DFAState<T>> t = new Transition<>(condition, this, to); t = transitions.put(t.getCondition(), t); assert t == null; edges.add(to); to.inStates.add(this); }
python
def nu_mu_converter(rho, mu=None, nu=None): r'''Calculates either kinematic or dynamic viscosity, depending on inputs. Used when one type of viscosity is known as well as density, to obtain the other type. Raises an error if both types of viscosity or neither type of viscosity is provided. .. math:...
python
def _get_graph_properties(self, plot, element, data, mapping, ranges, style): "Computes the args and kwargs for the GraphRenderer" sources = [] properties, mappings = {}, {} for key in ('scatter_1', self.edge_glyph): gdata = data.pop(key, {}) group_style = dict(s...
python
def optimal_t(self, t_max=100, plot=False, ax=None): """Find the optimal value of t Selects the optimal value of t based on the knee point of the Von Neumann Entropy of the diffusion operator. Parameters ---------- t_max : int, default: 100 Maximum value of ...
java
@Override public int compare(final Runnable r1, final Runnable r2) { int res = 0; final JRebirthRunnable jrr1 = (JRebirthRunnable) r1; final JRebirthRunnable jrr2 = (JRebirthRunnable) r2; if (jrr1 == null) { res = jrr2 == null ? 0 : 1; } else if (jrr2 =...
python
def google_register(username:str, email:str, full_name:str, google_id:int, bio:str, token:str=None): """ Register a new user from google. This can raise `exc.IntegrityError` exceptions in case of conflics found. :returns: User """ auth_data_model = apps.get_model("users", "AuthData") use...
java
public static void addTimestampForId(String context, String ip, String time) { BDBMap bdbMap = getContextMap(context); bdbMap.put(ip, time); }
python
def hsl_to_rgb(h, s, l): """Convert a color in h, s, l to a color in r, g, b""" h /= 360 s /= 100 l /= 100 m2 = l * (s + 1) if l <= .5 else l + s - l * s m1 = 2 * l - m2 def h_to_rgb(h): h = h % 1 if 6 * h < 1: return m1 + 6 * h * (m2 - m1) if 2 * h < 1:...
java
public String getParameterClassName(final int param) throws SQLException { try { return this.parameters.get(param-1).className; } catch (NullPointerException e) { throw new SQLException("Parameter is not set: " + param); } catch (IndexOutOfBoundsException out) { ...
java
public static LicenseApi licenseApiFactory() { String licensePath = System.getProperty("user.dir") + "/" + licenseFileName; LicenseApi licenseApi = MiscUtils.licenseApiFactory(licensePath); if (licenseApi == null) { try { // Get location of jar file ...
java
private void createAreas(final BufferedImage IMAGE) { if (!getAreas().isEmpty() && bImage != null) { final double ORIGIN_CORRECTION = 180.0; final double OUTER_RADIUS = bImage.getWidth() * 0.38f; final double RADIUS; if (isSectionsVisible()) { RADI...
python
def write_idx(self, idx, buf): """Inserts input record at given index. Examples --------- >>> for i in range(5): ... record.write_idx(i, 'record_%d'%i) >>> record.close() Parameters ---------- idx : int Index of a file. bu...
python
def get_download_url(self, instance, default=None): """Calculate the download url """ download = default # calculate the download url download = "{url}/@@download/{fieldname}/{filename}".format( url=api.get_url(instance), fieldname=self.get_field_name(), ...
java
public MessageProcessInfoModel getMessageProcessInfo(String strMessageInfoType, String strContactType, String strRequestType, String strMessageProcessType, String strProcessType) { int iOldKeyArea = this.getDefaultOrder(); try { Record recMessageInfo = ((ReferenceField)this.getField(Mess...
java
private static String formatResolution(Resolution resolution, int depth) { return new StringBuilder(MIN_LENGTH).append(String.valueOf(resolution.getWidth())) .append(Constant.STAR) .append(String.valueOf(resolution.getHe...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.GSMC__CELLWI: return CELLWI_EDEFAULT == null ? cellwi != null : !CELLWI_EDEFAULT.equals(cellwi); case AfplibPackage.GSMC__CELLHI: return CELLHI_EDEFAULT == null ? cellhi != null : !CELLHI_EDEFAULT.equals(cellhi); ...
java
@SuppressWarnings("unchecked") private CompletableFuture<Void> completeTransaction( TransactionId transactionId, TransactionState expectState, Function<TransactionInfo, TransactionInfo> updateFunction, Predicate<TransactionInfo> updatedPredicate, BiFunction<TransactionId, Transactional<?...
java
@Deprecated public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { return mf.format(obj, toAppendTo, pos); }
python
def close( self, nonce: Nonce, balance_hash: BalanceHash, additional_hash: AdditionalHash, signature: Signature, block_identifier: BlockSpecification, ): """ Closes the channel using the provided balance proof. """ self.token_ne...
java
@Nullable public static com.google.rpc.Status fromStatusAndTrailers(Status status, Metadata trailers) { if (trailers != null) { com.google.rpc.Status statusProto = trailers.get(STATUS_DETAILS_KEY); if (statusProto != null) { checkArgument( status.getCode().value() == statusProto.ge...
python
def setup_console_logger(log_level='error', log_format=None, date_format=None): ''' Setup the console logger ''' if is_console_configured(): logging.getLogger(__name__).warning('Console logging already configured') return # Remove the temporary logging handler __remove_temp_logg...
java
protected JvmTypeReference getDeclaredType(JvmIdentifiableElement identifiable) { if (identifiable instanceof JvmOperation) { return ((JvmOperation) identifiable).getReturnType(); } if (identifiable instanceof JvmField) { return ((JvmField) identifiable).getType(); } if (identifiable instanceof JvmConst...
python
def index(self, i): """xrangeobject.index(value, [start, [stop]]) -> integer -- return index of value. Raise ValueError if the value is not present. """ if self.count(i) == 0: raise ValueError("{} is not in range".format(i)) return (i - self._start) // self._s...
python
def Add(self, key, help="", default=None, validator=None, converter=None, **kw): """ Add an option. @param key: the name of the variable, or a list or tuple of arguments @param help: optional help text for the options @param default: optional default value @param valida...
python
def _generate_art(self, image, width, height): """ Return an iterator that produces the ascii art. """ image = image.resize((width, height), Image.ANTIALIAS).convert("RGB") pixels = list(image.getdata()) for y in range(0, height - 1, 2): for x in range(width)...
python
def capture(self, tunnel_addr, tunnel_port, filename=None, bucket=None, destination=None): """ Captures memory based on the provided OutputDestination :type tunnel_addr: str :param tunnel_port: ssh tunnel hostname or ip :type tunnel_port: int :param tunne...
python
def match_empty(self, el): """Check if element is empty (if requested).""" is_empty = True for child in self.get_children(el, tags=False): if self.is_tag(child): is_empty = False break elif self.is_content_string(child) and RE_NOT_EMPTY.se...
java
public static void parse(final String range, final RangeConfig tc) throws RangeException { if (range == null) { throw new RangeException("Range can't be null"); } ROOT_STAGE.parse(range, tc); checkBoundaries(tc); }
python
def _expose_rule_functions(self, expose_all_rules=False): """add parse functions for public grammar rules Defines a function for each public grammar rule, based on introspecting the grammar. For example, the `c_interval` rule is exposed as a method `parse_c_interval` and used like this:...
java
@Override public int countByLtD_S(Date displayDate, int status) { FinderPath finderPath = FINDER_PATH_WITH_PAGINATION_COUNT_BY_LTD_S; Object[] finderArgs = new Object[] { _getTime(displayDate), status }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBu...
python
def index_template_delete(name, hosts=None, profile=None): ''' Delete an index template (type) along with its data name Index template name CLI example:: salt myminion elasticsearch.index_template_delete testindex_templ user ''' es = _get_instance(hosts, profile) try: ...
python
def auth_gssapi_with_mic(self, username, gss_host, gss_deleg_creds): """ Authenticate to the Server using GSS-API / SSPI. :param str username: The username to authenticate as :param str gss_host: The target host :param bool gss_deleg_creds: Delegate credentials or not :r...
java
public final CommitResponse commit( SessionName session, ByteString transactionId, List<Mutation> mutations) { CommitRequest request = CommitRequest.newBuilder() .setSession(session == null ? null : session.toString()) .setTransactionId(transactionId) .addAllMutati...
java
public static PackageInfo getSignaturePackageInfo(Context context, String targetPackage) throws NameNotFoundException { PackageManager manager = context.getPackageManager(); return manager.getPackageInfo(targetPackage, PackageManager.GET_SIGNATURES); }
java
private static int computeFieldSize(AttributeValue value) throws DBaseFileException, AttributeException { final DBaseFieldType dbftype = DBaseFieldType.fromAttributeType(value.getType()); return dbftype.getFieldSize(value.getString()); }
python
def caleom(date): """ Adjust date to last day of the month, regardless of work days. Args: date (date, datetime or str): Date to be adjusted. Returns: datetime: Adjusted date. """ date = parsefun(date) date += datetime.timedelt...
java
public Object invokeOperation(Map<String, String[]> parameterMap) throws JMException { MBeanParameterInfo[] parameterInfoArray = operationInfo.getSignature(); Object[] values = new Object[parameterInfoArray.length]; String[] types = new String[parameterInfoArray.length]; MBeanValueConv...
python
def anonymous_required(function): """Redirect to user profile if user is already logged-in""" def wrapper(*args, **kwargs): if args[0].user.is_authenticated(): url = settings.ANONYMOUS_REQUIRED_REDIRECT_URL return HttpResponseRedirect(reverse(url)) return function(*args,...
python
def update_subscription(netid, action, subscription_code, data_field=None): """ Post a subscription action for the given netid and subscription_code """ url = '{0}/subscription.json'.format(url_version()) action_list = [] if isinstance(subscription_code, list): for code in subscription_...