language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@SuppressWarnings({"unchecked", "unused"}) protected <T extends IGPSObject> List<T> parseObjectArray(final JSONArray array, final Class<T> type) throws ParseException { try { if (array == null) { return new ArrayList<T>(10); } final List<T> objects = new ArrayList<T>(10); for (int i = 0; i < array.le...
python
def zip_dicts(left, right, prefix=()): """ Modified zip through two dictionaries. Iterate through all keys of left dictionary, returning: - A nested path - A value and parent for both dictionaries """ for key, left_value in left.items(): path = prefix + (key, ) right...
java
public T messageType(String messageType) { this.messageType = messageType; getAction().setMessageType(messageType); if (binaryMessageConstructionInterceptor.supportsMessageType(messageType)) { getMessageContentBuilder().add(binaryMessageConstructionInterceptor); } i...
java
private void copyLanguageNodes() { CmsObject cms = getCms(); CmsMultiplexReport report = (CmsMultiplexReport)getReport(); CmsFile file; CmsXmlContent content; int totalFiles = m_copyresources.length; int processedFiles = 0; Locale sourceLocale = CmsLocaleManager....
python
def make_from_catalogue(cls, catalogue, spacing, dilate): ''' Defines the grid on the basis of the catalogue ''' new = cls() cat_bbox = get_catalogue_bounding_polygon(catalogue) if dilate > 0: cat_bbox = cat_bbox.dilate(dilate) # Define Grid spacing ...
python
def minimize(self, loss, global_step=None, var_list=None, gate_gradients=GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None): """Adapted from TensorFlow...
python
def sill(self): """ get the sill of the GeoStruct Return ------ sill : float the sill of the (nested) GeoStruct, including nugget and contribution from each variogram """ sill = self.nugget for v in self.variograms: sill += v.c...
java
public static Class<?>[] toClass(final Object... array) { if (array == null) { return null; } else if (array.length == 0) { return ArrayUtils.EMPTY_CLASS_ARRAY; } final Class<?>[] classes = new Class<?>[array.length]; for (int i = 0; i < array.length; i++)...
python
def discard_incoming_messages(self): """ Discard all incoming messages for the time of the context manager. """ # Flush any received message so far. self.inbox.clear() # This allows nesting of discard_incoming_messages() calls. previous = self._discard_incoming_m...
java
public PoolGetAllLifetimeStatisticsOptions withOcpDate(DateTime ocpDate) { if (ocpDate == null) { this.ocpDate = null; } else { this.ocpDate = new DateTimeRfc1123(ocpDate); } return this; }
python
def insert_into_obj(self, data): '''Insert text into selected object. Args: data: The data you want to insert. Returns: None Raises: None ''' if not data: data = '' size = len(data) n1 = size%256 ...
python
def backgroundCMD(self, catalog, mode='cloud-in-cells', weights=None): """ Generate an empirical background model in color-magnitude space. INPUTS: catalog: Catalog object OUTPUTS: background """ # Select objects in annulus cut_an...
java
@Override public R visitDocComment(DocCommentTree node, P p) { return defaultAction(node, p); }
python
def _glyph_for_monomer_pattern(self, pattern): """Add glyph for a PySB MonomerPattern.""" pattern.matches_key = lambda: str(pattern) agent_id = self._make_agent_id(pattern) # Handle sources and sinks if pattern.monomer.name in ('__source', '__sink'): return None ...
python
def after_initial_login(self, response): """ This method is called *only* if the crawler is started with an email and password combination. It verifies that the login request was successful, and then generates requests from `self.start_urls`. """ if LOGIN_FAILURE_...
java
protected FwAssistantDirector getAssistantDirector() { if (cachedAssistantDirector != null) { return cachedAssistantDirector; } synchronized (this) { if (cachedAssistantDirector != null) { return cachedAssistantDirector; } cachedAss...
python
def move_to_next_address(self, size_of_current): """Moves the register's current address to the next available. size_of_current specifies how many bytes/words to skip""" self._size_of_current_register_address = size_of_current self._current_address = self.next_address() self.mark...
python
def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs): """ Resolve resource references within a GetAtt dict. Example: { "Fn::GetAtt": ["LogicalId", "Arn"] } => {"Fn::GetAtt": ["ResolvedLogicalId", "Arn"]} Theoretically, only the first element of the...
python
def _start_of_decade(self): """ Reset the date to the first day of the decade. :rtype: Date """ year = self.year - self.year % YEARS_PER_DECADE return self.set(year, 1, 1)
java
public JobDisableOptions withIfModifiedSince(DateTime ifModifiedSince) { if (ifModifiedSince == null) { this.ifModifiedSince = null; } else { this.ifModifiedSince = new DateTimeRfc1123(ifModifiedSince); } return this; }
python
def _flush_bits_to_stream(self): """Flush the bits to the stream. This is used when a few bits have been read and ``self._bits`` contains unconsumed/ flushed bits when data is to be written to the stream """ if len(self._bits) == 0: return 0 bits = list(self....
python
def _create_variables(self, n_features): """Create the TensorFlow variables for the model. :param n_features: number of features :return: self """ w_name = 'weights' self.W = tf.Variable(tf.truncated_normal( shape=[n_features, self.num_hidden], stddev=0.1), n...
python
def OSXEnumerateRunningServicesFromClient(args): """Get running launchd jobs. Args: args: Unused. Yields: `rdf_client.OSXServiceInformation` instances. Raises: UnsupportedOSVersionError: for OS X earlier than 10.6. """ del args # Unused. osx_version = client_utils_osx.OSXVersion() vers...
java
private void preserveAttributes(AlluxioURI srcPath, AlluxioURI dstPath) throws IOException, AlluxioException { if (mPreservePermissions) { URIStatus srcStatus = mFileSystem.getStatus(srcPath); mFileSystem.setAttribute(dstPath, SetAttributePOptions.newBuilder() .setOwner(srcStatus.getOwne...
java
public ApplicationException wrap(Throwable cause) { if (cause instanceof ApplicationException) return (ApplicationException) cause; this.withCause(cause); return this; }
java
private void setUpAnimations() { slideUp = AnimationUtils.loadAnimation(this, R.anim.slide_up); slideDown = AnimationUtils.loadAnimation(this, R.anim.slide_down); }
java
public static PrimitiveIterator.OfDouble iterator(Spliterator.OfDouble spliterator) { Objects.requireNonNull(spliterator); class Adapter implements PrimitiveIterator.OfDouble, DoubleConsumer { boolean valueReady = false; double nextElement; @Override publ...
python
def filter(self): """Generate a filtered query from request parameters. :returns: Filtered SQLALchemy query """ argmap = { filter.label or label: filter.field for label, filter in self.filters.items() } args = self.opts.parser.parse(argmap) ...
java
ArgumentMarshaller getVersionedArgumentMarshaller(final Method getter, Object getterReturnResult) { synchronized (versionArgumentMarshallerCache) { if ( !versionArgumentMarshallerCache.containsKey(getter) ) { ArgumentMarshaller marshaller = null; final Class<?> ret...
java
public Analyzer getPropertyAnalyzer(String fieldName) { if (analyzers.containsKey(fieldName)) { return analyzers.get(fieldName); } return null; }
java
public String getLabel(HasOther e) { List<LangString> labels = ((HasLabel) e).getLabel(); if ((labels == null) || (labels.isEmpty())) return null; if (e instanceof HasLabel) return labels.get(0).getValue(); return "pFact: label TODO"; }
java
@Override public void inAppNotificationDidShow(Context context, CTInAppNotification inAppNotification, Bundle formData) { pushInAppNotificationStateEvent(false, inAppNotification, formData); }
java
public static void invokeProxied(final ProxiedAction action, final ClassLoader classLoader) throws Exception { ProxiedAction proxy = (ProxiedAction) Proxy.newProxyInstance(classLoader, new Class<?>[] { ProxiedAction.class }, new InvocationHandler() { @Override public Object invoke(Object...
java
public static void jacobian_Control3( DMatrixRMaj L_full , double beta[] , DMatrixRMaj A) { int indexA = 0; double b0 = beta[0]; double b1 = beta[1]; double b2 = beta[2]; final double ld[] = L_full.data; for( int i = 0; i < 3; i++ ) { int li = L_full.numCols*i; A.data[indexA++] = 2*ld[li+...
java
private void publish(Cache<K, V> cache, EventType eventType, K key, @Nullable V oldValue, @Nullable V newValue, boolean quiet) { if (dispatchQueues.isEmpty()) { return; } JCacheEntryEvent<K, V> event = null; for (Registration<K, V> registration : dispatchQueues.keySet()) { if (!regist...
java
public Map<String, Object> toMap(List<QueryParameters> paramsList) { Map<String, Object> result = null; Iterator<QueryParameters> iterator = paramsList.iterator(); // skipping header if (iterator.hasNext() == true) { iterator.next(); } if (iterator.hasNext(...
python
def seen_tasks(self): """Shows a list of seen task types.""" print('\n'.join(self._stub.seen_tasks(clearly_pb2.Empty()).task_types))
java
public static vpnformssoaction[] get(nitro_service service) throws Exception{ vpnformssoaction obj = new vpnformssoaction(); vpnformssoaction[] response = (vpnformssoaction[])obj.get_resources(service); return response; }
python
def post(self, service, data): """Generic POST operation for sending data to Learning Modules API. Data should be a JSON string or a dict. If it is not a string, it is turned into a JSON string for the POST body. Args: service (str): The endpoint service to use, i.e. grade...
python
def modify(self, dn: str, mod_list: dict) -> None: """ Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled. """ _debug("modify", self, dn, mod_list) # need to work out how to reverse changes in mod_list; result in revlist ...
python
def convert_shaders(convert, shaders): """ Modify shading code so that we can write code once and make it run "everywhere". """ # New version of the shaders out = [] if convert == 'es2': for isfragment, shader in enumerate(shaders): has_version = False has_prec...
java
@BetaApi( "The surface for long-running operations is not stable yet and may change in the future.") public final OperationFuture<Instance, Any> failoverInstanceAsync( FailoverInstanceRequest request) { return failoverInstanceOperationCallable().futureCall(request); }
java
private void calculateMinimumScaleToFit() { float minimumScaleX = getWidth() / (float) getContentWidth(); float minimumScaleY = getHeight() / (float) getContentHeight(); float recalculatedMinScale = computeMinimumScaleForMode(minimumScaleX, minimumScaleY); if (recalculatedMinScale != mEffectiveMinScale)...
java
public void run() { Protos.FrameworkInfo.Builder frameworkInfo = Protos.FrameworkInfo.newBuilder() .setName("alluxio").setCheckpoint(true); if (ServerConfiguration.isSet(PropertyKey.INTEGRATION_MESOS_ROLE)) { frameworkInfo.setRole(ServerConfiguration.get(PropertyKey.INTEGRATION_MESOS_ROLE)); ...
java
@Override public void rollback(Savepoint savepoint) throws SQLException { delegate.rollback(savepoint); isCommitStateDirty = false; lastAccess = currentTime(); }
java
private void completeCall(ClientResponseImpl response) { // if we're keeping track, calculate result size if (m_perCallStats.samplingProcedure()) { m_perCallStats.setResultSize(response.getResults()); } m_statsCollector.endProcedure(response.getStatus() == ClientResponse.USER...
python
def get_loaded_rules(rules_paths): """Yields all available rules. :type rules_paths: [Path] :rtype: Iterable[Rule] """ for path in rules_paths: if path.name != '__init__.py': rule = Rule.from_path(path) if rule.is_enabled: yield rule
java
public int[] transferValues(int state, int codePoint) { if (state < 1) { return EMPTY_WALK_STATE; } if ((state != 1) && (isEmpty(state))) { return EMPTY_WALK_STATE; } int[] ids = this.charMap.toIdList(codePoint); if (ids.length ...
python
def detached(name, rev, target=None, remote='origin', user=None, password=None, force_clone=False, force_checkout=False, fetch_remote=True, hard_reset=False, submodules=False, identity=None, ...
java
public alluxio.grpc.MountPOptions getProperties() { return properties_ == null ? alluxio.grpc.MountPOptions.getDefaultInstance() : properties_; }
python
def _exception_free_callback(self, callback, *args, **kwargs): """ A wrapper that remove all exceptions raised from hooks """ try: return callback(*args, **kwargs) except Exception: self._logger.exception("An exception occurred while calling a hook! ",exc_info=True) ...
python
def off(self): """Send the Off command to an X10 device.""" msg = X10Send.unit_code_msg(self.address.x10_housecode, self.address.x10_unitcode) self._send_method(msg) msg = X10Send.command_msg(self.address.x10_housecode, ...
java
@Nullable public static String replaceMacro( @CheckForNull String s, @Nonnull Map<String,String> properties) { return replaceMacro(s, new VariableResolver.ByMap<>(properties)); }
python
def close(self): """ Closes the handle opened by open(). The remapped function is WinDivertClose:: BOOL WinDivertClose( __in HANDLE handle ); For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_close """ ...
java
public UserPartAvailableMessage createUPA(int cic) { UserPartAvailableMessage msg = createUPA(); CircuitIdentificationCode code = this.parameterFactory.createCircuitIdentificationCode(); code.setCIC(cic); msg.setCircuitIdentificationCode(code); return msg; }
java
public static double rmsd(Point3d[] x, Point3d[] y) { if (x.length != y.length) { throw new IllegalArgumentException( "Point arrays are not of the same length."); } double sum = 0.0; for (int i = 0; i < x.length; i++) { sum += x[i].distanceSquared(y[i]); } return Math.sqrt(sum / x.length); }
python
def add_task_status(self, name, **attrs): """ Add a Task status to the project and returns a :class:`TaskStatus` object. :param name: name of the :class:`TaskStatus` :param attrs: optional attributes for :class:`TaskStatus` """ return TaskStatuses(self.requester)...
java
protected void submitCycleCompletionEvent() { if (!this.lowWatermark.equalsIgnoreCase(ComplianceConfigurationKeys.NO_PREVIOUS_WATERMARK)) { return; } if (this.executionCount > 1) { // Cycle completed Map<String, String> metadata = new HashMap<>(); metadata.put(ComplianceConfiguration...
java
public String getLanguage(boolean bCheckLocaleAlso) { String strLanguage = this.getProperty(Params.LANGUAGE); if ((strLanguage == null) || (strLanguage.length() == 0)) if (bCheckLocaleAlso) return Locale.getDefault().getLanguage(); return strLanguage; }
python
def get_row_height(self, row, tab): """Returns row height""" try: return self.row_heights[(row, tab)] except KeyError: return config["default_row_height"]
python
def __get_distribution_tags(self, client, arn): """Returns a dict containing the tags for a CloudFront distribution Args: client (botocore.client.CloudFront): Boto3 CloudFront client object arn (str): ARN of the distribution to get tags for Returns: `dict` ...
python
def connect(self, address): """ Connect to a remote or local gpiod daemon. :param address: a pair (address, port), the address must be already resolved (for example an ip address) :return: """ self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self...
python
def _parse_sigmak(line, lines): """Parse Energy, Re sigma xx, Im sigma xx, Re sigma zz, Im sigma zz""" split_line = line.split() energy = float(split_line[0]) re_sigma_xx = float(split_line[1]) im_sigma_xx = float(split_line[2]) re_sigma_zz = float(split_line[3]) im_sigma_zz = float(split_...
java
@SuppressWarnings("unchecked") protected final void updateComponentType(E newElement) { final Class<? extends E> lclazz = (Class<? extends E>) newElement.getClass(); this.clazz = (Class<? extends E>) ReflectionUtil.getCommonType(this.clazz, lclazz); }
python
def unregister(self, observer): """ Remove the observers of the observers list. It will not receive any more notifications when occurs changes. :param UpdatesObserver observer: Observer you will not receive any more notifications then occurs chan...
python
def overview(index, start, end): """Compute metrics in the overview section for enriched git indexes. Returns a dictionary. Each key in the dictionary is the name of a metric, the value is the value of that metric. Value can be a complex object (eg, a time series). :param index: index object :...
python
def GetData(EPIC, season=None, cadence='lc', clobber=False, delete_raw=False, aperture_name='k2sff_15', saturated_aperture_name='k2sff_19', max_pixels=75, download_only=False, saturation_tolerance=-0.1, bad_bits=[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17], get_hir...
python
def setup_session(endpoint_context, areq, uid, client_id='', acr='', salt='salt', authn_event=None): """ Setting up a user session :param endpoint_context: :param areq: :param uid: :param acr: :param client_id: :param salt: :param authn_event: A already made AuthnE...
java
public int add(Object label) { ensureCapacity(used); states[used] = new State(label); return used++; }
python
def scores_to_probs(scores, proba, eps=0.01): """Transforms scores to probabilities by applying the logistic function""" if np.any(~proba): # Need to convert some of the scores into probabilities probs = copy.deepcopy(scores) n_class = len(proba) for m in range(n_class): ...
java
@Override public void layoutViews(RecyclerView.Recycler recycler, RecyclerView.State state, VirtualLayoutManager.LayoutStateWrapper layoutState, LayoutChunkResult result, LayoutManagerHelper helper) { // reach the end of this layout if (isOutOf...
java
public CertificateDescriptionInner verify(String resourceGroupName, String resourceName, String certificateName, String ifMatch) { return verifyWithServiceResponseAsync(resourceGroupName, resourceName, certificateName, ifMatch).toBlocking().single().body(); }
python
def ρ(self, e): """Density of states. :param e: Energy :math:`E`. :type e: float :return: :math:`ρ(E) = \\left|k'(E) k(E)\\right|` :rtype: float """ d = self._dichalcogenide at, λ = d.at, d.λ return abs(2 * e - λ) * (2 * at**2)**(-1)
python
def get_block_transactions( self, header: BlockHeader, transaction_class: Type['BaseTransaction']) -> Iterable['BaseTransaction']: """ Returns an iterable of transactions for the block speficied by the given block header. """ return self._get_b...
python
def get_instances_with_configs(configs): """Create AndroidDevice instances from a list of dict configs. Each config should have the required key-value pair 'serial'. Args: configs: A list of dicts each representing the configuration of one android device. Returns: A list o...
python
def _app_base_start(self, option: str, args: list or tuple) -> None: ''' Args: option: -a <ACTION> -c <CATEGORY> -n <COMPONENT> ''' _, error = self._execute('-s', self.device_sn, 'shell', 'am', '...
python
def configure_engine(self): """ Configure the databse connection. Sets appropriate transaction isolation levels and handle errors. Returns: True, if we did not encounter any unrecoverable errors, else False. """ try: self.connection.execution_opt...
java
public DrawerView addFixedItem(DrawerItem item) { if (item.getId() <= 0) { item.setId(System.nanoTime() * 100 + Math.round(Math.random() * 100)); } for (DrawerItem oldItem : mAdapterFixed.getItems()) { if (oldItem.getId() == item.getId()) { mAdapterFixed.r...
python
def get_share_file (filename, devel_dir=None): """Return a filename in the share directory. @param devel_dir: directory to search when developing @ptype devel_dir: string @param filename: filename to search for @ptype filename: string @return: the found filename or None @rtype: string @r...
java
private Node newBranchInstrumentationNode(NodeTraversal traversal, Node node, int idx) { String arrayName = createArrayName(traversal); // Create instrumentation Node Node getElemNode = IR.getelem(IR.name(arrayName), IR.number(idx)); // Make line number 0-based Node exprNode = IR.exprResult(IR.assign(g...
python
def set_position(self, x, y, speed=None): ''' Move chuck to absolute position in um''' if speed: self._intf.write('MoveChuckSubsite %1.1f %1.1f R Y %d' % (x, y, speed)) else: self._intf.write('MoveChuckSubsite %1.1f %1.1f R Y' % (x, y))
python
def AgregarOperador(self, cuit, iibb=None, nro_ruca=None, nro_renspa=None, cuit_autorizado=None, **kwargs): "Agrego los datos del operador a la liq." d = {'cuit': cuit, 'iibb': iibb, 'nroRUCA': nro_ruca, 'nroRenspa': nro_renspa, ...
python
async def _on_response_prepare(self, request: web.Request, response: web.StreamResponse): """Non-preflight CORS request response processor. If request is done on CORS-enabled route, process request parameters and set appropri...
java
public static List parseAppliesTo(String appliesTo) { List matches = new ArrayList(); if (appliesTo != null) { boolean quoted = false; int index = 0; ProductMatch match = new ProductMatch(); for (int i = 0; i < appliesTo.length(); i++) { c...
python
def postprocess(self, json_string): """Displays each entry on its own line.""" is_compressing, is_hash, compressed, spaces = False, False, [], 0 for row in json_string.split('\n'): if is_compressing: if (row[:spaces + 5] == ' ' * (spaces + 4) + ...
python
def filter(self, source_file, encoding): # noqa A001 """Parse XML file.""" sources = [] for content, filename, enc in self.get_content(source_file): self.additional_context = self.get_context(filename) sources.extend(self._filter(content, source_file, enc)) retu...
python
def store(self, name=None): """ Get a cache store instance by name. :param name: The cache store name :type name: str :rtype: Repository """ if name is None: name = self.get_default_driver() self._stores[name] = self._get(name) retu...
python
def decrypt_data(self, name, ciphertext, context="", nonce="", batch_input=None, mount_point=DEFAULT_MOUNT_POINT): """Decrypt the provided ciphertext using the named key. Supported methods: POST: /{mount_point}/decrypt/{name}. Produces: 200 application/json :param name: Specifies t...
java
public List<TargetRelationship> getLinkListLevelRelationships() { final ArrayList<TargetRelationship> relationships = new ArrayList<TargetRelationship>(); for (final TargetRelationship relationship : levelRelationships) { if (relationship.getType() == RelationshipType.LINKLIST) { ...
python
def terminate(self, reboot=False): """Delete VIOM configuration from iRMC.""" self.root.manage.manage = False self.root.mode = 'delete' self.root.init_boot = reboot self.client.set_profile(self.root.get_json())
java
public MetaMethod getMethod(String name, Class[] parameters) { return impl.pickMethod(name, parameters); }
java
public OrderInner get(String deviceName, String resourceGroupName) { return getWithServiceResponseAsync(deviceName, resourceGroupName).toBlocking().single().body(); }
java
public final Post withContent(final String content) { return new Post(id, slug, title, excerpt, content, authorId, author, publishTimestamp, modifiedTimestamp, status, parentId, guid, commentCount, metadata, type, mimeType, taxonomyTerms, children); }
java
public BlockInfo getBlockInfo(final long blockId) throws IOException { return retryRPC(() -> { return GrpcUtils.fromProto( mClient.getBlockInfo(GetBlockInfoPRequest.newBuilder().setBlockId(blockId).build()) .getBlockInfo()); }); }
python
def sample(self, qubits: List[ops.Qid], repetitions: int=1): """Samples from the wave function at this point in the computation. Note that this does not collapse the wave function. Returns: Measurement results with True corresponding to the `|1>` state. The outer list i...
python
def width_aware_splitlines(self, columns): # type: (int) -> Iterator[FmtStr] """Split into lines, pushing doublewidth characters at the end of a line to the next line. When a double-width character is pushed to the next line, a space is added to pad out the line. """ if columns ...
java
public String convertMMORGLengthToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
python
def get_section_hdrgos(self): """Get the GO group headers explicitly listed in sections.""" return set([h for _, hs in self.sections for h in hs]) if self.sections else set()
python
def init_model_gaussian1d(observations, nstates, reversible=True): """Generate an initial model with 1D-Gaussian output densities Parameters ---------- observations : list of ndarray((T_i), dtype=float) list of arrays of length T_i with observation data nstates : int The number of s...
java
@Override public GetDistributionConfigResult getDistributionConfig(GetDistributionConfigRequest request) { request = beforeClientExecution(request); return executeGetDistributionConfig(request); }