language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static MongoDS getDS(Collection<String> groups) { return getDS(groups.toArray(new String[groups.size()])); }
java
@Override public String getNormalizeName(String name) { return Normalizer.normalize(name, Normalizer.Form.NFD).replaceAll("'", " ").replaceAll("-", " ").replaceAll("[\\p{InCombiningDiacriticalMarks}]", "").trim(); }
java
public static <T extends java.util.Date> T addDays(final T date, final int amount) { return roll(date, amount, CalendarUnit.DAY); }
java
public com.google.api.ads.adwords.axis.v201809.cm.AdServingOptimizationStatus getAdServingOptimizationStatus() { return adServingOptimizationStatus; }
java
public static boolean isParityAdjusted(byte[] key, int offset) throws InvalidKeyException { if (key.length - offset < 24) { throw new InvalidKeyException("Wrong key size"); } if (DESKeySpec.isParityAdjusted(key, offset) == false || DESKeySpec.i...
python
def ignored_double_corner( intersection, tangent_s, tangent_t, edge_nodes1, edge_nodes2 ): """Check if an intersection is an "ignored" double corner. .. note:: This is a helper used only by :func:`ignored_corner`, which in turn is only used by :func:`classify_intersection`. Helper for :...
python
def _classify_arithmetic(self, regs_init, regs_fini, mem_fini, written_regs, read_regs): """Classify binary-operation gadgets. """ matches = [] # TODO: Review these restrictions. op_restrictions = { "+": lambda x, y: False, "-": lambda x, y: x == y, ...
python
def copyData(self, source): """ Subclasses may override this method. If so, they should call the super. """ for attr in self.copyAttributes: selfValue = getattr(self, attr) sourceValue = getattr(source, attr) if isinstance(selfValue, BaseObject...
java
public void addPackageDescription(Content packageContentTree) { if (packageDoc.inlineTags().length > 0) { packageContentTree.addContent( getMarkerAnchor(SectionName.PACKAGE_DESCRIPTION)); Content h2Content = new StringContent( configuration.getText...
java
protected EObject findAccessibleType(String fragment, ResourceSet resourceSet, Iterator<IEObjectDescription> fromIndex) throws UnknownNestedTypeException { IEObjectDescription description = fromIndex.next(); return getAccessibleType(description, fragment, resourceSet); }
java
private ParseTree parseLogicalOR(Expression expressionIn) { SourcePosition start = getTreeStartLocation(); ParseTree left = parseLogicalAND(expressionIn); while (peek(TokenType.OR)) { Token operator = eat(TokenType.OR); ParseTree right = parseLogicalAND(expressionIn); left = new BinaryOper...
java
private static List<File> findFiles(final File parent, boolean recurse) { final List<File> result = new ArrayList<>(); if (parent.isDirectory()) { File[] files = parent.listFiles(); files = (files != null ? files : new File[0]); for (File child : files) { ...
python
def build_images(prefix, images, tag=None, commit_range=None, push=False, chart_version=None): """Build a collection of docker images Args: prefix (str): the prefix to add to images images (dict): dict of image-specs from chartpress.yml tag (str): Specific tag to use instead of the last mod...
python
def analisar(retorno): """Constrói uma :class:`RespostaCancelarUltimaVenda` a partir do retorno informado. :param unicode retorno: Retorno da função ``CancelarUltimaVenda``. """ resposta = analisar_retorno(forcar_unicode(retorno), funcao='EnviarDadosVenda', ...
python
def status_to_string(dbus_status): ''' Converts a numeric dbus snapper status into a string CLI Example: .. code-block:: bash salt '*' snapper.status_to_string <dbus_status> ''' status_tuple = ( dbus_status & 0b000000001, dbus_status & 0b000000010, dbus_status & 0b000000100, ...
java
protected void setKeyringMonitorRegistration(ServiceRegistration<KeyringMonitor> keyringMonitorRegistration) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(this, tc, "setKeyringMonitorRegistration"); } this.keyringMonitorRegistration = keyringMonitorReg...
java
public LogWatchBuilder withDelayBetweenSweeps(final int length, final TimeUnit unit) { this.delayBetweenSweeps = LogWatchBuilder.getDelay(length, unit); return this; }
java
public static InetAddress getLocalAddress() { InetAddress localAddress = null; try { localAddress = InetAddress.getLocalHost(); if (isValidAddress(localAddress)) { return localAddress; } } catch (Throwable e) { if (LOGGER.isWarnEnab...
python
def makefractalCIJ(mx_lvl, E, sz_cl, seed=None): ''' This function generates a directed network with a hierarchical modular organization. All modules are fully connected and connection density decays as 1/(E^n), with n = index of hierarchical level. Parameters ---------- mx_lvl : int ...
python
def get_correction(self, entry): """ Gets the BandEdge correction for a defect entry """ # TODO: add smarter defect level shifting based on defect level projection onto host bands hybrid_cbm = entry.parameters["hybrid_cbm"] hybrid_vbm = entry.parameters["hybrid_vbm"] ...
java
private List<CmsContainerBean> collectModelStructure( String modelInstanceId, String replaceModelId, Map<String, List<CmsContainerBean>> containerByParent, boolean isCopyGroup) { List<CmsContainerBean> result = new ArrayList<CmsContainerBean>(); if (containerByParent.co...
java
@JsonProperty("x") @JsonSerialize(using = Base64UrlJsonSerializer.class) @JsonDeserialize(using = Base64UrlJsonDeserializer.class) public byte[] x() { return ByteExtensions.clone(this.x); }
python
def axes(self, offset = False): """returns measured value in miligauss""" reg, self._scale = self.SCALES[self._gauss] x = self.bus.read_int16_data(self.address, self.HMC5883L_DXRA) if x == -4096: x = OVERFLOW y = self.bus.read_int16_data(self.address, self.HMC5883L_DYRA) ...
python
def QueryAttachments(self, document_link, query, options=None): """Queries attachments in a document. :param str document_link: The link to the document. :param (str or dict) query: :param dict options: The request options for the request. :return: ...
java
private List<Map<StreamStateHandle, OperatorStateHandle>> repartition( GroupByStateNameResults nameToStateByMode, int newParallelism) { // We will use this to merge w.r.t. StreamStateHandles for each parallel subtask inside the maps List<Map<StreamStateHandle, OperatorStateHandle>> mergeMapList = new ArrayLi...
python
def get_data(self, query): """Fetch parsed data from a THREDDS server using NCSS. Requests data from the NCSS endpoint given the parameters in `query` and handles parsing of the returned content based on the mimetype. Parameters ---------- query : NCSSQuery ...
java
public static int copyPropertiesExcept( final Object dst, final Object src, final String[] properties ) { if (dst == null) { throw new IllegalArgumentException( "no destination object specified" ); } ...
java
public static byte[] encode(final byte[] source, final int off, final int len) { if (source == null) { throw new NullPointerException("Cannot serialize a null array."); } if (off < 0) { throw new IllegalArgumentException("Cannot have negative offset: " + off); } ...
python
def check_output(*args, **kwargs): '''Compatibility wrapper for Python 2.6 missin g subprocess.check_output''' if hasattr(subprocess, 'check_output'): return subprocess.check_output(stderr=subprocess.STDOUT, universal_newlines=True, *args, **kwargs) else: ...
java
public static File writeDataToFile(final byte[] data, final File file, final boolean append) { try (FileOutputStream out = new FileOutputStream(file, append)) { out.write(data); out.flush(); out.close(); return file; } catch (Exception e) { JKExceptionUtil.handle(e); return null; } }
java
public Long hset(Object key, Object field, Object value) { Jedis jedis = getJedis(); try { return jedis.hset(keyToBytes(key), fieldToBytes(field), valueToBytes(value)); } finally {close(jedis);} }
java
private void registerJsonFormatInterceptor() { RestTemplate restTemplate = getRestTemplate(); if (interceptorsSupported) { List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors(); interceptors.add(new JsonFormatInterceptor()); } else { // for Spring 3.0.x where interceptors are...
java
public static ChronoFormatter<PlainTime> ofTimeStyle( DisplayMode style, Locale locale ) { Builder<PlainTime> builder = new Builder<>(PlainTime.axis(), locale); builder.addProcessor(new StyleProcessor<>(style, style)); return builder.build(); }
java
protected Set<String> getAccessTokenDependencies(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) { Set<String> deps = new TreeSet<String>(); if (getObjectDefinitionSource() != null) { FilterInvocation invocation = new FilterInvocation(request, response, filterChain); ...
python
def get_contributors(self, anon=github.GithubObject.NotSet): """ :calls: `GET /repos/:owner/:repo/contributors <http://developer.github.com/v3/repos>`_ :param anon: string :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser` """ url_p...
python
def upload_folder(self, folder_path, container=None, ignore=None, ttl=None): """ Convenience method for uploading an entire folder, including any sub-folders, to Cloud Files. All files will be uploaded to objects with the same name as the file. In the case of nested folders, fil...
java
public static Class<?> getElementType(Iterator<?> iterator) { final Iterator<?> iter2 = new CopiedIter<>(iterator); if (null != iter2) { Object t; while (iter2.hasNext()) { t = iter2.next(); if (null != t) { return t.getClass(); } } } return null; }
python
def bin2str(b): """ Binary to string. """ ret = [] for pos in range(0, len(b), 8): ret.append(chr(int(b[pos:pos + 8], 2))) return ''.join(ret)
java
public static long sizeToLong(String size) { size = size.trim(); if (Checker.isNotEmpty(size)) { String num; if (size.contains(ValueConsts.SPACE)) { num = size.split(ValueConsts.SPACE)[0]; } else { num = Utils.extractDigit(size); ...
python
def set_size(self, width, height): """ Informs cairo of the new size of the X Drawable underlying the surface. For a surface created for a Window (rather than a Pixmap), this function must be called each time the size of the window changes (for a subwindow, you are normally resiz...
python
def _get_md5(name, path): ''' Get the MD5 checksum of a file from a container ''' output = run_stdout(name, 'md5sum {0}'.format(pipes.quote(path)), ignore_retcode=True) try: return output.split()[0] except IndexError: # Destination ...
java
private CompiledForeachRangeArgs calculateRangeArgs(ForNode forNode, Scope scope) { RangeArgs rangeArgs = RangeArgs.createFromNode(forNode).get(); ForNonemptyNode nonEmptyNode = (ForNonemptyNode) forNode.getChild(0); ImmutableList.Builder<Statement> initStatements = ImmutableList.builder(); Expression s...
python
async def create_websocket(url: str, ssl: Optional[SSLContext] = None, headers: Optional[list] = None, subprotocols: Optional[list] = None): """ A more low-level form of open_websocket. You are responsible for closing this webs...
java
public DynamicType.Builder<T> transform(ElementMatcher<? super TypeDescription.Generic> matcher, Transformer<TypeVariableToken> transformer) { throw new UnsupportedOperationException("Cannot transform decorated type: " + instrumentedType); }
java
public static Iterator<MutableLongTuple> iterator( Order order, LongTuple min, LongTuple max) { if (order == null) { return null; } LongTuple localMin = LongTuples.copy(min); LongTuple localMax = LongTuples.copy(max); return new LongTupleI...
java
public void free() { m_MergeRecord = null; m_strLinkedRecord = null; m_FieldSeq = -1; if (m_vArray != null) { while (m_vArray.size() > 0) { ((InfoList)m_vArray.elementAt(0)).free(); m_vArray.removeElementAt(0); ...
python
def npy_to_numpy(npy_array): # type: (object) -> np.array """Convert an NPY array into numpy. Args: npy_array (npy array): to be converted to numpy array Returns: (np.array): converted numpy array. """ stream = BytesIO(npy_array) return np.load(stream, allow_pickle=True)
python
def get_avg_price_stat(self) -> Decimal: """ Calculates the statistical average price for the security, by averaging only the prices paid. Very simple first implementation. """ avg_price = Decimal(0) price_total = Decimal(0) price_count = 0 for account i...
java
@Override void remove(int n, int m) { size--; m1[n] = m2[m] = UNMAPPED; matrix.resetRows(n, -(n + 1)); }
python
def getattr(self, name, default: Any = _missing): """ Convenience method equivalent to ``deep_getattr(mcs_args.clsdict, mcs_args.bases, 'attr_name'[, default])`` """ return deep_getattr(self.clsdict, self.bases, name, default)
python
def _pop(self, command, *args, **kwargs): """ Shortcut for commands that pop a value from the field, returning it while removing it. The returned value will be deindexed """ result = self._traverse_command(command, *args, **kwargs) if self.indexable: s...
python
def _run_formula(self, variable, population, period): """ Find the ``variable`` formula for the given ``period`` if it exists, and apply it to ``population``. """ formula = variable.get_formula(period) if formula is None: return None if self.trace: ...
java
public void setup(@Observes EventContext<SetupContainer> setup) throws Exception { SetupContainer event = setup.getEvent(); if (isChameleonContainer(event)) { initiateChameleon(event); } setup.proceed(); }
python
def delete(self): """Delete the customer profile remotely and locally""" response = delete_profile(self.profile_id) response.raise_if_error() super(CustomerProfile, self).delete()
python
def sync(self): """Retrieve areas from ElkM1""" self.elk.send(cs_encode()) self.get_descriptions(TextDescriptions.OUTPUT.value)
python
def df_query(self, query, with_labels=False): """ Run a :mod:`sqlalchemy` query and return result as a :class:`pandas.DataFrame` Args: query (sqlalchemy.orm.query.Query): query object, usually generated by :func:`session.query()` in an :class:`sqlalchemy.orm.session...
python
def validate(self, profile): """Check to see if any args are "missing" from profile. Validate all args from install.json are in the profile. This can be helpful to validate that any new args added to App are included in the profiles. .. Note:: This method does not work with layout.jso...
java
public void serviceName_udp_farm_farmId_DELETE(String serviceName, Long farmId) throws IOException { String qPath = "/ipLoadbalancing/{serviceName}/udp/farm/{farmId}"; StringBuilder sb = path(qPath, serviceName, farmId); exec(qPath, "DELETE", sb.toString(), null); }
python
def expire(self, key, max_age, **opts): """Set the maximum age of a given key, in seconds.""" self.expire_at(key, time() + max_age, **opts)
java
private List<TaskTrackerStatus> getStatusesOnHost(String hostName) { List<TaskTrackerStatus> statuses = new ArrayList<TaskTrackerStatus>(); synchronized (taskTrackers) { for (TaskTracker tt : taskTrackers.values()) { TaskTrackerStatus status = tt.getStatus(); if (hostName.equals(status.get...
python
def resize(image, width=None, height=None, crop=False): """ Resize an image and return the resized file. """ # First normalize params to determine which file to get width, height, crop = _normalize_params(image, width, height, crop) try: # Check the image file state for clean close ...
java
@Override public List<CommerceNotificationTemplate> filterFindByGroupId(long groupId) { return filterFindByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
public void marshall(AttackVectorDescription attackVectorDescription, ProtocolMarshaller protocolMarshaller) { if (attackVectorDescription == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(attackVect...
python
def progress_indicator(self, fmt=None, interval=100, values=None): """ Creates a new progress indicator. """ return ProgressIndicator(self.io, fmt, interval, values)
python
def predictive_probability(self, M_c, X_L, X_D, Y, Q): """Calculate probability of cells jointly taking values given a latent state. :param Y: A list of constraints to apply when querying. Each constraint is a triplet of (r, d, v): r is the row index, d is the column in...
python
def decode(string): """Decode a raw base64 string, returning a bytes object. This function does not parse a full MIME header value encoded with base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high level email.header class for that functionality. """ if not string: return b...
python
def fetch_liked_datasets(self, **kwargs): """ List liked datasets Fetch datasets that the currently authenticated user likes. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked w...
java
protected String argumentTypeString(final Type type) { if (type instanceof ParameterizedType) { final ParameterizedType parameterizedType = (ParameterizedType) type; final List<String> subs = new ArrayList<>(); for (final Type actualType : parameterizedType.getActualTypeArgum...
java
public synchronized void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { registerOutParameter(findParameterIndex(parameterName), sqlType); }
java
@Override protected boolean doHandleRequest(final Request request) { handleExpandedState(request); Set<String> values = getRequestValue(request); Set<String> current = getValue(); boolean changed = !selectionsEqual(values, current); if (changed) { setData(values); } return changed; }
java
public static boolean isFullyTransparent(BufferedImage image) { boolean transparent = true; for (int x = 0; x < image.getWidth(); x++) { for (int y = 0; y < image.getHeight(); y++) { transparent = isTransparent(image, x, y); if (!transparent) { break; } } if (!transparent) { break; ...
java
public static final DoubleMatrix2D fillSubdiagonalSymmetricMatrix(DoubleMatrix2D S){ if(S.rows() != S.columns()){ throw new IllegalArgumentException("Not square matrix"); } boolean isSparse = S instanceof SparseDoubleMatrix2D; DoubleFactory2D F2D = (isSparse)? DoubleFactory2D.sparse: DoubleFactory2D...
java
public double trace() { double t = 0; for (int i = 0; i < Math.min(m, n); i++) { t += A[i][i]; } return t; }
java
public static <E> CloseableSpliterator<E> spliterator(CloseableIterator<? extends E> iterator, long size, int characteristics) { return new CloseableIteratorAsCloseableSpliterator<>(iterator, size, characteristics); }
java
protected JsonObjectBase buildGlobalError(String message, ErrorCode errorCode) { return JsonObjectUtils.buildGlobalError(message, errorCode); }
python
def update_record(self, **attrs): # The `_record` is to avoid conflicts with MutableMapping.update. """ Update the record, modifying any number of its attributes (except ``id``). ``update_record`` takes the same keyword arguments as :meth:`Domain.create_record`; pass in only tho...
python
def _pars_total_indexes(names, dims, fnames, pars): """Obtain all the indexes for parameters `pars` in the sequence of names. `names` references variables that are in column-major order Parameters ---------- names : sequence of str All the parameter names. dim : sequence of list of int...
java
@Override public <K,V> Map<K,V> getBigMap(String name, Class<K> keyClass, Class<V> valueClass, StorageEngine.MapType type, StorageEngine.StorageHint storageHint, boolean isConcurrent, boolean isTemporary) { assertConnectionOpen(); if(storageHint == StorageEngine.StorageHint.IN_MEMORY && sto...
python
def undo(self): """ Rewind the game to the previous state. """ self.undo_manager.undo() self.notify_observers() logging.debug('undo_manager undo stack={}'.format(self.undo_manager._undo_stack))
python
def _remove_rule(self, group, role, value=None): """Implementation detail""" if role not in group: return if value is None: group.pop(role, None) else: group[role].remove(value) self.invalidate()
java
public int read() throws IOException { int ch = in.read(); if (on && ch != -1) { digest.update((byte)ch); } return ch; }
java
public LinkVar getLinkVar(int parent, int child) { if (parent == -1) { return rootVars[child]; } else { return childVars[parent][child]; } }
python
def _is_running(self, tries=10): """ Return if the server is running according to pg_ctl. """ # We can't possibly be running if our base_pathname isn't defined. if not self.base_pathname: return False if tries < 1: raise ValueError('tries must be ...
python
def render_value(value): """Render a value, ensuring that any nested dicts are sorted by key.""" if isinstance(value, list): return '[' + ', '.join(render_value(v) for v in value) + ']' elif isinstance(value, dict): return ( '{' + ', '.join('{k!r}: {v}'.format( ...
java
public int degree(int vertex) { SparseWeightedDirectedTypedEdgeSet<T> edges = vertexToEdges.get(vertex); return (edges == null) ? 0 : edges.size(); }
java
protected Content getProfile(String profileName) { Content profileLinkContent; Content profileLabel; profileLabel = new StringContent(profileName); profileLinkContent = getHyperLink(DocPaths.profileFrame(profileName), profileLabel, "", "packageListFrame"); Con...
python
def create_subscription(self, url, events): """ Create subscription :param events: Events to subscribe :param url: Url to send events """ params = { 'url': url, 'events': events } url = self.SUBSCRIPTIONS_URL connection = ...
java
public static String renderPackage(final Class<?> type) { return PACKAGE_FORMATTER.abbreviate(type.isMemberClass() && !type.isAnonymousClass() ? type.getDeclaringClass().getName() : type.getPackage().getName()); }
java
public void addOverrideMap(Map<String, String> overrideMap) { if (sealed) { throw new IllegalStateException("Instance is sealed."); } for (Map.Entry<String, String> entry : overrideMap.entrySet()) { try { ParameterOverrideInfo info = new ParameterOverrideInfo(entry.getKey()); if ...
java
public boolean matchContent(Fingerprint fp) { for (Tag tag : CONTENT_TAGS) { if (!getTag(tag).equals(fp.getTag(tag))) { return false; } } return true; }
java
public final Ix<List<T>> bufferSplit(IxPredicate<? super T> predicate) { return new IxBufferSplit<T>(this, nullCheck(predicate, "predicate is null")); }
python
def wait_for_repo_creation(task_id, retry=30): """ Using polling check if the task finished """ success_event_types = ("RC_CREATION_SUCCESS", ) error_event_types = ("RC_REPO_CREATION_ERROR", "RC_REPO_CLONE_ERROR", "RC_CREATION_ERROR") while retry > 0: bpm_task = get_bpm_task_by_id(task_...
java
public static String stringFor(int n) { switch (n) { case CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM: return "CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM"; case CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM: return "CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM"; ...
python
def construct_payload(self, registration_ids, data=None, collapse_key=None, delay_while_idle=False, time_to_live=None, is_json=True, dry_run=False): """ Construct the dictionary mapping of parameters. Encodes the dictionary into JSON if for json requests. Helps ...
python
def replace_complexes(self, linked_stmts=None): """Remove Complex Statements that can be inferred out. This function iterates over self.statements and looks for Complex Statements that either match or are refined by inferred Complex Statements that were linked (provided as the linked_st...
java
public void setServiceIds(java.util.Collection<ServiceId> serviceIds) { if (serviceIds == null) { this.serviceIds = null; return; } this.serviceIds = new java.util.ArrayList<ServiceId>(serviceIds); }
java
public OvhOrder cdn_dedicated_serviceName_cacheRule_duration_POST(String serviceName, String duration, OvhOrderCacheRuleEnum cacheRule) throws IOException { String qPath = "/order/cdn/dedicated/{serviceName}/cacheRule/{duration}"; StringBuilder sb = path(qPath, serviceName, duration); HashMap<String, Object>o = n...
python
def dens_alum_nanocluster(coag): """Return the density of the aluminum in the nanocluster. This is useful for determining the volume of nanoclusters given a concentration of aluminum. """ density = (coag.PrecipDensity * MOLEC_WEIGHT_ALUMINUM * coag.PrecipAluminumMPM / coag.PrecipMole...
java
public CouchDB verifySSL(String yesOrNo) { if (yesOrNo == null || !"yes".equals(yesOrNo) || !"no".equals(yesOrNo)) { throw new IllegalArgumentException("The strings yes or no are the only valid options for the veirfy ssl " + "option"); } return setParam("verify_ss...
java
protected int getBufferSize(Dsn dsn) { return Util.parseInteger(Lookup.lookup(BUFFER_SIZE_OPTION, dsn), BUFFER_SIZE_DEFAULT); }