language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public Collection<PartnerSubscription> deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject obj = element.getAsJsonObject(); JsonArray subscriptions = obj.getAsJsonArray("subscriptions"); List<PartnerSubs...
java
public void setVideoPositionWithinPod(com.google.api.ads.admanager.axis.v201811.VideoPositionWithinPod videoPositionWithinPod) { this.videoPositionWithinPod = videoPositionWithinPod; }
java
@Deprecated protected int getTimeOffset(SignableRequest<?> request) { final int globleOffset = SDKGlobalTime.getGlobalTimeOffset(); return globleOffset == 0 ? request.getTimeOffset() : globleOffset; }
java
public ServiceFuture<LiveOutputInner> getAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName, final ServiceCallback<LiveOutputInner> serviceCallback) { return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOut...
java
@Override public void validate() throws Exception { super.validate(); this.parse(); Assert.assertTrue("The upper date should be after the initial date", this.upper.after(this.lower)); }
python
def add_resource(self, resource): """Add a resource to the minimum needs table. :param resource: The resource to be added :type resource: dict """ updated_sentence = NeedsProfile.format_sentence( resource['Readable sentence'], resource) if self.edit_item: ...
java
private void updateNPMExecutable(NodeInstallationInformation information) throws MojoExecutionException { getLog().info("Installing specified npm version " + npmVersion); NpmInstallTask npmInstallTask = new NpmInstallTask(); npmInstallTask.setLog(getLog()); npmInstallTask.setNpmBundledWithNodeJs(true); ...
python
def insert(self, space, t, *, replace=False, timeout=-1) -> _MethodRet: """ Insert request coroutine. Examples: .. code-block:: pycon # Basic usage >>> await conn.insert('tester', [0, 'hello']) <Response sync=3 rowcount=1 dat...
python
def _pre_flight(self): ''' Run pre flight checks. If anything in this method fails then the master should not start up. ''' errors = [] critical_errors = [] try: os.chdir('/') except OSError as err: errors.append( '...
java
@SuppressWarnings("unchecked") @Override public Boolean execute() { SmartFoxServer.getInstance() .getAPIManager() .getGameApi() .sendInvitation(CommandUtil.getSfsUser(inviter, api), CommandUtil.getSFSUserList(invitees, api), ...
python
def docs(context: Context): """ Generates static documentation """ try: from sphinx.application import Sphinx except ImportError: context.pip_command('install', 'Sphinx') from sphinx.application import Sphinx context.shell('cp', 'README.rst', 'docs/README.rst') app =...
java
protected void renderTableHeaderRow(FacesContext facesContext, ResponseWriter writer, UIComponent component, UIComponent headerFacet, String headerStyleClass, int colspan) throws IOException { renderTableHeaderOrFooterRow(facesContext, writer, component, headerFacet, headerStyleClass, ...
java
static int glhInvertMatrixf2(float[] m, float[] out) { float[][] wtmp = new float[4][8]; float m0, m1, m2, m3, s; float[] r0, r1, r2, r3; r0 = wtmp[0]; r1 = wtmp[1]; r2 = wtmp[2]; r3 = wtmp[3]; r0[0] = MAT(m, 0, 0); r0[1] = MAT(m, 0, 1); r0...
python
def generate_feature_matrix(self, mode='tfidf'): """ Returns a feature matrix in the form of a list of lists which represents the terms and documents in this Inverted Index using the tf-idf weighting by default. The term counts in each document can alternatively be used by specif...
java
protected String getDiscoveryResponseURL(String entityBaseURL, String entityAlias) { if (extendedMetadata != null && extendedMetadata.getIdpDiscoveryResponseURL() != null && extendedMetadata.getIdpDiscoveryResponseURL().length() > 0) { return extendedMetadata.getIdpDiscoveryResponseU...
java
@Override public void writeRef(int ref) { require(1); _buffer[_offset++] = (byte) ConstH3.REF; writeUnsigned(ref); }
java
@Override public DescribeMatchmakingResult describeMatchmaking(DescribeMatchmakingRequest request) { request = beforeClientExecution(request); return executeDescribeMatchmaking(request); }
python
def get_response(self): """Generate the response block of this request. Careful: it only sets the fields which can be set from the request """ res = IODControlRes() for field in ["ARUUID", "SessionKey", "AlarmSequenceNumber"]: res.setfieldval(field, self.getfieldval(f...
java
public Set<CommandDefinition> getAllCommandDefinition(final String pluginName) { Set<CommandDefinition> res = new HashSet<CommandDefinition>(); for (CommandDefinition cd : commandDefinitionsMap.values()) { if (cd.getPluginName().equals(pluginName)) { res.add(cd); ...
java
private void flush() { if (pendingAbsoluteValueBug != null) { absoluteValueAccumulator.accumulateBug(pendingAbsoluteValueBug, pendingAbsoluteValueBugSourceLine); pendingAbsoluteValueBug = null; pendingAbsoluteValueBugSourceLine = null; } accumulator.reportAcc...
java
public void updateXIDToRolledback(PersistentTranId xid) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "updateXIDToRolledback", "XID="+xid); if (_deferredException == null) { // We are rolling back a transaction. This should only be ...
python
def p_iteration_statement_3(self, p): """ iteration_statement \ : FOR LPAREN expr_noin_opt SEMI expr_opt SEMI expr_opt RPAREN \ statement | FOR LPAREN VAR variable_declaration_list_noin SEMI expr_opt SEMI\ expr_opt RPAREN statement """ ...
java
@Override public ApiZone find(String name) { Zone zone = SmartFoxServer.getInstance() .getZoneManager() .getZoneByName(name); if(zone != null && zone.containsProperty(APIKey.ZONE)) return (ApiZone) zone.getProperty(APIKey.ZONE); return null; }
python
def group_entries_by_structure(entries, species_to_remove=None, ltol=0.2, stol=.4, angle_tol=5, primitive_cell=True, scale=True, comparator=SpeciesComparator(), ncpus=None): """ Given a se...
python
def get_page(self, page_id): """ Get short page info and body html code """ try: result = self._request('/getpage/', {'pageid': page_id}) return TildaPage(**result) except NetworkError: return []
java
private static Calendar getEndOfDay(Calendar calendar) { // Copy given calender only up to given month Calendar endOfMonth = Calendar.getInstance(); endOfMonth.clear(); endOfMonth.set(Calendar.YEAR, calendar.get(Calendar.YEAR)); endOfMonth.set(Calendar.MONTH, cale...
java
boolean isReady() { final C[] ds = destinations.get(); if (ds == null) return false; for (final C d : ds) if (d == null) return false; final boolean ret = ds.length != 0; // this method is only called in tests and this needs to be true there. ...
python
def conjugate(self): """Complex conjugate of of the indexed sum""" return self.__class__.create(self.term.conjugate(), *self.ranges)
python
def is_diff(self): """Return True if there are any differences logged""" if not isinstance(self.details, dict): return False for key in ['additions', 'updates', 'deletions']: if self.details.get(key, None): return True return False
java
public static List<Integer> createListOfNonExistentFields(List<String> list, JavacNode type, boolean excludeStandard, boolean excludeTransient) { boolean[] matched = new boolean[list.size()]; for (JavacNode child : type.down()) { if (list.isEmpty()) break; if (child.getKind() != Kind.FIELD) continue; JC...
java
public void saveGlobalProperties() throws IOException { File propFile = new File(getGlobalPropertiesFile()); if (propFile.createNewFile() || propFile.isFile()) { java.util.Properties prop = new java.util.Properties(); if (getRoundingMode() != null) prop.put...
python
def register_cmaps(category, provider, source, bg, names): """ Maintain descriptions of colormaps that include the following information: name - string name for the colormap category - intended use or purpose, mostly following matplotlib provider - package providing the colormap directly so...
java
public static boolean urisEqualAfterPortNormalization(final URI uri1, final URI uri2) { if (uri1 == null && uri2 == null) { return true; } if (uri1 == null || uri2 == null) { return false; } try { URI normalizedUri1 = normalizePortNumb...
java
protected void findCreds() { if (System.getProperty(ACCESS_KEY) != null && System.getProperty(ACCESS_SECRET) != null) { accessKey = System.getProperty(ACCESS_KEY); secretKey = System.getProperty(ACCESS_SECRET); } else if (System.getenv(AWS_ACCESS_KEY) != null && System.g...
python
def _get_addresses(self, text): '''Returns a list of addresses found in text''' # find addresses addresses = [] matches = utils.findall( self.rules, text, flags=re.VERBOSE | re.U) if(matches): for match in matches: ...
python
def del_properties(elt, keys=None, ctx=None): """Delete elt property. :param elt: properties elt to del. Not None methods. :param keys: property keys to delete from elt. If empty, delete all properties. """ # get the best context if ctx is None: ctx = find_ctx(elt=elt) elt...
python
def _offset_of_next_ff_byte(self, start): """ Return the offset of the next '\xFF' byte in *stream* starting with the byte at offset *start*. Returns *start* if the byte at that offset is a hex 255; it does not necessarily advance in the stream. """ self._stream.seek(star...
python
def type_last(self, obj: JsonObj) -> JsonObj: """ Move the type identifiers to the end of the object for print purposes """ def _tl_list(v: List) -> List: return [self.type_last(e) if isinstance(e, JsonObj) else _tl_list(e) if isinstance(e, list) else e for...
python
def codemirror_field_js_bundle(field): """ Filter to get CodeMirror Javascript bundle name needed for a single field. Example: :: {% load djangocodemirror_tags %} {{ form.myfield|codemirror_field_js_bundle }} Arguments: field (django.forms.fields.Field): A form field t...
java
public static boolean checkAggregateReferences(Application app) { Map<DomainObject, Set<DomainObject>> aggregateGroups = getAggregateGroups(app); for (Set<DomainObject> group1 : aggregateGroups.values()) { for (Set<DomainObject> group2 : aggregateGroups.values()) { if (group1 == group2) { continue; ...
python
def load_target(cls, scheme, path, fragment, username, password, hostname, port, query, load_method, **kwargs): """Override this method to use values from the parsed uri to initialize the expected target. """ raise NotImplementedError("load_target...
python
def check_config_mode(self, check_string="config", pattern=""): """Checks if the device is in configuration mode or not.""" if not pattern: pattern = re.escape(self.base_prompt) return super(CiscoWlcSSH, self).check_config_mode(check_string, pattern)
java
@Override public boolean handles(String command) { if (command.startsWith(this.tree.getTopNode().getData())) { return true; } return false; }
python
def param_dict_to_list(dict,skeys=None): """convert from param dictionary to list""" #sort keys RV = SP.concatenate([dict[key].flatten() for key in skeys]) return RV pass
python
def reply(): """Fetch a reply from RiveScript. Parameters (JSON): * username * message * vars """ params = request.json if not params: return jsonify({ "status": "error", "error": "Request must be of the application/json type!", }) username =...
python
def napi_or(values, **kwargs): """Perform element-wise logical *or* operation on arrays. If *values* contains a non-array object with truth_ value **True**, the outcome will be an array of **True**\s with suitable shape without arrays being evaluated. Non-array objects with truth value **False** are om...
python
def decorate_event_js(js_code): """setup a method as an event, adding also javascript code to generate Args: js_code (str): javascript code to generate the event client-side. js_code is added to the widget html as widget.attributes['onclick'] = js_code%{'emitter_identifier':wid...
java
protected void notifySendMessage(String method, List<?> params) { for (ISharedObjectListener listener : listeners) { listener.onSharedObjectSend(this, method, params); } }
python
def _log_future_exception(future, logger): """Log any exception raised by future.""" if not future.done(): return try: future.result() except: #pylint:disable=bare-except;This is a background logging helper logger.warning("Exception in ignored future: %s", future, exc_info=Tru...
java
public static PlanarImage convertCMYK2RGB(PlanarImage src) { ColorSpace srcColorSpace = src.getColorModel().getColorSpace(); // check if BufferedImage is cmyk format if (srcColorSpace.getType() != ColorSpace.TYPE_CMYK) { return src; } /** * ICC_ColorSpace o...
python
def unset_env(): """Remove coverage info from env.""" os.environ.pop('COV_CORE_SOURCE', None) os.environ.pop('COV_CORE_DATA_FILE', None) os.environ.pop('COV_CORE_CONFIG', None)
python
def get_as_integer_with_default(self, key, default_value): """ Converts map element into an integer or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: integer value ot the element or ...
python
def form_to_json(form): """ Takes the form from the POST request in the web interface, and generates the JSON config\ file :param form: The form from the POST request :return: None """ config = dict() if form['project_name'] == "": raise Exception('Project name cannot be empty.') if form['selector_type'] ...
python
def rank_targets(sample_frame, ref_targets, ref_sample): """Uses the geNorm algorithm to determine the most stably expressed genes from amongst ref_targets in your sample. See Vandesompele et al.'s 2002 Genome Biology paper for information about the algorithm: http://dx.doi.org/10.1186/gb-2002-3-7-rese...
python
def _assert_ssl_exc_contains(exc, *msgs): """Check whether SSL exception contains either of messages provided.""" if len(msgs) < 1: raise TypeError( '_assert_ssl_exc_contains() requires ' 'at least one message to be passed.', ) err_msg_lower = str(exc).lower() ret...
java
public DescribeScheduledActionsRequest withScheduledActionNames(String... scheduledActionNames) { if (this.scheduledActionNames == null) { setScheduledActionNames(new java.util.ArrayList<String>(scheduledActionNames.length)); } for (String ele : scheduledActionNames) { th...
python
def pair(self): """ Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were sent by a pair socket. Note that the iterable returns as many parts as sent by a pair. Also, the sender function has ...
python
def _validate_columns(self): """Validate the options in the styles""" geom_cols = {'the_geom', 'the_geom_webmercator', } col_overlap = set(self.style_cols) & geom_cols if col_overlap: raise ValueError('Style columns cannot be geometry ' 'columns. ...
python
def NotificationsGet(self, notification_id = -1): """ Obtain either all notifications from CommonSense, or the details of a specific notification. If successful, the result can be obtained from getResponse(), and should be a json string. @param notification_...
java
public List<String> getValues(final String propertyName) { Preconditions.checkNotNull(propertyName); List<String> values = properties.get(propertyName); if (values == null) { return null; } // creates a shallow defensive copy return new ArrayList<>(values); ...
python
def update(self, fname): """ Adds a handler to save to a file. Includes debug stuff. """ ltfh = FileHandler(fname) self._log.addHandler(ltfh)
python
def get_new_access_token(refresh_token, client_id, client_secret, scope=None, **kwargs): """使用 Refresh Token 刷新以获得新的 Access Token. :param refresh_token: 用于刷新 Access Token 用的 Refresh Token; :param client_id: 应用的 API Key; :param client_secret: 应用的 Secret Key; :param scope: 以空...
python
def sign(allocate_quota_request): """Obtains a signature for an operation in a `AllocateQuotaRequest` Args: op (:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): an operation used in a `AllocateQuotaRequest` Returns: string: a secure hash generated from the op...
python
def _get_searchable_regex(basic=None, hidden=None): """Return the searchable regular expressions for the single keyword.""" # Hidden labels are used to store regular expressions. basic = basic or [] hidden = hidden or [] hidden_regex_dict = {} for hidden_label in hidden: if _is_regex(hi...
python
def _modem_sm(self): """Handle modem response state machine.""" import datetime read_timeout = READ_IDLE_TIMEOUT while self.ser: try: resp = self.read(read_timeout) except (serial.SerialException, SystemExit, TypeError): _LOGGER.de...
java
public static <T> ObjectInstantiator<T> getInstantiatorOf(Class<T> clazz) { return OBJENESIS_STD.getInstantiatorOf(clazz); }
java
private int findNextMatchingLine(String[] textLines, int startingLine, String textToMatch) { int _foundLeft = -1; { int _tempLine = startingLine + 1; while (_tempLine < textLines.length) { String _tempText = getTextLine(textLines, _tempLine); if (_tempText.equals(textToMatch)) { _foundLef...
python
def plate(self): """ Serves up a delicious plate with your models """ request = self.request if self.settings is None: graph_settings = deepcopy(getattr(settings, 'SPAGHETTI_SAUCE', {})) graph_settings.update(self.override_settings) else: ...
java
public void setDayPartTargeting(com.google.api.ads.admanager.axis.v201805.DayPartTargeting dayPartTargeting) { this.dayPartTargeting = dayPartTargeting; }
java
public static int month(EvaluationContext ctx, Object date) { return Conversions.toDateOrDateTime(date, ctx).get(ChronoField.MONTH_OF_YEAR); }
python
def get_example(cls) -> dict: """Returns an example value for the Dict type. If an example isn't a defined attribute on the class we return a dict of example values based on each property's annotation. """ if cls.example is not None: return cls.example return...
java
public StorageAccountInner update(String resourceGroupName, String accountName, StorageAccountUpdateParameters parameters) { return updateWithServiceResponseAsync(resourceGroupName, accountName, parameters).toBlocking().single().body(); }
python
def iter_module_paths(modules=None): """ Yield paths of all imported modules.""" modules = modules or list(sys.modules.values()) for module in modules: try: filename = module.__file__ except (AttributeError, ImportError): # pragma: no cover continue if filena...
python
def _bucket_boundaries(max_length, min_length=8, length_bucket_step=1.1): """A default set of length-bucket boundaries.""" assert length_bucket_step > 1.0 x = min_length boundaries = [] while x < max_length: boundaries.append(x) x = max(x + 1, int(x * length_bucket_step)) return boundaries
python
async def build_get_cred_def_request(submitter_did: Optional[str], id_: str) -> str: """ Builds a GET_CRED_DEF request. Request to get a credential definition (in particular, public key), that Issuer creates for a particular Credential Schema. :param submitter_did: (O...
python
def createNetwork(self, data, headers=None, query_params=None, content_type="application/json"): """ Create a new network It is method for POST /network """ uri = self.client.base_url + "/network" return self.client.post(uri, data, headers, query_params, content_type)
java
static PageWrapper wrapExisting(BTreePage page, PageWrapper parent, PagePointer pointer) { return new PageWrapper(page, parent, pointer, false); }
java
public static DefaultListOperation<AssetDeliveryPolicyInfo> list(LinkInfo<AssetDeliveryPolicyInfo> link) { return new DefaultListOperation<AssetDeliveryPolicyInfo>(link.getHref(), new GenericType<ListResult<AssetDeliveryPolicyInfo>>() { }); }
python
def latex_quote(s): """Quote special characters for LaTeX. (Incomplete, currently only deals with underscores, dollar and hash.) """ special = {'_':r'\_', '$':r'\$', '#':r'\#'} s = str(s) for char,repl in special.items(): new = s.replace(char, repl) s = new[:] return s
python
def MI_enumInstanceNames(self, env, ns, cimClass): # pylint: disable=invalid-name """Return instance names of a given CIM class Implements the WBEM operation EnumerateInstanceNames in terms of the enu...
java
static String implode(final String glue, final String[] what) { final StringBuilder builder = new StringBuilder(); for (int i = 0; i < what.length; i++) { builder.append(what[i]); if (i + 1 != what.length) { builder.append(glue); } } r...
java
@Override public String getProperty(String name) { Validate.notNull(name, "Property name can not be null"); return this.portalProperties.getProperty(name); }
python
def vector_unit_nonull(v): """Return unit vectors. Any null vectors raise an Exception. Parameters ---------- v: array, shape (a1, a2, ..., d) Cartesian vectors, with last axis indexing the dimension. Returns ------- v_new: array, shape of v """ if v.size == 0: ...
python
def _onsuccess(self, result): """ To execute on execution success :param cdumay_result.Result result: Execution result :return: Execution result :rtype: cdumay_result.Result """ self._set_status("SUCCESS", result) logger.info( "{}.Success: {}[{}]: {}"....
java
private CellFormatResult getCellValue(final Cell cell, final Locale locale) { return getCellValue(new POICell(cell), locale); }
java
HsqlName getSchemaHsqlName(String name) { return name == null ? currentSchema : database.schemaManager.getSchemaHsqlName(name); }
java
public void cleanup() { long currentTime = System.currentTimeMillis(); // remove entries which have exceeded their time to live cachedExecutionGraphs.values().removeIf( (ExecutionGraphEntry entry) -> currentTime >= entry.getTTL()); }
java
private SuggestionsWsResponse loadSuggestionsWithoutSearch(int skip, int limit, Set<String> recentlyBrowsedKeys, List<String> qualifiers) { List<ComponentDto> favoriteDtos = favoriteFinder.list(); if (favoriteDtos.isEmpty() && recentlyBrowsedKeys.isEmpty()) { return newBuilder().build(); } try (Db...
python
def to_json(self): """ Returns the JSON representation of the resource. """ result = { 'sys': {} } for k, v in self.sys.items(): if k in ['space', 'content_type', 'created_by', 'updated_by', 'published_by']: v ...
python
def write_tree_from_cache(entries, odb, sl, si=0): """Create a tree from the given sorted list of entries and put the respective trees into the given object database :param entries: **sorted** list of IndexEntries :param odb: object database to store the trees in :param si: start index at which we ...
python
def indent(s, spaces=4): """ Inserts `spaces` after each string of new lines in `s` and before the start of the string. """ new = re.sub('(\n+)', '\\1%s' % (' ' * spaces), s) return (' ' * spaces) + new.strip()
python
def external_session_url(self, email, chrome, url, integrator_id, client_id): """ Get a URL which initiates a new external session for the user with the given email. Full details: http://www.campaignmonitor.com/api/account/#single_sign_on :param email: String The representing th...
java
@Override public final String getString(final String key) { String result = optString(key); if (result == null) { throw new ObjectMissingException(this, key); } return result; }
python
def shp_dict(shp_fn, fields=None, geom=True): """Get a dictionary for all features in a shapefile Optionally, specify fields """ from pygeotools.lib import timelib ds = ogr.Open(shp_fn) lyr = ds.GetLayer() nfeat = lyr.GetFeatureCount() print('%i input features\n' % nfeat) if fie...
java
public static Set<Annotation> getAllAnnotations(Method m) { Set<Annotation> annotationSet = new LinkedHashSet<Annotation>(); Annotation[] annotations = m.getAnnotations(); List<Class<?>> annotationTypes = new ArrayList<Class<?>>(); // Iterate through all annotations of the current class...
python
def _add(self, uri, methods, handler, host=None): """Add a handler to the route list :param uri: path to match :param methods: sequence of accepted method names. If none are provided, any method is allowed :param handler: request handler function. When executed, ...
python
def get_resource(url): """ Issue a GET request to SWS with the given url and return a response in json format. :returns: http response with content in json """ response = DAO.getURL(url, {'Accept': 'application/json', 'Connection': 'keep-alive'}) if response.s...
python
def create_inputs(data): """Index input reads and prepare groups of reads to process concurrently. Allows parallelization of alignment beyond processors available on a single machine. Prepares a bgzip and grabix indexed file for retrieving sections of files. """ from bcbio.pipeline import sampl...
python
def issamedoc(self): """Return :const:`True` if this is a same-document reference.""" return (self.scheme is None and self.authority is None and not self.path and self.query is None)
java
private int checkExponent(int length) { if (length >= nDigits || length < 0) return decExponent; for (int i = 0; i < length; i++) if (digits[i] != '9') // a '9' anywhere in digits will absorb the round return decExponent; return decExponen...