language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _set_serializer_by_mime_type(self, mime_type): """ :param mime_type: :return: used by content_type_set to set get a reference to the appropriate serializer """ # ignore if binary response if isinstance(self._app_iter, BinaryResponse): self.logger.info("ignoring setting serializer for binary response") return for available_serializer in self._serializers: if available_serializer.content_type() == mime_type: self._selected_serializer = available_serializer self.logger.info("set serializer for mime type: %s" % mime_type) return self.logger.info("could not find serializer for mime type: %s" % mime_type) raise exception.UnsupportedVocabularyError(mime_type, self.supported_mime_types_str)
java
@Override public void postVisit(PlanNode node) { try { // --------- check special cases for which we handle post visit differently ---------- // skip data source node (they have no inputs) // also, do nothing for union nodes, we connect them later when gathering the inputs for a task // solution sets have no input. the initial solution set input is connected when the iteration node is in its postVisit if (node instanceof SourcePlanNode || node instanceof NAryUnionPlanNode || node instanceof SolutionSetPlanNode) { return; } // check if we have an iteration. in that case, translate the step function now if (node instanceof IterationPlanNode) { // prevent nested iterations if (node.isOnDynamicPath()) { throw new CompilerException("Nested Iterations are not possible at the moment!"); } // if we recursively go into an iteration (because the constant path of one iteration contains // another one), we push the current one onto the stack if (this.currentIteration != null) { this.iterationStack.add(this.currentIteration); } this.currentIteration = (IterationPlanNode) node; this.currentIteration.acceptForStepFunction(this); // pop the current iteration from the stack if (this.iterationStack.isEmpty()) { this.currentIteration = null; } else { this.currentIteration = this.iterationStack.remove(this.iterationStack.size() - 1); } // inputs for initial bulk partial solution or initial workset are already connected to the iteration head in the head's post visit. // connect the initial solution set now. if (node instanceof WorksetIterationPlanNode) { // connect the initial solution set WorksetIterationPlanNode wsNode = (WorksetIterationPlanNode) node; JobVertex headVertex = this.iterations.get(wsNode).getHeadTask(); TaskConfig headConfig = new TaskConfig(headVertex.getConfiguration()); int inputIndex = headConfig.getDriverStrategy().getNumInputs(); headConfig.setIterationHeadSolutionSetInputIndex(inputIndex); translateChannel(wsNode.getInitialSolutionSetInput(), inputIndex, headVertex, headConfig, false); } return; } final JobVertex targetVertex = this.vertices.get(node); // --------- Main Path: Translation of channels ---------- // // There are two paths of translation: One for chained tasks (or merged tasks in general), // which do not have their own task vertex. The other for tasks that have their own vertex, // or are the primary task in a vertex (to which the others are chained). // check whether this node has its own task, or is merged with another one if (targetVertex == null) { // node's task is merged with another task. it is either chained, of a merged head vertex // from an iteration final TaskInChain chainedTask; if ((chainedTask = this.chainedTasks.get(node)) != null) { // Chained Task. Sanity check first... final Iterator<Channel> inConns = node.getInputs().iterator(); if (!inConns.hasNext()) { throw new CompilerException("Bug: Found chained task with no input."); } final Channel inConn = inConns.next(); if (inConns.hasNext()) { throw new CompilerException("Bug: Found a chained task with more than one input!"); } if (inConn.getLocalStrategy() != null && inConn.getLocalStrategy() != LocalStrategy.NONE) { throw new CompilerException("Bug: Found a chained task with an input local strategy."); } if (inConn.getShipStrategy() != null && inConn.getShipStrategy() != ShipStrategyType.FORWARD) { throw new CompilerException("Bug: Found a chained task with an input ship strategy other than FORWARD."); } JobVertex container = chainedTask.getContainingVertex(); if (container == null) { final PlanNode sourceNode = inConn.getSource(); container = this.vertices.get(sourceNode); if (container == null) { // predecessor is itself chained container = this.chainedTasks.get(sourceNode).getContainingVertex(); if (container == null) { throw new IllegalStateException("Bug: Chained task predecessor has not been assigned its containing vertex."); } } else { // predecessor is a proper task job vertex and this is the first chained task. add a forward connection entry. new TaskConfig(container.getConfiguration()).addOutputShipStrategy(ShipStrategyType.FORWARD); } chainedTask.setContainingVertex(container); } // add info about the input serializer type chainedTask.getTaskConfig().setInputSerializer(inConn.getSerializer(), 0); // update name of container task String containerTaskName = container.getName(); if (containerTaskName.startsWith("CHAIN ")) { container.setName(containerTaskName + " -> " + chainedTask.getTaskName()); } else { container.setName("CHAIN " + containerTaskName + " -> " + chainedTask.getTaskName()); } //update resource of container task container.setResources(container.getMinResources().merge(node.getMinResources()), container.getPreferredResources().merge(node.getPreferredResources())); this.chainedTasksInSequence.add(chainedTask); return; } else if (node instanceof BulkPartialSolutionPlanNode || node instanceof WorksetPlanNode) { // merged iteration head task. the task that the head is merged with will take care of it return; } else { throw new CompilerException("Bug: Unrecognized merged task vertex."); } } // -------- Here, we translate non-chained tasks ------------- if (this.currentIteration != null) { JobVertex head = this.iterations.get(this.currentIteration).getHeadTask(); // Exclude static code paths from the co-location constraint, because otherwise // their execution determines the deployment slots of the co-location group if (node.isOnDynamicPath()) { targetVertex.setStrictlyCoLocatedWith(head); } } // create the config that will contain all the description of the inputs final TaskConfig targetVertexConfig = new TaskConfig(targetVertex.getConfiguration()); // get the inputs. if this node is the head of an iteration, we obtain the inputs from the // enclosing iteration node, because the inputs are the initial inputs to the iteration. final Iterator<Channel> inConns; if (node instanceof BulkPartialSolutionPlanNode) { inConns = ((BulkPartialSolutionPlanNode) node).getContainingIterationNode().getInputs().iterator(); // because the partial solution has its own vertex, is has only one (logical) input. // note this in the task configuration targetVertexConfig.setIterationHeadPartialSolutionOrWorksetInputIndex(0); } else if (node instanceof WorksetPlanNode) { WorksetPlanNode wspn = (WorksetPlanNode) node; // input that is the initial workset inConns = Collections.singleton(wspn.getContainingIterationNode().getInput2()).iterator(); // because we have a stand-alone (non-merged) workset iteration head, the initial workset will // be input 0 and the solution set will be input 1 targetVertexConfig.setIterationHeadPartialSolutionOrWorksetInputIndex(0); targetVertexConfig.setIterationHeadSolutionSetInputIndex(1); } else { inConns = node.getInputs().iterator(); } if (!inConns.hasNext()) { throw new CompilerException("Bug: Found a non-source task with no input."); } int inputIndex = 0; while (inConns.hasNext()) { Channel input = inConns.next(); inputIndex += translateChannel(input, inputIndex, targetVertex, targetVertexConfig, false); } // broadcast variables int broadcastInputIndex = 0; for (NamedChannel broadcastInput: node.getBroadcastInputs()) { int broadcastInputIndexDelta = translateChannel(broadcastInput, broadcastInputIndex, targetVertex, targetVertexConfig, true); targetVertexConfig.setBroadcastInputName(broadcastInput.getName(), broadcastInputIndex); targetVertexConfig.setBroadcastInputSerializer(broadcastInput.getSerializer(), broadcastInputIndex); broadcastInputIndex += broadcastInputIndexDelta; } } catch (Exception e) { throw new CompilerException( "An error occurred while translating the optimized plan to a JobGraph: " + e.getMessage(), e); } }
python
def __reset_parser(self): """Reset parser's internal variables Restore the parser to an initial state. Useful when creating a new parser or reusing an existing one. """ self.result = [] self.hash_comments = [] self.__cstate = None self.__curcommand = None self.__curstringlist = None self.__expected = None self.__opened_blocks = 0 RequireCommand.loaded_extensions = []
java
@Nonnull public static <T1, T2> LBiObjCharPredicateBuilder<T1, T2> biObjCharPredicate(Consumer<LBiObjCharPredicate<T1, T2>> consumer) { return new LBiObjCharPredicateBuilder(consumer); }
python
def native_obj(self): """Native storage object.""" if self.__native is None: self.__native = self._get_object() return self.__native
java
private static void encodeHeader(DnsQuery query, ByteBuf buf) { buf.writeShort(query.id()); int flags = 0; flags |= (query.opCode().byteValue() & 0xFF) << 14; if (query.isRecursionDesired()) { flags |= 1 << 8; } buf.writeShort(flags); buf.writeShort(query.count(DnsSection.QUESTION)); buf.writeShort(0); // answerCount buf.writeShort(0); // authorityResourceCount buf.writeShort(query.count(DnsSection.ADDITIONAL)); }
python
def newest(cls, session): """Fetches the latest media added to MAL. :type session: :class:`myanimelist.session.Session` :param session: A valid MAL session :rtype: :class:`.Media` :return: the newest media on MAL :raises: :class:`.MalformedMediaPageError` """ media_type = cls.__name__.lower() p = session.session.get(u'http://myanimelist.net/' + media_type + '.php?o=9&c[]=a&c[]=d&cv=2&w=1').text soup = utilities.get_clean_dom(p) latest_entry = soup.find(u"div", {u"class": u"hoverinfo"}) if not latest_entry: raise MalformedMediaPageError(0, p, u"No media entries found on recently-added page") latest_id = int(latest_entry[u'rel'][1:]) return getattr(session, media_type)(latest_id)
python
def find_whole_word(w): """ Scan through string looking for a location where this word produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. """ return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search
java
@Override public DeleteScheduledAuditResult deleteScheduledAudit(DeleteScheduledAuditRequest request) { request = beforeClientExecution(request); return executeDeleteScheduledAudit(request); }
python
def list_resources(self, device_id): """List all resources registered to a connected device. .. code-block:: python >>> for r in api.list_resources(device_id): print(r.name, r.observable, r.uri) None,True,/3/0/1 Update,False,/5/0/3 ... :param str device_id: The ID of the device (Required) :returns: A list of :py:class:`Resource` objects for the device :rtype: list """ api = self._get_api(mds.EndpointsApi) return [Resource(r) for r in api.get_endpoint_resources(device_id)]
python
def get_items(self, source=None, target=None, crit=None): """Copy records from source to target collection. :param source: Input collection :type source: QueryEngine :param target: Output collection :type target: QueryEngine :param crit: Filter criteria, e.g. "{ 'flag': True }". :type crit: dict """ self._target_coll = target.collection if not crit: # reduce any False-y crit value to None crit = None cur = source.query(criteria=crit) _log.info("source.collection={} crit={} source_records={:d}" .format(source.collection, crit, len(cur))) return cur
python
def _trade(self, security, price=0, amount=0, volume=0, entrust_bs="buy"): """ 调仓 :param security: :param price: :param amount: :param volume: :param entrust_bs: :return: """ stock = self._search_stock_info(security) balance = self.get_balance()[0] if stock is None: raise exceptions.TradeError(u"没有查询要操作的股票信息") if not volume: volume = int(float(price) * amount) # 可能要取整数 if balance["current_balance"] < volume and entrust_bs == "buy": raise exceptions.TradeError(u"没有足够的现金进行操作") if stock["flag"] != 1: raise exceptions.TradeError(u"未上市、停牌、涨跌停、退市的股票无法操作。") if volume == 0: raise exceptions.TradeError(u"操作金额不能为零") # 计算调仓调仓份额 weight = volume / balance["asset_balance"] * 100 weight = round(weight, 2) # 获取原有仓位信息 position_list = self._get_position() # 调整后的持仓 is_have = False for position in position_list: if position["stock_id"] == stock["stock_id"]: is_have = True position["proactive"] = True old_weight = position["weight"] if entrust_bs == "buy": position["weight"] = weight + old_weight else: if weight > old_weight: raise exceptions.TradeError(u"操作数量大于实际可卖出数量") else: position["weight"] = old_weight - weight position["weight"] = round(position["weight"], 2) if not is_have: if entrust_bs == "buy": position_list.append( { "code": stock["code"], "name": stock["name"], "enName": stock["enName"], "hasexist": stock["hasexist"], "flag": stock["flag"], "type": stock["type"], "current": stock["current"], "chg": stock["chg"], "percent": str(stock["percent"]), "stock_id": stock["stock_id"], "ind_id": stock["ind_id"], "ind_name": stock["ind_name"], "ind_color": stock["ind_color"], "textname": stock["name"], "segment_name": stock["ind_name"], "weight": round(weight, 2), "url": "/S/" + stock["code"], "proactive": True, "price": str(stock["current"]), } ) else: raise exceptions.TradeError(u"没有持有要卖出的股票") if entrust_bs == "buy": cash = ( (balance["current_balance"] - volume) / balance["asset_balance"] * 100 ) else: cash = ( (balance["current_balance"] + volume) / balance["asset_balance"] * 100 ) cash = round(cash, 2) log.debug("weight:%f, cash:%f", weight, cash) data = { "cash": cash, "holdings": str(json.dumps(position_list)), "cube_symbol": str(self.account_config["portfolio_code"]), "segment": 1, "comment": "", } try: resp = self.s.post(self.config["rebalance_url"], data=data) # pylint: disable=broad-except except Exception as e: log.warning("调仓失败: %s ", e) return None else: log.debug( "调仓 %s%s: %d", entrust_bs, stock["name"], resp.status_code ) resp_json = json.loads(resp.text) if "error_description" in resp_json and resp.status_code != 200: log.error("调仓错误: %s", resp_json["error_description"]) return [ { "error_no": resp_json["error_code"], "error_info": resp_json["error_description"], } ] return [ { "entrust_no": resp_json["id"], "init_date": self._time_strftime(resp_json["created_at"]), "batch_no": "委托批号", "report_no": "申报号", "seat_no": "席位编号", "entrust_time": self._time_strftime( resp_json["updated_at"] ), "entrust_price": price, "entrust_amount": amount, "stock_code": security, "entrust_bs": "买入", "entrust_type": "雪球虚拟委托", "entrust_status": "-", } ]
python
def _days_from_last_update(catalog, date_field="modified"): """Calcula días desde la última actualización del catálogo. Args: catalog (dict): Un catálogo. date_field (str): Campo de metadatos a utilizar para considerar los días desde la última actualización del catálogo. Returns: int or None: Cantidad de días desde la última actualización del catálogo o None, si no pudo ser calculada. """ # el "date_field" se busca primero a nivel catálogo, luego a nivel # de cada dataset, y nos quedamos con el que sea más reciente date_modified = catalog.get(date_field, None) dias_ultima_actualizacion = None # "date_field" a nivel de catálogo puede no ser obligatorio, # si no está pasamos if isinstance(date_modified, string_types): date = helpers.parse_date_string(date_modified) dias_ultima_actualizacion = ( datetime.now() - date).days if date else None for dataset in catalog.get('dataset', []): date = helpers.parse_date_string(dataset.get(date_field, "")) days_diff = float((datetime.now() - date).days) if date else None # Actualizo el indicador de días de actualización si corresponde if not dias_ultima_actualizacion or \ (days_diff and days_diff < dias_ultima_actualizacion): dias_ultima_actualizacion = days_diff if dias_ultima_actualizacion: return int(dias_ultima_actualizacion) else: return None
python
def _format_summary(lines, element, spacer=" "): """Adds the element's summary tag to the lines if it exists.""" summary = spacer + element.summary if element.summary == "": summary = spacer + "No description given in XML documentation for this element." lines.append(summary)
python
def unregister(self, type_, handler): """注销事件处理函数监听""" # 尝试获取该事件类型对应的处理函数列表,若无则忽略该次注销请求 handlerList = self.__handlers[type_] # 如果该函数存在于列表中,则移除 if handler in handlerList: handlerList.remove(handler) # 如果函数列表为空,则从引擎中移除该事件类型 if not handlerList: del self.__handlers[type_]
java
public static Calendar getThreadCalendar(Locale l, TimeZone tz) { if (tz == null) tz = ThreadLocalPageContext.getTimeZone(); Calendar c = localeCalendar.get(tz, l); c.setTimeZone(tz); return c; }
java
@NonNull public List<Address> getFromLocationName(final String locationName, final int maxResults, final boolean parseAddressComponents) throws GeocoderException { if (locationName == null) { throw new IllegalArgumentException("locationName == null"); } if (isLimitExceeded()) { throw GeocoderException.forQueryOverLimit(); } final Uri.Builder uriBuilder = buildBaseRequestUri() .appendQueryParameter("sensor", "false") .appendQueryParameter("address", locationName); final String url = uriBuilder.toString(); byte[] data; try { data = download(url); } catch (IOException e) { throw new GeocoderException(e); } try { return Parser.parseJson(data, maxResults, parseAddressComponents); } catch (GeocoderException e) { if (e.getStatus() == Status.OVER_QUERY_LIMIT) { // OVER_QUERY_LIMIT could be thrown if too many calls per second // If after two seconds, it is thrown again - then it means there are too much calls // per 24 hours try { Thread.sleep(2000); } catch (InterruptedException e1) { // Safely abort when interrupted return new ArrayList<>(); } try { data = download(url); } catch (IOException ioe) { throw new GeocoderException(ioe); } try { return Parser.parseJson(data, maxResults, parseAddressComponents); } catch (GeocoderException e1) { if (e1.getStatus() == Status.OVER_QUERY_LIMIT) { // available in 24 hours setAllowedDate(System.currentTimeMillis() + 86400000L); } throw e1; } } else { throw e; } } }
python
def status_delete(self, id): """ Delete a status """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}'.format(str(id)) self.__api_request('DELETE', url)
java
public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub) { checkNotNull(priv); checkNotNull(pub); return new ECKey(new BigInteger(1, priv), CURVE.getCurve().decodePoint(pub)); }
python
def _add_expansion_to_acronym_dict(acronym, expansion, level, dictionary): """Add an acronym to the dictionary. Takes care of avoiding duplicates and keeping the expansion marked with the best score. """ if len(acronym) >= len(expansion) or acronym in expansion: return for punctuation in re.findall("\W", expansion): # The expansion contains non-basic punctuation. It is probable # that it is invalid. Discard it. if punctuation not in (",", " ", "-"): return False if acronym in dictionary: add = True for stored_expansion, stored_level in dictionary[acronym]: if _equivalent_expansions(stored_expansion, expansion): if level < stored_level: dictionary[acronym].remove( (stored_expansion, stored_level)) break else: add = False if add: dictionary[acronym].append((expansion, level)) return True else: dictionary.setdefault(acronym, []).append((expansion, level)) return True return False
java
@Override public Collection<Alternative> getAlternatives() { List<Alternative> allSuggestions = new ArrayList<>(); for (List<Alternative> suggestions : this.suggestions.values()) { allSuggestions.addAll(suggestions); } return allSuggestions; }
java
public DataMigrationServiceInner beginCreateOrUpdate(String groupName, String serviceName, DataMigrationServiceInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(groupName, serviceName, parameters).toBlocking().single().body(); }
python
def select(self, fields, **exprs): """ Create a new table containing a subset of attributes, with optionally newly-added fields computed from each rec in the original table. @param fields: list of strings, or single space-delimited string, listing attribute name to be included in the output @type fields: list, or space-delimited string @param exprs: one or more named callable arguments, to compute additional fields using the given function @type exprs: C{name=callable}, callable takes the record as an argument, and returns the new attribute value If a string is passed as a callable, this string will be used using string formatting, given the record as a source of interpolation values. For instance, C{fullName = '%(lastName)s, %(firstName)s'} """ fields = self._parse_fields_string(fields) def _make_string_callable(expr): if isinstance(expr, basestring): return lambda r: expr % r else: return expr exprs = dict((k, _make_string_callable(v)) for k, v in exprs.items()) raw_tuples = [] for ob in self.obs: attrvalues = tuple(getattr(ob, fieldname, None) for fieldname in fields) if exprs: attrvalues += tuple(expr(ob) for expr in exprs.values()) raw_tuples.append(attrvalues) all_names = tuple(fields) + tuple(exprs.keys()) ret = Table() ret._indexes.update(dict((k, v.copy_template()) for k, v in self._indexes.items() if k in all_names)) return ret().insert_many(DataObject(**dict(zip(all_names, outtuple))) for outtuple in raw_tuples)
python
def _plt_pydot(self, fout_img): """Plot using the pydot graphics engine.""" dag = self._get_pydot_graph() img_fmt = os.path.splitext(fout_img)[1][1:] dag.write(fout_img, format=img_fmt) self.log.write(" {GO_USR:>3} usr {GO_ALL:>3} GOs WROTE: {F}\n".format( F=fout_img, GO_USR=len(self.godag.go_sources), GO_ALL=len(self.godag.go2obj)))
python
def get_logger(): """ Instantiate a logger. """ root = logging.getLogger() root.setLevel(logging.WARNING) ch = logging.StreamHandler(sys.stderr) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(message)s') ch.setFormatter(formatter) root.addHandler(ch) return root
java
public static boolean clientIdentEqual(final ClntIdent ident1, final ClntIdent ident2) { boolean areEqual = true; if (ident1 == null || ident2 == null || ident1.discriminator() == null || ident2.discriminator() == null) { areEqual = false; } else if (ident1.discriminator().value() != ident2.discriminator().value()) { areEqual = false; } else if (ident1.discriminator().equals(LockerLanguage.CPP) && ident1.cpp_clnt() != ident2.cpp_clnt()) { areEqual = false; } else if (ident1.discriminator().equals(LockerLanguage.JAVA) && ident1.java_clnt().MainClass.equalsIgnoreCase(ident2.java_clnt().MainClass)) { areEqual = false; } else if (ident1.discriminator().equals(LockerLanguage.JAVA) && !Arrays.equals(ident1.java_clnt().uuid, ident2.java_clnt().uuid)) { areEqual = false; } return areEqual; }
python
def container(self, cls, **kwargs): """Container context manager.""" self.start_container(cls, **kwargs) yield self.end_container()
java
@Override public Long getRepositoryObjectCount() { final Repository repo = getJcrRepository(repository); try { return getRepositoryCount(repo); } catch (final RepositoryException e) { throw new RepositoryRuntimeException(e); } }
java
public void billingAccount_rsva_serviceName_PUT(String billingAccount, String serviceName, OvhRsva body) throws IOException { String qPath = "/telephony/{billingAccount}/rsva/{serviceName}"; StringBuilder sb = path(qPath, billingAccount, serviceName); exec(qPath, "PUT", sb.toString(), body); }
java
@Override public int compareTo(final MutableByte other) { return (this.value > other.value) ? 1 : ((this.value == other.value) ? 0 : -1); }
java
public void resolve(@Nullable View view, @NonNull HttpRequest request, @NonNull HttpResponse response) { if (view == null) return; Object output = view.output(); if (output == null) return; if (view.rest()) { resolveRest(output, request, response); } else { resolvePath(output, request, response); } }
python
def iter_tar(arch_f, gz=False, stream=False): """Iter over tar archive, yielding (path, object-like) tuples. Args: arch_f: File object of the archive to iterate. gz: If True, open a gzip'ed archive. stream: If True, open the archive in stream mode which allows for faster processing and less temporary disk consumption, but random access to the file is not allowed. Yields: (filepath, extracted_fobj) for each file in the archive. """ read_type = 'r' + ('|' if stream else ':') if gz: read_type += 'gz' with _open_or_pass(arch_f) as fobj: tar = tarfile.open(mode=read_type, fileobj=fobj) for member in tar: extract_file = tar.extractfile(member) if extract_file: # File with data (not directory): path = _normpath(member.path) if not path: continue yield [path, extract_file]
java
public void shiftValuesLeft(final int numberOfBinaryOrdersOfMagnitude) { if (numberOfBinaryOrdersOfMagnitude < 0) { throw new IllegalArgumentException("Cannot shift by a negative number of magnitudes"); } if (numberOfBinaryOrdersOfMagnitude == 0) { return; } if (getTotalCount() == getCountAtIndex(0)) { // (no need to shift any values if all recorded values are at the 0 value level:) return; } final int shiftAmount = numberOfBinaryOrdersOfMagnitude << subBucketHalfCountMagnitude; int maxValueIndex = countsArrayIndex(getMaxValue()); // indicate overflow if maxValue is in the range being wrapped: if (maxValueIndex >= (countsArrayLength - shiftAmount)) { throw new ArrayIndexOutOfBoundsException( "Operation would overflow, would discard recorded value counts"); } long maxValueBeforeShift = maxValueUpdater.getAndSet(this, 0); long minNonZeroValueBeforeShift = minNonZeroValueUpdater.getAndSet(this, Long.MAX_VALUE); boolean lowestHalfBucketPopulated = (minNonZeroValueBeforeShift < subBucketHalfCount); // Perform the shift: shiftNormalizingIndexByOffset(shiftAmount, lowestHalfBucketPopulated); // adjust min, max: updateMinAndMax(maxValueBeforeShift << numberOfBinaryOrdersOfMagnitude); if (minNonZeroValueBeforeShift < Long.MAX_VALUE) { updateMinAndMax(minNonZeroValueBeforeShift << numberOfBinaryOrdersOfMagnitude); } }
java
private void addWarpExtensionsDeployment(WebArchive archive) { final Collection<WarpDeploymentEnrichmentExtension> lifecycleExtensions = serviceLoader.get().all( WarpDeploymentEnrichmentExtension.class); for (WarpDeploymentEnrichmentExtension extension : lifecycleExtensions) { JavaArchive library = extension.getEnrichmentLibrary(); if (library != null) { archive.addAsLibrary(library); } extension.enrichWebArchive(archive); } }
java
public static Range valueOf(final String value) { final Optional<Integer[]> vals = parse(value); if (vals.isPresent()) { return new Range(vals.get()[0], vals.get()[1]); } return null; }
python
def _compile(self, module=None): """ Compile functions for argparsing. """ # get the main module mod = module or sys.modules['__main__'] self.mod = mod # setup the script version if hasattr(mod, '__version__'): version = "%(prog)s " + mod.__version__ self.ap_args.append( ap_arg('-v', '--version', action='version', version=version)) # setup the script description if module is None: if 'description' not in self.argparse_args and hasattr(mod, '__doc__'): self.argparse_args['description'] = mod.__doc__ # setup main parser self.parser = argparse.ArgumentParser( formatter_class=self.formatter_class, **self.argparse_args) if self.error: # setup the error method if we have one setattr( self.parser, 'error', types.MethodType(self.error, self.parser)) if self.add_output: # add the output options if we have the add_output true if isinstance(self.add_output, basestring): odefault = self.add_output else: odefault = None self.parser.add_argument( '-o', '--output', metavar="FILE", default=odefault, help="Output to file") self.parser.add_argument( '--encoding', default="utf-8", help="Encoding for output file.") self.parser.add_argument( '--write-mode', default=self.write_mode, help="Write mode") if self._cfg_factory: # if we have a config factory add the config options self.parser.add_argument( '-c', '--config', metavar="FILE", default=self.cfg_file, help="Configuration file") if self.auths: # if we have authorizations enabled add the auth options self.parser.add_argument( '--auth', help="Authorization phrase for special commands.") # let's exexcute plugins for plugin in ArgParseInator._plugins.values(): plugin(self) if self.ap_args is not None: # if we have argment parser args we will add them to the main parser for aargs, akargs in self.ap_args: self.parser.add_argument(*aargs, **akargs) if len(self.commands) == 1 and self.never_single is False: # if we have only one command ad never_single is False # setup the command as the only command. func = six.next(six.itervalues(self.commands)) # add the arguments to the main parser for args, kwargs in func.__arguments__: self.parser.add_argument(*args, **kwargs) # shortcut for the single command self._single = func if not self.parser.description: # replace the description if we dont' have one self.parser.description = func.__doc__ or self.parser.description else: # or add to the main description if func.__doc__: self.parser.description += linesep + linesep + func.__doc__ if not self.parser.epilog: # replace the description if we dont' have one self.parser.epilog = getattr( func, "__epilog__", self.parser.epilog) else: # or add to the main description if hasattr(func, '__epilog__'): self.parser.epilog += linesep + linesep + func.__epilog__ utils.set_subcommands(func, self.parser) else: # if we have more than one command or we don't want a single command # set the single to None self._single = None # setup the subparsers self.subparsers = self.parser.add_subparsers( title=utils.COMMANDS_LIST_TITLE, dest='command', description=utils.COMMANDS_LIST_DESCRIPTION) # add all the commands for func in self.commands.values(): parser = utils.get_parser(func, self.subparsers) utils.set_subcommands(func, parser) return self.parser
java
public String toHtml(Locale locale) { CmsMessages mg = Messages.get().getBundle(locale); if (m_brokenLinks.size() > 0) { StringBuffer result = new StringBuffer(1024); Iterator<Entry<String, String>> brokenLinks = m_brokenLinks.entrySet().iterator(); result.append(mg.key(Messages.GUI_LINK_VALIDATION_RESULTS_INTRO_1, new Object[] {m_validationDate})).append( "<ul>"); while (brokenLinks.hasNext()) { Entry<String, String> link = brokenLinks.next(); String linkPath = link.getKey(); String linkUrl = link.getValue(); String msg = mg.key(Messages.GUI_LINK_POINTING_TO_2, new Object[] {linkPath, linkUrl}); result.append("<li>").append(msg).append("</li>"); } return result.append("</ul>").toString(); } else { return mg.key(Messages.GUI_LINK_VALIDATION_RESULTS_ALL_VALID_1, new Object[] {m_validationDate}); } }
python
def _raise_on_invalid_client(self, request): """Raise on failed client authentication.""" if self.request_validator.client_authentication_required(request): if not self.request_validator.authenticate_client(request): log.debug('Client authentication failed, %r.', request) raise InvalidClientError(request=request) elif not self.request_validator.authenticate_client_id(request.client_id, request): log.debug('Client authentication failed, %r.', request) raise InvalidClientError(request=request)
java
public void setItem(int index) { if (index < 0 || index >= items.size()) { return; } stop(); currentItemIndex = index; try { PlayItemEntry entry = items.get(currentItemIndex); if (entry != null) { IPlayItem item = entry.item; engine.play(item); entry.played = true; } } catch (IOException e) { log.warn("setItem caught a IOException", e); } catch (StreamNotFoundException e) { // let the engine retain the STOPPED stateand wait for control from outside log.debug("setItem caught a StreamNotFoundException"); } catch (IllegalStateException e) { log.warn("Illegal state exception on playlist item setup", e); } }
python
def ticket_form_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/ticket_forms#show-ticket-form" api_path = "/api/v2/ticket_forms/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
java
public static URLEntity createUrlEntity(int start, int end, String url, String expandedURL, String displayURL) { return new URLEntityJSONImpl(start, end, url, expandedURL, displayURL); }
python
def _get_connection(self, cluster): """Return a connection to a Cluster. Return a MongoClient or a MongoReplicaSetClient for the given Cluster. This is done in a lazy manner (if there is already a Client connected to the Cluster, it is returned and no other Client is created). Args: cluster: A dict containing information about a cluster. Returns: A MongoClient or MongoReplicaSetClient instance connected to the desired cluster """ # w=1 because: # http://stackoverflow.com/questions/14798552/is-mongodb-2-x-write-concern-w-1-truly-equals-to-safe-true if 'connection' not in cluster: cluster['connection'] = self._connection_class( socketTimeoutMS=self._network_timeout, w=1, j=self.j, **cluster['params']) return cluster['connection']
java
public static double xbarVariance(double variance, int sampleN, int populationN) { if(populationN<=0 || sampleN<=0 || sampleN>populationN) { throw new IllegalArgumentException("All the parameters must be positive and sampleN smaller than populationN."); } double xbarVariance=(1.0 - (double)sampleN/populationN)*variance/sampleN; return xbarVariance; }
java
public void setMatchedText(String v) { if (BioVerb_Type.featOkTst && ((BioVerb_Type)jcasType).casFeat_matchedText == null) jcasType.jcas.throwFeatMissing("matchedText", "ch.epfl.bbp.uima.types.BioVerb"); jcasType.ll_cas.ll_setStringValue(addr, ((BioVerb_Type)jcasType).casFeatCode_matchedText, v);}
java
public static DiscountCurveInterpolation createDiscountCurveFromZeroRates( String name, LocalDate referenceDate, double[] times, double[] givenZeroRates, boolean[] isParameter, InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity) { double[] givenDiscountFactors = new double[givenZeroRates.length]; for(int timeIndex=0; timeIndex<times.length;timeIndex++) { givenDiscountFactors[timeIndex] = Math.exp(- givenZeroRates[timeIndex] * times[timeIndex]); } return createDiscountCurveFromDiscountFactors(name, referenceDate, times, givenDiscountFactors, isParameter, interpolationMethod, extrapolationMethod, interpolationEntity); }
java
@Override public Evidence convert(BELEvidence be) { if (be == null) { return null; } return CommonModelFactory.getInstance().createEvidence( be.getEvidenceLine()); }
java
public java.util.List<DBSecurityGroupMembership> getDBSecurityGroupMemberships() { if (dBSecurityGroupMemberships == null) { dBSecurityGroupMemberships = new com.amazonaws.internal.SdkInternalList<DBSecurityGroupMembership>(); } return dBSecurityGroupMemberships; }
python
def declared_date(self, value): """ The date on which the corporate action was declared :param value: :return: """ if value: self._declared_date = parse(value).date() if isinstance(value, type_check) else value
python
def fetch(self, request, callback=None, raise_error=True, **kwargs): """Executes a request by AsyncHTTPClient, asynchronously returning an `tornado.HTTPResponse`. The ``raise_error=False`` argument currently suppresses *all* errors, encapsulating them in `HTTPResponse` objects following the tornado http-client standard """ # accepts request as string then convert it to HTTPRequest if isinstance(request, str): request = HTTPRequest(request, **kwargs) try: # The first request calls tornado-client ignoring the # possible exception, in case of 401 response, # renews the access token and replay it response = yield self._authorized_fetch(request, callback, raise_error=False, **kwargs) if response.code == BAD_TOKEN: yield self._token_manager.reset_token() elif response.error and raise_error: raise response.error else: raise gen.Return(response) # The request with renewed token response = yield self._authorized_fetch(request, callback, raise_error=raise_error, **kwargs) raise gen.Return(response) except TokenError as err: yield self._token_manager.reset_token() raise err
java
public Future<List<PlayerStats>> getStatsSummary(long summoner, Season season) { return new ApiFuture<>(() -> handler.getStatsSummary(summoner, season)); }
python
def distinct(self): """ Only return distinct row. Return a new query set with distinct mark """ new_query_set = self.clone() new_query_set.query.distinct = True return new_query_set
java
void removeProducer(JmsMsgProducerImpl producer) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "removeProducer", producer); producers.remove(producer); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "removeProducer"); }
java
public static synchronized LocalConfig getConfig(String name) { SeLionLogger.getLogger().entering(name); checkArgument(StringUtils.isNotBlank(name), "The test name for which configuration is being retrieved cannot be null (or) empty."); // if no local config added? I.e reading from a TestNG listener (before AddConfig) or listeners disabled? LocalConfig localConfiguration = configsMap.get(name); if (localConfiguration == null) { throw new IllegalArgumentException( "A local configuration with specified name was not found. Please double check the <test> name and retry."); } SeLionLogger.getLogger().exiting(localConfiguration); return localConfiguration; }
java
public void addToToolbar( JComponent comp ) { toolbar.add(comp,1+algBoxes.length); toolbar.revalidate(); addedComponents.add(comp); }
java
@Override public GetPatchBaselineResult getPatchBaseline(GetPatchBaselineRequest request) { request = beforeClientExecution(request); return executeGetPatchBaseline(request); }
java
protected static List getFileListFromServer(boolean includeFolders) { List result = new ArrayList(); // get the RFS package export path String exportpath = OpenCms.getSystemInfo().getPackagesRfsPath(); File folder = new File(exportpath); // get a list of all files of the packages folder String[] files = folder.list(); for (int i = 0; i < files.length; i++) { File diskFile = new File(exportpath, files[i]); // check this is a file and ends with zip -> this is a database upload file if (diskFile.isFile() && diskFile.getName().endsWith(".zip")) { result.add(diskFile.getName()); } else if (diskFile.isDirectory() && includeFolders && (!diskFile.getName().equalsIgnoreCase(FOLDER_MODULES)) && ((new File(diskFile + File.separator + FILE_MANIFEST)).exists())) { // this is an unpacked package, add it to uploadable files result.add(diskFile.getName()); } } return result; }
python
def get_order_in_album(self, reversed_ordering=True): ''' Returns image order number. It is calculated as (number+1) of images attached to the same content_object whose order is greater (if 'reverse_ordering' is True) or lesser (if 'reverse_ordering' is False) than image's order. ''' lookup = 'order__gt' if reversed_ordering else 'order__lt' return self.__class__.objects.\ for_model(self.content_object, self.content_type).\ filter(**{lookup: self.order}).count() + 1
python
def sentiment(text): """ Returns a float for sentiment strength based on the input text. Positive values are positive valence, negative value are negative valence. """ sentiment.valence_dict = load_valence_dict() if sentiment.valence_dict is None else sentiment_valence_dict wordsAndEmoticons = str(text).split() #doesn't separate words from adjacent punctuation (keeps emoticons & contractions) text_mod = regex_remove_punctuation.sub('', text) # removes punctuation (but loses emoticons & contractions) wordsOnly = str(text_mod).split() # get rid of empty items or single letter "words" like 'a' and 'I' from wordsOnly for word in wordsOnly: if len(word) <= 1: wordsOnly.remove(word) # now remove adjacent & redundant punctuation from [wordsAndEmoticons] while keeping emoticons and contractions puncList = [".", "!", "?", ",", ";", ":", "-", "'", "\"", "!!", "!!!", "??", "???", "?!?", "!?!", "?!?!", "!?!?"] for word in wordsOnly: for p in puncList: pword = p + word x1 = wordsAndEmoticons.count(pword) while x1 > 0: i = wordsAndEmoticons.index(pword) wordsAndEmoticons.remove(pword) wordsAndEmoticons.insert(i, word) x1 = wordsAndEmoticons.count(pword) wordp = word + p x2 = wordsAndEmoticons.count(wordp) while x2 > 0: i = wordsAndEmoticons.index(wordp) wordsAndEmoticons.remove(wordp) wordsAndEmoticons.insert(i, word) x2 = wordsAndEmoticons.count(wordp) # get rid of residual empty items or single letter "words" like 'a' and 'I' from wordsAndEmoticons for word in wordsAndEmoticons: if len(word) <= 1: wordsAndEmoticons.remove(word) # remove stopwords from [wordsAndEmoticons] #stopwords = [str(word).strip() for word in open('stopwords.txt')] #for word in wordsAndEmoticons: # if word in stopwords: # wordsAndEmoticons.remove(word) # check for negation negate = ["aint", "arent", "cannot", "cant", "couldnt", "darent", "didnt", "doesnt", "ain't", "aren't", "can't", "couldn't", "daren't", "didn't", "doesn't", "dont", "hadnt", "hasnt", "havent", "isnt", "mightnt", "mustnt", "neither", "don't", "hadn't", "hasn't", "haven't", "isn't", "mightn't", "mustn't", "neednt", "needn't", "never", "none", "nope", "nor", "not", "nothing", "nowhere", "oughtnt", "shant", "shouldnt", "uhuh", "wasnt", "werent", "oughtn't", "shan't", "shouldn't", "uh-uh", "wasn't", "weren't", "without", "wont", "wouldnt", "won't", "wouldn't", "rarely", "seldom", "despite"] def negated(list, nWords=[], includeNT=True): nWords.extend(negate) for word in nWords: if word in list: return True if includeNT: for word in list: if "n't" in word: return True if "least" in list: i = list.index("least") if i > 0 and list[i-1] != "at": return True return False def normalize(score, alpha=15): # normalize the score to be between -1 and 1 using an alpha that approximates the max expected value normScore = score/math.sqrt( ((score*score) + alpha) ) return normScore def wildCardMatch(patternWithWildcard, listOfStringsToMatchAgainst): listOfMatches = fnmatch.filter(listOfStringsToMatchAgainst, patternWithWildcard) return listOfMatches def isALLCAP_differential(wordList): countALLCAPS= 0 for w in wordList: if str(w).isupper(): countALLCAPS += 1 cap_differential = len(wordList) - countALLCAPS if cap_differential > 0 and cap_differential < len(wordList): isDiff = True else: isDiff = False return isDiff isCap_diff = isALLCAP_differential(wordsAndEmoticons) b_incr = 0.293 #(empirically derived mean sentiment intensity rating increase for booster words) b_decr = -0.293 # booster/dampener 'intensifiers' or 'degree adverbs' http://en.wiktionary.org/wiki/Category:English_degree_adverbs booster_dict = {"absolutely": b_incr, "amazingly": b_incr, "awfully": b_incr, "completely": b_incr, "considerably": b_incr, "decidedly": b_incr, "deeply": b_incr, "effing": b_incr, "enormously": b_incr, "entirely": b_incr, "especially": b_incr, "exceptionally": b_incr, "extremely": b_incr, "fabulously": b_incr, "flipping": b_incr, "flippin": b_incr, "fricking": b_incr, "frickin": b_incr, "frigging": b_incr, "friggin": b_incr, "fully": b_incr, "fucking": b_incr, "greatly": b_incr, "hella": b_incr, "highly": b_incr, "hugely": b_incr, "incredibly": b_incr, "intensely": b_incr, "majorly": b_incr, "more": b_incr, "most": b_incr, "particularly": b_incr, "purely": b_incr, "quite": b_incr, "really": b_incr, "remarkably": b_incr, "so": b_incr, "substantially": b_incr, "thoroughly": b_incr, "totally": b_incr, "tremendously": b_incr, "uber": b_incr, "unbelievably": b_incr, "unusually": b_incr, "utterly": b_incr, "very": b_incr, "almost": b_decr, "barely": b_decr, "hardly": b_decr, "just enough": b_decr, "kind of": b_decr, "kinda": b_decr, "kindof": b_decr, "kind-of": b_decr, "less": b_decr, "little": b_decr, "marginally": b_decr, "occasionally": b_decr, "partly": b_decr, "scarcely": b_decr, "slightly": b_decr, "somewhat": b_decr, "sort of": b_decr, "sorta": b_decr, "sortof": b_decr, "sort-of": b_decr} sentiments = [] for item in wordsAndEmoticons: v = 0 i = wordsAndEmoticons.index(item) if (i < len(wordsAndEmoticons)-1 and str(item).lower() == "kind" and \ str(wordsAndEmoticons[i+1]).lower() == "of") or str(item).lower() in booster_dict: sentiments.append(v) continue item_lowercase = str(item).lower() if item_lowercase in sentiment.valence_dict: #get the sentiment valence v = float(sentiment.valence_dict[item_lowercase]) #check if sentiment laden word is in ALLCAPS (while others aren't) c_incr = 0.733 #(empirically derived mean sentiment intensity rating increase for using ALLCAPs to emphasize a word) if str(item).isupper() and isCap_diff: if v > 0: v += c_incr else: v -= c_incr #check if the preceding words increase, decrease, or negate/nullify the valence def scalar_inc_dec(word, valence): scalar = 0.0 word_lower = str(word).lower() if word_lower in booster_dict: scalar = booster_dict[word_lower] if valence < 0: scalar *= -1 #check if booster/dampener word is in ALLCAPS (while others aren't) if str(word).isupper() and isCap_diff: if valence > 0: scalar += c_incr else: scalar -= c_incr return scalar n_scalar = -0.74 if i > 0 and str(wordsAndEmoticons[i-1]).lower() not in sentiment.valence_dict: s1 = scalar_inc_dec(wordsAndEmoticons[i-1], v) v = v+s1 if negated([wordsAndEmoticons[i-1]]): v = v*n_scalar if i > 1 and str(wordsAndEmoticons[i-2]).lower() not in sentiment.valence_dict: s2 = scalar_inc_dec(wordsAndEmoticons[i-2], v) if s2 != 0: s2 = s2*0.95 v = v+s2 # check for special use of 'never' as valence modifier instead of negation if wordsAndEmoticons[i-2] == "never" and (wordsAndEmoticons[i-1] == "so" or wordsAndEmoticons[i-1] == "this"): v = v*1.5 # otherwise, check for negation/nullification elif negated([wordsAndEmoticons[i-2]]): v = v*n_scalar if i > 2 and str(wordsAndEmoticons[i-3]).lower() not in sentiment.valence_dict: s3 = scalar_inc_dec(wordsAndEmoticons[i-3], v) if s3 != 0: s3 = s3*0.9 v = v+s3 # check for special use of 'never' as valence modifier instead of negation if wordsAndEmoticons[i-3] == "never" and \ (wordsAndEmoticons[i-2] == "so" or wordsAndEmoticons[i-2] == "this") or \ (wordsAndEmoticons[i-1] == "so" or wordsAndEmoticons[i-1] == "this"): v = v*1.25 # otherwise, check for negation/nullification elif negated([wordsAndEmoticons[i-3]]): v = v*n_scalar # check for special case idioms using a sentiment-laden keyword known to SAGE special_case_idioms = {"the shit": 3, "the bomb": 3, "bad ass": 1.5, "yeah right": -2, "cut the mustard": 2, "kiss of death": -1.5, "hand to mouth": -2} # future work: consider other sentiment-laden idioms #other_idioms = {"back handed": -2, "blow smoke": -2, "blowing smoke": -2, "upper hand": 1, "break a leg": 2, # "cooking with gas": 2, "in the black": 2, "in the red": -2, "on the ball": 2,"under the weather": -2} onezero = "{} {}".format(str(wordsAndEmoticons[i-1]), str(wordsAndEmoticons[i])) twoonezero = "{} {}".format(str(wordsAndEmoticons[i-2]), str(wordsAndEmoticons[i-1]), str(wordsAndEmoticons[i])) twoone = "{} {}".format(str(wordsAndEmoticons[i-2]), str(wordsAndEmoticons[i-1])) threetwoone = "{} {} {}".format(str(wordsAndEmoticons[i-3]), str(wordsAndEmoticons[i-2]), str(wordsAndEmoticons[i-1])) threetwo = "{} {}".format(str(wordsAndEmoticons[i-3]), str(wordsAndEmoticons[i-2])) if onezero in special_case_idioms: v = special_case_idioms[onezero] elif twoonezero in special_case_idioms: v = special_case_idioms[twoonezero] elif twoone in special_case_idioms: v = special_case_idioms[twoone] elif threetwoone in special_case_idioms: v = special_case_idioms[threetwoone] elif threetwo in special_case_idioms: v = special_case_idioms[threetwo] if len(wordsAndEmoticons)-1 > i: zeroone = "{} {}".format(str(wordsAndEmoticons[i]), str(wordsAndEmoticons[i+1])) if zeroone in special_case_idioms: v = special_case_idioms[zeroone] if len(wordsAndEmoticons)-1 > i+1: zeroonetwo = "{} {}".format(str(wordsAndEmoticons[i]), str(wordsAndEmoticons[i+1]), str(wordsAndEmoticons[i+2])) if zeroonetwo in special_case_idioms: v = special_case_idioms[zeroonetwo] # check for booster/dampener bi-grams such as 'sort of' or 'kind of' if threetwo in booster_dict or twoone in booster_dict: v = v+b_decr # check for negation case using "least" if i > 1 and str(wordsAndEmoticons[i-1]).lower() not in sentiment.valence_dict \ and str(wordsAndEmoticons[i-1]).lower() == "least": if (str(wordsAndEmoticons[i-2]).lower() != "at" and str(wordsAndEmoticons[i-2]).lower() != "very"): v = v*n_scalar elif i > 0 and str(wordsAndEmoticons[i-1]).lower() not in sentiment.valence_dict \ and str(wordsAndEmoticons[i-1]).lower() == "least": v = v*n_scalar sentiments.append(v) # check for modification in sentiment due to contrastive conjunction 'but' if 'but' in wordsAndEmoticons or 'BUT' in wordsAndEmoticons: try: bi = wordsAndEmoticons.index('but') except: bi = wordsAndEmoticons.index('BUT') for s in sentiments: si = sentiments.index(s) if si < bi: sentiments.pop(si) sentiments.insert(si, s*0.5) elif si > bi: sentiments.pop(si) sentiments.insert(si, s*1.5) if sentiments: sum_s = float(sum(sentiments)) #print sentiments, sum_s # check for added emphasis resulting from exclamation points (up to 4 of them) ep_count = str(text).count("!") if ep_count > 4: ep_count = 4 ep_amplifier = ep_count*0.292 #(empirically derived mean sentiment intensity rating increase for exclamation points) if sum_s > 0: sum_s += ep_amplifier elif sum_s < 0: sum_s -= ep_amplifier # check for added emphasis resulting from question marks (2 or 3+) qm_count = str(text).count("?") qm_amplifier = 0 if qm_count > 1: if qm_count <= 3: qm_amplifier = qm_count*0.18 else: qm_amplifier = 0.96 if sum_s > 0: sum_s += qm_amplifier elif sum_s < 0: sum_s -= qm_amplifier compound = normalize(sum_s) # want separate positive versus negative sentiment scores pos_sum = 0.0 neg_sum = 0.0 neu_count = 0 for sentiment_score in sentiments: if sentiment_score > 0: pos_sum += (float(sentiment_score) +1) # compensates for neutral words that are counted as 1 if sentiment_score < 0: neg_sum += (float(sentiment_score) -1) # when used with math.fabs(), compensates for neutrals if sentiment_score == 0: neu_count += 1 if pos_sum > math.fabs(neg_sum): pos_sum += (ep_amplifier+qm_amplifier) elif pos_sum < math.fabs(neg_sum): neg_sum -= (ep_amplifier+qm_amplifier) total = pos_sum + math.fabs(neg_sum) + neu_count pos = math.fabs(pos_sum / total) neg = math.fabs(neg_sum / total) neu = math.fabs(neu_count / total) else: compound, pos, neg, neu = 0., 0., 0., 0. s = {"neg" : round(neg, 3), "neu" : round(neu, 3), "pos" : round(pos, 3), "compound" : round(compound, 4)} return s
python
def _dump_additional_attributes(additional_attributes): """ try to parse additional attributes, but ends up to hexdump if the scheme is unknown """ attributes_raw = io.BytesIO(additional_attributes) attributes_hex = binascii.hexlify(additional_attributes) if not len(additional_attributes): return attributes_hex len_attribute, = unpack('<I', attributes_raw.read(4)) if len_attribute != 8: return attributes_hex attr_id, = unpack('<I', attributes_raw.read(4)) if attr_id != APK._APK_SIG_ATTR_V2_STRIPPING_PROTECTION: return attributes_hex scheme_id, = unpack('<I', attributes_raw.read(4)) return "stripping protection set, scheme %d" % scheme_id
python
def _validate_prepostcmd_hook(cls, func: Callable, data_type: Type) -> None: """Check parameter and return types for pre and post command hooks.""" signature = inspect.signature(func) # validate that the callable has the right number of parameters cls._validate_callable_param_count(func, 1) # validate the parameter has the right annotation paramname = list(signature.parameters.keys())[0] param = signature.parameters[paramname] if param.annotation != data_type: raise TypeError('argument 1 of {} has incompatible type {}, expected {}'.format( func.__name__, param.annotation, data_type, )) # validate the return value has the right annotation if signature.return_annotation == signature.empty: raise TypeError('{} does not have a declared return type, expected {}'.format( func.__name__, data_type, )) if signature.return_annotation != data_type: raise TypeError('{} has incompatible return type {}, expected {}'.format( func.__name__, signature.return_annotation, data_type, ))
java
public JClass []getParameterTypes() { Class []types = _method.getParameterTypes(); JClass []jTypes = new JClass[types.length]; for (int i = 0; i < types.length; i++) { jTypes[i] = _loader.forName(types[i].getName()); } return jTypes; }
python
def SortBy(*qs): """Convert a list of Q objects into list of sort instructions""" sort = [] for q in qs: if q._path.endswith('.desc'): sort.append((q._path[:-5], DESCENDING)) else: sort.append((q._path, ASCENDING)) return sort
java
public boolean isHomeKeyPresent() { final GVRApplication application = mApplication.get(); if (null != application) { final String model = getHmtModel(); if (null != model && model.contains("R323")) { return true; } } return false; }
java
@SuppressWarnings({ "unchecked", "rawtypes" }) public static <D> SimpleExpression<D> constantAs(D source, Path<D> alias) { if (source == null) { return as((Expression) nullExpression(), alias); } else { return as(ConstantImpl.create(source), alias); } }
java
@Override public SessionHandle openSessionWithImpersonation(String username, String password, Map<String, String> configuration, String delegationToken) throws HiveSQLException { SessionHandle sessionHandle = sessionManager.openSession(SERVER_VERSION, username, password, null, configuration, true, delegationToken); LOG.debug(sessionHandle + ": openSession()"); return sessionHandle; }
python
def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False
python
def GetHiResImage(ID): ''' Queries the Palomar Observatory Sky Survey II catalog to obtain a higher resolution optical image of the star with EPIC number :py:obj:`ID`. ''' # Get the TPF info client = kplr.API() star = client.k2_star(ID) k2ra = star.k2_ra k2dec = star.k2_dec tpf = star.get_target_pixel_files()[0] with tpf.open() as f: k2wcs = WCS(f[2].header) shape = np.array(f[1].data.field('FLUX'), dtype='float64')[0].shape # Get the POSS URL hou = int(k2ra * 24 / 360.) min = int(60 * (k2ra * 24 / 360. - hou)) sec = 60 * (60 * (k2ra * 24 / 360. - hou) - min) ra = '%02d+%02d+%.2f' % (hou, min, sec) sgn = '' if np.sign(k2dec) >= 0 else '-' deg = int(np.abs(k2dec)) min = int(60 * (np.abs(k2dec) - deg)) sec = 3600 * (np.abs(k2dec) - deg - min / 60) dec = '%s%02d+%02d+%.1f' % (sgn, deg, min, sec) url = 'https://archive.stsci.edu/cgi-bin/dss_search?v=poss2ukstu_red&' + \ 'r=%s&d=%s&e=J2000&h=3&w=3&f=fits&c=none&fov=NONE&v3=' % (ra, dec) # Query the server r = urllib.request.Request(url) handler = urllib.request.urlopen(r) code = handler.getcode() if int(code) != 200: # Unavailable return None data = handler.read() # Atomically write to a temp file f = NamedTemporaryFile("wb", delete=False) f.write(data) f.flush() os.fsync(f.fileno()) f.close() # Now open the POSS fits file with pyfits.open(f.name) as ff: img = ff[0].data # Map POSS pixels onto K2 pixels xy = np.empty((img.shape[0] * img.shape[1], 2)) z = np.empty(img.shape[0] * img.shape[1]) pwcs = WCS(f.name) k = 0 for i in range(img.shape[0]): for j in range(img.shape[1]): ra, dec = pwcs.all_pix2world(float(j), float(i), 0) xy[k] = k2wcs.all_world2pix(ra, dec, 0) z[k] = img[i, j] k += 1 # Resample grid_x, grid_y = np.mgrid[-0.5:shape[1] - 0.5:0.1, -0.5:shape[0] - 0.5:0.1] resampled = griddata(xy, z, (grid_x, grid_y), method='cubic') # Rotate to align with K2 image. Not sure why, but it is necessary resampled = np.rot90(resampled) return resampled
python
def _create_edge_by_target(self): """creates a edge_by_target dict with the same edge objects as the edge_by_source. Also adds an '@id' field to each edge.""" ebt = {} for edge_dict in self._edge_by_source.values(): for edge_id, edge in edge_dict.items(): target_id = edge['@target'] edge['@id'] = edge_id assert target_id not in ebt ebt[target_id] = edge # _check_rev_dict(self._tree, ebt) return ebt
java
protected boolean relevantSubspace(long[] subspace, DoubleDBIDList neigh, KernelDensityEstimator kernel) { final double crit = K_S_CRITICAL001 / FastMath.sqrt(neigh.size() - 2); double[] data = new double[neigh.size()]; Relation<? extends NumberVector> relation = kernel.relation; for(int dim = BitsUtil.nextSetBit(subspace, 0); dim >= 0; dim = BitsUtil.nextSetBit(subspace, dim + 1)) { // TODO: can/should we save this copy? int count = 0; for(DBIDIter neighbor = neigh.iter(); neighbor.valid(); neighbor.advance()) { data[count++] = relation.get(neighbor).doubleValue(dim); } assert (count == neigh.size()); Arrays.sort(data); final double min = data[0], norm = data[data.length - 1] - min; // Kolmogorow-Smirnow-Test against uniform distribution: boolean flag = false; for(int j = 1, end = data.length - 1; j < end; j++) { if(Math.abs(j / (data.length - 2.) - (data[j] - min) / norm) > crit) { flag = true; break; } } if(!flag) { return false; } } return true; }
python
def choose_tag(self: object, tokens: List[str], index: int, history: List[str]): """ Looks up token in ``lemmas`` dict and returns the corresponding value as lemma. :rtype: str :type tokens: list :param tokens: List of tokens to be lemmatized :type index: int :param index: Int with current token :type history: list :param history: List with tokens that have already been lemmatized; NOT USED """ keys = self.lemmas.keys() if tokens[index] in keys: return self.lemmas[tokens[index]]
java
public static BundleAdjustment<SceneStructureMetric> bundleDenseMetric(boolean robust, @Nullable ConfigBundleAdjustment config ) { if( config == null ) config = new ConfigBundleAdjustment(); UnconstrainedLeastSquaresSchur<DMatrixRMaj> minimizer; if( config.configOptimizer instanceof ConfigTrustRegion ) minimizer = FactoryOptimization.doglegSchur(robust,(ConfigTrustRegion)config.configOptimizer); else minimizer = FactoryOptimization.levenbergMarquardtSchur(robust,(ConfigLevenbergMarquardt)config.configOptimizer); return new BundleAdjustmentSchur_DDRM<>(minimizer, new BundleAdjustmentMetricResidualFunction(), new BundleAdjustmentMetricSchurJacobian_DDRM(), new CodecSceneStructureMetric()); }
java
public static ns_ssl_certkey[] gen_csr(nitro_service client, ns_ssl_certkey[] resources) throws Exception { if(resources == null) throw new Exception("Null resource array"); if(resources.length == 1) return ((ns_ssl_certkey[]) resources[0].perform_operation(client, "gen_csr")); return ((ns_ssl_certkey[]) perform_operation_bulk_request(client, resources, "gen_csr")); }
java
@Test public void MPJwtNoMpJwtConfig_formLoginInWebXML_basicInApp() throws Exception { genericLoginConfigFormLoginVariationTest( MpJwtFatConstants.LOGINCONFIG_FORM_LOGIN_IN_WEB_XML_SERVLET_BASIC_IN_APP_ROOT_CONTEXT, MpJwtFatConstants.LOGINCONFIG_FORM_LOGIN_IN_WEB_XML_SERVLET_BASIC_IN_APP, MpJwtFatConstants.MPJWT_APP_CLASS_LOGIN_CONFIG_FORMLOGININWEBXML_BASICINAPP, UseJWTToken.NO); }
java
public void getItemInfo(int[] ids, Callback<List<Item>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ids)); gw2API.getItemInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback); }
java
public String decrypt(String toDecrypt) throws DuraCloudRuntimeException { try { byte[] input = decodeBytes(toDecrypt); cipher.init(Cipher.DECRYPT_MODE, key); byte[] plainText = cipher.doFinal(input); return new String(plainText, "UTF-8"); } catch (Exception e) { throw new DuraCloudRuntimeException(e); } }
java
@Override public void destroy() { synchronized (channels) { isCurrentlyShutingDown = true; for (final SynchronizeFXTomcatChannel server : channels.values()) { server.shutdown(); } servers.clear(); channels.clear(); isCurrentlyShutingDown = false; } }
python
def param_cred(ns_run, logw=None, simulate=False, probability=0.5, param_ind=0): """One-tailed credible interval on the value of a single parameter (component of theta). Parameters ---------- ns_run: dict Nested sampling run dict (see the data_processing module docstring for more details). logw: None or 1d numpy array, optional Log weights of samples. simulate: bool, optional Passed to ns_run_utils.get_logw if logw needs to be calculated. probability: float, optional Quantile to estimate - must be in open interval (0, 1). For example, use 0.5 for the median and 0.84 for the upper 84% quantile. Passed to weighted_quantile. param_ind: int, optional Index of parameter for which the credible interval should be calculated. This corresponds to the column of ns_run['theta'] which contains the parameter. Returns ------- float """ if logw is None: logw = nestcheck.ns_run_utils.get_logw(ns_run, simulate=simulate) w_relative = np.exp(logw - logw.max()) # protect against overflow return weighted_quantile(probability, ns_run['theta'][:, param_ind], w_relative)
python
def get_workers_with_qualification(self, qualification_id): """Get workers with the given qualification.""" done = False next_token = None while not done: if next_token is not None: response = self.mturk.list_workers_with_qualification_type( QualificationTypeId=qualification_id, MaxResults=MAX_SUPPORTED_BATCH_SIZE, Status="Granted", NextToken=next_token, ) else: response = self.mturk.list_workers_with_qualification_type( QualificationTypeId=qualification_id, MaxResults=MAX_SUPPORTED_BATCH_SIZE, Status="Granted", ) if response: for r in response["Qualifications"]: yield {"id": r["WorkerId"], "score": r["IntegerValue"]} if "NextToken" in response: next_token = response["NextToken"] else: done = True
java
public static int cusolverRfBatchSolve( cusolverRfHandle handle, Pointer P, Pointer Q, int nrhs, //only nrhs=1 is supported Pointer Temp, //of size 2*batchSize*(n*nrhs) int ldt, //only ldt=n is supported /** Input/Output (in the device memory) */ Pointer XF_array, /** Input */ int ldxf) { return checkResult(cusolverRfBatchSolveNative(handle, P, Q, nrhs, Temp, ldt, XF_array, ldxf)); }
java
private static DefaultDirectedGraph<DataPropertyExpression,DefaultEdge> getDataPropertyGraph(OntologyImpl.UnclassifiedOntologyTBox ontology) { DefaultDirectedGraph<DataPropertyExpression,DefaultEdge> graph = new DefaultDirectedGraph<>(DefaultEdge.class); for (DataPropertyExpression role : ontology.dataProperties()) if (!role.isBottom() && !role.isTop()) graph.addVertex(role); DataPropertyExpression top = null; for (BinaryAxiom<DataPropertyExpression> roleIncl : ontology.getSubDataPropertyAxioms()) { if (roleIncl.getSub().isBottom() || roleIncl.getSuper().isTop()) continue; if (roleIncl.getSuper().isBottom()) { throw new RuntimeException("BOT cannot occur on the LHS - replaced by DISJ"); } if (roleIncl.getSub().isTop()) { top = roleIncl.getSub(); graph.addVertex(top); } graph.addEdge(roleIncl.getSub(), roleIncl.getSuper()); } if (top != null) { for (DataPropertyExpression dpe : graph.vertexSet()) graph.addEdge(dpe, top); } return graph; }
python
def bind(self, name, filterset): """ attach filter to filterset gives a name to use to extract arguments from querydict """ if self.name is not None: name = self.name self.field.bind(name, self)
java
public void addDecorations(CmsDecorationDefintion decorationDefinition) throws CmsException { m_decorations.putAll(decorationDefinition.createDecorationBundle(m_cms, m_configurationLocale).getAll()); }
java
public void marshall(HlsTimedMetadataScheduleActionSettings hlsTimedMetadataScheduleActionSettings, ProtocolMarshaller protocolMarshaller) { if (hlsTimedMetadataScheduleActionSettings == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(hlsTimedMetadataScheduleActionSettings.getId3(), ID3_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
public void marshall(FailedCreateAssociation failedCreateAssociation, ProtocolMarshaller protocolMarshaller) { if (failedCreateAssociation == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(failedCreateAssociation.getEntry(), ENTRY_BINDING); protocolMarshaller.marshall(failedCreateAssociation.getMessage(), MESSAGE_BINDING); protocolMarshaller.marshall(failedCreateAssociation.getFault(), FAULT_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
python
def _on_client_connect(self, data): """Handle client connect.""" client = None if data.get('id') in self._clients: client = self._clients[data.get('id')] client.update_connected(True) else: client = Snapclient(self, data.get('client')) self._clients[data.get('id')] = client if self._new_client_callback_func and callable(self._new_client_callback_func): self._new_client_callback_func(client) _LOGGER.info('client %s connected', client.friendly_name)
java
@Override public CommerceSubscriptionEntry fetchByC_C_C(String CPInstanceUuid, long CProductId, long commerceOrderItemId, boolean retrieveFromCache) { Object[] finderArgs = new Object[] { CPInstanceUuid, CProductId, commerceOrderItemId }; Object result = null; if (retrieveFromCache) { result = finderCache.getResult(FINDER_PATH_FETCH_BY_C_C_C, finderArgs, this); } if (result instanceof CommerceSubscriptionEntry) { CommerceSubscriptionEntry commerceSubscriptionEntry = (CommerceSubscriptionEntry)result; if (!Objects.equals(CPInstanceUuid, commerceSubscriptionEntry.getCPInstanceUuid()) || (CProductId != commerceSubscriptionEntry.getCProductId()) || (commerceOrderItemId != commerceSubscriptionEntry.getCommerceOrderItemId())) { result = null; } } if (result == null) { StringBundler query = new StringBundler(5); query.append(_SQL_SELECT_COMMERCESUBSCRIPTIONENTRY_WHERE); boolean bindCPInstanceUuid = false; if (CPInstanceUuid == null) { query.append(_FINDER_COLUMN_C_C_C_CPINSTANCEUUID_1); } else if (CPInstanceUuid.equals("")) { query.append(_FINDER_COLUMN_C_C_C_CPINSTANCEUUID_3); } else { bindCPInstanceUuid = true; query.append(_FINDER_COLUMN_C_C_C_CPINSTANCEUUID_2); } query.append(_FINDER_COLUMN_C_C_C_CPRODUCTID_2); query.append(_FINDER_COLUMN_C_C_C_COMMERCEORDERITEMID_2); String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); if (bindCPInstanceUuid) { qPos.add(CPInstanceUuid); } qPos.add(CProductId); qPos.add(commerceOrderItemId); List<CommerceSubscriptionEntry> list = q.list(); if (list.isEmpty()) { finderCache.putResult(FINDER_PATH_FETCH_BY_C_C_C, finderArgs, list); } else { CommerceSubscriptionEntry commerceSubscriptionEntry = list.get(0); result = commerceSubscriptionEntry; cacheResult(commerceSubscriptionEntry); } } catch (Exception e) { finderCache.removeResult(FINDER_PATH_FETCH_BY_C_C_C, finderArgs); throw processException(e); } finally { closeSession(session); } } if (result instanceof List<?>) { return null; } else { return (CommerceSubscriptionEntry)result; } }
python
def get_all(self): """ Gets all component references registered in this reference map. :return: a list with component references. """ components = [] self._lock.acquire() try: for reference in self._references: components.append(reference.get_component()) finally: self._lock.release() return components
python
def username_access_time(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") username = ET.SubElement(config, "username", xmlns="urn:brocade.com:mgmt:brocade-aaa") name_key = ET.SubElement(username, "name") name_key.text = kwargs.pop('name') access_time = ET.SubElement(username, "access-time") access_time.text = kwargs.pop('access_time') callback = kwargs.pop('callback', self._callback) return callback(config)
python
def _get_variable_names(arr): """Return the variable names of an array""" if VARIABLELABEL in arr.dims: return arr.coords[VARIABLELABEL].tolist() else: return arr.name
java
public final Pair<String, String> simpleDim() throws RecognitionException { Pair<String, String> dims = null; Token a=null; Token b=null; try { // druidG.g:292:2: ( (a= ID ( WS AS WS b= ID )? ) ) // druidG.g:292:4: (a= ID ( WS AS WS b= ID )? ) { // druidG.g:292:4: (a= ID ( WS AS WS b= ID )? ) // druidG.g:292:5: a= ID ( WS AS WS b= ID )? { a=(Token)match(input,ID,FOLLOW_ID_in_simpleDim1974); // druidG.g:292:10: ( WS AS WS b= ID )? int alt130=2; int LA130_0 = input.LA(1); if ( (LA130_0==WS) ) { int LA130_1 = input.LA(2); if ( (LA130_1==AS) ) { alt130=1; } } switch (alt130) { case 1 : // druidG.g:292:11: WS AS WS b= ID { match(input,WS,FOLLOW_WS_in_simpleDim1977); match(input,AS,FOLLOW_AS_in_simpleDim1979); match(input,WS,FOLLOW_WS_in_simpleDim1981); b=(Token)match(input,ID,FOLLOW_ID_in_simpleDim1985); } break; } dims = (b != null)? new Pair<String, String>((a!=null?a.getText():null), (b!=null?b.getText():null)): new Pair<String, String>((a!=null?a.getText():null), null); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return dims; }
python
def _pos(self, idx): """Convert an index into a pair (alpha, beta) that can be used to access the corresponding _lists[alpha][beta] position. Most queries require the index be built. Details of the index are described in self._build_index. Indexing requires traversing the tree to a leaf node. Each node has two children which are easily computable. Given an index, pos, the left-child is at pos * 2 + 1 and the right-child is at pos * 2 + 2. When the index is less than the left-child, traversal moves to the left sub-tree. Otherwise, the index is decremented by the left-child and traversal moves to the right sub-tree. At a child node, the indexing pair is computed from the relative position of the child node as compared with the offset and the remaining index. For example, using the index from self._build_index: _index = 14 5 9 3 2 4 5 _offset = 3 Tree: 14 5 9 3 2 4 5 Indexing position 8 involves iterating like so: 1. Starting at the root, position 0, 8 is compared with the left-child node (5) which it is greater than. When greater the index is decremented and the position is updated to the right child node. 2. At node 9 with index 3, we again compare the index to the left-child node with value 4. Because the index is the less than the left-child node, we simply traverse to the left. 3. At node 4 with index 3, we recognize that we are at a leaf node and stop iterating. 4. To compute the sublist index, we subtract the offset from the index of the leaf node: 5 - 3 = 2. To compute the index in the sublist, we simply use the index remaining from iteration. In this case, 3. The final index pair from our example is (2, 3) which corresponds to index 8 in the sorted list. """ if idx < 0: last_len = len(self._lists[-1]) if (-idx) <= last_len: return len(self._lists) - 1, last_len + idx idx += self._len if idx < 0: raise IndexError('list index out of range') elif idx >= self._len: raise IndexError('list index out of range') if idx < len(self._lists[0]): return 0, idx _index = self._index if not _index: self._build_index() pos = 0 child = 1 len_index = len(_index) while child < len_index: index_child = _index[child] if idx < index_child: pos = child else: idx -= index_child pos = child + 1 child = (pos << 1) + 1 return (pos - self._offset, idx)
java
protected void startServing(String startMessage, String stopMessage) { MetricsSystem.startSinks(ServerConfiguration.get(PropertyKey.METRICS_CONF_FILE)); startServingWebServer(); startJvmMonitorProcess(); LOG.info( "Alluxio master version {} started{}. bindAddress={}, connectAddress={}, webAddress={}", RuntimeConstants.VERSION, startMessage, mRpcBindAddress, mRpcConnectAddress, mWebBindAddress); startServingRPCServer(); LOG.info("Alluxio master ended{}", stopMessage); }
python
def getjp2header(Id): ''' GET /api/v1/getJP2Header/ Get the XML header embedded in a JPEG2000 image. Includes the FITS header as well as a section of Helioviewer-specific metadata. Request Parameters: Parameter Required Type Example Description id Required number 7654321 Unique JP2 image identifier. callback Optional string Wrap the response object in a function call of your choosing. Example (A): string (XML) Example Request: http://helioviewer.org/api/v1/getJP2Header/?id=7654321 ''' base_url = 'http://helioviewer.org/api/v1/getJP2Header/?' if not isinstance(Id, int): raise ValueError("The Id argument should be an int, ignoring it") else: base_url += "id=" + str(Id) return dispatch_http_get(base_url)
python
def patch_cmdline_parser(): """ Patches the ``luigi.cmdline_parser.CmdlineParser`` to store the original command line arguments for later processing in the :py:class:`law.config.Config`. """ # store original functions _init = luigi.cmdline_parser.CmdlineParser.__init__ # patch init def __init__(self, cmdline_args): _init(self, cmdline_args) self.cmdline_args = cmdline_args luigi.cmdline_parser.CmdlineParser.__init__ = __init__
python
def call_later( self, delay: float, callback: Callable[..., None], *args: Any, **kwargs: Any ) -> object: """Runs the ``callback`` after ``delay`` seconds have passed. Returns an opaque handle that may be passed to `remove_timeout` to cancel. Note that unlike the `asyncio` method of the same name, the returned object does not have a ``cancel()`` method. See `add_timeout` for comments on thread-safety and subclassing. .. versionadded:: 4.0 """ return self.call_at(self.time() + delay, callback, *args, **kwargs)
python
def find_visible(hull, observer, background): '''Given an observer location, find the first and last visible points in the hull The observer at "observer" is looking at the hull whose most distant vertex from the observer is "background. Find the vertices that are the furthest distance from the line between observer and background. These will be the start and ends in the vertex chain of vertices visible by the observer. ''' pt_background = hull[background,:] vector = pt_background - observer i = background dmax = 0 while True: i_next = (i+1) % hull.shape[0] pt_next = hull[i_next,:] d = -np.cross(vector, pt_next-pt_background) if d < dmax or i_next == background: i_min = i break dmax = d i = i_next dmax = 0 i = background while True: i_next = (i+hull.shape[0]-1) % hull.shape[0] pt_next = hull[i_next,:] d = np.cross(vector, pt_next-pt_background) if d < dmax or i_next == background: i_max = i break dmax = d i = i_next return (i_min, i_max)
java
public boolean hasRole(String roleName){ if (roles != null) { for (String r : roles) { if (r.equals(roleName)) return true; } } return false; }
java
public final <C extends IRequestablePage> C newPage(final Class<C> pageClass) { PageFactory<C> content = getFactory(pageClass); if (content != null) { return content.createPage(new PageParameters()); } return new DefaultPageFactory().newPage(pageClass); }
java
@Override public List<GroupState> listGroups() { TrackerListGroupsCommand command = new TrackerListGroupsCommand(); return trackerConnectionManager.executeFdfsTrackerCmd(command); }
java
public ModuleDefinitionDataComponent addData() { //3 ModuleDefinitionDataComponent t = new ModuleDefinitionDataComponent(); if (this.data == null) this.data = new ArrayList<ModuleDefinitionDataComponent>(); this.data.add(t); return t; }