language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def grid_from_coordinate_transform(numPix, Mpix2coord, ra_at_xy_0, dec_at_xy_0): """ return a grid in x and y coordinates that satisfy the coordinate system :param numPix: :param Mpix2coord: :param ra_at_xy_0: :param dec_at_xy_0: :return: """ a = np.arange(numPix) matrix = np.d...
python
def unlock_repo(self, repo_name): """ :calls: `DELETE /user/migrations/:migration_id/repos/:repo_name/lock`_ :param repo_name: str :rtype: None """ assert isinstance(repo_name, (str, unicode)), repo_name headers, data = self._requester.requestJsonAndCheck( ...
java
@Override protected void entering(NodeData node, int level) throws RepositoryException { if (ancestorToSave == null) { ancestorToSave = curParent().getQPath(); } NodeData parent = curParent(); QPath qpath = calculateNewNodePath(node, level); // Calc order number if p...
java
private boolean isSendEmail(Map<String, String> map) { return StringUtils.hasText(map.get(RequestElements.REQ_PARAM_ENTITY_SELECTOR)) && map.get(RequestElements.REQ_PARAM_ENTITY_SELECTOR).equalsIgnoreCase(RequestElements.PARAM_SEND_SELECTOR); }
java
public static void checkIfUnmodifiedSince(final String ifUnmodifiedSince, final Instant modified) { final Instant time = parseDate(ifUnmodifiedSince); if (time != null && modified.truncatedTo(SECONDS).isAfter(time)) { throw new ClientErrorException(status(PRECONDITION_FAILED).build()); ...
python
def check_perms(path, ret=None, owner=None, grant_perms=None, deny_perms=None, inheritance=True, reset=False): ''' Check owner and permissions for the passed directory. This function checks the permissions and se...
java
public static String autoQuoteApostrophe(String pattern) { StringBuilder buf = new StringBuilder(pattern.length() * 2); int state = STATE_INITIAL; int braceCount = 0; for (int i = 0, j = pattern.length(); i < j; ++i) { char c = pattern.charAt(i); switch (state) { ...
python
def trigger_deleted(self, filepath): """Triggers deleted event if the flie doesn't exist.""" if not os.path.exists(filepath): self._trigger('deleted', filepath)
python
def service_checks(self, name): """ Return the service checks received under the given name """ return [ ServiceCheckStub( ensure_unicode(stub.check_id), ensure_unicode(stub.name), stub.status, normalize_tags(stu...
java
public boolean suspendConsumer(int suspendFlag) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "suspendConsumer", Integer.valueOf(suspendFlag)); boolean didSuspendConsumer; // Lock down the consumerpoint and suspend it this.lock(); try { if ...
python
def device_filter(self): """The device filter to use. :rtype: dict """ if isinstance(self._device_filter, str): return self._decode_query(self._device_filter) return self._device_filter
python
def downcase_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData: """A hook to make uppercase commands lowercase.""" command = data.statement.command.lower() data.statement = self.statement_parser.parse("{} {}".format( command, '' if data.statemen...
java
public static void findSourceFiles(List<SourceLocation> sourceLocations, Set<String> sourceTypes, Map<String,Source> foundFiles, Map<String, Module> foundModules, M...
python
def make_order_and_cancel(api_svr_ip, api_svr_port, unlock_password, test_code, trade_env, acc_id): """ 使用请先配置正确参数: :param api_svr_ip: (string) ip :param api_svr_port: (string) ip :param unlock_password: (string) 交易解锁密码, 必需修改! :param test_code: (string) 股票 :param trade_env: 参见 ft.TrdEnv的定义 ...
python
def get_probes_results(self): """Return the results of the RPM probes.""" probes_results = {} probes_results_table = junos_views.junos_rpm_probes_results_table(self.device) probes_results_table.get() probes_results_items = probes_results_table.items() for probe_result i...
python
def secure(self, value): """Set the secure parameter and regenerate the thumbnail link.""" self._secure = value self._thumb = self._link_to_img()
java
public void run() { String packageName = this.getProperty("package"); ClassProject classProject = (ClassProject)this.getRecord(ClassProject.CLASS_PROJECT_FILE); if (packageName != null) if (packageName.length() > 0) { String projectID = this.getProperty("project"); ...
java
public MapUpdate removeCounter(String key) { BinaryValue k = BinaryValue.create(key); removes.add(new MapOp.MapField(MapOp.FieldType.COUNTER, k)); return this; }
python
def get_unique_column(self, table): """Determine if any of the columns in a table contain exclusively unique values.""" for col in self.get_columns(table): if self.count_rows_duplicates(table, col) == 0: return col
java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { permissionHelper.onActivityForResult(requestCode); super.onActivityResult(requestCode, resultCode, data); }
java
public static <E extends Enum<E>> E getEnum(final Class<E> enumClass, final String enumName) { if (enumName == null) { return null; } try { return Enum.valueOf(enumClass, enumName); } catch (final IllegalArgumentException ex) { return null; } ...
java
@Override public void renderHead(final Component component, final IHeaderResponse response) { super.renderHead(component, response); switch (bindEvent) { case ONDOMREADY : response.render(OnDomReadyHeaderItem.forScript(this.javascript)); break; case ONEVENT : response.render(OnEventHeaderItem....
java
public boolean removeValue(Object value) { try { boolean result = false; if (isCluster(groupName)) { result = getBinaryJedisClusterCommands(groupName).lrem(keyBytes, 0, valueSerialize(value)) >= 1; } else { result = getBinaryJedisCommands(groupName).lrem(keyBytes, 0, valueSerialize(value)) >= 1; }...
python
def _ensure_someone_took_responsability(self, state, _responses): ''' Called as a callback for sending *died* notifications to all the partners. Check if someone has offered to restart the agent. If yes, setup expiration call and wait for report. If no, initiate doing it ...
python
def include(self): """ If the next line is an include statement, inserts the contents of the included file into the pending buffer. """ if len(self.pending) == 0 or not self.pending[0].startswith('include '): return name = self.pending.pop(0)[8:].strip()[1:-1]...
python
def _get_named_graph(context): """ Returns the named graph for this context. """ if context is None: return None return models.NamedGraph.objects.get_or_create(identifier=context.identifier)[0]
python
def query(action=None, command=None, args=None, method='GET', location=None, data=None): ''' Make a web call to Joyent ''' user = config.get_cloud_config_value( 'user', get_configured_provider(), __opts__, search_global=False ) if not us...
java
private Map<String, Object> sendRequest(final URL url, final String method, final String authKey, final Map<String, ?> requestData) throws IOException { boolean useOutp...
java
@Override public ServiceDelegate createServiceDelegate(URL url, QName qname, @SuppressWarnings("rawtypes") Class cls) { Bus bus = null; JaxWsClientMetaData clientMetaData = JaxWsMetaDataManager.getJaxWsClientMetaData(); if (clientMetaData != n...
python
def workflows(self): """ Access the workflows :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList """ if self._workflows is None: self._workflows = WorkflowList(self._version, w...
java
public void print() throws MtasParserException { Iterator<MtasToken> it = this.iterator(); while (it.hasNext()) { MtasToken token = it.next(); System.out.println(token); } }
python
def metas(self, prefix=None, limit=None, delimiter=None): """ RETURN THE METADATA DESCRIPTORS FOR EACH KEY """ limit = coalesce(limit, TOO_MANY_KEYS) keys = self.bucket.list(prefix=prefix, delimiter=delimiter) prefix_len = len(prefix) output = [] for i, k ...
java
@InterfaceAudience.Private protected void queueRemoteRevision(RevisionInternal rev) { if (rev.isDeleted()) { deletedRevsToPull.add(rev); } else { revsToPull.add(rev); } }
java
@Override public boolean isBillingAvailable(final String packageName) { Logger.d("isBillingAvailable() packageName: ", packageName); if (billingAvailable != null) { return billingAvailable; // return previosly checked result } if (Utils.uiThread()) { throw ne...
java
private boolean isResponseType(String text, String label) { return label.equals(text) || StrUtil.formatMessage(label).equals(text); }
python
def get_streams(environment, start_response, headers): """ List all streams that can be read from Kronos right now. POST body should contain a JSON encoded version of: { namespace: namespace_name (optional) } """ start_response('200 OK', headers) streams_seen_so_far = set() namespace = environment...
java
public SIBUuid8 getRemoteMEUuid(SIBUuid12 linkUuid) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getRemoteMEUuid", linkUuid); LinkSelection s = null; SIBUuid8 remoteMEUuid = null; s = _localisationManager. g...
java
public final void publish(String channel, byte[] message) { if (client != null) { client.publish(channel.getBytes(StandardCharsets.UTF_8), message); } }
python
def ReferenceResults(self, field, allow_edit=False): """Render Reference Results Table """ instance = getattr(self, "instance", field.aq_parent) table = api.get_view("table_reference_results", context=instance, request=self.REQUES...
java
void appendNSDeclaration(int prefixIndex, int namespaceIndex, boolean isID) { // %REVIEW% I'm assigning this node the "namespace for namespaces" // which the DOM defined. It is expected that the Namespace spec will // adopt this as official. It isn't strictly needed since it's i...
java
@NullSafe public static double min(final double... values) { double minValue = Double.NaN; if (values != null) { for (double value : values) { minValue = (Double.isNaN(minValue) ? value : Math.min(minValue, value)); } } return minValue; }
python
def phonemes_to_phonetic_representation(self, phonemes: list) -> str: """ Use of rules to precise pronunciation of a preprocessed list of transcribed words :param phonemes: list(Vowel or Consonant) :return: str """ phonetic_representation = [] if len(phonemes) >= ...
java
public void registerProxyObject (DObject object, DObjectManager omgr) { int origObjectId = object.getOid(); // register the object locally which will reassign its oid and set us as its manager registerObject(object); // and note a proxy reference for the object which we'll use to for...
java
private String getControlInterfaceHint() { Control controlAnnotation = _fieldDecl.getAnnotation(Control.class); String interfaceHint = null; try { // always excepts controlAnnotation.interfaceHint(); } catch (MirroredTypeException mte) { interfaceHint...
java
private void resetJoinTimer() { cancelJoinTimer(); joinTimeout = raft.getThreadContext().schedule(raft.getElectionTimeout().multipliedBy(2), () -> { join(getActiveMemberStates().iterator()); }); }
java
public void setAssessmentRunArns(java.util.Collection<String> assessmentRunArns) { if (assessmentRunArns == null) { this.assessmentRunArns = null; return; } this.assessmentRunArns = new java.util.ArrayList<String>(assessmentRunArns); }
java
public <T extends AppController> RouteBuilder to(Class<T> type) { boolean hasControllerSegment = false; for (Segment segment : segments) { hasControllerSegment = segment.controller; } if (type != null && hasControllerSegment) { throw new IllegalArgumentExceptio...
python
def dump(self, function_name): """ Pretty-dump the bytecode for the function with the given name. """ assert isinstance(function_name, str) self.stdout.write(function_name) self.stdout.write("\n") self.stdout.write("-" * len(function_name)) self.stdout.w...
python
def verify_registration(request): """ Verify registration via signature. """ user = process_verify_registration_data(request.data) extra_data = None if registration_settings.REGISTER_VERIFICATION_AUTO_LOGIN: extra_data = perform_login(request, user) return get_ok_response('User verif...
java
public void deselectByValue(String value) { getDispatcher().beforeDeselect(this, value); new Select(getElement()).deselectByValue(value); if (Config.getBoolConfigProperty(ConfigProperty.ENABLE_GUI_LOGGING)) { logUIActions(UIActions.CLEARED, value); } ...
python
def search_all(self, template: str) -> _Result: """Search the :class:`Element <Element>` (multiple times) for the given parse template. :param template: The Parse template to use. """ return [r for r in findall(template, self.html)]
java
public SIMPReceivedMessageRequestInfo getRequestMessageInfo() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getRequestMessageInfo"); SIMPReceivedMessageRequestInfo requestInfo = null; Object tickValue = aoStream.getTickRange(tick).value; if(tickValue...
python
def getPermissionBit(self, t, m): ''' returns a permission bit of the string permission value for the specified object type ''' try: if isinstance(m, string_types): return self.rights[t][m]['BITS'] else: return m except KeyE...
java
private void runMessage(MessageAmp msg) { try (OutboxAmp outbox = OutboxAmpFactory.newFactory().get()) { outbox.inbox(msg.inboxTarget()); outbox.message(msg); //RampActor systemActor = null; StubAmp systemActor = _stub; msg.invoke(InboxExecutorBase.this, systemActor); ...
java
public alluxio.grpc.UfsInfo getUfsInfo() { return ufsInfo_ == null ? alluxio.grpc.UfsInfo.getDefaultInstance() : ufsInfo_; }
python
def unpack_scalar(cls, dataset, data): """ Given a dataset object and data in the appropriate format for the interface, return a simple scalar. """ import dask.dataframe as dd if len(data.columns) > 1 or len(data) != 1: return data if isinstance(data, ...
java
public static Iterable<BoxMetadataCascadePolicy.Info> getAll(final BoxAPIConnection api, String folderID, String ownerEnterpriseID, int limit, String... fields) { QueryStringBuilder...
java
public String convertColorFidelityRepCoExToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
java
public PactDslJsonArray template(DslPart template, int occurrences) { for(int i = 0; i < occurrences; i++) { template(template); } return this; }
python
def switch_toggle(context, ain): """Toggle an actor's power state""" context.obj.login() actor = context.obj.get_actor_by_ain(ain) if actor: if actor.get_state(): actor.switch_off() click.echo("State for {} is now OFF".format(ain)) else: actor.switch_o...
python
def requires_libsodium(func): """ Mark a function as requiring libsodium. If no libsodium support is detected, a `RuntimeError` is thrown. """ @wraps(func) def wrapper(*args, **kwargs): libsodium_check() return func(*args, **kwargs) return wrapper
python
def render(self, name, value, attrs=None): """Override the render() method to replace value with our current values This approach is based on the approach that Django's PasswordInput widget uses to ensure that passwords are not re-rendered in forms, except instead of prohibiting initial...
python
def ensure_newline(self, n): """Make sure there are 'n' line breaks at the end.""" assert n >= 0 text = self._output.getvalue().rstrip('\n') if not text: return self._output = StringIO() self._output.write(text) self._output.write('\n' * n) tex...
python
def do_default_fill(request): """Change all Mondays to 'Anchor Day' Change all Tuesday/Thursdays to 'Blue Day' Change all Wednesday/Fridays to 'Red Day'.""" monday = 0 tuesday = 1 wednesday = 2 thursday = 3 friday = 4 try: anchor_day = DayType.objects.get(name="Anchor Day") ...
python
def make_extra_json_fields(args): """ From the parsed command-line arguments, generate a dictionary of additional fields to be inserted into JSON logs (logstash_formatter module) """ extra_json_fields = { 'data_group': _get_data_group(args.query), 'data_type': _get_data_type(args.que...
python
def cosmetics(flat1, flat2 = None, mask=None, lowercut=6.0, uppercut=6.0, siglev=2.0): """Find cosmetic defects in a detector using two flat field images. Two arrays representing flat fields of different exposure times are required. Cosmetic defects are selected as points that deviate significantly of ...
java
public static void validate(final ArtifactQuery artifactQuery) { final Pattern invalidChars = Pattern.compile("[^A-Fa-f0-9]"); if(artifactQuery.getUser() == null || artifactQuery.getUser().isEmpty()){ throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) ...
python
def _write_mosaic(self, key, outfile): """Write out mosaic data (or any new data generated within Ginga) to single-extension FITS. """ maxsize = self.settings.get('max_mosaic_size', 1e8) # Default 10k x 10k channel = self.fv.get_channel(self.chname) image = channel.data...
java
public static void acceptsStoreSingle(OptionParser parser) { parser.acceptsAll(Arrays.asList(OPT_S, OPT_STORE), "store name") .withRequiredArg() .describedAs("store-name") .ofType(String.class); }
python
def match(self, method, path): """find handler from registered rules Example: handler, params = match('GET', '/path') """ segments = path.split('/') while len(segments): index = '/'.join(segments) if index in self.__idx__: ha...
python
def add_to_sys_modules(mod_name, mod_obj=None): """Add a module object to `sys.modules`. @param mod_name: module name, used as key to `sys.modules`. If `mod_name` is `a.b.c` while modules `a` and `a.b` are not existing, empty modules will be created for `a` and `a.b` as well. @param mod_obj: a mod...
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.SEC__RESERVED: setRESERVED(RESERVED_EDEFAULT); return; case AfplibPackage.SEC__COLSPCE: setCOLSPCE(COLSPCE_EDEFAULT); return; case AfplibPackage.SEC__COLSIZE1: setCOLSIZE1(COLSIZE1_EDEFAULT); return...
python
def consume_keys_asynchronous_threads(self): """ Work through the keys to look up asynchronously using multiple threads """ print("\nLooking up " + self.input_queue.qsize().__str__() + " keys from " + self.source_name + "\n") jobs = multiprocessing.cpu_count()*4 if (multiprocessi...
python
def _import(self): """ Makes imports :return: """ import os.path import gspread self.path = os.path self.gspread = gspread self._login()
java
private String trimPrefix(final String className) { for (final String prefix : this.dropPrefix) { if (className.startsWith(prefix)) { return className.substring(prefix.length()); } } return className; }
java
private <T> void submitCommand(Command<T> command, CompletableFuture<T> future) { CommandRequest request = CommandRequest.builder() .withSession(state.getSessionId()) .withSequence(state.nextCommandRequest()) .withCommand(command) .build(); submitCommand(request, future); }
python
def _set_ldp_protocol_stats_instance_since_clear(self, v, load=False): """ Setter method for ldp_protocol_stats_instance_since_clear, mapped from YANG variable /mpls_state/ldp/statistics/ldp_protocol_stats_instance_since_clear (container) If this variable is read-only (config: false) in the source YANG ...
python
def get_log_tag(process_name): """method returns tag that all messages will be preceded with""" process_obj = context.process_context[process_name] if isinstance(process_obj, FreerunProcessEntry): return str(process_obj.token) elif isinstance(process_obj, ManagedProcessEntry): return str...
python
def rsh(self, num, cin=None): """Right shift the farray by *num* places. The *num* argument must be a non-negative ``int``. If the *cin* farray is provided, it will be shifted in. Otherwise, the carry-in is zero. Returns a two-tuple (farray fs, farray cout), where *fs*...
python
def name_usage(key = None, name = None, data = 'all', language = None, datasetKey = None, uuid = None, sourceId = None, rank = None, shortname = None, limit = 100, offset = None, **kwargs): ''' Lookup details for specific names in all taxonomies in GBIF. :param key: [fixnum] A GBIF key for a taxon :param name: [...
python
def get_sci_segs_for_ifo(ifo, cp, start_time, end_time, out_dir, tags=None): """ Obtain science segments for the selected ifo Parameters ----------- ifo : string The string describing the ifo to obtain science times for. start_time : gps time (either int/LIGOTimeGPS) The time at...
python
def detect_mobile(view): """View Decorator that adds a "mobile" attribute to the request which is True or False depending on whether the request should be considered to come from a small-screen device such as a phone or a PDA""" @wraps(view) def detected(request, *args, **kwargs): Mob...
java
public @NotNull SuffixBuilder resource(@NotNull Resource resource, @NotNull Resource suffixBaseResource) { // get relative path to base resource String relativePath = getRelativePath(resource, suffixBaseResource); resourcePaths.add(relativePath); return this; }
java
@Override public GetDeploymentStatusResult getDeploymentStatus(GetDeploymentStatusRequest request) { request = beforeClientExecution(request); return executeGetDeploymentStatus(request); }
java
@Override public TagRoleResult tagRole(TagRoleRequest request) { request = beforeClientExecution(request); return executeTagRole(request); }
java
public static double toClassifierPrediction(Vector vector) { double max = Double.NEGATIVE_INFINITY; int maxIndex = 0; for (int i = 0; i < vector.size(); i++) { double curr = vector.apply(i); if (curr > max) { maxIndex = i; max = curr; ...
python
def pad_to_size(data, shape, value=0.0): """ This is similar to `pad`, except you specify the final shape of the array. Parameters ---------- data : ndarray Numpy array of any dimension and type. shape : tuple Final shape of padded array. Should be tuple of length ``data.ndim``....
java
public static Object getFirstValue(final Object iObject) { if (iObject == null) return null; if (!isMultiValue(iObject)) return null; try { if (iObject instanceof Collection<?>) return ((Collection<Object>) iObject).iterator().next(); else if (iObject instanceof M...
python
def _get_roles(self, username): """ Get roles of a user @str username: name of the user @rtype: dict, format { 'roles': [<list of roles>], 'unusedgroups': [<list of groups not matching roles>] } """ groups = self._get_groups(username) user_roles = self.roles.g...
java
@RequiresPermission(Manifest.permission.BLUETOOTH) static void checkAdapterStateOn(@Nullable final BluetoothAdapter adapter) { if (adapter == null || adapter.getState() != BluetoothAdapter.STATE_ON) { throw new IllegalStateException("BT Adapter is not turned ON"); } }
java
public static int cudaMemsetAsync(Pointer devPtr, int value, long count, cudaStream_t stream) { return checkResult(cudaMemsetAsyncNative(devPtr, value, count, stream)); }
python
def is_locator(self, path, relative=False): """ Returns True if path refer to a locator. Depending the storage, locator may be a bucket or container name, a hostname, ... args: path (str): path or URL. relative (bool): Path is relative to current root. ...
python
def ext_pillar(minion_id, pillar, # pylint: disable=W0613 collection='pillar', id_field='_id', re_pattern=None, re_replace='', fields=None): ''' Connect to a mongo database and read per-node pillar information. Param...
python
def graph(self, ASres=None, padding=0, vspread=0.75, title="Multi-Traceroute Probe (MTR)", timestamp="", rtt=1, **kargs): """x.graph(ASres=conf.AS_resolver, other args): ASres = None : Use AS default resolver => 'conf.AS_resolver' ASres = AS_resolver() : default whois AS resolver (riswh...
python
def tar_file(files, tarname): '''Compress a file or directory into a tar file.''' if isinstance(files, basestring): files = [files] o = tarfile.open(tarname, 'w:gz') for file in files: o.add(file) o.close()
java
@Override public ListAccessKeysResult listAccessKeys(ListAccessKeysRequest request) { request = beforeClientExecution(request); return executeListAccessKeys(request); }
java
@Bench(runs = RUNS) public void arrayListAdd() { arrayList = new ArrayList<Integer>(); for (final int i : intData) { arrayList.add(i); } }
java
public static double min( ImageBase input ) { if( input instanceof ImageGray) { if (GrayU8.class == input.getClass()) { return ImageStatistics.min((GrayU8) input); } else if (GrayS8.class == input.getClass()) { return ImageStatistics.min((GrayS8) input); } else if (GrayU16.class == input.getClass()) ...
java
public static String extractSubstring( String str, String open, String close, char escape, boolean cleanEscape) { int i; StringBuffer buf = new StringBuffer(); int len = str.length(); for (i = 0; i < len; i++) { if (str.startsWith(o...
python
def module_for_loader(fxn): """Decorator to handle selecting the proper module for loaders. The decorated function is passed the module to use instead of the module name. The module passed in to the function is either from sys.modules if it already exists or is a new module. If the module is new, then _...