language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def work(request, slug): """ :param request: Django request object. :param event_id: The `id` associated with the event. :param is_preview: Should the listing page be generated as a preview? This will allow preview specific actions to be done in the template...
java
private void init(PluralRules rules, PluralType type, ULocale locale, NumberFormat numberFormat) { ulocale = locale; pluralRules = (rules == null) ? PluralRules.forLocale(ulocale, type) : rules; resetPattern(); this.numberFormat = (numberFormat == nu...
java
protected static boolean computeAnd (Iterable<Value<Boolean>> values) { for (Value<Boolean> value : values) { if (!value.get()) { return false; } } return true; }
python
def _set_scene_transform(self, tr): """ Called by subclasses to configure the viewbox scene transform. """ # todo: check whether transform has changed, connect to # transform.changed event pre_tr = self.pre_transform if pre_tr is None: self._scene_transform = ...
java
public <V> double[][] getConfidenceInterval(final double alpha, final Map<V, Double>[] metricValuesPerDimension) { Map<Integer, Double> systemMeans = new HashMap<Integer, Double>(); Map<V, Double> dimensionSum = new HashMap<V, Double>(); Map<V, Integer> dimensionN = new HashMap<V, Integer>(); ...
java
private void addAction(NamedParameterStatement nps, Map<String, String> keysToColumns, Map<String, Object>[] maps) throws SQLException { Map<String, Object> params = new HashMap<>(); for (Map.Entry<String, String> entry : keysToColumns.entrySet()) { for (Map<String, Object> map : maps) { if (map.containsKey...
java
public byte[] engineDigest() { try { final byte hashvalue[] = new byte[HASH_LENGTH]; engineDigest(hashvalue, 0, HASH_LENGTH); return hashvalue; } catch (DigestException e) { return null; } }
java
public Waiter<DescribeVpcsRequest> vpcExists() { return new WaiterBuilder<DescribeVpcsRequest, DescribeVpcsResult>().withSdkFunction(new DescribeVpcsFunction(client)) .withAcceptors(new HttpSuccessStatusAcceptor(WaiterState.SUCCESS), new VpcExists.IsInvalidVpcIDNotFoundMatcher()) ...
python
def handle_api_error(resp): """Stolen straight from the Stripe Python source.""" content = yield resp.json() headers = HeaderWrapper(resp.headers) try: err = content['error'] except (KeyError, TypeError): raise error.APIError( "Invalid response object from API: %r (HTTP...
java
public final Cache2kBuilder<K, V> retryInterval(long v, TimeUnit u) { config().setRetryInterval(u.toMillis(v)); return this; }
python
def find_modules(import_path, include_packages=False, recursive=False): """Finds all the modules below a package. This can be useful to automatically import all views / controllers so that their metaclasses / function decorators have a chance to register themselves on the application. Packages are...
java
public static responderpolicy_responderglobal_binding[] get(nitro_service service, String name) throws Exception{ responderpolicy_responderglobal_binding obj = new responderpolicy_responderglobal_binding(); obj.set_name(name); responderpolicy_responderglobal_binding response[] = (responderpolicy_responderglobal_b...
java
@Override public String getLabel() { String l = label; if(l != null) return l; String p = path; if(p != null) { String filename = p.substring(p.lastIndexOf('/') + 1); if(filename.endsWith(DOT_EXTENSION)) filename = filename.substring(0, filename.length() - DOT_EXTENSION.length()); if(filename.isEmpty(...
python
def address(addr): """ A special argument type that splits a string on ':' and transforms the result into a tuple of host and (integer) port. """ if ':' in addr: # Using rpartition here means we should be able to support # IPv6, but only with a strict syntax host, _sep, port...
python
def _maybe_coerce_values(self, values): """Unbox to an extension array. This will unbox an ExtensionArray stored in an Index or Series. ExtensionArrays pass through. No dtype coercion is done. Parameters ---------- values : Index, Series, ExtensionArray Returns...
java
private void swapValues(final int src, final int dst) { final T item = data_.get(src); data_.set(src, data_.get(dst)); data_.set(dst, item); final Double wt = weights_.get(src); weights_.set(src, weights_.get(dst)); weights_.set(dst, wt); if (marks_ != null) { final Boolean mark = ma...
python
def init_shutit_map(self): """Initializes the module map of shutit based on the modules we have gathered. Checks we have core modules Checks for duplicate module details. Sets up common config. Sets up map of modules. """ shutit_global.shutit_global_object.yield_to_draw() modules = self.shutit_module...
java
CompletableFuture<PingTxnStatus> pingTxnBody(final String scope, final String stream, final UUID txnId, final long lease, fi...
python
def sph2cart(lon, lat): """ Converts a longitude and latitude (or sequence of lons and lats) given in _radians_ to cartesian coordinates, `x`, `y`, `z`, where x=0, y=0, z=0 is the center of the globe. Parameters ---------- lon : array-like Longitude in radians lat : array-like ...
java
public static void sort(List<? extends Extension> extensions, Collection<SortClause> sortClauses) { Collections.sort(extensions, new SortClauseComparator(sortClauses)); }
python
def read(filename: str, limit: Optional[int]=None) -> Tuple[list, int]: """ Reads any file supported by pydub (ffmpeg) and returns the data contained within. returns: (channels, samplerate) """ audiofile = AudioSegment.from_file(filename) if limit: audiofile = audiofile[:limit * 10...
java
public Behavior createBehavior(String behaviorId) throws FacesException { if (defaultApplication != null) { return defaultApplication.createBehavior(behaviorId); } return null; }
java
@Override public BlobDataID createBlob(long length) { long lobID = database.lobManager.createBlob(length); if (lobID == 0) { throw Error.error(ErrorCode.X_0F502); } sessionData.addToCreatedLobs(lobID); return new BlobDataID(lobID); }
java
public void onWrite(final SelectionKey key) { if (this.writeEventDispatcher == null) { dispatchWriteEvent(key); } else { this.writeEventDispatcher.dispatch(new WriteTask(key)); } }
java
public SimpleJob setJoin(String[] masterLabels, String masterColumn, String dataColumn, String masterPath) throws IOException, URISyntaxException { String separator = conf.get(SEPARATOR); return setJoin(masterLabels, masterColumn, dataColumn, masterPath, separator, false, DE...
python
def _parse_numbers(text): ''' Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K. Returns a decimal number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return decimal.Decimal(text) try: postPrefixes = {'K': '10E3'...
java
@SuppressWarnings("unchecked") @Override public EList<IfcRelAggregates> getDecomposes() { return (EList<IfcRelAggregates>) eGet(Ifc4Package.Literals.IFC_OBJECT_DEFINITION__DECOMPOSES, true); }
java
public static <K, V> Map<K, V> sortNumberMapByKeyAscending(Map<K, V> map) { return sortNumberMapByKeyAscending(map.entrySet()); }
python
def get_vdp_failure_reason(self, reply): """Parse the failure reason from VDP. """ try: fail_reason = reply.partition( "filter")[0].replace('\t', '').split('\n')[-2] if len(fail_reason) == 0: fail_reason = vdp_const.retrieve_failure_reason % (reply...
java
public static Class<?> wrap(final Class<?> cls) { N.checkArgNotNull(cls, "cls"); final Class<?> wrapped = PRIMITIVE_2_WRAPPER.get(cls); return wrapped == null ? cls : wrapped; }
python
def _get_mean(self, data, dctx, dists): """ Returns the mean intensity measure level from the tables :param data: The intensity measure level vector for the given magnitude and IMT :param key: The distance type :param distances: The distance ve...
python
def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subproces...
python
def AddGroupTags(r, group, tags, dry_run=False): """ Adds tags to a node group. @type group: str @param group: group to add tags to @type tags: list of string @param tags: tags to add to the group @type dry_run: bool @param dry_run: whether to perform a dry run @rtype: string @...
java
protected Route.Filtering get(final String path, final Result result) { return get(path, () -> result); }
python
def logloss(y, p): """Bounded log loss error. Args: y (numpy.array): target p (numpy.array): prediction Returns: bounded log loss error """ p[p < EPS] = EPS p[p > 1 - EPS] = 1 - EPS return log_loss(y, p)
python
def not_send_status(func): """ Do not send process status package back to scheduler. It's used by callbacks like on_message, on_result etc... """ @functools.wraps(func) def wrapper(self, response, task): self._extinfo['not_send_status'] = True function = func.__get__(self, self....
python
def strip_position(self): """The current position of the strip, normalized to the range [0, 1], with 0 being the top/left-most point in the tablet's current logical orientation. If the source is :attr:`~libinput.constant.TabletPadStripAxisSource.FINGER`, libinput sends a terminating event with a value of -...
java
Counter getMonthCounter() { final Counter monthCounter = createMonthCounterAtDate(currentDayCounter.getStartDate()); addRequestsAndErrorsForRange(monthCounter, Period.MOIS.getRange()); return monthCounter; }
java
public Bits encodePPM(String text, int context) { final String original = text; //if(verbose) System.p.println(String.format("Encoding %s run %s chars of context", text, context)); if (!text.endsWith("\u0000")) text += END_OF_STRING; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); BitOut...
java
public StructuredQueryDefinition geospatial(GeospatialRegionIndex index, GeospatialOperator operator, Region... regions) { checkRegions(regions); return new GeospatialRegionQuery((GeoRegionPathImpl)index, operator, null, regions, null); }
java
public ArrayList<OvhGeolocationEnum> serviceName_ipCountryAvailable_GET(String serviceName) throws IOException { String qPath = "/vps/{serviceName}/ipCountryAvailable"; StringBuilder sb = path(qPath, serviceName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t9); }
java
public Iterable<VariableElement> getImplicitPostfixParams(TypeElement type) { if (ElementUtil.isEnum(type)) { return implicitEnumParams; } return Collections.emptyList(); }
python
def list_hosting_device_handled_by_config_agent( self, client, cfg_agent_id, **_params): """Fetches a list of hosting devices handled by a config agent.""" return client.get((ConfigAgentHandlingHostingDevice.resource_path + CFG_AGENT_HOSTING_DEVICES) % cfg_agent_id...
python
def counter_multi(self, kvs, initial=None, delta=1, ttl=0): """Perform counter operations on multiple items :param kvs: Keys to operate on. See below for more options :param initial: Initial value to use for all keys. :param delta: Delta value for all keys. :param ttl: Expiratio...
java
@com.fasterxml.jackson.annotation.JsonProperty("FieldName") public void setFieldName(String fieldName) { this.fieldName = fieldName; }
java
public void startSearch() { stopSearch(); stop = false; MiscUtils.getExecutor().execute(new Runnable() { @Override public void run() { isSearching = true; try { if (finder != null) { finder.sta...
python
def save(self, *args, **kwargs): """Saves this model instance to the database.""" max_retries = getattr( settings, 'LOCALIZED_FIELDS_MAX_RETRIES', 100 ) if not hasattr(self, 'retries'): self.retries = 0 with transaction.atomic():...
java
public DocumentVersionMetadata withThumbnail(java.util.Map<String, String> thumbnail) { setThumbnail(thumbnail); return this; }
java
private IntIntDenseVector[][] countFeatures(FgExampleList data, FactorTemplateList templates) { IntIntDenseVector[][] counts = new IntIntDenseVector[numTemplates][]; for (int t=0; t<numTemplates; t++) { FactorTemplate template = templates.get(t); int numConfigs = template.getNumC...
java
public void buildExecutableList() { for(String labelExp : labels.split(",")) { List<Page> pages = getExpLabeledPages(labelExp); for(Page page : pages) { if (page.getSpaceKey().equals(spaceKey) && !executableList.contains(page) && gp...
java
public static base_response delete(nitro_service client, String variable) throws Exception { filterhtmlinjectionvariable deleteresource = new filterhtmlinjectionvariable(); deleteresource.variable = variable; return deleteresource.delete_resource(client); }
java
public GitLabApiForm withParam(String name, Object value) throws IllegalArgumentException { return (withParam(name, value, false)); }
java
@Override public Iterable<T> findAll() { return operation.findAll(information.getCollectionName(), information.getJavaType()); }
java
private void processAsyncSessionStoppedCallback (CommsByteBuffer buffer, Conversation conversation) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "processAsyncSessionStoppedCallback", new Object[]{buffer, conversation}); final short connectionObjectId = buffer.getSh...
java
@Override protected void searchStep() { // submit replicas for execution in thread pool // (future returns index of respective replica) for(int i=0; i < replicas.size(); i++){ futures.add(pool.submit(replicas.get(i), i)); } // logger.debug("{}: started {} Metropol...
python
def get_objective_lookup_session(self): """Gets the OsidSession associated with the objective lookup service. return: (osid.learning.ObjectiveLookupSession) - an ObjectiveLookupSession raise: OperationFailed - unable to complete request raise: Unimplemented - s...
java
@Override public EEnum getIfcElectricApplianceTypeEnum() { if (ifcElectricApplianceTypeEnumEEnum == null) { ifcElectricApplianceTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(974); } return ifcElectricApplianceTypeEnumEEnum; }
python
def _load(self, filename=None): """Read the AATSR rsr data""" if not filename: filename = self.aatsr_path wb_ = open_workbook(filename) for sheet in wb_.sheets(): ch_name = sheet.name.strip() if ch_name == 'aatsr_' + self.bandname: d...
java
@View(name = "by_throttle_params", map = "classpath:CouchDbAuditActionContext_by_throttle_params.js") public List<CouchDbAuditActionContext> findByThrottleParams(final String remoteAddress, final String username, final String failureCode, final String ...
java
@SuppressWarnings("index") // dependent: os[1] is legal when optionLength(os[0])==2 public void setOptions(String[] @MinLen(1) [] options) { String outFilename = null; File destDir = null; for (int oi = 0; oi < options.length; oi++) { String[] os = options[oi]; String opt = os[0].toLowerCase()...
python
def alter(self, tbl_properties=None): """ Change setting and parameters of the table. Parameters ---------- tbl_properties : dict, optional Returns ------- None (for now) """ def _run_ddl(**kwds): stmt = ddl.AlterTable(self._...
java
public void updateFeatures() { for (int i = 0; i < feaGen.features.size(); i++) { Feature f = (Feature)feaGen.features.get(i); f.wgt = lambda[f.idx]; } }
java
public static ListenableFuture<PaymentSession> createFromBitcoinUri(final BitcoinURI uri, final boolean verifyPki) throws PaymentProtocolException { return createFromBitcoinUri(uri, verifyPki, null); }
java
public Map<String, String> getParamMap(String params) { Map<String, String> result = new HashMap<String, String>(); String[] paramlist = params.split("&"); for (int i = 0; i < paramlist.length; i++) { String[] parts = paramlist[i].split("="); if (parts.length == 2) result.put(parts[0], p...
python
def get_objective_bank_hierarchy_session(self, proxy): """Gets the session traversing objective bank hierarchies. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ObjectiveBankHierarchySession) - an ``ObjectiveBankHierarchySession`` raise: NullArgument -...
java
public void processEventsUntilIdle() { boolean idle; do { idle = true; for (MessageProcessor actorThread : actorThreads) { if (actorThread.processNextMessageIfAny()) { idle = false; } if (Thread.interrupted()) { ...
python
def initializeSessionAsBob(sessionState, sessionVersion, parameters): """ :type sessionState: SessionState :type sessionVersion: int :type parameters: BobAxolotlParameters """ sessionState.setSessionVersion(sessionVersion) sessionState.setRemoteIdentityKey(paramet...
python
def add_broadcast_message(self, rawtx, message, sender_wif, dust_limit=common.DUST_LIMIT): """TODO add docstring""" tx = deserialize.tx(rawtx) message = deserialize.unicode_str(message) sender_key = deserialize.key(self.testnet, sender_wif) tx = cont...
java
protected boolean updateFileWindow(Dim.SourceInfo sourceInfo) { String fileName = sourceInfo.url(); FileWindow w = getFileWindow(fileName); if (w != null) { w.updateText(sourceInfo); w.show(); return true; } return false; }
python
def create_downloader_of_type(type_name): """ Create an instance of the downloader with the given name. Args: type_name: The name of a downloader. Returns: An instance of the downloader with the given type. """ downloaders = available_downloaders() if t...
java
public synchronized void configure(HistoryKey pKey, HistoryLimit pHistoryLimit) { // Remove entries if set to null if (pHistoryLimit == null) { removeEntries(pKey); return; } HistoryLimit limit = pHistoryLimit.respectGlobalMaxEntries(globalMaxEntries); if...
python
def rename(self, old_file_path, new_file_path, dir_fd=None): """Rename a FakeFile object at old_file_path to new_file_path, preserving all properties. Also replaces existing new_file_path object, if one existed (Unix only). Args: old_file_path: Path to filesystem obj...
java
public static base_responses delete(nitro_service client, String aliasname[]) throws Exception { base_responses result = null; if (aliasname != null && aliasname.length > 0) { dnscnamerec deleteresources[] = new dnscnamerec[aliasname.length]; for (int i=0;i<aliasname.length;i++){ deleteresources[i] = new ...
java
public void setLength(int size) { expand(size); for (int i = _size; i < size; i++) _data[i] = 0; _size = size; }
java
public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue) { generate(queue, null); }
java
public static Collection beanMap(String property, Collection c, boolean includeNull) { return beanMap(property, c.iterator(), includeNull); }
java
public SwitchBlock<T, R> Case(T ca, def<R> func) { if (!found) { if (method.applyCheckPrimitive(boolean.class, toSwitch, ca)) { res = func.apply(); found = true; } } ...
java
private static void FFT(double[] real, double[] imag) { int n = real.length; if (n == 0) { return; } else if ((n & (n - 1)) == 0) // Is power of 2 transformRadix2(real, imag); else // More complicated algorithm for arbitrary sizes transformBlu...
java
public static <E> List<E> find(Iterator<E> iterator, Predicate<E> predicate) { final Function<Iterator<E>, ArrayList<E>> consumer = new ConsumeIntoCollection<>(new ArrayListFactory<E>()); final FilteringIterator<E> filtered = new FilteringIterator<E>(iterator, predicate); final ArrayList<E> foun...
java
public static boolean acceptDescendant(String pattern, String absPath) { absPath = normalizePath(absPath); pattern = adopt2JavaPattern(pattern); // allows any descendants after pattern += "(/.+)?"; return absPath.matches(pattern); }
java
public static Writable fromEntry(int item,FieldVector from,ColumnType columnType) { if(from.getValueCount() < item) { throw new IllegalArgumentException("Index specified greater than the number of items in the vector with length " + from.getValueCount()); } switch(columnType) { ...
java
public synchronized boolean increase(Bitmap bitmap) { final int bitmapSize = BitmapUtil.getSizeInBytes(bitmap); if (mCount >= mMaxCount || mSize + bitmapSize > mMaxSize) { return false; } mCount++; mSize += bitmapSize; return true; }
python
def where(boolean_expr, true_expr, false_null_expr): """ Equivalent to the ternary expression: if X then Y else Z Parameters ---------- boolean_expr : BooleanValue (array or scalar) true_expr : value Values for each True value false_null_expr : value Values for False or NULL val...
python
def shift(self, periods, freq=None): """ Shift index by desired number of time frequency increments. This method is for shifting the values of datetime-like indexes by a specified time increment a given number of times. Parameters ---------- periods : int ...
python
def fingerprint_from_file(filename): """Extract a fingerprint from a GPG public key file""" cmd = flatten([gnupg_bin(), gnupg_home(), filename]) outp = stderr_output(cmd).split('\n') if not outp[0].startswith('pub'): raise CryptoritoError('probably an invalid gpg key') return outp[1].strip(...
python
def get_creator_by_name(name): """ Get creator function by name. Args: name (str): name of the creator function. Returns: function: creater function. """ return {'docker(container)': Container.creator, 'shell': Bash.creator, 'docker(image)': Image.creator, ...
python
def stop(self): """Stop listening for keyboard input events.""" self.state = False with display_manager(self.display) as d: d.record_disable_context(self.ctx) d.ungrab_keyboard(X.CurrentTime) with display_manager(self.display2): d.record_disable_contex...
java
public void update(long value, long timestamp) { rescaleIfNeeded(); lockForRegularUsage(); try { final double itemWeight = weight(timestamp - startTime); final WeightedSample sample = new WeightedSample(value, itemWeight); final double priority = itemWeight / ...
java
private int[][] calculateInstanceAccommodationMatrix() { if (this.availableInstanceTypes == null) { LOG.error("Cannot compute instance accommodation matrix: availableInstanceTypes is null"); return null; } final int matrixSize = this.availableInstanceTypes.length; final int[][] am = new int[matrixSize][...
java
public final EObject ruleXAnnotation() throws RecognitionException { EObject current = null; Token otherlv_1=null; Token otherlv_3=null; Token otherlv_5=null; Token otherlv_8=null; EObject lv_elementValuePairs_4_0 = null; EObject lv_elementValuePairs_6_0 = null;...
java
public final void deleteMetricDescriptor(MetricDescriptorName name) { DeleteMetricDescriptorRequest request = DeleteMetricDescriptorRequest.newBuilder() .setName(name == null ? null : name.toString()) .build(); deleteMetricDescriptor(request); }
java
public ServiceCall<Configuration> updateConfiguration(UpdateConfigurationOptions updateConfigurationOptions) { Validator.notNull(updateConfigurationOptions, "updateConfigurationOptions cannot be null"); String[] pathSegments = { "v1/environments", "configurations" }; String[] pathParameters = { updateConfig...
java
public static boolean isHostInNetworkCard(String host) { try { InetAddress addr = InetAddress.getByName(host); return NetworkInterface.getByInetAddress(addr) != null; } catch (Exception e) { return false; } }
python
def _get(self, *args, **kwargs): """ A wrapper for getting things :returns: The response of your get :rtype: dict :raises: This will raise a :class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServerException>` if there is an error from...
java
public InputStream asInputStream() { if ( tmp != null ) throw new RuntimeException("can create Input/OutputStream only once"); tmp = new byte[1]; return new InputStream() { @Override public void close() throws IOException { AsyncFile.this.clo...
python
def enums(*names): """Returns a set of `EnumValue` objects with specified names and optionally orders. Values in an enumeration must have unique names and be either all ordered or all unordered. """ if len(names) != len(list(set(names))): raise TypeError("Names in an enumeration must be unique...
java
public DataAppendResult append(StoreTxLogPosition txLog, byte[] dataBytes) throws IOException { int length = dataBytes.length; DataAppendResult result = new DataAppendResult(); synchronized (this) { if (length > maxDataEntrySize) { throw new DBException("Value siz...
python
def updateColumnValue(self, column, value, index=None): """ Assigns the value for the column of this record to the inputed value. :param index | <int> value | <variant> """ if index is None: index = self.treeWidget().column(co...
python
def validate_none(b): """Validate that None is given Parameters ---------- b: {None, 'none'} None or string (the case is ignored) Returns ------- None Raises ------ ValueError""" if isinstance(b, six.string_types): b = b.lower() if b is None or b == 'no...
java
private double ssqerr(int k0, int kmax, double[] logk, double[] log_kDist, double m, double t) { int k = kmax - k0; double result = 0; for(int i = 0; i < k; i++) { // double h = log_kDist[i] - (m * (logk[i] - logk[0]) + t); ??? double h = log_kDist[i] - m * logk[i] - t; result += h * h; ...