language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void setArtist(String newArtist) { if (newArtist.length() > ARTIST_SIZE) { artist = newArtist.substring(0, ARTIST_SIZE); } else { artist = newArtist; } }
python
def numpy_bins(self) -> np.ndarray: """Bins in the numpy format This might not be available for inconsecutive binnings. Returns ------- edges: np.ndarray shape=(bin_count+1,) """ if self._numpy_bins is None: self._numpy_bins = to_numpy_bi...
java
public Mapping<T> addFields() { if (idColumn == null) { throw new RuntimeException("Map ID column before adding class fields"); } for (Field f : ReflectionUtils.getDeclaredFieldsInHierarchy(clazz)) { if (!Modifier.isStatic(f.getModifiers()) && !isFie...
java
@Override public void close(IAsyncResultHandler<Void> result) { vertx.executeBlocking(blocking -> { super.close(result); }, res -> { if (res.failed()) result.handle(AsyncResultImpl.create(res.cause())); }); }
java
public double calcRegularizationScore() { Preconditions.checkState(trainingConfig != null, "No training configuration has been set. A training configuration must " + "be set before calculating the L2 loss. Use setTrainingConfig(TrainingConfig)"); if(trainingConfig.getRegularization() ==...
python
def analytical(src, rec, res, freqtime, solution='fs', signal=None, ab=11, aniso=None, epermH=None, epermV=None, mpermH=None, mpermV=None, verb=2): r"""Return the analytical full- or half-space solution. Calculate the electromagnetic frequency- or time-domain field due to infi...
java
@Override public Uri onInsert(T helper, SQLiteDatabase db, MatcherPattern target, InsertParameters parameter) { Uri result = null; long id = db.insert(target.getTableInfo().getName(), null, parameter.getValues()); if (id >= 0) { result = ContentUris.withAppendedId(target.getCont...
python
def transformToNative(obj): """ Turn obj.value into a Name. """ if obj.isNative: return obj obj.isNative = True obj.value = Name(**dict(zip(NAME_ORDER, splitFields(obj.value)))) return obj
python
def head(self, bytes): """ Returns the number of given bytes from the head of the buffer. The buffer remains unchanged. :type bytes: int :param bytes: The number of bytes to return. """ oldpos = self.io.tell() self.io.seek(0) head = self.io.read(...
java
public static FixedBucketsHistogram fromByteBuffer(ByteBuffer buf) { byte serializationVersion = buf.get(); Preconditions.checkArgument( serializationVersion == SERIALIZATION_VERSION, StringUtils.format("Only serialization version %s is supported.", SERIALIZATION_VERSION) ); byte mode ...
java
public Object readObject() throws IOException { int tag = read(); switch (tag) { case 'N': return null; case 'T': return Boolean.valueOf(true); case 'F': return Boolean.valueOf(false); case 'I...
python
def g_(self, X): """ computes h() :param X: :return: """ if self._interpol: if not hasattr(self, '_g_interp'): if self._lookup: x = self._x_lookup g_x = self._g_lookup else: ...
python
def equation(self): """Mix-in class that returns matrix rows for difference in head between inside and outside equals zeros Returns matrix part (nunknowns,neq) Returns rhs part nunknowns """ mat = np.empty((self.nunknowns, self.model.neq)) rhs = np.zeros(self.nunk...
python
def rename_columns(self, rename_dict): """ Renames the columns :param rename_dict: dict where the keys are the current column names and the values are the new names :return: nothing """ if not all([x in self._columns for x in rename_dict.keys()]): raise Value...
java
public static DateTimeZone forTimeZone(TimeZone zone) { if (zone == null) { return getDefault(); } final String id = zone.getID(); if (id == null) { throw new IllegalArgumentException("The TimeZone id must not be null"); } if (id.equals("UTC")) { ...
python
def mtf_image_transformer_cifar_4x(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base_cifar() hparams.mesh_shape = "batch:32" hparams.layout = "batch:batch" hparams.batch_size = 128 return hparams
java
private static int getEpisodeValue(Element eEpisode, String key) { int episodeValue; try { String value = DOMHelper.getValueFromElement(eEpisode, key); episodeValue = NumberUtils.toInt(value, 0); } catch (WebServiceException ex) { LOG.trace("Failed to read epi...
java
public static Alignment<NucleotideSequence> alignSemiLocalLeft(LinearGapAlignmentScoring scoring, NucleotideSequence seq1, NucleotideSequence seq2, int offset1, int length1, int offset2, int length2, ...
java
public boolean isCached(String requestUrl, int maxWidth, int maxHeight, ScaleType scaleType) { throwIfNotOnMainThread(); String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType); return imageCache.getBitmap(cacheKey) != null; }
java
public static FrameManager newInstance (ManagedRoot root, MediaTimer timer) { FrameManager fmgr = (root instanceof ManagedJFrame && _useFlip.getValue()) ? new FlipFrameManager() : new BackFrameManager(); fmgr.init(root, timer); return fmgr; }
java
public static List<InvocationStat> getInvocationStatSnapshots(List<InvocationStat> stats) { List<InvocationStat> snapshots = new ArrayList<InvocationStat>(stats.size()); for (InvocationStat stat : stats) { InvocationStat snapshot = stat.snapshot(); if (snapshot.getInvokeCount() <...
python
def create_backup(self, instance, name, description=None): """ Creates a backup of the specified instance, giving it the specified name along with an optional description. """ body = {"backup": { "instance": utils.get_id(instance), "name": name, ...
java
private void removeHdr(HeaderElement elem) { if (null == elem) { return; } HeaderKeys key = elem.getKey(); elem.remove(); if (key.useFilters()) { filterRemove(key, elem.asBytes()); } }
python
def uinit(self, ushape): """Return initialiser for working variable U.""" if self.opt['Y0'] is None: return np.zeros(ushape, dtype=self.dtype) else: # If initial Y is non-zero, initial U is chosen so that # the relevant dual optimality criterion (see (3.10) ...
python
def _convert_priority(p_priority): """ Converts todo.txt priority to an iCalendar priority (RFC 2445). Priority A gets priority 1, priority B gets priority 5 and priority C-F get priorities 6-9. This scheme makes sure that clients that use "high", "medium" and "low" show the correct priority. "...
python
def camera_action(self, mouse_pos): """Return a `sc_pb.Action` with the camera movement filled.""" action = sc_pb.Action() action_spatial = mouse_pos.action_spatial(action) mouse_pos.obs_pos.assign_to(action_spatial.camera_move.center_minimap) return action
java
public static boolean sameNetwork(int prefixLength, InetAddress address1, InetAddress address2) { if (logger.isDebugEnabled()) { logger.debug("Comparing address " + address1.getHostAddress() + " with " + address2.getHostAddress() + ", prefixLength=" + prefixLength); } long prefixMask...
python
def getAuthenticator(self, service_request): """ Gets an authenticator callable based on the service_request. This is granular, looking at the service method first, then at the service level and finally to see if there is a global authenticator function for the gateway. Returns C...
java
public static HighlightErrorConverter newInstance(Configuration config, String[] options) { if (options.length != 1) { LOGGER.error("Incorrect number of options on highlightError. Expected 1 received " + options.length); return null; } if (options[0] == null) { ...
java
private void rollback(final String patchID, final IdentityPatchContext context) throws PatchingException { try { // Load the patch history final PatchingTaskContext.Mode mode = context.getMode(); final Patch originalPatch = loadPatchInformation(patchID, installedImage); ...
java
public static void dumpClusterToFile(String outputDirName, String fileName, Cluster cluster) { if(outputDirName != null) { File outputDir = new File(outputDirName); if(!outputDir.exists()) { Utils.mkdirs(outputDir); } try { FileUt...
python
def _spark_rdd_metrics(self, instance, running_apps, addl_tags, requests_config): """ Get metrics for each Spark RDD. """ for app_id, (app_name, tracking_url) in iteritems(running_apps): base_url = self._get_request_url(instance, tracking_url) response = self._re...
python
def get_yaml_parser_roundtrip_for_context(): """Create a yaml parser that can serialize the pypyr Context. Create yaml parser with get_yaml_parser_roundtrip, adding Context. This allows the yaml parser to serialize the pypyr Context. """ yaml_writer = get_yaml_parser_roundtrip() # Context is a...
python
def dic(self): r""" Returns the corrected Deviance Information Criterion (DIC) for all chains loaded into ChainConsumer. If a chain does not have a posterior, this method will return `None` for that chain. **Note that the DIC metric is only valid on posterior surfaces which closely resemble mul...
java
public static <T extends Enum<T>> OperationStatisticBuilder<T> operation(Class<T> type) { return new OperationStatisticBuilder<>(type); }
python
def _build_word(syl, vowels): """Builds a Pinyin word re pattern from a Pinyin syllable re pattern. A word is defined as a series of consecutive valid Pinyin syllables with optional hyphens and apostrophes interspersed. Hyphens must be followed immediately by another valid Pinyin syllable. Apostrophes ...
java
public static BufferedImage createTracedImage ( ImageCreator isrc, BufferedImage src, Color tcolor, int thickness) { return createTracedImage(isrc, src, tcolor, thickness, 1.0f, 1.0f); }
java
public InternalCallContext createInternalCallContext(final UUID objectId, final ObjectType objectType, final String userName, final CallOrigin callOrigin, final UserType userType, @Nullable final UUID userToken, final Long tenantRecordId) { final Long acc...
java
public Double getDouble(String key, String group) { return getDouble(key, group, null); }
python
def etag(self, etag): """ Set the ETag of the resource. :param etag: the ETag """ if not isinstance(etag, bytes): etag = bytes(etag, "utf-8") self._etag.append(etag)
java
public void marshall(BaiduChannelRequest baiduChannelRequest, ProtocolMarshaller protocolMarshaller) { if (baiduChannelRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(baiduChannelRequest.ge...
java
public void addPTable(PTable physicalTable) { Object strKey = physicalTable.getLookupKey(); m_htTableList.put(strKey, physicalTable); this.getPDatabaseParent().addTableToCache(physicalTable); // If cache is on }
python
def arg_to_json(arg): """ Perform necessary JSON conversion on the arg. """ conversion = json_conversions.get(type(arg)) if conversion: return conversion(arg) for type_ in subclass_conversions: if isinstance(arg, type_): return json_conversions[type_](arg) return ...
java
public static <E extends Blob> E retrieveFromStream(String id, InputStream inputStream, Class<E> clazz) throws IOException { logger.debug("trying to retrieve from Stream. id = {}, class = {}", id, clazz); DataInputStream dataInputStream = new DataInputStream(inputStream); byte binaryVersion = dataInputStream...
python
def motif3struct_bin(A): ''' Structural motifs are patterns of local connectivity. Motif frequency is the frequency of occurrence of motifs around a node. Parameters ---------- A : NxN np.ndarray binary directed connection matrix Returns ------- F : 13xN np.ndarray ...
java
@Override public void visit(NodeVisitor v) { if (v.visit(this)) { expression.visit(v); statement.visit(v); } }
java
public void load(File authorizationFile) throws AuthorizationFileException { FileInputStream fis = null; try { fis = new FileInputStream(authorizationFile); ANTLRInputStream stream = new ANTLRInputStream(fis); SAFPLexer lexer = new SAFPLexer(stream); Commo...
python
def get_mailbox_list(value): """ mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS]) For this routine we go outside the formal grammar in order to improve error handling. We recognize the end of the mailbox list only at the end of t...
python
def _load_bond_length_data(): """Loads bond length data from json file""" with open(os.path.join(os.path.dirname(__file__), "bond_lengths.json")) as f: data = collections.defaultdict(dict) for row in json.load(f): els = sorted(row['elements']) d...
python
def get_first_host_port(self): """ Get the first mapping of the first (lowest) container port that has a mapping. Useful when a container publishes only one port. Note that unlike the Docker API, which sorts ports lexicographically (e.g. ``90/tcp`` > ``8000/tcp``), we sort ports...
java
@Override public boolean contains(IsoUnit unit) { if (unit == null) { return false; } boolean fractional = isFractionUnit(unit); for (int i = 0, n = this.items.size(); i < n; i++) { Item<U> item = this.items.get(i); U u = item.getUnit(); ...
java
public static appfwpolicylabel get(nitro_service service, String labelname) throws Exception{ appfwpolicylabel obj = new appfwpolicylabel(); obj.set_labelname(labelname); appfwpolicylabel response = (appfwpolicylabel) obj.get_resource(service); return response; }
python
def fork_pty(): '''This implements a substitute for the forkpty system call. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to resolve the issue with Python's pty.fork() not s...
python
def chmod(self, tarinfo, targetpath): """Set file permissions of targetpath according to tarinfo. """ if hasattr(os, 'chmod'): try: os.chmod(targetpath, tarinfo.mode) except EnvironmentError as e: raise ExtractError("could not change mode")
python
async def open_async(self): """ Opens partition pump. """ self.set_pump_status("Opening") self.partition_context = PartitionContext(self.host, self.lease.partition_id, self.host.eh_config.client_address, ...
python
def create(cls, bucket, key, _file_id=None, stream=None, mimetype=None, version_id=None, **kwargs): """Create a new object in a bucket. The created object is by default created as a delete marker. You must use ``set_contents()`` or ``set_location()`` in order to change this. ...
python
def get_pos_name(code, name='parent', english=True, pos_tags=POS_MAP): """Gets the part of speech name for *code*. :param str code: The part of speech code to lookup, e.g. ``'nsf'``. :param str name: Which part of speech name to include in the output. Must be one of ``'parent'``, ``'child'``, or ``...
java
void addFreeTypeListener(List<Type> types, FreeTypeListener ftl) { freeTypeListeners.put(ftl, freeVarsIn(types)); }
python
def form_user_term_matrix(user_twitter_list_keywords_gen, id_to_node, lemma_set=None, keyword_to_topic_manual=None): """ Forms a user-term matrix. Input: - user_twitter_list_keywords_gen: A python generator that yields a user Twitter id and a bag-of-words. - id_to_node: A Twitter id to node...
java
@Override public ResultStream<T> createMapSelf(ResultStream<? super T> result) { return new ResultStreamServicePrefetch<>(result, _prefetch); }
java
@Override public ISynchronizationPoint<Exception> start() { SynchronizationPoint<Exception> sp = new SynchronizationPoint<>(); io.canStartReading().listenAsync(new Task.Cpu.FromRunnable(() -> { try { Starter start = new Starter(io, defaultEncoding, charactersBuffersSize, maxBuffers); stream = star...
java
public final String entryRuleIdOrSuper() throws RecognitionException { String current = null; AntlrDatatypeRuleToken iv_ruleIdOrSuper = null; try { // InternalPureXbase.g:4998:49: (iv_ruleIdOrSuper= ruleIdOrSuper EOF ) // InternalPureXbase.g:4999:2: iv_ruleIdOrSuper= r...
java
public static Procedure compileMigrateProcedure(Table table, String procName, Column column, ComparisonOperation comparison) { Procedure proc = addProcedure(table, procName); // Select count(*) StringBuilder sb = new StringBuilder(); sb.append("SELECT COUNT(*) FROM " + table...
python
def getDetails(self): """Update check details, returns dictionary of details""" response = self.pingdom.request('GET', 'checks/%s' % self.id) self.__addDetails__(response.json()['check']) return response.json()['check']
python
def start_log_monitor(redis_address, logs_dir, stdout_file=None, stderr_file=None, redis_password=None): """Start a log monitor process. Args: redis_address (str): The address of the Redis instance. logs_dir...
java
public String getString(String strKey) { if (m_resources == null) { BaseApplication application = (BaseApplication)this.getTask().getApplication(); m_resources = application.getResources(ResourceConstants.MENU_RESOURCE, true); } return m_resources.getString(st...
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.FNMRG__CHAR_BOX_WD: setCharBoxWd(CHAR_BOX_WD_EDEFAULT); return; case AfplibPackage.FNMRG__CHAR_BOX_HT: setCharBoxHt(CHAR_BOX_HT_EDEFAULT); return; case AfplibPackage.FNMRG__PAT_DOSET: setPatDOset(PAT_DO...
python
def get_subcellular_locations(self, entry): """ get list of models.SubcellularLocation object from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.SubcellularLocation` object """ subcellular_locations = [] query = './...
python
def _validate_columns(self): ''' Same as _validate_rows but for columns. Also ignore used_cells as _validate_rows should update used_cells. ''' for column_index in range(self.start[1], self.end[1]): table_column = TableTranspose(self.table)[column_index] ...
java
private boolean alignProteinChains(List<Group> seqRes, List<Group> atomRes) { Map<Integer,Integer> seqresIndexPosition = new HashMap<Integer, Integer>(); Map<Integer,Integer> atomIndexPosition = new HashMap<Integer, Integer>(); String seq1 = getFullAtomSequence(seqRes, seqresIndexPosition, false); // Stri...
python
def get_queryset(self): '''Apply Datatables sort and search criterion to QuerySet''' qs = super(DatatablesView, self).get_queryset() # Perform global search qs = self.global_search(qs) # Perform column search qs = self.column_search(qs) # Return the ordered querys...
java
@Override public void setValue(final Object selectedItemId) { if (selectedItemId != null) { // Can happen during validation, leading to multiple database // queries, in order to get the caption property if (selectedItemId.equals(previousValue)) { return; ...
python
def notify_observers(self, signal, **kwargs): """ Notify observers of a given signal. Parameters ---------- signal : str a valid signal. kwargs : dict the parameters that will be sent to the observers. Returns ------- out: bool ...
python
def list_models(client, dataset_id): """Sample ID: go/samples-tracker/1512""" # [START bigquery_list_models] from google.cloud import bigquery # TODO(developer): Construct a BigQuery client object. # client = bigquery.Client() # TODO(developer): Set dataset_id to the ID of the dataset that co...
python
def _included_frames(frame_list, frame_format): """frame_list should be a list of filenames""" return INCLUDED_FRAMES.format(Nframes=len(frame_list), frame_dir=os.path.dirname(frame_list[0]), frame_format=frame_format)
java
@Override public CommerceDiscountRel fetchByCN_CPK_Last(long classNameId, long classPK, OrderByComparator<CommerceDiscountRel> orderByComparator) { int count = countByCN_CPK(classNameId, classPK); if (count == 0) { return null; } List<CommerceDiscountRel> list = findByCN_CPK(classNameId, classPK, co...
python
def prob_classify(self, text): """Return the label probability distribution for classifying a string of text. Example: :: >>> classifier = MaxEntClassifier(train_data) >>> prob_dist = classifier.prob_classify("I feel happy this morning.") >>> prob_di...
python
def resource_create_ticket(self, token, id, scopes, **kwargs): """ Create a ticket form permission to resource. https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_protection_permission_api_papi :param str token: user access token :param str id: reso...
java
public void writeData(long offset, ByteBuffer srcBuf) throws IOException { int len = srcBuf.remaining(); if (len == 0) return; final long minSize = offset + len; if (getLengthOnDisk() < minSize) { setSize(minSize); } final long[] chain = fa...
java
@Override public JavaShellToolBuilder in(InputStream cmdIn, InputStream userIn) { this.cmdIn = cmdIn; this.userIn = userIn; return this; }
python
def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs...
python
def on_train_end(self, **kwargs): "Load the best model." if self.every=="improvement" and (self.learn.path/f'{self.learn.model_dir}/{self.name}.pth').is_file(): self.learn.load(f'{self.name}', purge=False)
java
void get_basic_features(final Context ctx, final List<Integer> forms, final List<Integer> postags, final List<Integer> deprels, List<Integer> features) { PUSH(features, FORM(forms, ctx.S0)); ...
python
def add_entry_listener(self, include_value=False, key=None, added_func=None, removed_func=None, clear_all_func=None): """ Adds an entry listener for this multimap. The listener will be notified for all multimap add/remove/clear-all events. :param include_value: (bool), whether received ...
python
def simxGetInMessageInfo(clientID, infoType): ''' Please have a look at the function description/documentation in the V-REP user manual ''' info = ct.c_int() return c_GetInMessageInfo(clientID, infoType, ct.byref(info)), info.value
python
def get_tab_title(key, frame, overlay): """ Computes a title for bokeh tabs from the key in the overlay, the element and the containing (Nd)Overlay. """ if isinstance(overlay, Overlay): if frame is not None: title = [] if frame.label: title.append(fram...
python
def send(reg_id, message, **kwargs): """ Site: https://developers.google.com API: https://developers.google.com/web/updates/2016/03/web-push-encryption Desc: Web Push notifications for Chrome and FireFox Installation: pip install 'pywebpush>=0.4.0' """ subscription_info = kwargs.pop('s...
python
def match_files(files, pattern: Pattern): """Yields file name if matches a regular expression pattern.""" for name in files: if re.match(pattern, name): yield name
python
def add_predicateAnchor(self,my_predAnch): """ Adds a predAnch to the temporalRelations layer @type my_predAnch: L{CpredicateAnchor} @param my_predAnch: predicateAnchor object """ if self.temporalRelations_layer is None: self.temporalRelations_layer = Ctempora...
java
public String getAttributeTypeName(String attributeName) { CmsType attrType = m_types.get(attributeName); return attrType == null ? null : attrType.getId(); }
python
def export(self, container, chunk_size=DEFAULT_DATA_CHUNK_SIZE): """ Export the contents of a filesystem as a tar archive. Args: container (str): The container to export chunk_size (int): The number of bytes returned by each iteration of the generator. If...
java
public int getNumberWaiting() { final ReentrantLock lock = this.lock; lock.lock(); try { return parties - count; } finally { lock.unlock(); } }
java
public void writeString(final String value, final JBBPByteOrder order) throws IOException { if (value == null) { this.write(0xFF); } else if (value.length() == 0) { this.write(0); } else { final byte[] array = JBBPUtils.strToUtf8(value); final int len = array.length; if (len < ...
java
private int calculateMaxPendingSplits(int splitAffinity, int totalDepth) { if (totalDepth == 0) { return maxPendingSplitsPerTask; } // Use half the queue for any split // Reserve the other half for splits that have some amount of network affinity double queueFract...
python
def vrrp_shutdown(app, instance_name): """shutdown the instance. """ shutdown_request = vrrp_event.EventVRRPShutdownRequest(instance_name) app.send_event(vrrp_event.VRRP_MANAGER_NAME, shutdown_request)
python
def build_type(self, build_type): """ Sets the build_type of this BuildConfigurationRest. :param build_type: The build_type of this BuildConfigurationRest. :type: str """ allowed_values = ["MVN", "NPM"] if build_type not in allowed_values: raise Value...
java
public void cleanUpState(VirtualConnection vc) { // if discrimination returned MAYBE, then we stored a link object that // now needs to be cleaned up HttpInboundLink link = (HttpInboundLink) vc.getStateMap().get(CallbackIDs.CALLBACK_HTTPICL); if (null != link) { if (TraceComp...
java
@Override public CreateRuleGroupResult createRuleGroup(CreateRuleGroupRequest request) { request = beforeClientExecution(request); return executeCreateRuleGroup(request); }
python
def current_settings(self): """Return dict with all config include.""" settings = {} if not self.status_data: return settings for (key, val) in self.status_data.get('curvals', {}).items(): try: val = float(val) except ValueError: ...
python
def threshold_monitor_hidden_threshold_monitor_Cpu_limit(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor") threshold_monito...