language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static Diff fromDelta(String text1, String delta) throws IllegalArgumentException { return new Diff(changesFromDelta(text1, delta), DiffOptions.defaults()); }
python
def _find_best_fit(self, pbin): """ Return best fitness rectangle from rectangles packing _sorted_rect list Arguments: pbin (PackingAlgorithm): Packing bin Returns: key of the rectangle with best fitness """ fit = ((pbin.fitness(r[0], r[1]), k) f...
java
@Indexable(type = IndexableType.REINDEX) @Override public CommerceAvailabilityEstimate addCommerceAvailabilityEstimate( CommerceAvailabilityEstimate commerceAvailabilityEstimate) { commerceAvailabilityEstimate.setNew(true); return commerceAvailabilityEstimatePersistence.update(commerceAvailabilityEstimate); }
java
private DefBase getDefForLevel(String level) { if (LEVEL_CLASS.equals(level)) { return _curClassDef; } else if (LEVEL_FIELD.equals(level)) { return _curFieldDef; } else if (LEVEL_REFERENCE.equals(level)) { ...
python
def guest_unpause(self, userid): """Unpause a virtual machine. :param str userid: the id of the virtual machine to be unpaused :returns: None """ action = "unpause guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_unp...
python
def _get_stack(self, orchestration_client, stack_name): """Get the ID for the current deployed overcloud stack if it exists.""" try: stack = orchestration_client.stacks.get(stack_name) self.log.info("Stack found, will be doing a stack update") return stack ex...
python
def distinguish(self, as_made_by='mod', sticky=False): """Distinguish object as made by mod, admin or special. Distinguished objects have a different author color. With Reddit Enhancement Suite it is the background color that changes. `sticky` argument only used for top-level Comments....
python
def t_PARBREAK(self, token): ur'\n{2,}' token.lexer.lineno += len(token.value) return token
python
def add_index(self, mode, blob_id, path): """ Add new entry to the current index :param tree: :return: """ self.command_exec(['update-index', '--add', '--cacheinfo', mode, blob_id, path])
python
def _do_search(conf): ''' Builds connection and search arguments, performs the LDAP search and formats the results as a dictionary appropriate for pillar use. ''' # Build LDAP connection args connargs = {} for name in ['server', 'port', 'tls', 'binddn', 'bindpw', 'anonymous']: connar...
python
def send_message(host, data, timeout=None, properties=None): """ Send message to given `host`. Args: host (str): Specified host: aleph/ftp/whatever available host. data (str): JSON data. timeout (int, default None): How much time wait for connection. """ channel = _get_chann...
java
public Atom[] getAlignmentAtoms(Structure s) { String[] atomNames = params.getUsedAtomNames(); return StructureTools.getAtomArray(s, atomNames); }
python
def add_documents(self, docs): """Update dictionary from a collection of documents. Each document is a list of tokens. Args: docs (list): documents to add. """ for sent in docs: sent = map(self.process_token, sent) self._token_count.update(sen...
java
public static List<IAtomContainer> getOverlaps(IAtomContainer sourceGraph, IAtomContainer targetGraph, boolean shouldMatchBonds) throws CDKException { List<List<CDKRMap>> rMapsList = search(sourceGraph, targetGraph, new BitSet(), new BitSet(), true, false, shouldMatchBonds); ...
java
public String convertIfcActionSourceTypeEnumToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
python
def add_template_events_to_network(self, columns, vectors): """ Add a vector indexed """ # Just call through to the standard function self.template_events = self.template_event_dict['network'] self.add_template_network_events(columns, vectors) self.template_event_dict['network'] ...
python
def query_total_cat_recent_no_label(cat_id_arr, num=8, kind='1'): ''' :param cat_id_arr: list of categories. ['0101', '0102'] ''' return TabPost.select().join( TabPost2Tag, on=(TabPost.uid == TabPost2Tag.post_id) ).where( (TabPost.kind == kin...
python
def send(scope, data): """ Like exec(), but does not wait for a response of the remote host after sending the command. :type data: string :param data: The data that is sent. """ conn = scope.get('__connection__') for line in data: conn.send(line) return True
python
def generate_table(self, rows): """ Generates from a list of rows a PrettyTable object. """ table = PrettyTable(**self.kwargs) for row in self.rows: if len(row[0]) < self.max_row_width: appends = self.max_row_width - len(row[0]) for i i...
java
@Override public long skip(long n) throws IOException { byte[] buf = new byte[(int)Math.min(n,64*1024)]; return read(buf,0,buf.length); }
python
def calculate_y_ticks(self, plot_height): """Calculate the y-axis items dependent on the plot height.""" calibrated_data_min = self.calibrated_data_min calibrated_data_max = self.calibrated_data_max calibrated_data_range = calibrated_data_max - calibrated_data_min ticker = self...
java
protected String getMessage(String key, String... args) { return Messages.get().getBundle(m_cms.getRequestContext().getLocale()).key(key, args); }
java
@Override public TreeMap<Integer, NavigableMap<Integer, IScan>> getScansByRtSpan(double rtStart, double rtEnd) { TreeMap<Integer, NavigableMap<Integer, IScan>> viewMap = new TreeMap<>(); boolean hasNonZeroElements = false; for (Integer i : getMapMsLevel2index().keySet()) { NavigableMap<Integer...
java
public void sendRequest(Message request, Object context, Message.Builder responseBuilder, Duration timeout) { // Pack it as a no-timeout request and send it! final REQID rid = REQID.generate(); contextMap.put(rid, context); responseMessageMap.put(rid, responseBuilder); // ...
java
@Nullable public static short[] optShortArray(@Nullable Bundle bundle, @Nullable String key) { return optShortArray(bundle, key, new short[0]); }
python
def click(self, selector, btn=0): """ Click the targeted element. :param selector: A CSS3 selector to targeted element. :param btn: The number of mouse button. 0 - left button, 1 - middle button, 2 - right button """ return self.evalua...
python
def _filter_by_m2m_schema(self, qs, lookup, sublookup, value, schema, model=None): """ Filters given entity queryset by an attribute which is linked to given many-to-many schema. """ model = model or self.model schemata = dict((s.name, s) for s in model.get_schemata_for_m...
python
def _find_subclass(cls, module): """ Attempt to find subclass of :class:`RelationBase` in the given module. Note: This means strictly subclasses and not :class:`RelationBase` itself. This is to prevent picking up :class:`RelationBase` being imported to be used as the base class....
python
def get_search_regex(query, ignore_case=True): """Returns a compiled regex pattern to search for query letters in order. Parameters ---------- query : str String to search in another string (in order of character occurrence). ignore_case : True Optional value perform a case insensit...
java
public final void toJson(Writer out, T value) throws IOException { JsonWriter writer = new JsonWriter(out); write(writer, value); }
python
def update_buttons(self): """Updates the enable status of delete and reset buttons.""" current_scheme = self.current_scheme names = self.get_option("names") try: names.pop(names.index(u'Custom')) except ValueError: pass delete_enabled = current_sch...
java
private void checkFile() throws IORuntimeException { Assert.notNull(file, "File to write content is null !"); if(this.file.exists() && false == file.isFile()){ throw new IORuntimeException("File [{}] is not a file !", this.file.getAbsoluteFile()); } }
python
def longest_table(dfs): """ Return this single longest DataFrame that among an array/list/tuple of DataFrames Useful for automagically finding the DataFrame you want when using pd.read_html() on a Wikipedia page. """ sorted_indices = sorted((len(df if hasattr(df, '__len__') else []), i) for i, df in en...
python
def _load_mapping() -> Optional[Dict[str, str]]: """Return list of mappings `package_name -> module_name` Example: django-haystack -> haystack """ if not pipreqs: return None path = os.path.dirname(inspect.getfile(pipreqs)) path = os.path.join(pat...
java
public static Map<FieldType, String> getDefaultTaskFieldMap() { Map<FieldType, String> map = new LinkedHashMap<FieldType, String>(); map.put(TaskField.UNIQUE_ID, "task_id"); map.put(TaskField.GUID, "guid"); map.put(TaskField.NAME, "task_name"); map.put(TaskField.ACTUAL_DURATION, "act_d...
java
private Response cacheWritingResponse(final CacheRequest cacheRequest, Response response) throws IOException { // Some apps return a null body; for compatibility we treat that like a null cache request. if (cacheRequest == null) return response; Sink cacheBodyUnbuffered = cacheRequest.body(); if (...
java
private float[] getReduceAvarageProgresses(int tasksPerBar, int index , TaskReport[] reports ) { float[] progresses = new float[] {0,0,0}; int k=0; for(;k < tasksPerBar && index + k < reports.length; k++) { float progress = reports[index+k].getProgress(); for(int j=0; progress > 0 ; j++, p...
python
def _maybeCleanSessions(self): """ Clean expired sessions if it's been long enough since the last clean. """ sinceLast = self._clock.seconds() - self._lastClean if sinceLast > self.sessionCleanFrequency: self._cleanSessions()
python
def get_value_for_datastore(self, model_instance): """Get key of reference rather than reference itself.""" table_id = getattr(model_instance, self.table_fieldname, None) object_id = getattr(model_instance, self.object_fieldname, None) return table_id, object_id
java
public static <T> ScopedBindingBuilder createChoiceWithDefault( Binder binder, String property, Key<T> interfaceKey, String defaultPropertyValue ) { Preconditions.checkNotNull(defaultPropertyValue); ConfiggedProvider<T> provider = new ConfiggedProvider<>(interfaceKey, property, null,...
java
public static Histogram divide(Histogram x, double y) { return x.modifyEventCounters((r, d) -> d / y); }
java
public static boolean isDepthRenderable(final JCGLTextureFormat f) { switch (f) { case TEXTURE_FORMAT_DEPTH_16_2BPP: case TEXTURE_FORMAT_DEPTH_24_4BPP: case TEXTURE_FORMAT_DEPTH_24_STENCIL_8_4BPP: case TEXTURE_FORMAT_DEPTH_32F_4BPP: return true; case TEXTURE_FORMAT_R_16_2BPP:...
java
@InterfaceAudience.Public public void setIsDeletion(boolean isDeletion) { if (isDeletion == true) { properties.put("_deleted", true); } else { properties.remove("_deleted"); } }
python
def maximal_matching(G, sampler=None, **sampler_args): """Finds an approximate maximal matching. Defines a QUBO with ground states corresponding to a maximal matching and uses the sampler to sample from it. A matching is a subset of edges in which no node occurs more than once. A maximal matching ...
java
public String keyToString(Object key) { // This string should be in the format of: // "<TYPE>:<KEY>" for internally supported types or "T:<KEY_CLASS>:<KEY>" for custom types // e.g.: // "S:my string key" // "I:75" // "D:5.34" // "B:f" // "T:com.myorg.MyType:STRI...
java
public void crawlToOpen(TreePath path, ArrayList<BugLeafNode> bugLeafNodes, ArrayList<TreePath> treePaths) { for (int i = 0; i < getChildCount(path.getLastPathComponent()); i++) { if (!isLeaf(getChild(path.getLastPathComponent(), i))) { for (BugLeafNode p : bugLeafNodes) { ...
java
private Class<?> getClassFromBundle(Object resource, String className, String versionRange) { Class<?> c = null; if (resource == null) { Object classAccess = this.getClassBundleService(null, className, versionRange, null, 0); if (classAccess != null) { ...
java
private ModelNode removeAliasFromList(ModelNode list, String alias) throws OperationFailedException { // check for empty string if (alias == null || alias.equals("")) return list ; // check for undefined list (AS7-3476) if (!list.isDefined()) { throw InfinispanM...
java
public AddPermissionRequest withAWSAccountIds(String... aWSAccountIds) { if (this.aWSAccountIds == null) { setAWSAccountIds(new com.amazonaws.internal.SdkInternalList<String>(aWSAccountIds.length)); } for (String ele : aWSAccountIds) { this.aWSAccountIds.add(ele); ...
python
def _headers(self): """Ensure the Authorization Header has a valid Access Token.""" if not self.access_token or not self.access_token_expires: self._basic_login() elif datetime.now() > self.access_token_expires - timedelta(seconds=30): self._basic_login() return...
python
def get_lambda_to_execute(self): """ return a function that executes the function assigned to this job. If job.track_progress is None (the default), the returned function accepts no argument and simply needs to be called. If job.track_progress is True, an update_progress function ...
python
def concat(dfs): """Concatenate a series of `pyam.IamDataFrame`-like objects together""" if isstr(dfs) or not hasattr(dfs, '__iter__'): msg = 'Argument must be a non-string iterable (e.g., list or tuple)' raise TypeError(msg) _df = None for df in dfs: df = df if isinstance(df, I...
java
private List<EnhanceEntity> populateEnhanceEntities(EntityMetadata m, List<String> relationNames, List result) { List<EnhanceEntity> ls = null; if (!result.isEmpty()) { ls = new ArrayList<EnhanceEntity>(result.size()); for (Object o : result) { ...
java
public <T> Set<T> toSet(Class<T> classOfT) { return toSet(classOfT, null); }
java
public static Number or(Number left, Number right) { return NumberMath.or(left, right); }
python
def fetch_sampling_rules(self): """ Use X-Ray botocore client to get the centralized sampling rules from X-Ray service. The call is proxied and signed by X-Ray Daemon. """ new_rules = [] resp = self._xray_client.get_sampling_rules() records = resp['SamplingRuleRe...
python
def get_queue_settings(self, project_key): """ Get queue settings on project :param project_key: str :return: """ url = 'rest/servicedeskapi/queues/{}'.format(project_key) return self.get(url, headers=self.experimental_headers)
java
private void processOrphanCommits(GitHubRepo repo) { long refTime = Math.min(System.currentTimeMillis() - gitHubSettings.getCommitPullSyncTime(), gitHubClient.getRepoOffsetTime(repo)); List<Commit> orphanCommits = commitRepository.findCommitsByCollectorItemIdAndTimestampAfterAndPullNumberIsNull(repo.get...
java
public Image getFlippedCopy(boolean flipHorizontal, boolean flipVertical) { init(); Image image = copy(); if (flipHorizontal) { image.textureOffsetX = textureOffsetX + textureWidth; image.textureWidth = -textureWidth; } if (flipVertical) { image.textureOffsetY = textureOffsetY + textureHe...
java
@SuppressWarnings("unchecked") <T> void processBean(@Observes ProcessBean<T> processBean) { Bean<T> bean = processBean.getBean(); for (Type type : bean.getTypes()) { if (!(type instanceof Class<?>)) { continue; } // Check if the bean is an RedisUR...
python
def wrapped_help_text(wrapped_func): """Decorator to pass through the documentation from a wrapped function. """ def decorator(wrapper_func): """The decorator. Parameters ---------- f : callable The wrapped function. """ wrapper_func.__doc__ = ('...
python
def process_data(self, data): """Convert an unknown data input into a geojson dictionary.""" if isinstance(data, dict): self.embed = True return data elif isinstance(data, str): if data.lower().startswith(('http:', 'ftp:', 'https:')): if not se...
java
public static BitfinexOrderBookSymbol fromJSON(final JSONObject jsonObject) { BitfinexCurrencyPair symbol = BitfinexCurrencyPair.fromSymbolString(jsonObject.getString("symbol")); Precision prec = Precision.valueOf(jsonObject.getString("prec")); Frequency freq = null; Integer len = null; if (prec != Precision....
java
public static final SerIterable map(final Class<?> keyType, final Class<?> valueType, final List<Class<?>> valueTypeTypes) { final Map<Object, Object> map = new HashMap<>(); return map(keyType, valueType, valueTypeTypes, map); }
java
void putAll(BitArray array) { assert data.length == array.data.length : "BitArrays must be of equal length when merging"; long bitCount = 0; for (int i = 0; i < data.length; i++) { data[i] |= array.data[i]; bitCount += Long.bitCount(data[i]); } this.bitCount = bitCount; }
java
private Version getProductVersion(File wlpInstallationDirectory) throws VersionParsingException { // First get the properties Map<String, ProductInfo> productProperties = VersionUtils.getAllProductInfo(wlpInstallationDirectory); // Get the properties for WAS ProductInfo wasProperties = ...
python
def report_usage_to_host(host_ip, vmid): #base value cpu_usage = 0.0 os_mem_usage = 0.0 task_mem_usage = 0.0 io_usage = 0.0 cpu_usage = get_cpu_usage() os_mem_usage = get_os_mem_usage() task_mem_usage = get_task_mem_usage() io_usage = get_io_usage() usage = str(vmid.strip())+' | '+str(cpu_usage)+' | '+str...
java
private Force computeVector(Force vector, Localizable target) { final double sx = localizable.getX(); final double sy = localizable.getY(); double dx = target.getX(); double dy = target.getY(); if (target instanceof Transformable) { final Trans...
python
def _clean_background(data): """Clean up background specification, remaining back compatible. """ allowed_keys = set(["variant", "cnv_reference"]) val = tz.get_in(["algorithm", "background"], data) errors = [] if val: out = {} # old style specification, single string for variant ...
java
public static CommerceCountry fetchByG_S_A_Last(long groupId, boolean shippingAllowed, boolean active, OrderByComparator<CommerceCountry> orderByComparator) { return getPersistence() .fetchByG_S_A_Last(groupId, shippingAllowed, active, orderByComparator); }
java
public static String formatIPAddressForURI(InetAddress inet){ if(inet == null){ throw new IllegalArgumentException(); } if(inet instanceof Inet4Address){ return inet.getHostAddress(); } else if (inet instanceof Inet6Address){ return '[' + formatAddress...
python
def list_commands(self, ctx): """Override for showing commands in particular order""" commands = super(LegitGroup, self).list_commands(ctx) return [cmd for cmd in order_manually(commands)]
java
CpcSketch copy() { final CpcSketch copy = new CpcSketch(lgK, seed); copy.numCoupons = numCoupons; copy.mergeFlag = mergeFlag; copy.fiCol = fiCol; copy.windowOffset = windowOffset; copy.slidingWindow = (slidingWindow == null) ? null : slidingWindow.clone(); copy.pairTable = (pairTable == nul...
java
public TransactionInfo queryTransactionByID(String txID, User userContext) throws ProposalException, InvalidArgumentException { return queryTransactionByID(getShuffledPeers(EnumSet.of(PeerRole.LEDGER_QUERY)), txID, userContext); }
python
def create_css(self, fileid=None): """ Generate the final CSS string """ if fileid: rules = self._rules.get(fileid) or [] else: rules = self.rules compress = self._scss_opts.get('compress', True) if compress: sc, sp, tb, nl = F...
java
public static <I, D> int findLinearReverse(Query<I, D> ceQuery, AccessSequenceTransformer<I> asTransformer, SuffixOutput<I, D> hypOutput, MembershipOracle<I, D> oracle) { ...
java
public static <INPUT extends Comparable<INPUT>> Iterable<List<INPUT>> toUniqueAndSortedPartitions(Collection<INPUT> inputs) { return toUniqueAndSortedPartitions(inputs, i -> i); }
java
public static CommerceRegion removeByC_C(long commerceCountryId, String code) throws com.liferay.commerce.exception.NoSuchRegionException { return getPersistence().removeByC_C(commerceCountryId, code); }
java
public static Map<String, Object> getDefaultValueMap(Schema avroRecordSchema) { List<Field> defaultFields = new ArrayList<Field>(); for (Field f : avroRecordSchema.getFields()) { if (f.defaultValue() != null) { // Need to create a new Field here or we will get // org.apache.avro.AvroRuntim...
python
def upload_superfile(self, remote_path, block_list, ondup=None, **kwargs): """分片上传—合并分片文件. 与分片文件上传的 ``upload_tmpfile`` 方法配合使用, 可实现超大文件(>2G)上传,同时也可用于断点续传的场景。 :param remote_path: 网盘中文件的保存路径(包含文件名)。 必须以 /apps/ 开头。 .. warning:: ...
java
public Tree<T> build() { Tree<T> result = base; if (null == base && treeStack.size() == 1) { result = treeStack.get(0); } else if (treeStack.size() > 0) { result = new TreeStack<T>(treeStack, base); }else if(null==base) { throw new IllegalArgumentExcep...
java
public static String stringToString(String dateString, String desfmt) { // ISO_DATE_FORMAT = "yyyyMMdd"; if (dateString.trim().length() == 8) { return stringToString(dateString, ISO_DATE_FORMAT, desfmt); } else if (dateString.trim().length() == 10) { // ISO_EXPANDED_DATE_...
java
protected PluginStrategy createPluginStrategy() { String strategyName = SystemProperties.getString(PluginStrategy.class.getName()); if (strategyName != null) { try { Class<?> klazz = getClass().getClassLoader().loadClass(strategyName); Object strategy = klazz.getConstructor(PluginManager.class) .ne...
java
public void setChildren(List<PrintComponent<?>> children) { this.children = children; // needed for Json unmarshall !!!! for (PrintComponent<?> child : children) { child.setParent(this); } }
java
@Override public List<ConfigPropType> getConfigProps(Definition def) { return def.getMcfDefs().get(getNumOfMcf()).getMcfConfigProps(); }
java
public void setVastRedirectType(com.google.api.ads.admanager.axis.v201811.VastRedirectType vastRedirectType) { this.vastRedirectType = vastRedirectType; }
python
def update_slaves(self): """Update all `slave` |Substituter| objects. See method |Substituter.update_masters| for further information. """ for slave in self.slaves: slave._medium2long.update(self._medium2long) slave.update_slaves()
java
@MustBeLocked (ELockType.WRITE) protected final void internalUpdateItem (@Nonnull final IMPLTYPE aItem) { internalUpdateItem (aItem, true); }
python
def _insert_contents(self, fzpage, newcont, overlay): """_insert_contents(self, fzpage, newcont, overlay) -> PyObject *""" return _fitz.Tools__insert_contents(self, fzpage, newcont, overlay)
python
def getOutput(self, command, env={}, path=None, uid=None, gid=None, usePTY=0, childFDs=None): """Execute a command and get the output of the finished process. """ deferred = defer.Deferred() processProtocol = _SummaryProcessProtocol(deferred) self.execute(proces...
python
def load_folder_content(folder_path): """ load api/testcases/testsuites definitions from folder. Args: folder_path (str): api/testcases/testsuites files folder. Returns: dict: api definition mapping. { "tests/api/basic.yml": [ {"api": {"def"...
java
private Object getObjectValue(Node node, String fieldName) { // we have to take into account the fact that fieldName will be in the lower case if (node != null) { String name = node.getLocalName(); switch (node.getNodeType()) { case Node.ATTRIBUTE_NODE: ...
java
protected void destroy() { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "CompletionKey::destroy entered for:" + this); } // Free existing ByteBuffer objects. if (this.rawData != null) { if (this.wsByteBuf != null) { ...
python
def decode(self, codes): """Given PQ-codes, reconstruct original D-dimensional vectors via :func:`PQ.decode`, and applying an inverse-rotation. Args: codes (np.ndarray): PQ-cdoes with shape=(N, M) and dtype=self.code_dtype. Each row is a PQ-code Returns: ...
java
public ListVirtualNodesResult withVirtualNodes(VirtualNodeRef... virtualNodes) { if (this.virtualNodes == null) { setVirtualNodes(new java.util.ArrayList<VirtualNodeRef>(virtualNodes.length)); } for (VirtualNodeRef ele : virtualNodes) { this.virtualNodes.add(ele); ...
java
public List<GridCell<P>> consumeCells() { final List<GridCell<P>> list = new ArrayList<>(this.cells); this.cells.clear(); return list; }
java
protected void paint(SeaGlassContext context, Graphics g) { JSeparator separator = (JSeparator) context.getComponent(); context.getPainter().paintSeparatorForeground(context, g, 0, 0, separator.getWidth(), separator.getHeight(), separator.getOrienta...
python
def init_scalable( X, n_clusters, random_state=None, max_iter=None, oversampling_factor=2 ): """K-Means initialization using k-means|| This is algorithm 2 in Scalable K-Means++ (2012). """ logger.info("Initializing with k-means||") # Step 1: Initialize Centers idx = 0 centers = da.comp...
python
def get_events_in_both_arrays(events_one, events_two): """ Calculates the events that exist in both arrays. """ events_one = np.ascontiguousarray(events_one) # change memory alignement for c++ library events_two = np.ascontiguousarray(events_two) # change memory alignement for c++ library eve...
python
def reply_bytes(self, request): """Take a `Request` and return an OP_MSG message as bytes.""" flags = struct.pack("<I", self._flags) payload_type = struct.pack("<b", 0) payload_data = bson.BSON.encode(self.doc) data = b''.join([flags, payload_type, payload_data]) reply_i...