language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public Result call(CSRF configuration, RequestContext context) throws Exception { if (csrf.isValidRequest(context.context())) { String token = csrf.generateToken(context.context()); return csrf.addTokenToResult(context.context(), token, context.proceed()); } else { ...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case XtextPackage.GRAMMAR__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case XtextPackage.GRAMMAR__USED_GRAMMARS: return usedGrammars != null && !usedGrammars.isEmpty(); case XtextPackage.GRAMMA...
python
def centroid_2dg(data, error=None, mask=None): """ Calculate the centroid of a 2D array by fitting a 2D Gaussian (plus a constant) to the array. Invalid values (e.g. NaNs or infs) in the ``data`` or ``error`` arrays are automatically masked. The mask for invalid values represents the combinati...
python
def _export_corpus(self): """ Calls MALLET's `import-file` method. """ # bin/mallet import-file --input /Users/erickpeirson/mycorpus_docs.txt # --output mytopic-input.mallet --keep-sequence --remove-stopwords if not os.path.exists(self.mallet_bin): raise ...
java
@Override public void undefinedSubExpression(String subExprName, String exprName) { reporter.error(prefix(exprName), "Undefined subexpression <", subExprName, ">"); }
python
def _property_table(): """Download the PDB -> resolution table directly from the RCSB PDB REST service. See the other fields that you can get here: http://www.rcsb.org/pdb/results/reportField.do Returns: Pandas DataFrame: table of structureId as the index, resolution and experimentalTechnique as t...
java
public static base_responses update(nitro_service client, dnspolicy resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { dnspolicy updateresources[] = new dnspolicy[resources.length]; for (int i=0;i<resources.length;i++){ updateresources[i] = new d...
java
public static String[] requireAttributes(final XMLExtendedStreamReader reader, final String... attributeNames) throws XMLStreamException { final int length = attributeNames.length; final String[] result = new String[length]; for (int i = 0; i < length; i++) { final String...
java
@Override public CommercePriceList create(long commercePriceListId) { CommercePriceList commercePriceList = new CommercePriceListImpl(); commercePriceList.setNew(true); commercePriceList.setPrimaryKey(commercePriceListId); String uuid = PortalUUIDUtil.generate(); commercePriceList.setUuid(uuid); commer...
java
@Override protected void writeToOutput(final Map<String, Object> row) throws IOException { if (writer == null) { CsvMapper mapper = new CsvMapper(); mapper.disable(SerializationFeature.CLOSE_CLOSEABLE); mapper.getFactory() .configure(JsonGe...
java
@Override protected void initEventAdapters() throws CoreException { // Manage Ui Command Button linkCommand(view().getUndoButton(), MouseEvent.MOUSE_CLICKED, UndoCommand.class, UndoModel.stackName); linkCommand(view().getRedoButton(), MouseEvent.MOUSE_CLICKED, RedoCommand.class, UndoModel.s...
python
def process_climis_livestock_data(data_dir: str): """ Process CliMIS livestock data. """ records = [] livestock_data_dir = f"{data_dir}/Climis South Sudan Livestock Data" for filename in glob( f"{livestock_data_dir}/Livestock Body Condition/*2017.csv" ): records += process_file_wi...
java
private static void registerAllTypeFactories(GsonBuilder gsonBuilder) { ServiceLoader<TypeAdapterFactory> loader = ServiceLoader.load(TypeAdapterFactory.class); for (TypeAdapterFactory typeFactory : loader) { if (logger.isLoggable(Level.FINE)) { logger.fine("Add gson type fac...
java
public com.google.api.ChangeType getChangeType() { @SuppressWarnings("deprecation") com.google.api.ChangeType result = com.google.api.ChangeType.valueOf(changeType_); return result == null ? com.google.api.ChangeType.UNRECOGNIZED : result; }
java
public com.google.api.ads.admanager.axis.v201811.AdUnitSize[] getCompanions() { return companions; }
python
def _parse(self, data): """Parse API response. :param dict data: Parsed JSON response from API 'data' key. """ super(Image, self)._parse(data) self.height = data['height'] self.type = data['type'] self.width = data['width']
java
private void evaluateExpressions() throws JspException { /* * Note: we don't check for type mismatches here; we assume * the expression evaluator will return the expected type * (by virtue of knowledge we give it about what that type is). * A ClassCastException here is truly...
python
def solve_factorized_aug(z, Fval, LU, G, A): M, N=G.shape P, N=A.shape """Total number of inequality constraints""" m=M """Primal variable""" x=z[0:N] """Multiplier for equality constraints""" nu=z[N:N+P] """Multiplier for inequality constraints""" l=z[N+P:N+P+M] """...
java
public static ServiceSpecification merge(Iterable<ServiceSpecification> specs) { return new ServiceSpecification( Streams.stream(specs).flatMap(s -> s.services().stream())::iterator, Streams.stream(specs).flatMap(s -> s.enums().stream())::iterator, Streams.stream(...
java
public void stop() { MessageBatcher batcher = null; for (String originalAppenderName : originalAsyncAppenderNameMap.keySet()) { String batcherName = AsyncAppender.class.getName() + "." + originalAppenderName; batcher = BatcherFactory.getBatcher(batcherName); if (batch...
java
private boolean insertIndexEntry(final S userStorable, final Storable indexEntry) throws PersistException { if (indexEntry.tryInsert()) { return true; } // If index entry already exists, then index might be corrupt. try { Storable freshIndexE...
python
def get_embed_url(self, targeting=None, recirc=None): """gets a canonical path to an embedded iframe of the video from the hub :return: the path to create an embedded iframe of the video :rtype: str """ url = getattr(settings, "VIDEOHUB_EMBED_URL", self.DEFAULT_VIDEOHUB_EMBED_UR...
python
def get_django_user(self, username, password=None): """ Get the Django user with the given username, or create one if it doesn't already exist. If `password` is given, then set the user's password to that (regardless of whether the user was created or not). """ try: ...
java
@Override public void contextInitialized(ServletContextEvent event) { super.contextInitialized(event); _dict.addTypeSet(org.xillium.data.validation.StandardDataTypes.class); _packaged = _context.getResourcePaths("/WEB-INF/lib/"); _extended = discover(System.getProperty("xillium.servi...
java
private List<AdvancedModelWrapper> enhanceUpdates(List<AdvancedModelWrapper> updates, Map<Object, AdvancedModelWrapper> updated, EKBCommit commit) { List<AdvancedModelWrapper> additionalUpdates = new ArrayList<AdvancedModelWrapper>(); for (AdvancedModelWrapper model : updates) { ...
python
def get_user(self, username): """ Fetch the user from the database The function will return None if the user is not found """ sql = '''SELECT * FROM user WHERE username = ?''' self._db_curs.execute(sql, (username, )) user = self._db_curs.fetchone() return us...
java
void normalizeDependencies() { if (defineDependencies != null) { LinkedHashSet<String> temp = new LinkedHashSet<String>(Arrays.asList(PathUtil.normalizePaths(getParentPath(), defineDependencies))); // normalize and remove dups defineDependencies = temp.toArray(new String[temp.size()]); } if (requireD...
java
public void setIdentityPoolUsages(java.util.Collection<IdentityPoolUsage> identityPoolUsages) { if (identityPoolUsages == null) { this.identityPoolUsages = null; return; } this.identityPoolUsages = new com.amazonaws.internal.SdkInternalList<IdentityPoolUsage>(identityPoo...
python
def put(self, measurementId, deviceId): """ Store a bunch of data for this measurement session. :param measurementId: :param deviceId: :return: """ data = request.get_json() if data is not None: parsedData = json.loads(data) logger....
java
public Block[] getBlockReport(int namespaceId) throws IOException { ArrayList<Block> ret = new ArrayList<Block>(); org.apache.hadoop.hdfs.server.datanode.NamespaceMap nm = volumeMap .getNamespaceMap(namespaceId); if (nm == null) { return new Block[0]; } int n = nm.getNumBucket(); f...
java
public static java.sql.Time getSqlTime(int hour, int minute, int second) { Calendar cal = Calendar.getInstance(); cal.setTime(new java.util.Date(0)); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, minute); cal.set(Calendar.SECOND, second); cal.set(Cal...
java
public void saveSettings() { mCallbacks.saveExtensionSetting(SETTING_PROXY, setSetting(jCheckBoxProxy.isSelected())); mCallbacks.saveExtensionSetting(SETTING_REPEATER, setSetting(jCheckBoxRepeater.isSelected())); mCallbacks.saveExtensionSetting(SETTING_SCANNER, setSetting(jCheckBoxScanner.isSele...
python
def _get_cache_path(source_file): """Return the path where the cache should be written/located. :param onto_name: name of the ontology or the full path :return: string, abs path to the cache file """ local_name = os.path.basename(source_file) cache_name = local_name + ".db" cache_dir = os.p...
java
public static CommerceNotificationTemplate fetchByUuid_C_First( String uuid, long companyId, OrderByComparator<CommerceNotificationTemplate> orderByComparator) { return getPersistence() .fetchByUuid_C_First(uuid, companyId, orderByComparator); }
python
def setFilepath(self, filepath): """ Sets the filepath text for this widget to the inputed path. :param filepath | <str> """ if not filepath: self._filepathEdit.setText('') return if self.normalizePath(): fi...
java
public <RowT> ServerStreamingCallable<Query, RowT> readRowsCallable(RowAdapter<RowT> rowAdapter) { return stub.createReadRowsCallable(rowAdapter); }
python
def process_request(self, request): """ Setup the profiler for a profiling run and clear the SQL query log. If this is a resort of an existing profiling run, just return the resorted list. """ def unpickle(params): stats = unpickle_stats(b64decode(params.get(...
java
protected void resumeSession (AuthRequest req, PresentsConnection conn) { // check to see if we've already got a connection object, in which case it's probably stale Connection oldconn = getConnection(); if (oldconn != null && !oldconn.isClosed()) { log.info("Closing stale connec...
java
public void marshall(DisableDomainTransferLockRequest disableDomainTransferLockRequest, ProtocolMarshaller protocolMarshaller) { if (disableDomainTransferLockRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMar...
java
@FFDCIgnore(SQLException.class) private Boolean supportsUnicodeStaticCheck(DataSource ds) { Boolean res = null; try { Connection conn = ds.getConnection(); String product = null; try { DatabaseMetaData dmd = conn.getMetaData(); prod...
java
public ListenerUtils putListener(String tag, SuperActivityToast .OnButtonClickListener onButtonClickListener) { this.mOnButtonClickListenerHashMap.put(tag, onButtonClickListener); return this; }
java
public void save(File file) throws IOException { DataOutputStream dout = new DataOutputStream(new FileOutputStream(file)); dout.writeUTF(name); for (int i=0;i<256;i++) { dout.writeBoolean(chars[i]); } dout.close(); }
python
def string(self, *pattern, **kwargs): """ Add string pattern :param pattern: :type pattern: :param kwargs: :type kwargs: :return: :rtype: """ set_defaults(self._kwargs, kwargs) set_defaults(self._functional_defaults, kwargs) ...
java
protected byte[] getFileBytes(String filename) { try { // is this a zip-file? if (m_importZip != null) { // yes ZipEntry entry = m_importZip.getEntry(filename); // path to file might be relative, too if ((entry == null) &&...
java
protected static Container register(final DockerConfig config) { CONTAINERS_LOCK.lock(); try { final String name = config.getName(); Container container = CONTAINERS.get(name); if (container == null) { container = new Container(config); ...
python
def restore(self): 'Restore the file' # # # As of 2016-06-15, Jottacloud.com has changed their restore api # To restore, this is what's done # # HTTP POST to https://www.jottacloud.com/web/restore/trash/list # Data: # hash:undefined # ...
java
public Map<String, ConditionAndOutcomes> getConditionAndOutcomesBySource() { if (!this.addedAncestorOutcomes) { this.outcomes.forEach((source, sourceOutcomes) -> { if (!sourceOutcomes.isFullMatch()) { addNoMatchOutcomeToAncestors(source); } }); this.addedAncestorOutcomes = true; } return Col...
java
public boolean delist(BeanO beanO) throws TransactionRolledbackException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); // d532639.2 if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "delist", new Object[] { Boolean.valueOf(gl...
java
static void compileRules(String rules, OutputStream os) throws IOException { // // Read the input rules, generate a parse tree, symbol table, // and list of all Unicode Sets referenced by the rules. // RBBIRuleBuilder builder = new RBBIRuleBuilder(rules); builder.fSca...
python
def _list_clouds(self): """ Request a list of all added clouds. Populates self._clouds dict with mist.client.model.Cloud instances """ req = self.request(self.uri + '/clouds') clouds = req.get().json() if clouds: for cloud in clouds: s...
java
public static void timeSensitiveInit(Env env, AuthAPI authzAPI, AuthzFacade facade, final DirectAAFUserPass directAAFUserPass) throws Exception { /** * Basic Auth, quick Validation * * Responds OK or NotAuthorized */ authzAPI.route(env, HttpMethods.GET, "/authn/basicAuth", new Code(facade,"Is given Bas...
java
public static WildcardTypeName supertypeOf(TypeName lowerBound) { return new WildcardTypeName(Collections.singletonList(OBJECT), Collections.singletonList(lowerBound)); }
java
@Override public void complete(int arg0) throws InconsistentLocalTranException, RolledbackException, IllegalStateException { if (ltc != null) { ltc.complete(arg0); } }
python
def assign_objective_to_objective_bank(self, objective_id, objective_bank_id): """Adds an existing ``Objective`` to an ``ObjectiveBank``. arg: objective_id (osid.id.Id): the ``Id`` of the ``Objective`` arg: objective_bank_id (osid.id.Id): the ``Id`` of the ...
java
public void closeTx() { //Clear Collection Caches modifiedThings.clear(); modifiedRoles.clear(); modifiedRelationTypes.clear(); modifiedRules.clear(); modifiedCastings.clear(); newAttributes.clear(); newRelations.clear(); shardingCount.clear(); ...
python
def _title(fig, title, subtitle="", *, margin=1, fontsize=20, subfontsize=18): """Add a title to a figure. Parameters ---------- fig : matplotlib Figure Figure. title : string Title. subtitle : string Subtitle. margin : number (optional) Distance from top of ...
java
public static List<CmsModelResourceInfo> generateModelResourceList( CmsObject cms, String resourceType, List<CmsResource> modelResources, Locale contentLocale) throws CmsException { List<CmsModelResourceInfo> result = new ArrayList<CmsModelResourceInfo>(); Locale wpL...
java
@ReadOperation(produces = {ActuatorMediaType.V2_JSON, "application/vnd.cas.services+yaml", MediaType.APPLICATION_JSON_VALUE}) public RegisteredService fetchService(@Selector final String id) { if (NumberUtils.isDigits(id)) { return this.servicesManager.findServiceBy(Long.parseLong(id)); ...
python
def copy(self): """Make a deep copy of this object. Example:: >>> c2 = c.copy() """ vec = np.copy(self._vec) return ScalarCoefs(vec, self.nmax, self.mmax)
java
@SuppressWarnings("unchecked") // T == F when the chain is empty public T transform(final F item, final PipelineContext context) { if(chain == null || chain.isEmpty()) { return (T)item; } Object current = item; for(int i = 0; i < chain.size(); i++) { current ...
python
def univprop(self): ''' .foo ''' self.ignore(whitespace) if not self.nextstr('.'): self._raiseSyntaxError('universal property expected .') name = self.noms(varset) if not name: mesg = 'Expected a univeral property name.' self....
python
def parse_accept_header(value, cls=None): """Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction. Returns a new :class:`Accept` object (basically a list of ``(value, quality)`` tuples sorted by the quality w...
python
def save_state_with_reason(self, reason, progress, snapshot, state_file_path, pause_vm): """Internal method for triggering a VM save state with a specified reason code. The reason code can be interpreted by device/drivers and thus it might behave slightly differently than a normal VM save state....
python
def view_umatrix(self, figsize=None, colormap=cm.Spectral_r, colorbar=False, bestmatches=False, bestmatchcolors=None, labels=None, zoom=None, filename=None): """Plot the U-matrix of the trained map. :param figsize: Optional parameter to specify the size of the ...
python
def _get_value_from_ast(self, obj): """ Return the value of the ast object. """ if isinstance(obj, ast.Num): return obj.n elif isinstance(obj, ast.Str): return obj.s elif isinstance(obj, ast.List): return [self._get_value_from_ast(e) fo...
python
def enable_hostgroup_host_checks(self, hostgroup): """Enable host checks for a hostgroup Format of the line that triggers function call:: ENABLE_HOSTGROUP_HOST_CHECKS;<hostgroup_name> :param hostgroup: hostgroup to enable :type hostgroup: alignak.objects.hostgroup.Hostgroup ...
python
def visit_Return(self, node): """ Add edge from all possible callee to current function. Gather all the function call that led to the creation of the returned expression and add an edge to each of this function. When visiting an expression, one returns a list of frozensets. Eac...
java
public static <T extends AbstractJaxb> List<T> getDescendants(T target, List<T> resultList, Class<T> tagType) { return execute(target, resultList, tagType, null); }
java
@VisibleForTesting static <T> List<List<T>> getBuckets(Collection<Pair<T, Long>> files, long timeUnit, int base, long now) { // Sort files by age. Newest first. final List<Pair<T, Long>> sortedFiles = Lists.newArrayList(files); Collections.sort(sortedFiles, Collections.reverseOrder(new C...
python
def gff(args): """ %prog gff *.gff Draw exons for genes based on gff files. Each gff file should contain only one gene, and only the "mRNA" and "CDS" feature will be drawn on the canvas. """ align_choices = ("left", "center", "right") p = OptionParser(gff.__doc__) p.add_option("--align"...
java
public static void error(Log log, String format, Object... arguments) { error(log, null, format, arguments); }
java
@Override public DMatrixRMaj getQ(DMatrixRMaj Q , boolean compact ) { if( compact ) { if( Q == null ) { Q = CommonOps_DDRM.identity(numRows,minLength); } else { if( Q.numRows != numRows || Q.numCols != minLength ) { throw new Illega...
java
protected boolean cannotInstantiate(Class<?> actionClass) { return actionClass.isAnnotation() || actionClass.isInterface() || actionClass.isEnum() || (actionClass.getModifiers() & Modifier.ABSTRACT) != 0 || actionClass.isAnonymousClass(); }
java
private void newBlock(String m) { if (row==null) newRow(); else row.unnest(); row.nest(cell=new Block(m)); if (cellNestFactory!=null) cell.nest(cellNestFactory.newComposite()); }
python
def connect(polylines, max_dist=10): """ connect polylines that are close and have a similar orientation o---o <-> o---o ==> o----o--o----o TODO: max_dist as function of cell size """ ll = len(polylines) remove = [] for n in range(ll - 1, -1, -1): c = polylines[n] if ...
java
public int countOccupiedMapSlots() { int mapSlotsCount = 0; for (Iterator<TaskStatus> it = taskReports.iterator(); it.hasNext();) { TaskStatus ts = (TaskStatus) it.next(); if (ts.getIsMap() && isTaskRunning(ts)) { mapSlotsCount += ts.getNumSlots(); } } return mapSlotsCount; }
java
public T events_getMembers(Number eventId) throws FacebookException, IOException { assert (null != eventId); return this.callMethod(FacebookMethod.EVENTS_GET_MEMBERS, new Pair<String, CharSequence>("eid", eventId.toString())); }
python
def get_attrs(self, key): """ :param key: dataset path :returns: dictionary of attributes for that path """ try: dset = h5py.File.__getitem__(self.hdf5, key) except KeyError: if self.parent != (): dset = h5py.File.__getitem__(self.p...
python
def draw_text(data, obj): """Paints text on the graph. """ content = [] properties = [] style = [] if isinstance(obj, mpl.text.Annotation): _annotation(obj, data, content) # 1: coordinates # 2: properties (shapes, rotation, etc) # 3: text style # 4: the text # ...
java
public Map<String, Collection<String>> toMap() { Map<String, Collection<String>> params = new HashMap<String, Collection<String>>(); if (name != null) { ArrayList<String> valueList = new ArrayList<String>(); valueList.add(name); params.put("name", valueList); ...
python
def count_(self): """ Returns the number of rows of the main dataframe """ try: num = len(self.df.index) except Exception as e: self.err(e, "Can not count data") return return num
java
public static String encodeBackslash(char c) { if (isAlphanumeric(c) || c == ' ') return ("" + c); String hex = Integer.toHexString(c); while (hex.length() < 4) hex = "0" + hex; return ("\\u" + hex); }
java
public void setOwner(ListenerOwner owner) { super.setOwner(owner); if (owner != null) { BaseField field = m_field; if (field != null) if (field.getRecord() != owner) { // Points to different file... make sure this is removed if the other ...
python
def sgd(grad, x, callback=None, num_iters=200, step_size=0.1, mass=0.9): """Stochastic gradient descent with momentum. grad() must have signature grad(x, i), where i is the iteration number.""" velocity = np.zeros(len(x)) for i in range(num_iters): g = grad(x, i) if callback: callback(x,...
python
def get_asset_ids_by_repositories(self, repository_ids): """Gets the list of ``Asset Ids`` corresponding to a list of ``Repository`` objects. arg: repository_ids (osid.id.IdList): list of repository ``Ids`` return: (osid.id.IdList) - list of asset ``Ids`` raise: Null...
python
def erf(x): """ Error function. Works for floats, |GVar|\s, and :mod:`numpy` arrays. """ try: return math.erf(x) except TypeError: pass if isinstance(x, GVar): f = math.erf(x.mean) dfdx = 2. * math.exp(- x.mean ** 2) / math.sqrt(math.pi) return gvar_funct...
java
public Object getConnection() throws ResourceException { Object result = mc.getConnection(credential.getSubject(), credential.getConnectionRequestInfo()); addConnection(result); return result; }
python
def lgauss(x, mu, sigma=1.0, logpdf=False): """ Log10 normal distribution... x : Parameter of interest for scanning the pdf mu : Peak of the lognormal distribution (mean of the underlying normal distribution is log10(mu) sigma : Standard deviation of the underlying normal distributio...
java
private void prepareUploadParams(RequestElements requestElements) { Map<String, String> requestHeaders = requestElements.getRequestHeaders(); UploadRequestElements uploadRequestElements = requestElements.getUploadRequestElements(); String boundaryId = uploadRequestElements.getBoundaryId(); String formMetadataNa...
python
def hash_text(text): """Return MD5 hash of a string.""" md5 = hashlib.md5() md5.update(text) return md5.hexdigest()
java
public static void toKMLLineString(LineString lineString, ExtrudeMode extrude, int altitudeModeEnum, StringBuilder sb) { sb.append("<LineString>"); appendExtrude(extrude, sb); appendAltitudeMode(altitudeModeEnum, sb); appendKMLCoordinates(lineString.getCoordinates(), sb); sb.appe...
python
def _validate_in_port(self): """Validate in_port attribute. A valid port is either: * Greater than 0 and less than or equals to Port.OFPP_MAX * One of the valid virtual ports: Port.OFPP_LOCAL, Port.OFPP_CONTROLLER or Port.OFPP_NONE Raises: Val...
java
public void init(INDArray parameters, boolean cloneParametersArray) { if (layerWiseConfigurations == null || layers == null) intializeConfigurations(); if (initCalled) return; DataType netDtype = getLayerWiseConfigurations().getDataType(); if(parameters != null &...
java
public Expression<Short> lte(short value) { String valueString = "'" + value + "'"; return new Expression<Short>(this, Operation.lte, valueString); }
python
def package_remove(name): ''' Remove a "package" on the REST server ''' DETAILS = _load_state() DETAILS['packages'].pop(name) _save_state(DETAILS) return DETAILS['packages']
python
def data_discovery(self, region, keywords=None, regex=None, time=None, boundaries=None, include_quantiles=False): """Discover Data Observatory measures. This method returns the full Data Observatory metadata model for each measure or measures that match the conditions from...
java
protected void bindViewHelper(CustomBaseViewHolder viewHolder) { Context ctx = viewHolder.itemView.getContext(); //set the identifier from the drawerItem here. It can be used to run tests viewHolder.itemView.setId(hashCode()); //set the item selected if it is viewHolder.itemVie...
python
def set_items(self, items): """expects a list of key, value to work with""" res = [] max_value = max(sum((rec[1] for rec in items)), 1) for key, val in items: res.append((key, val, val * 1.0 / max_value)) self._items = res
java
public static boolean valueOf(String value) { return (value != null) && (value.trim().equalsIgnoreCase("true") || value.trim().equals("1")); }
python
def __find_sync_range(self, messages, preamble_end: int, search_end: int): """ Finding the synchronization works by finding the first difference between two messages. This is performed for all messages and the most frequent first difference is chosen :type messages: list of Message ...