language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static Widget newShim (int width, int height) { Image shim = new Image(_rsrc.blank()); shim.setWidth(width + "px"); shim.setHeight(height + "px"); return shim; }
python
def displayable(obj): """ Predicate that returns whether the object is displayable or not (i.e whether the object obeys the nesting hierarchy """ if isinstance(obj, Overlay) and any(isinstance(o, (HoloMap, GridSpace)) for o in obj): return False if...
java
private Map<Task, Map<LogName, LogFileDetail>> getAllLogsFileDetails( final List<Task> allAttempts) throws IOException { Map<Task, Map<LogName, LogFileDetail>> taskLogFileDetails = new HashMap<Task, Map<LogName, LogFileDetail>>(); for (Task task : allAttempts) { Map<LogName, LogFileDetail> a...
java
private ApplicationException getApplicationException(Class<?> klass) // F743-14982 { ApplicationException result = null; if (ivApplicationExceptionMap != null) { result = ivApplicationExceptionMap.get(klass.getName()); if (TraceComponent.isAnyTracingEnabled() && tc.is...
java
@Override public void reset(final String counterName) { Preconditions.checkNotNull(counterName); try { // Update the Counter's Status in a New TX to the RESETTING_STATE and apply the TX. // The "new" TX ensures that no other thread nor parent transaction is performing this operation at the // same tim...
python
def from_dict(self, d): """ Create a Stage from a dictionary. The change is in inplace. :argument: python dictionary :return: None """ if 'uid' in d: if d['uid']: self._uid = d['uid'] if 'name' in d: if d['name']: ...
java
public ListS3ResourcesResult withS3Resources(S3ResourceClassification... s3Resources) { if (this.s3Resources == null) { setS3Resources(new java.util.ArrayList<S3ResourceClassification>(s3Resources.length)); } for (S3ResourceClassification ele : s3Resources) { this.s3Resou...
python
def put(self): """ Save changes made to the object to DocumentCloud. According to DocumentCloud's docs, edits are allowed for the following fields: * title * source * description * related_article * access * publis...
java
public static <T> Collection<T> plus(Collection<T> left, Collection<T> right) { final Collection<T> answer = cloneSimilarCollection(left, left.size() + right.size()); answer.addAll(right); return answer; }
java
public Headers getHttpHeaders() { Headers headers = new Headers(); if ( byteRange != null ) { StringBuilder rangeBuilder = new StringBuilder( "bytes=" ); long start; if ( byteRange.offset >= 0 ) { rangeBuilder.append( byteRange.offset ); ...
python
def remove_team_membership(self, auth, team_id, username): """ Remove user from team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str username: Username of the user to be removed from the team :raises N...
java
public Set<MongoNamespace> getSynchronizedNamespaces() { instanceLock.readLock().lock(); try { return new HashSet<>(namespaces.keySet()); } finally { instanceLock.readLock().unlock(); } }
java
private ShareTarget findShareTarget(String pkg) { for (ShareTarget target : mShareTargets) { if (pkg.equals(target.packageName)) { return target; } } return null; }
java
private ProjectFile readDatabaseFile(InputStream inputStream) throws MPXJException { ProjectReader reader = new AstaDatabaseFileReader(); addListeners(reader); return reader.read(inputStream); }
java
public static <T> Predicate<T> or(Predicate<? super T> first, Predicate<? super T> second) { checkArgNotNull(first, "first"); checkArgNotNull(second, "second"); return new OrPredicate<T>(ImmutableList.<Predicate<? super T>>of(first, second)); }
python
def apply_trend_constraint(self, limit, dt, distribution_skip=False, **kwargs): """ Constrains change in RV to be less than limit over time dt. Only works if ``dRV`` and ``Plong`` attributes are defined for population. :param limit: Ra...
java
@Override public List<Integer> getReplicatingPartitionList(int index) { List<Node> preferenceNodesList = new ArrayList<Node>(getNumReplicas()); List<Integer> replicationPartitionsList = new ArrayList<Integer>(getNumReplicas()); // Copy Zone based Replication Factor HashMap<Integer, ...
python
def QA_util_realtime(strtime, client): """ 查询数据库中的数据 :param strtime: strtime str字符串 -- 1999-12-11 这种格式 :param client: client pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取 :return: Dictionary -- {'time_real': 时间,'id': id} """...
java
@XmlElementDecl(namespace = "http://www.opengis.net/citygml/texturedsurface/2.0", name = "Material", substitutionHeadNamespace = "http://www.opengis.net/citygml/texturedsurface/2.0", substitutionHeadName = "_Appearance") public JAXBElement<MaterialType> createMaterial(MaterialType value) { return new JAXBEl...
python
def _serialize_value(self, value): """ Called by :py:meth:`._serialize` to serialise an individual value. """ if isinstance(value, (list, tuple, set)): return [self._serialize_value(v) for v in value] elif isinstance(value, dict): return dict([(k, self._se...
java
@Override public void set(long timestampMs, long value) { long[] bucket = calcBucketOffset(timestampMs); String redisKey = getName() + ":" + bucket[0]; String redisField = String.valueOf(bucket[1]); try (Jedis jedis = getJedis()) { jedis.hset(redisKey, redisField, String....
python
def mchirp_sampler_imf(**kwargs): ''' Draw chirp mass samples for power-law model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- mchirp-astro: array The chirp mass samples for ...
java
@Override public void pin(Object key) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "pin", key); Bucket bucket = getOrCreateBucketForKey(key); // d739870 int pinCount; synchronized (bucket) { Element element = bucket.fin...
java
public synchronized ServletStats initServletStats(String _app, String _ser) { String _key = _app + "." + _ser; ServletStats nStats = this.servletCountByName.get(_key); if (nStats == null) { nStats = new ServletStats(_app, _ser); this.servletCountByName.put(_key, nStats);...
python
def randmatrix(m, n, random_seed=None): """Creates an m x n matrix of random values drawn using the Xavier Glorot method.""" val = np.sqrt(6.0 / (m + n)) np.random.seed(random_seed) return np.random.uniform(-val, val, size=(m, n))
python
def write_as_dot(self, f, data=None, max_levels=None): "Write the tree in the dot language format to f." assert (max_levels is None) or (max_levels >= 0) def visit_node(n, levels): lbl = "{" if data is None: if self.k <= max_k_labeled: ...
java
@Override public Iterator<T> iterator() { Iterator<T> transformed = Iterators.transform(rows.iterator(), row -> { T value = mapper.map(row); mapper.mappingComplete(); return value; }); mapper.mappingComplete(); return transformed; }
python
def get_random_word(dictionary, starting_letter=None): """ Takes the dictionary to read from and returns a random word optionally accepts a starting letter """ if starting_letter is None: starting_letter = random.choice(list(dictionary.keys())) try: to_return = random.choice(dic...
java
public static void setValue(Object target, String dPath, Object value) { setValue(target, dPath, value, false); }
java
private com.ibm.ws.javaee.ddmodel.webext.WebExtComponentImpl getConfigOverrides( OverlayContainer overlay, ArtifactContainer artifactContainer) throws UnableToAdaptException { // No match is possible, and no errors are possible, when there are no // web extension configuration overrides...
java
public Effort createEffort(double value, Map<String, Object> attributes) { return createEffort(value, null, null, attributes); }
python
def rgb2bgr(self): """ Converts data using the cv conversion. """ new_data = cv2.cvtColor(self.raw_data, cv2.COLOR_RGB2BGR) return ColorImage(new_data, frame=self.frame, encoding='bgr8')
python
def cancel(self): """ Cancels the current lookup. """ if self._running: self.interrupt() self._running = False self._cancelled = True self.loadingFinished.emit()
python
def append_manage_data_op(self, data_name, data_value, source=None): """Append a :class:`ManageData <stellar_base.operation.ManageData>` operation to the list of operations. :param str data_name: String up to 64 bytes long. If this is a new Name it will add the given name/value pair...
java
@Override public RoundedMoney subtract(MonetaryAmount subtrahend) { MoneyUtils.checkAmountParameter(subtrahend, currency); if (subtrahend.isZero()) { return this; } MathContext mc = monetaryContext.get(MathContext.class); if(mc==null){ mc = MathContext...
python
def print_debug(self, msg): """Log some debugging information to the console""" assert isinstance(msg, bytes) state = STATE_NAMES[self.state].encode() console_output(b'[dbg] ' + self.display_name.encode() + b'[' + state + b']: ' + msg + b'\n')
python
def genExamplePlanet(binaryLetter=''): """ Creates a fake planet with some defaults :param `binaryLetter`: host star is part of a binary with letter binaryletter :return: """ planetPar = PlanetParameters() planetPar.addParam('discoverymethod', 'transit') planetPar.addParam('discoveryyear', ...
java
public boolean execute(GString gstring) throws SQLException { List<Object> params = getParameters(gstring); String sql = asSql(gstring, params); return execute(sql, params); }
java
private static int parseServiceUuid(byte[] scanRecord, int currentPos, int dataLength, int uuidLength, List<ParcelUuid> serviceUuids) { while (dataLength > 0) { byte[] uuidBytes = extractBytes(scanRecord, currentPos, uuidLength); ...
python
def postprocess_keyevent(self, event): """Post-process keypress event: in InternalShell, this is method is called when shell is ready""" event, text, key, ctrl, shift = restore_keyevent(event) # Is cursor on the last line? and after prompt? if len(text): ...
python
def compare(cls, left, right): """ Main comparison function for all Firestore types. @return -1 is left < right, 0 if left == right, otherwise 1 """ # First compare the types. leftType = TypeOrder.from_value(left).value rightType = TypeOrder.from_value(right).valu...
java
@Deprecated public Object saveView(FacesContext context) { Object stateArray[] = null; if (!context.getAttributes().containsKey(IS_CALLED_FROM_API_CLASS)) { SerializedView view = saveSerializedView(context); if (null != view) { stateArray = new Object[]{view....
java
public static <E> String generateQuestion(Collection<E> args) { if (args == null || args.size() == 0) return ""; return generateInternal(args.size()); }
python
def ratio_deep_compare(self, other, settings): """ Compares each field of the name one at a time to see if they match. Each name field has context-specific comparison logic. :param Name other: other Name for comparison :return int: sequence ratio match (out of 100) """ ...
python
def _check_fill_title_row(self, row_index): ''' Checks the given row to see if it is all titles and fills any blanks cells if that is the case. ''' table_row = self.table[row_index] # Determine if the whole row is titles prior_row = self.table[row_index-1] if row_...
python
def organisation_group_id(self): """ str: Organisation Group ID """ self._validate() self._validate_for_organisation_group_id() parts = [] parts.append(self.election_type) if self.subtype: parts.append(self.subtype) parts.append(self.o...
python
def dataframe_select(df, *cols, **filters): ''' dataframe_select(df, k1=v1, k2=v2...) yields df after selecting all the columns in which the given keys (k1, k2, etc.) have been selected such that the associated columns in the dataframe contain only the rows whose cells match the given values. da...
java
public static void jenkins(final BitVector bv, final long seed, final long[] h) { final long length = bv.length(); long a, b, c, from = 0; if (length == 0) { h[0] = seed ^ 0x8de6a918d6538324L; h[1] = seed ^ 0x6bda2aef21654e7dL; h[2] = seed ^ 0x36071e726d0ba0c5L; return; } /* Set up the internal ...
python
def all(): """clean the dis and uninstall cloudmesh""" dir() cmd3() banner("CLEAN PREVIOUS CLOUDMESH INSTALLS") r = int(local("pip freeze |fgrep cloudmesh | wc -l", capture=True)) while r > 0: local('echo "y\n" | pip uninstall cloudmesh') r = int(local("pip freeze |fgrep cloudmes...
python
def _add_edge_dmap_fun(graph, edges_weights=None): """ Adds edge to the dispatcher map. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :param edges_weights: Edge weights. :type edges_weights: dict, optional :return: A function that ad...
java
public void unreferenceSSTables() { Set<SSTableReader> notCompacting; View currentView, newView; do { currentView = view.get(); notCompacting = currentView.nonCompactingSStables(); newView = currentView.replace(notCompacting, Collections.<SSTableR...
java
Symbol findImmediateMemberType(Env<AttrContext> env, Type site, Name name, TypeSymbol c) { Scope.Entry e = c.members().lookup(name); while (e.scope != null) { if (e.sym.kind == TYP) { ...
java
public static boolean checkCharacter(int c, boolean foundQuestionMark) throws IOException { if(foundQuestionMark) { switch(c) { case '.': case '-': case '*': case '_': case '+': // converted space case '%': // encoded value // Other characters used outside the URL data //case ':': ...
java
private final int getBlockIndexForPosition(final BlockLocation[] blocks, final long offset, final long halfSplitSize, final int startIndex) { // go over all indexes after the startIndex for (int i = startIndex; i < blocks.length; i++) { long blockStart = blocks[i].getOffset(); long blockEnd = blockStart...
python
def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :r...
python
async def vcx_agent_provision(config: str) -> None: """ Provision an agent in the agency, populate configuration and wallet for this agent. Example: import json enterprise_config = { 'agency_url': 'http://localhost:8080', 'agency_did': 'VsKV7grR1BUE29mG2Fm2kX', 'agency_verkey...
python
def Hooper2K(Di, Re, name=None, K1=None, Kinfty=None): r'''Returns loss coefficient for any various fittings, depending on the name input. Alternatively, the Hooper constants K1, Kinfty may be provided and used instead. Source of data is [1]_. Reviews of this model are favorable less favorable than the ...
python
def click_action(self): """|ActionSetting| instance providing access to click behaviors. Click behaviors are hyperlink-like behaviors including jumping to a hyperlink (web page) or to another slide in the presentation. The click action is that defined on the overall shape, not a run of ...
java
public Matrix4f lookAtLH(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ, Matrix4f dest) { if ((properties & PROPERTY_IDENTITY) != 0) return dest.setLookAtLH(eyeX, eyeY, eyeZ, c...
java
public CommandLine parse(Options options, String[] arguments, Properties properties, boolean stopAtNonOption) throws ParseException { this.options = options; this.stopAtNonOption = stopAtNonOption; skipParsing = false; currentOption = null; expectedOpts = new Arra...
java
@Override public void close(final URI uri, final ClassLoader classLoader) { if (uri == null || classLoader == null) { throw new NullPointerException(); } synchronized (cacheManagers) { final ConcurrentMap<URI, Eh107CacheManager> map = cacheManagers.get(classLoader); if (map != null) { ...
python
def getColumnsByName(elem, name): """ Return a list of Column elements named name under elem. The name comparison is done with CompareColumnNames(). """ name = StripColumnName(name) return elem.getElements(lambda e: (e.tagName == ligolw.Column.tagName) and (e.Name == name))
java
protected final BufferedImage create_LED_Image(final int SIZE, final int STATE, final LedColor LED_COLOR) { return LED_FACTORY.create_LED_Image(SIZE, STATE, LED_COLOR, model.getCustomLedColor()); }
python
def create(self, unique_name, friendly_name=values.unset, actions=values.unset, actions_url=values.unset): """ Create a new TaskInstance :param unicode unique_name: An application-defined string that uniquely identifies the resource :param unicode friendly_name: descript...
python
def _transform_data(self, X): """Binarize the data for each column separately.""" if self._binarizers == []: raise NotFittedError() if self.binarize is not None: X = binarize(X, threshold=self.binarize) if len(self._binarizers) != X.shape[1]: raise ...
python
def get_default_config(self): """ Returns the default collector settings """ config = super(SidekiqCollector, self).get_default_config() config.update({ 'path': 'sidekiq', 'host': 'localhost', 'ports': '6379', 'password': None, ...
java
public com.google.api.ads.adwords.axis.v201809.cm.ConversionOptimizerEligibility getConversionOptimizerEligibility() { return conversionOptimizerEligibility; }
java
public String getParameterName(Parameter parameter) { Name annotation = parameter.getAnnotation(Name.class); if (null == annotation) { return parameter.getName(); } return annotation.value(); }
java
private boolean topicImplicity(final String topic, final String[] splitTopic) { try { return topicMatcher.matches(stripedTopic, this.splitTopic, nonWildCard, endsWithWildCard, rootWildCard, topic, splitTopic); } catch (InvalidTopicException e) { return false; } }
python
def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 conf, nesting_key=None): ''' Get pillar data from Vault for the configuration ``conf``. ''' comps = conf.split() paths = [comp for comp in comps if comp.startswith('path=...
python
def serialize(self, config): """ :param config: :type config: yowsup.config.base.config.Config :return: :rtype: bytes """ for transform in self._transforms: config = transform.transform(config) return config
java
public SerializationObject getSerializationObject() { SerializationObject object; synchronized (ivListOfObjects) { if (ivListOfObjects.isEmpty()) { object = createNewObject(); } else { object = ivListOfObjects.remove(ivListOfObjects.size() - 1); } } return object; }
java
public int read() throws IOException { int c; if (mFirst != 0) { c = mFirst; mFirst = 0; } else { c = super.read(); } if (c == '\n') { mLine++; } else if (c == ENTER_CODE) { mUnicodeReader.setEs...
java
@NotNull public static String getStoreSku(@NotNull final String appStoreName, @NotNull String sku) { return SkuManager.getInstance().getStoreSku(appStoreName, sku); }
python
def _get_argument(self, argument_node): """ Returns a FritzActionArgument instance for the given argument_node. """ argument = FritzActionArgument() argument.name = argument_node.find(self.nodename('name')).text argument.direction = argument_node.find(self.nodename('direc...
java
public static void readable(final String path, final String message) throws IllegalArgumentException { notNullOrEmpty(path, message); readable(new File(path), message); }
java
public ResourcePendingMaintenanceActions withPendingMaintenanceActionDetails(PendingMaintenanceAction... pendingMaintenanceActionDetails) { if (this.pendingMaintenanceActionDetails == null) { setPendingMaintenanceActionDetails(new com.amazonaws.internal.SdkInternalList<PendingMaintenanceAction>(pend...
java
public static void main(String[] args) throws FileNotFoundException, IOException { InputStream codeStream = FeatureCodeBuilder.class.getClassLoader().getResourceAsStream("featureCodes_en.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(codeStream, Charset.forName("UTF-8"))); /...
java
private int[] map(int u, int v, int[] us, int[] mapping) { for (int i = 0; i < us.length; i++) us[i] = mapping[us[i]]; return us; }
java
protected void addDescription(PackageDoc pkg, Content dlTree, SearchIndexItem si) { Content link = getPackageLink(pkg, new StringContent(utils.getPackageName(pkg))); si.setLabel(utils.getPackageName(pkg)); si.setCategory(getResource("doclet.Packages").toString()); Content dt = HtmlTree.D...
java
public static <T> T objectFromClause(Class<T> type, String clause, Object... args) { return SqlClosure.sqlExecute(c -> OrmElf.objectFromClause(c, type, clause, args)); }
java
@BetaApi( "The surface for long-running operations is not stable yet and may change in the future.") public final OperationFuture<Instruction, CreateInstructionMetadata> createInstructionAsync( CreateInstructionRequest request) { return createInstructionOperationCallable().futureCall(request); }
python
def _ModifiedDecoder(wire_type, decode_value, modify_value): """Like SimpleDecoder but additionally invokes modify_value on every value before storing it. Usually modify_value is ZigZagDecode. """ # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but # not enough to make a significan...
python
def _get_batch_name(sample): """Retrieve batch name for use in SV calling outputs. Handles multiple batches split via SV calling. """ batch = dd.get_batch(sample) or dd.get_sample_name(sample) if isinstance(batch, (list, tuple)) and len(batch) > 1: batch = dd.get_sample_name(sample) ret...
java
public boolean hasNext() { if (tc.isEntryEnabled()) SibTr.entry(this, tc, "hasNext"); if (tc.isEntryEnabled()) SibTr.exit(this, tc, "hasNext", ""+transmissionsRemaining); return transmissionsRemaining; }
python
def thread_safe_client(client, lock=None): """Create a thread-safe proxy which locks every method call for the given client. Args: client: the client object to be guarded. lock: the lock object that will be used to lock client's methods. If None, a new lock will be used. Re...
java
public static int getDefaultFlags ( CIFSContext tc ) { return NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_VERSION | ( tc.getConfig().isUseUnicode() ? NTLMSSP_NEGOTIATE_UNICODE : NTLMSSP_NEGOTIATE_OEM ); }
python
def cube2matrix(data_cube): r"""Cube to Matrix This method transforms a 3D cube to a 2D matrix Parameters ---------- data_cube : np.ndarray Input data cube, 3D array Returns ------- np.ndarray 2D matrix Examples -------- >>> from modopt.base.transform import cube2...
java
public static TypeAnnotationPosition resourceVariable(final List<TypePathEntry> location, final JCLambda onLambda, final int pos) { return new TypeAnnotationPosition(TargetType.RESOURCE_VARIABLE, pos, Integer.MIN...
python
def get_session_data( username, password_verifier, salt, client_public, private, preset): """Print out server session data.""" session = SRPServerSession( SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private) session.process(client_pub...
java
@Override public void correctDataTypes(DAO[] daoList, ModelDef model) { for(DAO dao : daoList){ correctDataTypes(dao, model); } }
python
def _set_dac_value(self, channel, value): '''Write DAC ''' # DAC value cannot be -128 if value == -128: value = -127 if value < 0: sign = 1 else: sign = 0 value = (sign << 7) | (0x7F & abs(value)) self._intf.write(self._...
java
@Override public Object processResponse(Object rawResponse) throws ServiceException { PipelineHelpers.throwIfNotSuccess((ClientResponse) rawResponse); return rawResponse; }
python
def run_script(pycode): """Run the Python in `pycode`, and return a dict of the resulting globals.""" # Fix up the whitespace in pycode. if pycode[0] == "\n": pycode = pycode[1:] pycode.rstrip() pycode = textwrap.dedent(pycode) # execute it. globs = {} six.exec_(pycode, globs, g...
python
def get(self, copy=False): """Return the value of the attribute""" array = getattr(self.owner, self.name) if copy: return array.copy() else: return array
java
public static void leaveSafeBlock() { if (!inSafe) { return; } GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glPopMatrix(); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPopMatrix(); GL11.glPopClientAttrib(); GL11.glPopAttrib(); if (lastUsed != null) { lastUsed.bind(); } else...
java
private void runFileFormatValidation() throws IOException { Preconditions.checkArgument(this.props.containsKey(VALIDATION_FILE_FORMAT_KEY)); this.configStoreUri = StringUtils.isNotBlank(this.props.getProperty(ConfigurationKeys.CONFIG_MANAGEMENT_STORE_URI)) ? Optional.of( this.props.getPrope...
java
protected ModificationHistory getModificationHistory(Type type) { ModificationHistory history = new ModificationHistory(); ClassDoc classDoc = this.wrDoc.getConfiguration().root.classNamed(type.qualifiedTypeName()); if (classDoc != null) { LinkedList<ModificationRecord> list = this.getModificationRecords(class...
python
def toggle_concatenate(self): """Enable and disable concatenation options.""" if not (self.chunk['epoch'].isChecked() and self.lock_to_staging.get_value()): for i,j in zip([self.idx_chan, self.idx_cycle, self.idx_stage, self.idx_evt_type], ...
python
def dInd_calc(TNR, TPR): """ Calculate dInd (Distance index). :param TNR: specificity or true negative rate :type TNR : float :param TPR: sensitivity, recall, hit rate, or true positive rate :type TPR : float :return: dInd as float """ try: result = math.sqrt(((1 - TNR)**2) ...