language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_all_service_user_objects(self, include_machine = False): """ Fetches all service user objects from the AD, and returns MSADUser object. Service user refers to an user whith SPN (servicePrincipalName) attribute set """ logger.debug('Polling AD for all user objects, machine accounts included: %s'% inclu...
java
public void onCreate() { Bundle bundle = new Bundle(); if (mParentDelegate != null) { bundle = mParentDelegate.mBundle; } onCreate(bundle); }
java
public long read(OutputStream stream, long length, long position) throws IOException { return delegate.read(stream, length, position); }
python
def post_message(name, channel, from_name, message, api_key=None, icon=None): ''' Send a message to a Slack channel. .. code-block:: yaml slack-message: slack.post_message: - channel: '#gener...
java
@Override public Map<String, Collection<String>> getRequireFeatureWithTolerates() { // The feature may be an older feature which never had the tolerates information // stored, in which case, look in the older requireFeature field and massage // that info into the required format. // ...
python
def in_qtconsole(): """ check if we're inside an IPython qtconsole DEPRECATED: This is no longer needed, or working, in IPython 3 and above. """ try: ip = get_ipython() front_end = ( ip.config.get('KernelApp', {}).get('parent_appname', "") or ip.config.get('I...
java
@UiThread public int getParentAdapterPosition() { int flatPosition = getAdapterPosition(); if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) { return RecyclerView.NO_POSITION; } return mExpandableAdapter.getNearestParentPosition(flatPosition); ...
python
def read(self, encoding="utf8"): """ :param encoding: :return: """ with open(self._filename, "rb") as f: if self.key: return get_module("mo_math.crypto").decrypt(f.read(), self.key) else: content = f.read().decode(encoding) ...
java
public static synchronized String char2DOS437( StringBuffer stringbuffer, int i, char c ) { if (unicode2DOS437 == null) { unicode2DOS437 = new char[0x10000]; for( int j = 0; j < 256; j++ ) { char c1; if ((c1 = unicode[2][j]) != '\uFFFF') ...
python
def proportional_char(self, action): '''Specifies proportional characters. When turned on, the character spacing set with charSpacing. Args: action: Turn proportional characters on or off. Returns: None Raises: RuntimeError: Invalid ac...
python
def update_rejection_permissions(portal): """Adds the permission 'Reject Analysis Request' and update the permission mappings accordingly """ updated = update_rejection_permissions_for(portal, "bika_ar_workflow", "Reject Analysis Request") if updated: ...
java
@Override public synchronized boolean addEntry(Principal caller, Principal principal, String permission) { return addEntry(caller, new SecurityAccessControl(principal, permission)); }
java
public static HLL fromBytes(final byte[] bytes) { final ISchemaVersion schemaVersion = SerializationUtil.getSchemaVersion(bytes); final IHLLMetadata metadata = schemaVersion.readMetadata(bytes); final HLLType type = metadata.HLLType(); final int regwidth = metadata.registerWidth(); ...
python
async def write(self, data): """Writes a chunk of data to the streaming response. :param data: bytes-ish data to be written. """ if type(data) != bytes: data = self._encode_body(data) self.protocol.push_data(b"%x\r\n%b\r\n" % (len(data), data)) await self.pr...
python
def rasterize_pdf( input_file, output_file, xres, yres, raster_device, log, pageno=1, page_dpi=None, rotation=None, filter_vector=False, ): """Rasterize one page of a PDF at resolution (xres, yres) in canvas units. The image is sized to match the integer pixels dimension...
java
@Override public void writeHeader(RandomAccessFile file) throws IOException { super.writeHeader(file); file.writeInt(this.k_max); }
java
public Callbacks fire(Object... o) { if (!done) { done = isOnce; if (isMemory) { memory = new ArrayList<>(Arrays.asList(o)); } if (stack != null) for (Object c : stack) { if (!run(c, o) && stopOnFalse) { break; } } } return this...
java
protected Map<String,String> getHeadersMap(String headerPart) { final int len = headerPart.length(); final Map<String,String> headers = new HashMap<String,String>(); int start = 0; for (;;) { int end = parseEndOfLine(headerPart, start); if (start == end) { break; } String header = headerPart.su...
python
def run_toy_HMC(gpu_id=None): """Run HMC on toy dataset""" X, Y, X_test, Y_test = load_toy() minibatch_size = Y.shape[0] noise_precision = 1 / 9.0 net = get_toy_sym(True, noise_precision) data_shape = (minibatch_size,) + X.shape[1::] data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id...
python
def update(self, dictionary=None, **kwargs): """ Adds/overwrites all the keys and values from the dictionary. """ if not dictionary == None: kwargs.update(dictionary) for k in list(kwargs.keys()): self[k] = kwargs[k]
java
void rfftf(final double a[], final int offa) { if (n == 1) return; int l1, l2, na, kh, nf, ip, iw, ido, idl1; final int twon = 2 * n; nf = (int) wtable_r[1 + twon]; na = 1; l2 = n; iw = twon - 1; for (int k1 = 1; k1 <= nf; ++k1) { kh = nf - k1; ip = (int) wtable_r[kh + 2 + twon]; l1 = l2 / ...
python
def _add_series_only_operations(cls): """ Add the series only operations to the cls; evaluate the doc strings again. """ axis_descr, name, name2 = _doc_parms(cls) def nanptp(values, axis=0, skipna=True): nmax = nanops.nanmax(values, axis, skipna) ...
python
def spdhg_generic(x, f, g, A, tau, sigma, niter, **kwargs): r"""Computes a saddle point with a stochastic PDHG. This means, a solution (x*, y*), y* = (y*_1, ..., y*_n) such that (x*, y*) in arg min_x max_y sum_i=1^n <y_i, A_i> - f*[i](y_i) + g(x) where g : X -> IR_infty and f[i] : Y[i] -> IR_infty ar...
java
private Object doMoskitoProfiling(ProceedingJoinPoint pjp, String statement) throws Throwable { String statementGeneralized = removeParametersFromStatement(statement); long callTime = System.nanoTime(); QueryStats cumulatedStats = producer.getDefaultStats(); QueryStats statementStats = null; try{ statement...
java
public synchronized void write(byte[] buf, int off, int len) throws IOException { super.write(buf, off, len); crc.update(buf, off, len); }
python
def addAllowMAC(self, xEUI): """add a given extended address to the whitelist addressfilter Args: xEUI: a given extended address in hex format Returns: True: successful to add a given extended address to the whitelist entry False: fail to add a given extende...
python
def range_iter(fd, offset, length, chunk=CHUNK): """ Iterator generator that iterates over chunks in specified range This generator is meant to be used when returning file descriptor as a response to Range request (byte serving). It limits the reads to the region specified by ``offset`` (in bytes form ...
java
public <T> F4<P1, P2, P3, P4, T> andThen(final Function<? super R, ? extends T> f) { E.NPE(f); final Func4<P1, P2, P3, P4, R> me = this; return new F4<P1, P2, P3, P4, T>() { @Override public T apply(P1 p1, P2 p2, P3 p3, P4 p4) { R r...
python
def _set_attr(self, **kwargs): """Set the attribute of the symbol. Parameters ---------- **kwargs The attributes to set """ keys = c_str_array(kwargs.keys()) vals = c_str_array([str(s) for s in kwargs.values()]) num_args = mx_uint(len(kwargs))...
java
public static HashMap<String, HashMap<String, Float>> getAllHypotheses( BayesianReasonerShanksAgent agent) throws ShanksException { return ShanksAgentBayesianReasoningCapability.getAllHypotheses(agent .getBayesianNetwork()); }
java
@Override public int read() throws IOException { if (max >= 0 && pos >= max) { return -1; } int result = in.read(); pos++; return result; }
python
def get_metadata(self): """ Fetch repository repomd.xml file """ metadata_path = "{}/{}/{}".format(self.url, self.metadata_dir, self.metadata_file) metadata_sig_path = "{}/{}/{}.sig".format(self.u...
python
def _update_transient_database( self, crossmatches, classifications, transientsMetadataList, colMaps): """ update transient database with classifications and crossmatch results **Key Arguments:** - ``crossmatches`` -- the crossmatc...
python
def _async_sub_acc_push(self, acc_id_list): """ 异步连接指定要接收送的acc id :param acc_id: :return: """ kargs = { 'acc_id_list': acc_id_list, 'conn_id': self.get_async_conn_id(), } ret_code, msg, push_req_str = SubAccPush.pack_req(**kargs) ...
java
public Observable<ManagedClusterInner> getByResourceGroupAsync(String resourceGroupName, String resourceName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<ManagedClusterInner>, ManagedClusterInner>() { @Override public...
python
def can_update(self, user, **kwargs): """ Sys admin's can change anything If the user is an organisation administrator or created the repository, they may change any field other than "organisation_id" If the user is a service administrator the user may change the "state" ...
java
public static DiscreteFactor getVariances(DiscreteFactor featureFactor, int featureVariableNum) { return getVariances(Arrays.asList(featureFactor), featureVariableNum); }
python
def quoted(arg): """ Given a string, return a quoted string as per RFC 3501, section 9. Implementation copied from https://github.com/mjs/imapclient (imapclient/imapclient.py), 3-clause BSD license """ if isinstance(arg, str): arg = arg.replace('\\', '\\\\') arg = arg.replac...
python
def set_options(self, options): """ Configure all the many options we'll need to make this happen. """ self.verbosity = int(options.get('verbosity')) # Will we be gzipping? self.gzip = getattr(settings, 'BAKERY_GZIP', False) # And if so what content types will w...
python
def showpath(path): """Format a path for displaying.""" if logger.verbose: return os.path.abspath(path) else: path = os.path.relpath(path) if path.startswith(os.curdir + os.sep): path = path[len(os.curdir + os.sep):] return path
java
public Object parseObject(String pStr, ParsePosition pStatus) { Time t = parse(pStr); pStatus.setIndex(pStr.length()); // Not 100% return t; }
java
protected int resolveSimpleEntity(boolean checkStd) throws XMLStreamException { char[] buf = mInputBuffer; int ptr = mInputPtr; char c = buf[ptr++]; // Numeric reference? if (c == '#') { c = buf[ptr++]; int value = 0; int inputLen ...
java
public UpdateTableRequest withGlobalSecondaryIndexUpdates(GlobalSecondaryIndexUpdate... globalSecondaryIndexUpdates) { if (this.globalSecondaryIndexUpdates == null) { setGlobalSecondaryIndexUpdates(new java.util.ArrayList<GlobalSecondaryIndexUpdate>(globalSecondaryIndexUpdates.length)); } ...
python
def on_deleted(self, event): """ Called when a file or directory is deleted. Todo: May be bugged with inspector and sass compiler since the does not exists anymore. Args: event: Watchdog event, ``watchdog.events.DirDeletedEvent`` or `...
java
public void wrapDescription(StringBuilder out, int indent, int currentLineIndent, String description) { int max = commander.getColumnSize(); String[] words = description.split(" "); int current = currentLineIndent; for (int i = 0; i < words.length; i++) { String word = words...
java
private Path renameToInProgressFile(Path file) throws IOException { Path newFile = new Path( file.toString() + inprogress_suffix ); try { if (hdfs.rename(file, newFile)) { return newFile; } throw new RenameException(file, newFile); } catch (IOException e){ throw ne...
python
def normalize_address(self, hostname): """Ensure that address returned is an IP address (i.e. not fqdn)""" if config_get('prefer-ipv6'): # TODO: add support for ipv6 dns return hostname if hostname != unit_get('private-address'): return get_host_ip(hostname, ...
python
def pack(fmt, *values, **kwargs): """Pack the values according to the format string and return a new BitStream. fmt -- A single string or a list of strings with comma separated tokens describing how to create the BitStream. values -- Zero or more values to pack according to the format. kwarg...
python
def SetAttributes(self, urn, attributes, to_delete, add_child_index=True, mutation_pool=None): """Sets the attributes in the data store.""" attributes[AFF4Object.SchemaCls.LAST] = [ rdfvalue.RDFDatetime....
python
def parse(self, what): """ :param what: can be 'rlz-1/ref-asset1', 'rlz-2/sid-1', ... """ if '/' not in what: key, spec = what, '' else: key, spec = what.split('/') if spec and not spec.startswith(('ref-', 'sid-')): raise Va...
java
public boolean add() { if (root == NIL) { root = nodeAllocator.newNode(); copy(root); fixAggregates(root); return true; } else { int node = root; assert parent(root) == NIL; int parent; int cmp; do { ...
python
def get_template_sources(self, template_name, template_dirs=None): """ Returns the absolute paths to "template_name" in the specified app. If the name does not contain an app name (no colon), an empty list is returned. The parent FilesystemLoader.load_template_source() will take ...
java
@Nullable public static Date createDate (@Nullable final ZonedDateTime aZDT) { // The timezone gets lost here return aZDT == null ? null : Date.from (aZDT.toInstant ()); }
java
public static void launchIPs(Class<? extends Job> job, String... ips) throws Exception { Cloud cloud = new Cloud(); cloud.publicIPs.addAll(Arrays.asList(ips)); launch(cloud, job); }
java
@Nullable private Object getTypedCellValue(TableFieldSchema fieldSchema, Object v) { if (Data.isNull(v)) { return null; } if (Objects.equals(fieldSchema.getMode(), "REPEATED")) { TableFieldSchema elementSchema = fieldSchema.clone().setMode("REQUIRED"); @SuppressWarnings("unchecked") ...
java
@Override protected double score1(Chunk[] chks, double weight, double offset, double[/*nclass*/] fs, int row) { return score1static(chks, idx_tree(0), offset, fs, row, new Distribution(_parms), _nclass); }
python
def get_user_data(user=None,group=None,data_kind=DINGOS_USER_DATA_TYPE_NAME): """ Returns either stored settings of a given user or default settings. This behavior reflects the need for views to have some settings at hand when running. The settings are returned as dict object. ""...
java
public void process( T image1 , T image2 ) { // declare image data structures if( pyr1 == null || pyr1.getInputWidth() != image1.width || pyr1.getInputHeight() != image1.height ) { pyr1 = UtilDenseOpticalFlow.standardPyramid(image1.width, image1.height, scale, sigma, 5, maxLayers, GrayF32.class); pyr2 = Util...
java
public static String removeSubstring(String inString, String substring) { StringBuffer result = new StringBuffer(); int oldLoc = 0, loc = 0; while ((loc = inString.indexOf(substring, oldLoc))!= -1) { result.append(inString.substring(oldLoc, loc)); oldLoc = loc + substring.length(); } re...
python
def query(self, query_dict: Dict[str, Any]) -> None: """ 重写 query """ self.parse_url.query = cast(Any, query_dict)
python
def create_key_ring( self, parent, key_ring_id, key_ring, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Create a new ``KeyRing`` in a given Project and Location. E...
java
public void setWeekDay(String dayString) { final WeekDay day = WeekDay.valueOf(dayString); if (m_model.getWeekDay() != day) { removeExceptionsOnChange(new Command() { public void execute() { m_model.setWeekDay(day); onValueChange(); ...
java
public void marshall(User user, ProtocolMarshaller protocolMarshaller) { if (user == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(user.getId(), ID_BINDING); protocolMarshaller.marshall(...
java
public static CommerceShippingMethod fetchByG_E(long groupId, String engineKey, boolean retrieveFromCache) { return getPersistence().fetchByG_E(groupId, engineKey, retrieveFromCache); }
python
def getpeptides(self, chain): """If peptide ligand chains are defined via the command line options, try to extract the underlying ligand formed by all residues in the given chain without water """ all_from_chain = [o for o in pybel.ob.OBResidueIter( self.proteincomple...
java
public ListDeploymentTargetsResult withTargetIds(String... targetIds) { if (this.targetIds == null) { setTargetIds(new com.amazonaws.internal.SdkInternalList<String>(targetIds.length)); } for (String ele : targetIds) { this.targetIds.add(ele); } return thi...
python
def load_template(self, template_name, template_source=None, template_path=None, **template_vars): """ Will load a templated configuration on the device. :param cls: Instance of the driver class. :param template_name: Identifies the template name. :param te...
python
def add(self, client): """Add a client to the penalty box.""" if client.pool_id in self._client_ids: log.info("%r is already in the penalty box. Ignoring.", client) return release = time.time() + self._min_wait heapq.heappush(self._clients, (release, (client, self...
python
def ok_embedded_video(node): """Check if this embed/video is an ok one to count.""" good_keywords = ('youtube', 'blip.tv', 'vimeo') node_str = tounicode(node) for key in good_keywords: if key in node_str: return True return False
java
protected IScope createLocalVariableScope(EObject featureCall, IScope parent, IFeatureScopeSession session, IResolvedTypes resolvedTypes) { return new LocalVariableScope(parent, session, asAbstractFeatureCall(featureCall)); }
java
public void commitAttrValuesInDB() throws EFapsException { synchronized (this.attrUpdated) { if (this.attrUpdated.size() > 0) { Connection con = null; try { con = Context.getConnection(); final StringBuilder cmd = n...
java
public VirtualFile getFile(VirtualFile mountPoint, VirtualFile target) { final String path = target.getPathNameRelativeTo(mountPoint); return rootNode.getFile(new Path(path), mountPoint); }
java
public static Map<String, Object> configureProperties(final PropertyResolver resolver, final Object object) { //use a default scope of InstanceOnly if the Property doesn't specify it return configureProperties(resolver, buildDescription(object, D...
java
public static Object stripShallow(Object decorated) { try { InjectableProperty delegateProperty = new ConfigClassAnalyzer(decorated.getClass()).getDelegateProperty(); if (delegateProperty == null) { return decorated; } else { return delegatePro...
python
def check_signature(self, msgbuf, srcSystem, srcComponent): '''check signature on incoming message''' if isinstance(msgbuf, array.array): msgbuf = msgbuf.tostring() timestamp_buf = msgbuf[-12:-6] link_id = msgbuf[-13] (tlow, thigh) = struct.unp...
python
def visitLanguageRange(self, ctx: ShExDocParser.LanguageRangeContext): """ ShExC: languageRange : LANGTAG (STEM_MARK languagExclusion*)? ShExJ: valueSetValue = objectValue | LanguageStem | LanguageStemRange """ baselang = ctx.LANGTAG().getText() if not ctx.STEM_MARK(): ...
python
def get(self, sid): """ Constructs a DomainContext :param sid: The unique string that identifies the resource :returns: twilio.rest.api.v2010.account.sip.domain.DomainContext :rtype: twilio.rest.api.v2010.account.sip.domain.DomainContext """ return DomainContext...
python
def ProduceExtractionWarning(self, message, path_spec=None): """Produces an extraction warning. Args: message (str): message of the warning. path_spec (Optional[dfvfs.PathSpec]): path specification, where None will use the path specification of current file entry set in the medi...
python
def make_spectrum_plot(model_plot, data_plot, desc, xmin_clamp=0.01, min_valid_x=None, max_valid_x=None): """Make a plot of a spectral model and data. *model_plot* A model plot object returned by Sherpa from a call like `ui.get_model_plot()` or `ui.get_bkg_model_plot()`. ...
java
public BlockchainInfo queryBlockchainInfo() throws ProposalException, InvalidArgumentException { return queryBlockchainInfo(getShuffledPeers(EnumSet.of(PeerRole.LEDGER_QUERY)), client.getUserContext()); }
java
public static String extractHtmlBody(String content) { Matcher startMatcher = BODY_START_PATTERN.matcher(content); Matcher endMatcher = BODY_END_PATTERN.matcher(content); int start = 0; int end = content.length(); if (startMatcher.find()) { start = startMatcher.end...
python
def pst_from_parnames_obsnames(parnames, obsnames, tplfilename='model.input.tpl', insfilename='model.output.ins'): """ Creates a Pst object from a list of parameter names and a list of observation names. Default values are provided for the TPL and INS Args: parname...
python
def valid_domains(self): """ :return: A list of unicode strings of valid domain names for the certificate. Wildcard certificates will have a domain in the form: *.example.com """ if self._valid_domains is None: self._valid_domains = [] # ...
python
def tatoeba(language, word, minlength = 10, maxlength = 100): ''' Returns a list of suitable textsamples for a given word using Tatoeba.org. ''' word, sentences = unicode(word), [] page = requests.get('http://tatoeba.org/deu/sentences/search?query=%s&from=%s&to=und' % (word, lltk.locale.iso639_1to3(language))) tre...
python
def key_value_pairs(self): """ convert list to key value pairs This should also create unique id's to allow for any dataset to be transposed, and then later manipulated r1c1,r1c2,r1c3 r2c1,r2c2,r2c3 should be converted to ID COLNUM VAL...
python
def _get_adjtime_timezone(): ''' Return the timezone in /etc/adjtime of the system clock ''' adjtime_file = '/etc/adjtime' if os.path.exists(adjtime_file): cmd = ['tail', '-n', '1', adjtime_file] return __salt__['cmd.run'](cmd, python_shell=False) elif os.path.exists('/dev/rtc'):...
java
public static String readFile(String string) { InputStream inputStream = getInputStream(string); if (inputStream != null) { return new String(readStream(inputStream)); } return null; }
python
def p_var_decl_at(p): """ var_decl : DIM idlist typedef AT expr """ p[0] = None if len(p[2]) != 1: syntax_error(p.lineno(1), 'Only one variable at a time can be declared this way') return idlist = p[2][0] entry = SYMBOL_TABLE.declare_variable(idlist[0], id...
python
def show_message(self, c_attack, c_defend, result, dmg, print_console='Yes'): """ function to wrap the display of the battle messages """ perc_health_att = '[' + str(round((c_attack.stats['Health']*100) / c_attack.stats['max_health'] )) + '%]' perc_health_def = '[' + str(round((c...
java
public static boolean isInternalRequest(HttpServletRequest request){ // if(Boolean.parseBoolean(request.getHeader(WebConstants.HEADER_INTERNAL_REQUEST))){ return true; } boolean isInner = IpUtils.isInnerIp(request.getServerName()); String forwardHost = request.getHeader(WebConstants.HEADER_FORWARDED_HOST)...
python
def _register_admin(admin_site, model, admin_class): """ Register model in the admin, ignoring any previously registered models. Alternatively it could be used in the future to replace a previously registered model. """ try: admin_site.register(model, admin_class) except admin.s...
python
def run(self): '''命令行交互程序''' while(True): oiraw = cInput() if(len(oiraw) < 1): break cutted = self.cut(oiraw, text = True) print(cutted)
java
@Override protected void logImpl(LogLevel level,Object[] message,Throwable throwable) { //format log message String text=this.formatLogMessage(level,message,throwable); //print text to system out System.out.println(text); }
java
public static int writeIdenticalLevelRun(int prev, CharSequence s, int i, int length, ByteArrayWrapper sink) { while (i < length) { // We must have capacity>=SLOPE_MAX_BYTES in case writeDiff() writes that much, // but we do not want to force the sink to allocate // for a lar...
python
def _improve_class_docs(app, cls, lines): """Improve the documentation of a class.""" if issubclass(cls, models.Model): _add_model_fields_as_params(app, cls, lines) elif issubclass(cls, forms.Form): _add_form_fields(cls, lines)
java
@Deprecated public static <T> String marshal(final T data, @NotNull final Class<?>... classesToBeBound) { return JaxbUtils.marshal(data, classesToBeBound); }
java
private boolean waitForWebElementsToBeCreated(){ final long endTime = SystemClock.uptimeMillis() + 5000; while(SystemClock.uptimeMillis() < endTime){ if(isFinished){ return true; } sleeper.sleepMini(); } return false; }
java
private void setMethods(String methodList) { String[] methodNames = methodList.trim().split(","); for (String methodName : methodNames) { HttpMethod method = HttpMethod.valueOf(methodName.trim().toUpperCase()); Utils.require(method != null, "Unknown REST method: " + methodName); ...
python
def _reset_em(self): """Resets self.em and the shared instances.""" self.em = _ExtendedManager(self.addr, self.authkey, mode=self.mode, start=False) self.em.start() self._set_shared_instances()
python
def SegmentMax(a, ids): """ Segmented max op. """ func = lambda idxs: np.amax(a[idxs], axis=0) return seg_map(func, a, ids),