language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def cancelMatchRequest(cfg): """obtain information housed on the ladder about playerName""" payload = json.dumps([cfg.thePlayer]) ladder = cfg.ladder return requests.post( url = c.URL_BASE%(ladder.ipAddress, ladder.serverPort, "cancelmatch"), data = payload, #headers=headers, ...
python
def update_message(self, queue_name, message_id, pop_receipt, visibility_timeout, content=None, timeout=None): ''' Updates the visibility timeout of a message. You can also use this operation to update the contents of a message. This operation can be used to cont...
python
def add(self,dimlist,dimvalues): ''' add dimensions :parameter dimlist: list of dimensions :parameter dimvalues: list of values for dimlist ''' for i,d in enumerate(dimlist): self[d] = dimvalues[i] self.set_ndims()
java
public void setUnprocessedResourceIdentifiers(java.util.Collection<AggregateResourceIdentifier> unprocessedResourceIdentifiers) { if (unprocessedResourceIdentifiers == null) { this.unprocessedResourceIdentifiers = null; return; } this.unprocessedResourceIdentifiers = new...
java
public Observable<ConnectionInner> getAsync(String resourceGroupName, String automationAccountName, String connectionName) { return getWithServiceResponseAsync(resourceGroupName, automationAccountName, connectionName).map(new Func1<ServiceResponse<ConnectionInner>, ConnectionInner>() { @Override ...
python
def ServiceAccountCredentialsFromFile(filename, scopes, user_agent=None): """Use the credentials in filename to create a token for scopes.""" filename = os.path.expanduser(filename) # We have two options, based on our version of oauth2client. if oauth2client.__version__ > '1.5.2': # oauth2client...
python
def shorten_name(name, char_limit, side='right'): """Shorten `name` if it is longer than `char_limit`. If `side` == "right" then the right side of the name is shortened; if "left" then the left side is shortened. In either case, the suffix of the name is preserved. """ # TODO: A more elegant way...
python
def _get_local_fields(self, model): "Return the names of all locally defined fields on the model class." local = [f for f in model._meta.fields] m2m = [f for f in model._meta.many_to_many] fields = local + m2m names = tuple([x.name for x in fields]) return { ...
java
protected String getRelativePath(final HttpServletRequest request) { // IMPORTANT: DefaultServlet can be mapped to '/' or '/path/*' but // always // serves resources from the web app root with context rooted paths. // i.e. it can not be used to mount the web app root under a sub-path // This method must const...
java
public static <T> List<T> resultSetToList(final ResultSet resultSet, final Class<T> targetClass) throws SQLException { final List<T> list = new ArrayList<>(); if (!resultSet.next()) { resultSet.close(); return list; } final Introspected introspected = Introspector.getIntros...
python
def on_startup(self, callback: callable, polling=True, webhook=True): """ Register a callback for the startup process :param callback: :param polling: use with polling :param webhook: use with webhook """ self._check_frozen() if not webhook and not pollin...
java
public int fasthdlc_rx_run(HdlcState h) { int next; int retval = RETURN_EMPTY_FLAG; while ((h.bits >= minbits[h.state]) && (retval == RETURN_EMPTY_FLAG)) { /* * Run until we can no longer be assured that we will have enough bits to continue */ sw...
java
public static Description createSuiteDescription(Class<?> testClass) { return new Description(testClass, testClass.getName(), testClass.getAnnotations()); }
java
public static Builder newParserConfigBuilder() { return new Builder() { boolean used = false; CollectionBuilder.Factory listFactory = DEFAULT_LIST_FACTORY; CollectionBuilder.Factory vectorFactory = DEFAULT_VECTOR_FACTORY; CollectionBuilder.Factory setFactory = DEF...
java
private void removeVetoedClasses(Set<Class<?>> classes) { //get hold of classnames Set<String> classNames = new HashSet<String>(); for (Class<?> clazz : classes) { classNames.add(clazz.getName()); } // take into considerations of the exclude in beans.xml Colle...
java
protected void checkUnboundPrefixInEntRef(Node node) { Node child, next; for (child = node.getFirstChild(); child != null; child = next) { next = child.getNextSibling(); if (child.getNodeType() == Node.ELEMENT_NODE) { //If a NamespaceURI is not declared for the ...
python
def create_code_cell(block): """Create a notebook code cell from a block.""" code_cell = nbbase.new_code_cell(source=block['content']) attr = block['attributes'] if not attr.is_empty: code_cell.metadata \ = nbbase.NotebookNode({'attributes': attr.to_dict()}) ...
java
public OMVRBTreeEntry<K, V> getPreviousInMemory() { OMVRBTreeEntry<K, V> t = this; OMVRBTreeEntry<K, V> p = null; if (t.getLeftInMemory() != null) { p = t.getLeftInMemory(); while (p.getRightInMemory() != null) p = p.getRightInMemory(); } else { p = t.getParentInMemor...
java
@When("^I create an elasticsearch index named '(.+?)'( removing existing index if exist)?$") public void createElasticsearchIndex(String index, String removeIndex) { if (removeIndex != null && commonspec.getElasticSearchClient().indexExists(index)) { commonspec.getElasticSearchClient().dropSingl...
java
public void setValue(CharSequence value) { Validate.notNull(value); setValue(value, 0, value.length()); }
python
def pyxb_to_dict(rp_pyxb): """Convert ReplicationPolicy PyXB object to a normalized dict. Args: rp_pyxb: ReplicationPolicy to convert. Returns: dict : Replication Policy as normalized dict. Example:: { 'allowed': True, 'num': 3, 'blockedMemberNode': {'urn:...
python
def get_portchannel_info_by_intf_output_lacp_partner_brcd_state(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf") config = get_portchannel_info_by_intf output = ET.SubElement...
python
def _search(self, base, fltr, attrs=None, scope=ldap.SCOPE_SUBTREE): """Perform LDAP search""" try: results = self._conn.search_s(base, scope, fltr, attrs) except Exception as e: log.exception(self._get_ldap_msg(e)) results = False return results
java
private void removeParentPropertyChangeListener(PropertyChangeListener listener) { if (rootParent instanceof JFrame) { ((JFrame) rootParent).removePropertyChangeListener(listener); } else if (rootParent instanceof JDialog) { ((JDialog) rootParent).removePropertyChangeListener...
python
def ystep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`. If this method is not overridden, the problem is solved without any regularisation other than the option enforcement of non-negativity of the solution and filter boundary crossing supression. W...
java
public Datatype.Builder setHasToBuilderMethod(boolean hasToBuilderMethod) { this.hasToBuilderMethod = hasToBuilderMethod; _unsetProperties.remove(Property.HAS_TO_BUILDER_METHOD); return (Datatype.Builder) this; }
java
private void autoDetectAnimatedGroups() { animatedShapes = model.getAnimatedShapes(); staticShapes = model.getShapeNames().stream().filter(s -> !animatedShapes.contains(s)).collect(Collectors.toSet()); //Debug: all animated // animatedShapes.addAll(staticShapes); // staticShapes.clear(); }
python
def get_cpuid_leaf(self, idx, idx_sub): """Returns the virtual CPU cpuid information for the specified leaf. Currently supported index values for cpuid: Standard CPUID leaves: 0 - 0x1f Extended CPUID leaves: 0x80000000 - 0x8000001f VIA CPUID leaves: 0xc0000000 - 0xc...
java
@Override public String resolveVariant(HttpServletRequest request) { String browser = null; String userAgent = request.getHeader("User-Agent"); if (userAgent != null) { Matcher matcher = IE_PATTERN.matcher(userAgent); if (matcher.find()) { browser = "ie" + matcher.group(1); } else if (userAgent.con...
java
public List<FacesConfigConverterType<FacesConfigType<T>>> getAllConverter() { List<FacesConfigConverterType<FacesConfigType<T>>> list = new ArrayList<FacesConfigConverterType<FacesConfigType<T>>>(); List<Node> nodeList = childNode.get("converter"); for(Node node: nodeList) { FacesCon...
java
public Evaluator sync(Map<String, List<Subscription>> subs) { Set<String> removed = subscriptions.keySet(); removed.removeAll(subs.keySet()); removed.forEach(this::removeGroupSubscriptions); subs.forEach(this::addGroupSubscriptions); return this; }
python
def y(self, y): """Project reversed y""" if y is None: return None return (self.height * (y - self.box.ymin) / self.box.height)
java
public void project_serviceName_storage_containerId_cors_DELETE(String serviceName, String containerId, String origin) throws IOException { String qPath = "/cloud/project/{serviceName}/storage/{containerId}/cors"; StringBuilder sb = path(qPath, serviceName, containerId); query(sb, "origin", origin); exec(qPath,...
java
public static void validBigTextLength(String pContent) throws APPErrorException { if(!StringUtil.isNullOrEmpty(pContent)&&pContent.length()>10000) { throw new APPErrorException("内容长度超过10000,请调整;"); } }
java
static public final String formatForSource(String s) { StringBuilder buffer = new StringBuilder(); for (int i=0; i<s.length();) { if (i > 0) buffer.append('+').append(LINE_SEPARATOR); buffer.append(" \""); int count = 11; while (i<s.length() && coun...
java
private void initializePasswordEditText() { passwordEditText = (PasswordEditText) findViewById(R.id.password_edit_text); passwordEditText.addValidator(Validators .minLength(this, R.string.password_min_length_validator_error_message, MIN_PASSWORD_LENGTH)); ...
python
def interface_to_relations(interface_name): """ Given an interface, return a list of relation names for the current charm that use that interface. :returns: A list of relation names. """ results = [] for role in ('provides', 'requires', 'peers'): results.extend(role_and_interface_to...
python
def setOutBoundLinkQuality(self, LinkQuality): """set custom LinkQualityIn for all receiving messages from the any address Args: LinkQuality: a given custom link quality link quality/link margin mapping table 3: 21 - 255 (dB) ...
python
def mygenerator(n=5, n_edges=5): ''' Just a simple generator that creates a network with n nodes and n_edges edges. Edges are assigned randomly, only avoiding self loops. ''' G = nx.Graph() for i in range(n): G.add_node(i) for i in range(n_edges): nodes = list(G.nodes) ...
java
public EnableEnhancedMonitoringResult withCurrentShardLevelMetrics(MetricsName... currentShardLevelMetrics) { com.amazonaws.internal.SdkInternalList<String> currentShardLevelMetricsCopy = new com.amazonaws.internal.SdkInternalList<String>( currentShardLevelMetrics.length); for (MetricsNa...
java
private static void setField(Object object, Object value, Field foundField) { foundField.setAccessible(true); try { int fieldModifiersMask = foundField.getModifiers(); removeFinalModifierIfPresent(foundField); foundField.set(object, value); restoreModifier...
python
def edit_user_login(self, id, account_id, login_integration_id=None, login_password=None, login_sis_user_id=None, login_unique_id=None): """ Edit a user login. Update an existing login for a user in the given account. """ path = {} data = {} params = {} ...
python
def schema(body_schema=None, body_required=False, query_schema=None, # noqa content_types=None, default_body=None): """Decorator to parse and validate API body and query string. This decorator allows one to define the entire 'schema' for an API endpoint. :keyword body_schema: Calla...
java
public void insertAll(List<E> entries) { if(!initialized && !entries.isEmpty()) { initialize(entries.get(0)); } for(E entry : entries) { insert(entry, false); } }
python
def load_genotypes(self): """This really just intializes the file by opening it up. """ if DataParser.compressed_pedigree: self.genotype_file = gzip.open("%s.gz" % self.tped_file, 'rb') else: self.genotype_file = open(self.tped_file) self.filter_missing()
java
public static <N extends Number> Number average(List<N> numberList) { return cal(numberList, DoubleStream::average); }
python
def _set_least_batch_id(self, txn_signature): """Set the first batch id that doesn't have all results. Args: txn_signature (str): The txn identifier of the transaction with results being set. """ batch = self._batches_by_txn_id[txn_signature] least...
java
protected void setProjectEnabled(boolean selection) { // chkEnableFindBugs.setEnabled(selection); // chkRunAtFullBuild.setEnabled(selection && // chkEnableFindBugs.getSelection()); if (enableProjectCheck != null) { // this link should always be enabled //workspace...
java
@SuppressWarnings("deprecation") public Element toElement(final ElasticSearchDatastore datastore) { final Element ds = getDocument().createElement("elasticsearch-datastore"); ds.setAttribute("name", datastore.getName()); if (!Strings.isNullOrEmpty(datastore.getDescription())) { d...
java
public SampleSetEQOracle<I, D> add(Word<I> input, D expectedOutput) { testQueries.add(new DefaultQuery<>(input, expectedOutput)); return this; }
python
def touch_multi(self, keys, ttl=0): """Touch multiple keys. Multi variant of :meth:`touch` :param keys: the keys to touch :type keys: :ref:`iterable<argtypes>`. ``keys`` can also be a dictionary with values being integers, in which case the value for each key will be use...
java
CompletableFuture<Boolean> actualRemoveMaxIdleExpireEntry(K key, V value, long maxIdle, boolean skipLocking) { CompletableFuture<Boolean> completableFuture = new CompletableFuture<>(); Object expiringObject = expiring.putIfAbsent(key, completableFuture); if (expiringObject == null) { if (trac...
java
protected List<ISource> locate(ConfigurationWrapper configuration) { if(configuration == null) { throw new IllegalArgumentException("A non-null Configuration annotation must be provided"); } // create resolver from configuration annotation's resolver element ResolverWrapper resolverWrapper = configur...
python
def select_module(self, module_id): ''' Select module and give access to the module. ''' if not isinstance(module_id, basestring) and isinstance(module_id, Iterable) and set(module_id) - set(self._modules): raise ValueError('Module IDs invalid:' % ", ".join(set(module_id) - set(self....
java
public static int computeObjectSizeNoTag(Object o) { int size = 0; if (o == null) { return size; } Class cls = o.getClass(); Codec target = ProtobufProxy.create(cls); try { size = target.size(o); size = size + CodedOutputStre...
python
def WriteEventBody(self, event): """Writes the body of an event object to the output. Args: event (EventObject): event. """ if not hasattr(event, 'timestamp'): return row = self._GetSanitizedEventValues(event) try: self._cursor.execute(self._INSERT_QUERY, row) except MySQ...
java
private boolean isValidH2Request(HashMap<String, String> pseudoHeaders) { if (MethodValues.CONNECT.getName().equals(pseudoHeaders.get(HpackConstants.METHOD))) { if (pseudoHeaders.get(HpackConstants.PATH) == null && pseudoHeaders.get(HpackConstants.SCHEME) == null && pseudoHeaders.get...
java
@Override public Short unmarshal(String object) { return Short.valueOf(Short.parseShort(object)); }
java
public Object replace(CacheKey key, Object value) { return parentCache.replace(key, value); }
java
public void initializeStringTable() { stringTable = new byte[4096][]; for (int i=0; i<256; i++) { stringTable[i] = new byte[1]; stringTable[i][0] = (byte)i; } tableIndex = 258; bitsToGet = 9; }
java
public void update() { embeddedAn = (Embedded) getAnnotation(Embedded.class); entityAn = (Entity) getFirstAnnotation(Entity.class); // polymorphicAn = (Polymorphic) getAnnotation(Polymorphic.class); final List<MappedField> fields = getFieldsAnnotatedWith(Id.class); if (fields != ...
java
private static TimeZoneRule createRuleByRRULE(String tzname, int rawOffset, int dstSavings, long start, List<String> dates, int fromOffset) { if (dates == null || dates.size() == 0) { return null; } // Parse the first rule String rrule = dates.get(0); lon...
java
protected URI createUri(FileStatus i, UnixUserGroupInformation ugi, ClientProtocol nnproxy, HttpServletRequest request) throws IOException, URISyntaxException { return createUri(i.getPath().toString(), pickSrcDatanode(i, nnproxy), ugi, request); }
java
@Override public <H> Choice8<A, B, C, D, E, F, G, H> diverge() { return match(Choice8::a, Choice8::b, Choice8::c, Choice8::d, Choice8::e, Choice8::f, Choice8::g); }
java
@SuppressWarnings(UNUSED) @CheckForNull @Exported public Run getFirstBuild() { Run retVal = null; for (Job job : getAllJobs()) { Run run = job.getFirstBuild(); if (run != null && (retVal == null || run.getTimestamp().before(retVal.getTimestamp()))) { r...
python
def delete(self, session, commit=True, soft=True): """ Delete a row from the DB. :param session: flask_sqlalchemy session object :param commit: whether to issue the commit :param soft: whether this is a soft delete (i.e., update time_removed) """ if soft: ...
java
private void initializeMeta() throws BlockAlreadyExistsException, IOException, WorkerOutOfSpaceException { // Create the storage directory path boolean isDirectoryNewlyCreated = FileUtils.createStorageDirPath(mDirPath, ServerConfiguration.get(PropertyKey.WORKER_DATA_FOLDER_PERMISSIONS)); if (...
java
public static RawMessage toRawMessage(final short sendingNodeId, final ByteBuffer buffer) { buffer.flip(); final RawMessage message = new RawMessage(buffer.limit()); message.put(buffer, false); buffer.clear(); final RawMessageHeader header = new RawMessageHeader(sendingNodeId, (short) 0, (short)...
python
def randomly_init_variable(tax_benefit_system, input_dataframe_by_entity, variable_name, max_value, condition = None, seed = None): """ Initialise a variable with random values (from 0 to max_value). If a condition vector is provided, only set the value of persons or groups for which condition is Tr...
java
public static String setProperty(ArgumentUnit argumentUnit, String propertyName, String propertyValue) { Properties properties = ArgumentUnitUtils.getProperties(argumentUnit); String result = (String) properties.setProperty(propertyName, propertyValue); ArgumentUnitUtils.setPrope...
java
public String queryString(String sql, Object... params) throws SQLException { return query(sql, new StringHandler(), params); }
python
def setCenter(self, loc): """ Move this region so it is centered on ``loc`` """ offset = self.getCenter().getOffset(loc) # Calculate offset from current center return self.setLocation(self.getTopLeft().offset(offset)) # Move top left corner by the same offset
java
@Override public double distance(NumberVector v1, NumberVector v2) { return 1 - PearsonCorrelation.weightedCoefficient(v1, v2, weights); }
java
@SuppressWarnings("resource") protected ISynchronizationPoint<? extends Exception> serializeInputStreamValue( SerializationContext context, InputStream in, String path, List<SerializationRule> rules) { return serializeIOReadableValue(context, new IOFromInputStream(in, in.toString(), Threading.getUnmanagedTaskMa...
java
private void removeRRInstance(PackingPlanBuilder packingPlanBuilder, String componentName) throws RuntimeException { List<Scorer<Container>> scorers = new ArrayList<>(); scorers.add(new HomogeneityScorer(componentName, true)); // all-same-component containers first scorers.a...
python
def as_int(self, method): """ This value as an int, rounded according to ``method``. :param method: rounding method :raises BasesValueError: on bad parameters :returns: corresponding int value :rtype: int """ (new_radix, relation) = self.rounded(0, metho...
python
def gc(cn, ns=None, lo=None, iq=None, ico=None, pl=None): """ This function is a wrapper for :meth:`~pywbem.WBEMConnection.GetClass`. Retrieve a class. Parameters: cn (:term:`string` or :class:`~pywbem.CIMClassName`): Name of the class to be retrieved (case independent). ...
java
public static CompletableFuture<IMessageReceiver> createMessageReceiverFromEntityPathAsync(MessagingFactory messagingFactory, String entityPath) { return createMessageReceiverFromEntityPathAsync(messagingFactory, entityPath, DEFAULTRECEIVEMODE); }
java
public static void showSummary(String projectName, Dependency[] dependencies) { final StringBuilder summary = new StringBuilder(); for (Dependency d : dependencies) { final String ids = d.getVulnerabilities(true).stream() .map(v -> v.getName()) .collec...
python
def compatible(self, a, b): """Return `True` if type *a* is compatible with type *b*.""" return len(set([a] + self.descendants(a)) .intersection([b] + self.descendants(b))) > 0
java
@Override public Node visitQuery(SqlBaseParser.QueryContext context) { Query body = (Query) visit(context.queryNoWith()); return new Query( getLocation(context), visitIfPresent(context.with(), With.class), body.getQueryBody(), body...
java
@SuppressWarnings("unchecked") public void reduceToKeys(Set<String> keys) { if (size > 0) { int sizeCopy = size; String[] keyListCopy = keyList.clone(); int[] errorNumberCopy = errorNumber.clone(); HashMap<String, Integer>[] errorListCopy = errorList.clone(); int[] sourceNumberListCo...
java
protected void readFileData(final ParserData parserData, final BufferedReader br) throws IOException { // Read in the entire file so we can peek ahead later on String line; while ((line = br.readLine()) != null) { parserData.addLine(line); } }
java
public void marshall(UpdateFacetRequest updateFacetRequest, ProtocolMarshaller protocolMarshaller) { if (updateFacetRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateFacetRequest.getSch...
python
def process_from_file(signor_data_file, signor_complexes_file=None): """Process Signor interaction data from CSV files. Parameters ---------- signor_data_file : str Path to the Signor interaction data file in CSV format. signor_complexes_file : str Path to the Signor complexes data ...
python
def get_decrpyted_path(encrypted_path, surfix=default_surfix): """ Find the original path of encrypted file or dir. Example: - file: ``${home}/test-encrypted.txt`` -> ``${home}/test.txt`` - dir: ``${home}/Documents-encrypted`` -> ``${home}/Documents`` """ surfix_reversed = surfix[::-1] ...
python
def get_default_currency(self) -> Commodity: """ returns the book default currency """ result = None if self.default_currency: result = self.default_currency else: def_currency = self.__get_default_currency() self.default_currency = def_currency ...
java
@BetaApi public final Operation deleteRegionDisk(String disk) { DeleteRegionDiskHttpRequest request = DeleteRegionDiskHttpRequest.newBuilder().setDisk(disk).build(); return deleteRegionDisk(request); }
java
@Nonnull private static File writeDataToTempFileOrDie(@Nonnull final OutputStreamCallback callback, @Nonnull final File targetFile, @Nonnull final Logger log) throws IOException { Preconditions.checkNotNull...
java
private long parseTime(String day, String hours) { DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Date utcDate = new Date(); try { utcDate = format.parse(day.concat(" " + hours)); } catch (Exception e) { } return utcDate.getTime(); ...
java
private void checkInitialized() throws StorageException { if (storageAccountManager == null || !storageAccountManager.isInitialized()) { String error = "DuraStore must be initialized with an XML file " + "containing storage account information before any " + ...
java
public static <T> T use(Object self, Class categoryClass, Closure<T> closure) { return GroovyCategorySupport.use(categoryClass, closure); }
java
public static double innerProduct(double[] a, double[] b) { double result = 0.0; int len = Math.min(a.length, b.length); for (int i = 0; i < len; i++) { result += a[i] * b[i]; } return result; }
java
public void buildMethodDescription(XMLNode node, Content methodsContentTree) { methodWriter.addMemberDescription((MethodDoc) currentMember, methodsContentTree); }
java
public boolean dependsOn (T elem1, T elem2) { DependencyNode<T> node1 = _nodes.get(elem1); DependencyNode<T> node2 = _nodes.get(elem2); List<DependencyNode<T>> nodesToCheck = new ArrayList<DependencyNode<T>>(); List<DependencyNode<T>> nodesAlreadyChecked = new ArrayList<DependencyNo...
python
def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. We look up the name with the svcs command to get back the FMRI This allows users to use simpler service names CLI Example: .. code-block:: bash salt '*' service.available...
java
protected void afterMaterialization() { if (_listeners != null) { MaterializationListener listener; // listeners may remove themselves during the afterMaterialization // callback. // thus we must iterate through the listeners vector from back to // front // to avoid index problems. ...
java
public String get(Property<String> property) throws ConfigurationException { return tryGet(property, s -> s); }
python
def quote_for_pydot(string): """ takes a string (or int) and encloses it with "-chars. if the string contains "-chars itself, they will be escaped. """ if isinstance(string, int): string = str(string) escaped_str = QUOTE_RE.sub(r'\\"', string) return u'"{}"'.format(escaped_str)
python
def list_records(self, domain, limit=None, offset=None): """ Returns a list of all records configured for the specified domain. """ return domain.list_records(limit=limit, offset=offset)