repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
geometryzen/GeoCAS
build/module/lib/checks/isInteger.js
import isNumber from '../checks/isNumber'; export default function isInteger(x) { // % coerces its operand to numbers so a typeof test is required. // Not ethat ECMAScript 6 provides Number.isInteger(). return isNumber(x) && x % 1 === 0; }
metagomics/metagomics_root
pipeline-parts/metagomics-run-blast-and-jc-wrapper/metagomics-run-blast/src/org/uwpr/metagomics/run_blast/exceptions/RunBlastProgramAlreadyReportedErrorException.java
package org.uwpr.metagomics.run_blast.exceptions; public class RunBlastProgramAlreadyReportedErrorException extends Exception { public RunBlastProgramAlreadyReportedErrorException() { super(); // TODO Auto-generated constructor stub } public RunBlastProgramAlreadyReportedErrorException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } public RunBlastProgramAlreadyReportedErrorException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public RunBlastProgramAlreadyReportedErrorException(String message) { super(message); // TODO Auto-generated constructor stub } public RunBlastProgramAlreadyReportedErrorException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } private static final long serialVersionUID = 1L; }
phetsims/sherpa
js/fontawesome-5/laughWinkRegularShape.js
// Copyright 2021, University of Colorado Boulder // Auto-generated by modulifyFontAwesomeIcons.js, please do not modify directly. import Shape from '../../../kite/js/Shape.js'; import laughWinkRegularString from './laughWinkRegularString.js'; export default new Shape( laughWinkRegularString );
jhunhwang/goldenretriever
app/api/upload_es_kb_service.py
<filename>app/api/upload_es_kb_service.py """ Version: -------- 0.1 11th May 2020 Usage: ------ Script to handle indexing of QnA datasets into Elasticsearch for downstream finetuning and serving - Connect and upload Documents to Elasticsearch CSV files should have the following columns: [ans_id, ans_str, context_str (optional), query_str, query_id] To see how index is built, refer to src.elasticsearch.create_doc_index.py """ from elasticsearch_dsl import Document, InnerDoc, Date, Nested, Keyword, Text, Integer import pandas as pd from datetime import datetime from pydantic import BaseModel class EsParam(BaseModel): index_name: str def upload_es_kb_service(es_param, csv_file): class QA(InnerDoc): ans_id = Integer() ans_str = Text(fields={'raw': Keyword()}) query_id = Integer() query_str = Text() class Doc(Document): doc = Text() created_at = Date() qa_pair = Nested(QA) class Index: name = es_param.index_name def add_qa_pair(self, ans_id, ans_str, query_id, query_str): self.qa_pair.append(QA(ans_id=ans_id, ans_str=ans_str, query_id=query_id, query_str=query_str)) def save(self, **kwargs): self.created_at = datetime.now() return super().save(**kwargs) def send_docs(qa_pairs): """adds document with qa pair to elastic index assumes that index fields correspond to template in src.elasticsearch.create_doc_index.py Args: full_text: full text of document containing answer qa_pairs: list of dictionaries with key:value='ans_id':integer, 'ans_str':str, 'ans_index'=integer, 'query_str'=str, 'query_id'=integer Returns: document and qa_pair indexed to Elastic """ print('uploading docs') counter = 0 for pair in qa_pairs: first = Doc(doc=pair['ans_str']) first.add_qa_pair(pair['ans_id'], pair['ans_str'], pair['query_id'], pair['query_str']) first.save() counter += 1 return counter qa_pairs = pd.read_csv(csv_file.file).fillna('nan').to_dict('records') counter = send_docs(qa_pairs) return {'message': 'success', 'number of docs': counter}
cxcruz/math-facts-play
app/models/Task.scala
package models case class Task(id: Long, label: String) object Task { def all(): List[Task] = Nil def create(label: String) {} def delete(id: Long) {} }
mad-dukes/DAVEtools
DAVE/src/gov/nasa/daveml/dave/BlockMath.java
<filename>DAVE/src/gov/nasa/daveml/dave/BlockMath.java // BlockMath // // Part of DAVE-ML utility suite, written by <NAME>, NASA LaRC // <<EMAIL>> // Visit <http://daveml.org> for more info. // Latest version can be downloaded from http://dscb.larc.nasa.gov/Products/SW/DAVEtools.html // Copyright (c) 2007 United States Government as represented by LAR-17460-1. No copyright is // claimed in the United States under Title 17, U.S. Code. All Other Rights Reserved. package gov.nasa.daveml.dave; /** * * <p> Superclass representing an arbitrary math function </p> * <p> 031212 <NAME> <mailto:<EMAIL>> </p> * **/ import java.util.Iterator; import java.util.List; import org.jdom.Element; /** * * <p> The Math block represents an arbitrary math function </p> * **/ abstract public class BlockMath extends Block { /** * * <p>Basic constructor for math Block <p> * **/ public BlockMath() { // Initialize Block elements super(); } /** * * <p> Constructor for math Block <p> * * @param m <code>Model</code> we're part of * **/ public BlockMath( Model m) { // Initialize Block elements super(m); } /** * * <p> Constructor for math Block <p> * * @param blockName our name * @param blockType our type * @param m <code>Model</code> we're part of * **/ public BlockMath(String blockName, String blockType, Model m) { // Initialize Block elements super(blockName, blockType, 1, m); } /** * * <p> Constructor for math Block <p> * * @param blockName our name * @param blockType our type * @param numInputs how many inputs we have * @param m <code>Model</code> we're part of * **/ public BlockMath(String blockName, String blockType, int numInputs, Model m) { // Initialize Block elements super(blockName, blockType, numInputs, m); } /** * * <p> Determines block type and calls appropriate constructor </p> * * @param applyElement Reference to <code>org.jdom.Element</code> * containing "apply" element * @param m The parent <code>Model</code> * @return Math block of appropriate type * @throws DAVEException if problems were encountered * **/ @SuppressWarnings("unchecked") public static BlockMath factory( Element applyElement, Model m) throws DAVEException { //System.out.println(" BlockMath factory called."); // Parse parts of the Apply element List<Element> kids = applyElement.getChildren(); Iterator<Element> ikid = kids.iterator(); // first element should be our type Element first = ikid.next(); String theType = first.getName(); // take appropriate action based on type if( theType.equals("abs") ) { return new BlockMathAbs( applyElement, m ); } if( theType.equals("lt" ) || theType.equals("leq") || theType.equals("eq" ) || theType.equals("geq") || theType.equals("gt" ) || theType.equals("neq") ) { return new BlockMathRelation( applyElement, m ); } if( theType.equals("not") || theType.equals("or" ) || theType.equals("and") ) { return new BlockMathLogic( applyElement, m ); } if( theType.equals("minus") ) { return new BlockMathMinus( applyElement, m ); } if( theType.equals("piecewise") ) { return new BlockMathSwitch( applyElement, m ); } if( theType.equals("plus") ) { return new BlockMathSum( applyElement, m ); } if( theType.equals("times") || theType.equals("quotient") || theType.equals("divide") ) { return new BlockMathProduct( applyElement, m ); } if( theType.equals("max" ) || theType.equals("min" ) ) { return new BlockMathMinmax( applyElement, m ); } if( theType.equals("power" ) || theType.equals("sin" ) || theType.equals("cos" ) || theType.equals("tan" ) || theType.equals("arcsin" ) || theType.equals("arccos" ) || theType.equals("arctan" ) || theType.equals("ceiling") || theType.equals("floor" ) ) { try { return new BlockMathFunction( applyElement, m); } catch (DAVEException e) { System.err.println("Exception when tryng to build a math function of type '" + theType + "' - which is unrecognized. Aborting..."); System.exit(-1); } } if( theType.equals("csymbol") ) { return new BlockMathFunctionExtension( applyElement, m); } System.err.println("DAVE's BlockMath factory() method doesn't allow a <" + theType + "> element directly after an <apply> element."); return null; } /** * * <p> Finds or generates appropriate inputs from math constructs </p> * * @param ikid List <code>Iterator</code> for elements of top-level &lt;apply&gt;. * @param inputPortNumber <code>Int</code> with 1-based input number * **/ public void genInputsFromApply( Iterator<Element> ikid, int inputPortNumber ) { int i = inputPortNumber; while( ikid.hasNext() ) { // look at each input Element in = ikid.next(); String name = in.getName(); // if (this.getName().equals("divide_4")) // System.out.println("*-*-*-* In building block '" + this.getName() // + "' I found input math type " + name + "... adding as input " + i); // is it single scalar variable name <ci>? if( name.equals("ci") ) { String varID = in.getTextTrim(); // get variable name this.addVarID(i, varID); // add it to proper input //this.hookUpInput(i++); // and hook up to signal, if defined. // this is now done later } else if( name.equals("cn") ) { // or maybe a constant value? String constantValue = in.getTextTrim(); // get constant value // this.addVarID(i, constantValue); // add it as input - placeholder, not needed this.addConstInput(constantValue, i); // Create and hook up constant block } else if( name.equals("apply") ) { // recurse this.addVarID(i, ""); // placeholder - no longer needed // next throws DAVEException if bad syntax in <apply>. Catch and abend here // so we don't have to change the many calling routines. Signal s = null; try { s = new Signal(in, ourModel); // Signal constructor recognizes <apply>... } catch (DAVEException e) { System.err.println("Bad syntax while parsing <apply> in element '" + in.getName() + "'. Aborting."); } // .. and will call our BlockMath.factory() ... if( s!= null ) { // .. and creates upstream blocks & signals s.addSink(this,i); // hook us up as output of new signal path s.setDerivedFlag(); // Note that this is a newly-created signal not part of orig model } else { System.err.println("Null signal returned when creating recursive math element."); } } else { System.err.println("BlockMath didn't find usable element (something like 'apply', 'ci' or 'cn')," + " instead found: " + in.getName()); } i++; } } }
xiapeng612430/multi-thread
src/main/java/cyclicBarrier/cyclicBarrier_run1/MyService.java
package cyclicBarrier.cyclicBarrier_run1; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * Created by xianpeng.xia * on 2020/5/5 11:16 下午 */ public class MyService { private CyclicBarrier cyclicBarrier; public MyService(CyclicBarrier cyclicBarrier) { super(); this.cyclicBarrier = cyclicBarrier; } public void beginRun() { try { long sleepValue = (int) (Math.random() * 10000); Thread.sleep(sleepValue); System.out.println(Thread.currentThread().getName() + " " + System.currentTimeMillis() + " begin跑第一阶段" + (cyclicBarrier.getNumberWaiting() + 1)); cyclicBarrier.await(); System.out.println(Thread.currentThread().getName() + " " + System.currentTimeMillis() + " end跑第一阶段" + cyclicBarrier.getNumberWaiting() ); sleepValue = (int) (Math.random() * 10000); Thread.sleep(sleepValue); System.out.println(Thread.currentThread().getName() + " " + System.currentTimeMillis() + " begin跑第二阶段" + (cyclicBarrier.getNumberWaiting() + 1)); cyclicBarrier.await(); System.out.println(Thread.currentThread().getName() + " " + System.currentTimeMillis() + " end跑第二阶段" + cyclicBarrier.getNumberWaiting() ); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } }
sibasish-palo/emodb
queue-api/src/main/java/com/bazaarvoice/emodb/queue/api/MoveQueueStatus.java
<filename>queue-api/src/main/java/com/bazaarvoice/emodb/queue/api/MoveQueueStatus.java package com.bazaarvoice.emodb.queue.api; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class MoveQueueStatus { private final String _from; private final String _to; private final Status _status; public enum Status { IN_PROGRESS, COMPLETE, ERROR } @JsonCreator public MoveQueueStatus(@JsonProperty ("from") String from, @JsonProperty ("to") String to, @JsonProperty ("status") Status status) { _from = from; _to = to; _status = status; } public String getFrom() { return _from; } public String getTo() { return _to; } public Status getStatus() { return _status; } }
binwen/sqldb
clause/on_conflict_test.go
package clause_test import ( "fmt" "testing" "github.com/binwen/sqldb/clause" ) func TestOnConflict(t *testing.T) { results := []struct { Clauses []clause.IClause Result string Vars []interface{} }{ { []clause.IClause{ clause.Insert{}, clause.Values{ Columns: []clause.Column{{Name: "name"}, {Name: "age"}}, Values: [][]interface{}{{"bin", 18}}, }, clause.OnConflict{ Columns: []clause.Column{{Name: "name"}}, Where: clause.Where{Exprs: []clause.Expression{clause.EQ{Column: "id", Value: 1}}}, DoUpdates: clause.Assignments(map[string]interface{}{"name": "upsert-name"}), }, }, "INSERT INTO `user` (`name`,`age`) VALUES (?,?) ON CONFLICT (`name`) WHERE `id` = ? DO UPDATE SET `name`=?", []interface{}{"bin", 18, 1, "upsert-name"}, }, { []clause.IClause{ clause.Insert{}, clause.Values{ Columns: []clause.Column{{Name: "name"}, {Name: "age"}}, Values: [][]interface{}{{"bin", 18}}, }, clause.OnConflict{DoNothing: true}, }, "INSERT INTO `user` (`name`,`age`) VALUES (?,?) ON CONFLICT DO NOTHING", []interface{}{"bin", 18}, }, } for idx, result := range results { t.Run(fmt.Sprintf("case #%v", idx), func(t *testing.T) { checkBuildClauses(t, result.Clauses, result.Result, result.Vars) }) } }
timfel/netbeans
ide/libs.git/src/org/netbeans/libs/git/jgit/commands/PullCommand.java
<reponame>timfel/netbeans /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.libs.git.jgit.commands; import java.io.IOException; import org.netbeans.libs.git.GitMergeResult; import org.netbeans.libs.git.GitTransportUpdate; import java.util.List; import java.util.Map; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.FetchResult; import org.eclipse.jgit.transport.RefSpec; import org.netbeans.libs.git.GitException; import org.netbeans.libs.git.GitPullResult; import org.netbeans.libs.git.jgit.GitClassFactory; import org.netbeans.libs.git.progress.ProgressMonitor; /** * * @author ondra */ public class PullCommand extends TransportCommand { private final ProgressMonitor monitor; private final List<String> refSpecs; private final String remote; private Map<String, GitTransportUpdate> updates; private FetchResult result; private final String branchToMerge; private GitMergeResult mergeResult; public PullCommand (Repository repository, GitClassFactory gitFactory, String remote, List<String> fetchRefSpecifications, String branchToMerge, ProgressMonitor monitor) { super(repository, gitFactory, remote, monitor); this.monitor = monitor; this.remote = remote; this.refSpecs = fetchRefSpecifications; this.branchToMerge = branchToMerge; } @Override protected void runTransportCommand () throws GitException.AuthorizationException, GitException { FetchCommand fetch = new FetchCommand(getRepository(), getClassFactory(), remote, refSpecs, monitor); fetch.setCredentialsProvider(getCredentialsProvider()); fetch.run(); this.updates = fetch.getUpdates(); MergeCommand merge = new MergeCommand(getRepository(), getClassFactory(), branchToMerge, null, monitor); merge.setCommitMessage("branch \'" + findRemoteBranchName() + "\' of " + fetch.getResult().getURI().setUser(null).setPass(null).toString()); merge.run(); this.mergeResult = merge.getResult(); } @Override protected String getCommandDescription () { StringBuilder sb = new StringBuilder("git pull ").append(remote); //NOI18N for (String refSpec : refSpecs) { sb.append(' ').append(refSpec); } return sb.toString(); } public GitPullResult getResult () { return getClassFactory().createPullResult(updates, mergeResult); } private String findRemoteBranchName () throws GitException { Ref ref = null; try { ref = getRepository().findRef(branchToMerge); } catch (IOException ex) { throw new GitException(ex); } if (ref != null) { for (String s : refSpecs) { RefSpec spec = new RefSpec(s); if (spec.matchDestination(ref)) { spec = spec.expandFromDestination(ref); String refName = spec.getSource(); if (refName.startsWith(Constants.R_HEADS)) { return refName.substring(Constants.R_HEADS.length()); } } } } return branchToMerge; } }
sandboxws/awesome_explain
app/models/awesome_explain/sql_plan_tree.rb
class AwesomeExplain::SqlPlanTree attr_accessor :root, :ids, :plans_count, :seq_scan, :seq_scans, :startup_cost, :total_cost, :rows, :width, :actual_startup_time, :actual_total_time, :actual_rows, :actual_loops, :plan_stats alias :seq_scan? :seq_scan def initialize @startup_cost = 0 @total_cost = 0 @rows = 0 @width = 0 @actual_startup_time = 0 @actual_total_time = 0 @actual_rows = 0 @actual_loops = 0 @seq_scans = 0 @plan_stats = ::AwesomeExplain::SqlPlanStats.new end def self.build(plan) tree = self.new tree.ids = (2..500).to_a # Ugh!!! root = ::AwesomeExplain::SqlPlanNode.build(plan.first.dig('Plan')) tree.root = root tree.update_tree_stats(root) root.id = 1 tree.plans_count = 1 build_recursive(plan.first.dig('Plan', 'Plans'), root, tree) tree end def self.build_recursive(data, parent, tree) return unless data.present? if data.is_a?(Array) data.each do |plan| build_recursive(plan, parent, tree) end elsif data.is_a?(Hash) && data.dig('Plans').present? node = ::AwesomeExplain::SqlPlanNode.build(data, parent) node.id = tree.ids.shift parent.children << node tree.plans_count += 1 tree.seq_scans += 1 if node.seq_scan? tree.update_tree_stats(node) build_recursive(data.dig('Plans'), node, tree) elsif data.is_a?(Hash) && data.dig('Plans').nil? node = ::AwesomeExplain::SqlPlanNode.build(data, parent) tree.update_tree_stats(node) node.id = tree.ids.shift tree.plans_count += 1 tree.seq_scans += 1 if node.seq_scan? parent.children << node end end def treeviz return unless root.present? output = [] queue = [root] while(!queue.empty?) do node = queue.shift output << node.treeviz node.children.each do |child| queue << child end end output end def update_tree_stats(node) self.startup_cost += node.startup_cost self.total_cost += node.total_cost self.rows += node.rows self.width += node.width self.actual_startup_time += node.actual_startup_time self.actual_total_time += node.actual_total_time self.actual_rows += node.actual_rows self.actual_loops += node.actual_loops # Plan Stats plan_stats.total_rows_planned += node.rows plan_stats.total_rows += node.actual_rows plan_stats.total_loops += node.actual_loops plan_stats.seq_scans += 1 if node.seq_scan? relation_name = node.relation_name if relation_name if plan_stats.table_stats.dig(relation_name).nil? plan_stats.table_stats[relation_name] = { count: 0, time: 0 } end plan_stats.table_stats[relation_name][:count] += 1 plan_stats.table_stats[relation_name][:time] += node.actual_total_time end node_type = node.type if node_type if plan_stats.node_type_stats.dig(node_type).nil? plan_stats.node_type_stats[node_type] = { count: 0 } end plan_stats.node_type_stats[node_type][:count] += 1 end index_name = node.index_name if index_name if plan_stats.index_stats.dig(index_name).nil? plan_stats.index_stats[index_name] = { count: 0 } plan_stats.index_stats[index_name][:count] += 1 end end end end
PerfectDreams/MCPainter
MCPainter/src/main/java/org/primesoft/mcpainter/drawing/filters/ColorEx.java
<gh_stars>10-100 /* * The MIT License * * Copyright 2013 SBPrime. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.primesoft.mcpainter.drawing.filters; import java.awt.Color; /** * * @author SBPrime */ public class ColorEx { public final static ColorEx TRANSPARENT = new ColorEx(0, 0, 0, 0); private int m_r; private int m_g; private int m_b; private int m_a; public ColorEx(int c) { this(new Color(c, true)); } public ColorEx(Color c) { m_r = c.getRed(); m_g = c.getGreen(); m_b = c.getBlue(); m_a = c.getAlpha(); } private ColorEx(int a, int r, int g, int b) { m_r = r; m_g = g; m_b = b; m_a = a; } /** * Is this colr transparent * * @return */ public boolean isTransparent() { return m_a < 128; } public static ColorEx add(ColorEx c1, ColorEx c2) { return new ColorEx(c1.m_a + c2.m_a, c1.m_r + c2.m_r, c1.m_g + c2.m_g, c1.m_b + c2.m_g); } public static ColorEx sub(ColorEx c1, ColorEx c2) { return new ColorEx(c1.m_a - c2.m_a, c1.m_r - c2.m_r, c1.m_g - c2.m_g, c1.m_b - c2.m_g); } public static ColorEx mul(ColorEx c, double m) { return new ColorEx((int) (c.m_a * m), (int) (c.m_r * m), (int) (c.m_g * m), (int) (c.m_b * m)); } public static double dist(ColorEx c1, ColorEx c2) { double rmean = (c1.m_r + c2.m_r) / 2.0; double r = c1.m_r - c2.m_r; double g = c1.m_g - c2.m_g; int b = c1.m_b - c2.m_b; double weightR = 2 + rmean / 256.0; double weightG = 4.0; double weightB = 2 + (255 - rmean) / 256.0; double a1 = c1.m_a; double a2 = c2.m_a; double a = Math.abs(a2 - a1) * (a1 <= a2 ? 1 : 1000); return Math.sqrt(weightR * r * r + weightG * g * g + weightB * b * b) + a * 512; } public static ColorEx clamp(ColorEx c) { return new ColorEx(clamp(c.m_a), clamp(c.m_r), clamp(c.m_g), clamp(c.m_b)); } /*public static double dist(ColorEx c1, ColorEx c2) { double dr = c1.m_r - c2.m_r; double dg = c1.m_g - c2.m_g; double db = c1.m_b - c2.m_b; return dr * dr + dg * dg + db * db; }*/ public Color toColor() { return new Color(clamp(m_r), clamp(m_g), clamp(m_b), clamp(m_a)); } public int toRGB() { return toColor().getRGB(); } private static int clamp(int c) { return Math.max(0, Math.min(255, c)); } }
laipaang/Paddle
python/paddle/fluid/tests/unittests/dygraph_to_static/test_tensor_shape.py
<reponame>laipaang/Paddle<filename>python/paddle/fluid/tests/unittests/dygraph_to_static/test_tensor_shape.py # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import numpy import unittest import paddle.fluid as fluid from paddle.fluid.dygraph.jit import declarative def dyfunc_tensor_shape_1(x): x = fluid.dygraph.to_variable(x) res = fluid.layers.reshape(x, shape=x.shape) return res def dyfunc_tensor_shape_2(x): x = fluid.dygraph.to_variable(x) shape = x.shape shape2 = shape res = fluid.layers.reshape(x, shape2) return res def dyfunc_tensor_shape_3(x): # Don't transform y.shape because y is numpy.ndarray x = fluid.dygraph.to_variable(x) y = numpy.ones(5) res = fluid.layers.reshape(x, shape=y.shape) return res def dyfunc_tensor_shape_4(x): x = fluid.dygraph.to_variable(x) res = fluid.layers.reshape(x, shape=(-1, x.shape[0], len(x.shape))) return res def dyfunc_tensor_shape_5(x): # `res = fluid.layers.reshape(x, shape=(-1, s))` to # `res = fluid.layers.reshape(x, shape=(-1, fluid.layers.shape(x)[0]))` x = fluid.dygraph.to_variable(x) s = x.shape[0] res = fluid.layers.reshape(x, shape=(-1, s)) return res def dyfunc_with_if_1(x): x = fluid.dygraph.to_variable(x) res = fluid.layers.reshape(x, [-1, 1]) x_shape_0 = x.shape[0] if x_shape_0 < 1: # `res.shape[0] > 1` is transformed into `if fluid.layers.shape(res)[0] > 1` if res.shape[0] > 1: res = fluid.layers.fill_constant( value=2, shape=x.shape, dtype="int32") else: res = fluid.layers.fill_constant( value=3, shape=x.shape, dtype="int32") return res def dyfunc_with_if_2(x): x = fluid.dygraph.to_variable(x) # `len(x.shape)` will not be transformed. if len(x.shape) < 1: res = x else: res = fluid.layers.fill_constant(value=8, shape=x.shape, dtype="int32") return res def dyfunc_with_for_1(x): x = fluid.dygraph.to_variable(x) res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32") # `x.shape[0]` is transformed into `fluid.layers.shape(x)[0]` for i in range(x.shape[0]): res += 1 return res def dyfunc_with_for_2(x): x = fluid.dygraph.to_variable(x) x_shape_0 = x.shape[0] res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32") # `x_shape_0` is transformed into `fluid.layers.shape(x)[0]` for i in range(x_shape_0): res += 1 return res def dyfunc_with_for_3(x): # TODO(liym27): # It will fail to run because `for i in range(len(x.shape))` will be transformed into Paddle while_loop. # Here the python list x.shape will be added to loop_vars. However, loop_vars doesn't support python list. # And the condition of `for i in range(len(x.shape))` only uses the length of x.shape, so it doesn't have to be transformed into Paddle while_loop. # After the AST tranformation of for loop is improved, add TestTensorShapeInFor3. x = fluid.dygraph.to_variable(x) res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32") # `len(x.shape)` is not transformed. for i in range(len(x.shape)): res += 1 return res def dyfunc_with_while_1(x): x = fluid.dygraph.to_variable(x) res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32") # `x.shape[0]` is transformed into `fluid.layers.shape(x)[0]` i = 1 while i < x.shape[0]: res += 1 i = i + 2 return res def dyfunc_with_while_2(x): x = fluid.dygraph.to_variable(x) x_shape_0 = x.shape[0] res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32") i = 1 # `x_shape_0` is transformed into `fluid.layers.shape(x)[0]` # TODO(liym27): If `x_shape_0` is at right like `while i < x_shape_0`, it will not be transformed. # Fix this bug next PR. while x_shape_0 > i: res += 1 i = i + 2 return res def dyfunc_with_while_3(x): # TODO(liym27): # It will fail to run because the same problem as `dyfunc_with_for_3`. # After the AST tranformation of for loop is improved, add TestTensorShapeInWhile3. x = fluid.dygraph.to_variable(x) x_shape = x.shape res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32") i = 1 # `len(x.shape)` is not transformed. while len(x_shape) > i: res += 1 i += 1 return res # 1. Basic tests without control flow class TestTensorShapeBasic(unittest.TestCase): def setUp(self): self.input = numpy.ones(5).astype("int32") self.place = fluid.CUDAPlace(0) if fluid.is_compiled_with_cuda( ) else fluid.CPUPlace() self.init_test_func() def init_test_func(self): self.dygraph_func = dyfunc_tensor_shape_1 def _run(self, to_static): with fluid.dygraph.guard(): if to_static: res = declarative(self.dygraph_func)(self.input).numpy() else: res = self.dygraph_func(self.input).numpy() return res def get_dygraph_output(self): return self._run(to_static=False) def get_static_output(self): return self._run(to_static=False) def test_transformed_static_result(self): static_res = self.get_static_output() dygraph_res = self.get_dygraph_output() self.assertTrue( numpy.allclose(dygraph_res, static_res), msg='dygraph res is {}\nstatic_res is {}'.format(dygraph_res, static_res)) class TestTensorShapeBasic2(TestTensorShapeBasic): def init_test_func(self): self.dygraph_func = dyfunc_tensor_shape_2 class TestTensorShapeBasic3(TestTensorShapeBasic): def init_test_func(self): self.dygraph_func = dyfunc_tensor_shape_3 class TestTensorShapeBasic4(TestTensorShapeBasic): def init_test_func(self): self.dygraph_func = dyfunc_tensor_shape_4 class TestTensorShapeBasic5(TestTensorShapeBasic): def init_test_func(self): self.dygraph_func = dyfunc_tensor_shape_5 # 2. Tests with control flow if class TestTensorShapeInIf1(TestTensorShapeBasic): def init_test_func(self): self.dygraph_func = dyfunc_with_if_1 class TestTensorShapeInIf2(TestTensorShapeBasic): def init_test_func(self): self.dygraph_func = dyfunc_with_if_2 # 3. Tests with control flow for loop class TestTensorShapeInFor1(TestTensorShapeBasic): def init_test_func(self): self.dygraph_func = dyfunc_with_for_1 class TestTensorShapeInFor2(TestTensorShapeBasic): def init_test_func(self): self.dygraph_func = dyfunc_with_for_2 # 4. Tests with control flow while loop class TestTensorShapeInWhile1(TestTensorShapeBasic): def init_test_func(self): self.dygraph_func = dyfunc_with_while_1 class TestTensorShapeInWhile2(TestTensorShapeBasic): def init_test_func(self): self.dygraph_func = dyfunc_with_while_2 if __name__ == '__main__': unittest.main()
thomasbarillot/DAQ
TOF/TOFAcqDigitizer.py
<filename>TOF/TOFAcqDigitizer.py import scipy.io as sio import math import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import numpy as np from matplotlib import pyplot as plt from datetime import datetime from PI_E750_CP_piezostageFunction import PI_E750_CP_piezostageFunction as dstage import time import os from ctypes import * ADQAPI = cdll.LoadLibrary("ADQAPI.dll") # ADQAPI.CreateADQControlUnit.restype = c_void_p #ADQAPI.ADQ14_GetRevision.restype = c_void_p ADQAPI.ADQControlUnit_FindDevices.argtypes = [c_void_p] dt=datetime thislogfilename='%i%s%s_%s%s%s.log' % (dt.today().year,str(dt.today().month).zfill(2),str(dt.today().day).zfill(2), \ str(dt.today().hour).zfill(2), \ str(dt.today().minute).zfill(2), \ str(dt.today().second).zfill(2)) class TOFAcqDigitizer(): def __init__(self,f): self.f=f self.ProgressBar=[] # Conversion factors self.mv_conv=(2**16)/300.0 self.ns_conv=2 #Acquisition parameters self.acqmode=1 # Choose either SINGLE_SHOT(0) or WAVEFORM_AVG(1) self.ltofA=5000 # %Record length per shot in ns self.ltofB=100 # %Record length per shot in ns self.analogbiasA_mv = 0.0 # Adjustable analog bias (DC offset) in mV. Range is +/-150mV self.analogbiasA=np.round(self.analogbiasA_mv*self.mv_conv) self.analogbiasB_mv =0.0 # Adjustable analog bias (DC offset) in mV. Range is +/-150mV self.analogbiasB=np.round(self.analogbiasB_mv*self.mv_conv) self.channel=2 #Delay Scan parameters self.dscanmode=0 self.dscanstart=0 self.dscanstop=80 self.dscanstep=1 self.dscanrange=np.arange(self.dscanstart,self.dscanstop,self.dscanstep) # Recording options self.nbuffrecords=2 # Number of buffer records self.nrecords=10000 # Number of records per sample self.nsaverecords=1000 self.nsamplesA=self.ltofA*2 #samples per buffer record self.nsamplesB=self.ltofB*2 #samples per buffer record self.buffer_sizeA = self.nsaverecords*self.nsamplesA self.buffer_sizeB = self.nsaverecords*self.nsamplesB self.bytes_per_sample = 2 # Trigger options self.triggermode=2 # choose: 'CH_A(3)','CH_B(3)' or 'EXTERNAL_TRIGGER (2)' self.trigchannel=1 # Choose 'CH_A(1)','CH_B(2)' self.trig_edge = 1 #RISING_EDGE(1) or FALLING EDGE(0) self.triglevel_mv =-0.70 #Trigger threshold in mV => For a level trigger this must be in the range +/-150mV. For external trigger this must be in the range -500mV to +3300mV. self.record_start_shift = 'NONE' #choose 'PRETRIGGER', 'HOLDOFF' OR 'NONE' self.pretrigger_ns=0 #only applicable if 'PRETRIGGER' is selected. self.holdoff_ns=0 #only applicable if 'HOLDOFF' is selected. self.f.write('nsamplesA: %i, nrecords: %i, buffer size: %i, channel: %i, Triggermode:%i, dscanmode: %i, acqmode: %i\n'\ % (self.nsamplesA,self.nrecords,self.buffer_sizeA,self.channel,self.triggermode,self.dscanmode,self.acqmode)) # Connect with the digitizer self.adq_cu = c_void_p(ADQAPI.CreateADQControlUnit()) ADQAPI.ADQControlUnit_FindDevices(self.adq_cu) n_of_ADQ = ADQAPI.ADQControlUnit_NofADQ(self.adq_cu) err2=ADQAPI.ADQControlUnit_GetLastFailedDeviceError(self.adq_cu) n_of_ADQ14 = ADQAPI.ADQControlUnit_NofADQ14(self.adq_cu) err3=ADQAPI.ADQControlUnit_GetLastFailedDeviceError(self.adq_cu) self.f.write('initialisation values: %i,%i,%i,%i \n' % (n_of_ADQ,n_of_ADQ14,err2,err3)) if (n_of_ADQ14 != 0): self.f.write('found ADQ device') #ADQAPI.ADQControlUnit_EnableErrorTraceAppend(self.adq_cu,3,'C:/Documents/...') self.f.write('enable ADQ log trace') def __del__(self): success = ADQAPI.DeleteADQControlUnit(self.adq_cu) if (success == 0): self.f.write('Delete ADQ control failed.\n') self.f.close() # GUI interaction functions def setDigitizerParameters(self,ParametersArray): self.f.write('set Dig Params0\n') self.nsamplesA=ParametersArray[0]*2 self.nrecords=ParametersArray[1] # Number of records per sample self.buffer_sizeA = self.nsaverecords*self.nsamplesA # self.channel=ParametersArray[2] self.triggermode=ParametersArray[3] # self.dscanmode=ParametersArray[4] self.dscanstart=ParametersArray[5] self.dscanstop=ParametersArray[6] self.dscanstep=ParametersArray[7] self.acqmode=ParametersArray[8] if (len(ParametersArray[9])!=0): self.dscanrange=ParametersArray[9] else: self.dscanrange=np.arange(self.dscanstart,self.dscanstop,self.dscanstep) self.f.write('nsamplesA: %i, nrecords: %i, buffer size: %i, channel: %i, Triggermode:%i, dscanmode: %i, acqmode: %i\n'\ % (self.nsamplesA,self.nrecords,self.buffer_sizeA,self.channel,self.triggermode,self.dscanmode,self.acqmode)) def StartRecording(self,foldername): #StartProgressBar() try: self.ProgressBar=QtGui.QProgressDialog('Acquisition in progress','Abort',0,100) self.ProgressBar.show() self.ProgressBar.setValue(0) except: print 'ERROR starting progress bar dialog box' success = ADQAPI.ADQ_SetSampleSkip(self.adq_cu,1,1) if (success == 0): self.f.write('ADQ_SetSampleSkip failed.\n') self.f.write('bp3\n') #success = ADQAPI.ADQ_SetAdjustableBias(self.adq_cu,1,0,self.analogbiasA) #if (success == 0): # print('ADQ_SetAdjustableBias failed.') #success = ADQAPI.ADQ_SetAdjustableBias(self.adq_cu,1,1,self.analogbiasB) #if (success == 0): # print('ADQ_SetAdjustableBias failed.') success = ADQAPI.ADQ_SetTriggerMode(self.adq_cu,1, self.triggermode) if (success == 0): self.f.write('ADQ_SetTriggerMode failed.\n') self.f.write('bp4\n') #trigth=0.6 if self.triggermode==2: success = ADQAPI.ADQ_SetExtTrigThreshold(self.adq_cu,1,1,c_double(0.5)) if (success == 0): self.f.write('ADQ_SetExternTrigLevel failed.\n') success = ADQAPI.ADQ_SetExternTrigEdge(self.adq_cu,1, self.trig_edge) if (success == 0): self.f.write('ADQ_SetExternTrigEdge failed.\n') if self.triggermode==3: triglvl=int(round(self.triglevel_mv*self.mv_conv)) success = ADQAPI.ADQ_SetLvlTrigChannel(self.adq_cu,1, self.trigchannel) if (success == 0): self.f.write('DParam: ADQ_SetLvlTrigChannel failed.\n') success = ADQAPI.ADQ_SetLvlTrigLevel(self.adq_cu,1, triglvl) if (success == 0): self.f.write('DParam: ADQ_SetLvlTrigLevel failed.\n') success = ADQAPI.ADQ_SetLvlTrigEdge(self.adq_cu,1, self.trig_edge) if (success == 0): self.f.write('DParam: ADQ_SetLvlTrigEdge failed.\n') ### DSCAN OFF ### if self.dscanmode==0: if self.acqmode==1: try: avgtraceA=np.zeros((self.nsamplesA),dtype=np.int64) avgtraceB=np.zeros((self.nsamplesA),dtype=np.int64) except: self.f.write('Initialisation of average trace failed.\n') success=ADQAPI.ADQ_MultiRecordSetup(self.adq_cu,1,self.nrecords,self.nsamplesA) if (success == 0): self.f.write('Recording: ADQ_MultiRecordSetup failed.\n') else: self.f.write('Recording: ADQ_MultiRecordSetup SUCCESS.\n') self.f.write('bp7\n') acquiredrecord=0 savestart= 0 NumberOfRecords = self.nsaverecords ChannelsMask = 0xF StartSample = 0 saveend=self.nsaverecords success=ADQAPI.ADQ_DisarmTrigger(self.adq_cu,1) if (success == 0): self.f.write('Recording: ADQ_DisarmTrigger failed.\n') success=ADQAPI.ADQ_ArmTrigger(self.adq_cu,1) if (success == 0): self.f.write('Recording: ADQ_ArmTrigger failed.\n') i=0 if self.acqmode==1: while (acquiredrecord<self.nrecords): acquiredrecord=ADQAPI.ADQ_GetAcquiredRecords(self.adq_cu,1) max_number_of_channels = 2 target_buffers=(POINTER(c_int16*self.nsamplesA*self.nsaverecords)*max_number_of_channels)() for bufp in target_buffers: bufp.contents = (c_int16*self.nsamplesA*self.nsaverecords)() #self.f.write('bp10; nofacq: %i\n' % acquiredrecord) if (acquiredrecord>=saveend): savestart=saveend-self.nsaverecords try: ADQAPI.ADQ_GetData(self.adq_cu,1,target_buffers,self.buffer_sizeA,self.bytes_per_sample,savestart,NumberOfRecords,ChannelsMask,StartSample,self.nsamplesA,0x00) data_16bit_ch0 = np.frombuffer(target_buffers[0].contents,dtype=np.int16) data_16bit_ch0[data_16bit_ch0>=-200]=0 data_16bit_ch1 = np.frombuffer(target_buffers[1].contents,dtype=np.int16) avgtraceA+=np.reshape(data_16bit_ch0,(self.nsaverecords,self.nsamplesA)).sum(0) avgtraceB+=np.reshape(data_16bit_ch1,(self.nsaverecords,self.nsamplesA)).sum(0) except: self.f.write('failed recording average trace\n') i+=1 saveend+=self.nsaverecords self.ProgressBar.setValue(np.round(100*aquiredrecord/np.float(self.nrecords))) data={'wf_ChA':avgtraceA,'wf_ChB':avgtraceB} path_mat='%s/WaveformAvg.mat' % (foldername) try: sio.savemat(path_mat,data) #path_npz='%s/WaveformAvg.npz' % (foldername,i) #np.savez(path_npz,**data) except: self.f.write('failed saving average trace\n') else: while (acquiredrecord<self.nrecords): acquiredrecord=ADQAPI.ADQ_GetAcquiredRecords(self.adq_cu,1) max_number_of_channels = 2 #target_headers=(POINTER(c_int64*self.nsaverecords))() #for headp in target_headers: # headp.contents= (c_int64*self.nsaverecords)() target_buffers=(POINTER(c_int16*self.nsamplesA*self.nsaverecords)*max_number_of_channels)() for bufp in target_buffers: bufp.contents = (c_int16*self.nsamplesA*self.nsaverecords)() #self.f.write('bp10; nofacq: %i\n' % acquiredrecord) if (acquiredrecord>=saveend): savestart=saveend-self.nsaverecords try: ADQAPI.ADQ_GetData(self.adq_cu,1,target_buffers,target_headers,self.buffer_sizeA,self.bytes_per_sample,savestart,NumberOfRecords,ChannelsMask,StartSample,self.nsamplesA,0x00) data_16bit_ch0 = np.frombuffer(target_buffers[0].contents,dtype=np.int16) data_16bit_ch1 = np.frombuffer(target_buffers[1].contents,dtype=np.int16) #timestamps=np.frombuffer(target_headers.contents,dtype=np.int64) data={'specmat_ChA':data_16bit_ch0,'specmat_ChB':data_16bit_ch1}#,'timestamps':timestamps} path_mat='%s/specfile_%s.mat' % (foldername,str(i).zfill(3)) #path_npz='%s/specfile_%i.npz' % (foldername,i) try: sio.savemat(path_mat,data) #np.savez(path_npz,**data) except: self.f.write('failed saving singleshot trace\n') except: self.f.write('failed recording singleshot trace\n') i+=1 saveend+=self.nsaverecords self.ProgressBar.setValue(np.round(100*aquiredrecord/np.float(self.nrecords))) success=ADQAPI.ADQ_DisarmTrigger(self.adq_cu,1) if (success == 0): self.f.write('Recording: ADQ_DisarmTrigger failed.\n') success=ADQAPI.ADQ_MultiRecordClose(self.adq_cu,1); if (success == 0): self.f.write('Recording: ADQ_MultiRecordClose failed.\n') self.f.write('Acquisition finished at %s:%s:%s' % (str(dt.today().hour).zfill(2), \ str(dt.today().minute).zfill(2), \ str(dt.today().second).zfill(2))) ### DSCAN ON ### elif self.dscanmode==1: if self.acqmode==1: try: avgscanA=np.zeros((len(self.dscanrange),self.nsamplesA),dtype=np.int64) avgscanB=np.zeros((len(self.dscanrange),self.nsamplesA),dtype=np.int64) except: self.f.write('Initialisation of average scan matrix failed.\n') for j,delayval in enumerate(self.dscanrange): # Change the delay on the delaystage (humongium computer) dstage('//192.168.127.12/CEP_remotecontrol/',delayval) if self.acqmode==0: if not os.path.exists('%s/SSdelay%s' % (foldername,str(j).zfill(2))): os.makedirs('%s/SSdelay%s' % (foldername,str(j).zfill(2))) if self.acqmode==1: try: avgtraceA=np.zeros((self.nsamplesA),dtype=np.int64) avgtraceB=np.zeros((self.nsamplesA),dtype=np.int64) except: self.f.write('Initialisation of average trace failed.\n') # Wait for 1 second that the stage has moved time.sleep(1.0) success=ADQAPI.ADQ_MultiRecordSetup(self.adq_cu,1,self.nrecords,self.nsamplesA) if (success == 0): self.f.write('Recording: ADQ_MultiRecordSetup failed.\n') else: self.f.write('Recording: ADQ_MultiRecordSetup SUCCESS.\n') self.f.write('bp7\n') acquiredrecord=0 savestart= 0 NumberOfRecords = self.nsaverecords ChannelsMask = 0xF StartSample = 0 saveend=self.nsaverecords success=ADQAPI.ADQ_DisarmTrigger(self.adq_cu,1) if (success == 0): self.f.write('Recording: ADQ_DisarmTrigger failed.\n') success=ADQAPI.ADQ_ArmTrigger(self.adq_cu,1) if (success == 0): self.f.write('Recording: ADQ_ArmTrigger failed.\n') i=0 if self.acqmode==1: while (acquiredrecord<self.nrecords): acquiredrecord=ADQAPI.ADQ_GetAcquiredRecords(self.adq_cu,1) max_number_of_channels = 2 target_buffers=(POINTER(c_int16*self.nsamplesA*self.nsaverecords)*max_number_of_channels)() for bufp in target_buffers: bufp.contents = (c_int16*self.nsamplesA*self.nsaverecords)() #self.f.write('bp10; nofacq: %i\n' % acquiredrecord) if (acquiredrecord>=saveend): savestart=saveend-self.nsaverecords try: ADQAPI.ADQ_GetData(self.adq_cu,1,target_buffers,self.buffer_sizeA,self.bytes_per_sample,savestart,NumberOfRecords,ChannelsMask,StartSample,self.nsamplesA,0x00) data_16bit_ch0 = np.frombuffer(target_buffers[0].contents,dtype=np.int16) data_16bit_ch0[data_16bit_ch0>=-150]=0 data_16bit_ch1 = np.frombuffer(target_buffers[1].contents,dtype=np.int16) avgtraceA+=np.reshape(data_16bit_ch0,(self.nsaverecords,self.nsamplesA)).sum(0) avgtraceB+=np.reshape(data_16bit_ch1,(self.nsaverecords,self.nsamplesA)).sum(0) except: self.f.write('failed recording average trace\n') i+=1 saveend+=self.nsaverecords try: avgscanA[j,:]=avgtraceA avgscanB[j,:]=avgtraceB except: self.f.write('failed building average scan\n') else: while (acquiredrecord<self.nrecords): acquiredrecord=ADQAPI.ADQ_GetAcquiredRecords(self.adq_cu,1) max_number_of_channels = 2 #target_headers=(POINTER(c_int64*self.nsaverecords))() #for headp in target_headers: # headp.contents= (c_int64*self.nsaverecords)() target_buffers=(POINTER(c_int16*self.nsamplesA*self.nsaverecords)*max_number_of_channels)() for bufp in target_buffers: bufp.contents = (c_int16*self.nsamplesA*self.nsaverecords)() #self.f.write('bp10; nofacq: %i\n' % acquiredrecord) if (acquiredrecord>=saveend): savestart=saveend-self.nsaverecords try: ADQAPI.ADQ_GetData(self.adq_cu,1,target_buffers,self.buffer_sizeA,self.bytes_per_sample,savestart,NumberOfRecords,ChannelsMask,StartSample,self.nsamplesA,0x00) data_16bit_ch0 = np.frombuffer(target_buffers[0].contents,dtype=np.int16) data_16bit_ch1 = np.frombuffer(target_buffers[1].contents,dtype=np.int16) #timestamps=np.frombuffer(target_headers.contents,dtype=np.int64) data={'specmat_ChA':data_16bit_ch0,'specmat_ChB':data_16bit_ch1}#'timestamps':timestamps} path_mat='%s/SSdelay%s/specfile_%s.mat' % (foldername,str(j).zfill(2),str(i).zfill(3)) #path_npz='%s/SSdelay%i/specfile_%i.npz' % (foldername,j,i) try: sio.savemat(path_mat,data) #np.savez(path_npz,**data) except: self.f.write('failed saving singleshot trace\n') except: self.f.write('failed recording singleshot trace\n') i+=1 saveend+=self.nsaverecords self.ProgressBar.setValue(np.round(100*j/np.float(len(self.dscanrange)))) if self.acqmode==1: data={'Scan_ChA':avgscanA, \ 'Scan_ChB':avgscanB,\ 'Delay':self.dscanrange} path_mat='%s/ScanAvg.mat' % (foldername) try: sio.savemat(path_mat,data) #path_npz='%s/ScanAvg.npz' % (foldername,i) #np.savez(path_npz,**data) except: self.f.write('failed saving singleshot trace\n') success=ADQAPI.ADQ_DisarmTrigger(self.adq_cu,1) if (success == 0): self.f.write('Recording: ADQ_DisarmTrigger failed.\n') success=ADQAPI.ADQ_MultiRecordClose(self.adq_cu,1); if (success == 0): self.f.write('Recording: ADQ_MultiRecordClose failed.\n') self.f.write('Acquisition finished at %s:%s:%s' % (str(dt.today().hour).zfill(2), \ str(dt.today().minute).zfill(2), \ str(dt.today().second).zfill(2))) self.ProgressBar.hide() ## def StopRecording(self): # ADQAPI.ADQ_DisarmTrigger(self.adq_cu,1) ADQAPI.ADQ_MultiRecordClose(self.adq_cu,1); # def StartStream(self): print 'teststream' def StopStream(self): print 'teststream' # #f=open(thislogfilename,'w') #TAQD=TOFAcqDigitizer(f) #TAQD.StartRecording('D:/labdata/2016/20160410_Isopropanol') #f.close()
kdsuneraavinash/neomerce
routes/checkout.js
<reponame>kdsuneraavinash/neomerce const router = require('express').Router(); const Cart = require('../models/cart'); const Order = require('../models/order'); router.get('/', async (req, res) => { const dataObj = Order.getOrderDetails(req); /* After order confirmation user redirect back to check out and try to check out again */ if (dataObj.subtotal === 0) { res.redirect('/'); } const result = await Cart.checkStock(req.sessionID); if (result == null) { const proceedCheckOutObj = await Cart.proceedCheckOut(req.sessionID, req.session.user); res.render('checkout', { userData: req.userData, proceedCheckOutObj, error: req.query.error, }); } else { res.redirect(`/cart?error=${result}`); } }); module.exports = router;
XilongPei/openparts
Openparts-framework/src/main/java/com/openparts/utils/elasticsearch/ElasticsearchClient.java
package com.openparts.utils.elasticsearch; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.RestClient; import org.apache.http.HttpHost; /* * Java REST Client [6.1] » Java High Level REST Client » Supported APIs * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-supported-apis.html */ class ElasticsearchClient { private RestHighLevelClient client; ElasticsearchClient() { /* PropertiesUtil.getValue("elasticsearch.server.num"); client = new RestHighLevelClient( RestClient.builder( new HttpHost("localhost", 9200, "http"), new HttpHost("localhost", 9201, "http"))); */ } public void close() { try { client.close(); } catch (Exception ex) { return; } } }
yuvalbdgit/TEST
internal/api/action_request_manager_test.go
/* * Copyright (c) 2019 the Octant contributors. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package api_test import ( "context" "testing" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" configFake "github.com/vmware-tanzu/octant/internal/config/fake" "github.com/vmware-tanzu/octant/internal/api" ocontext "github.com/vmware-tanzu/octant/internal/context" "github.com/vmware-tanzu/octant/internal/octant" octantFake "github.com/vmware-tanzu/octant/internal/octant/fake" "github.com/vmware-tanzu/octant/pkg/action" ) func TestActionRequestManager_Handlers(t *testing.T) { controller := gomock.NewController(t) defer controller.Finish() dashConfig := configFake.NewMockDash(controller) manager := api.NewActionRequestManager(dashConfig) AssertHandlers(t, manager, []string{api.RequestPerformAction}) } func TestActionRequestManager_PerformAction(t *testing.T) { controller := gomock.NewController(t) defer controller.Finish() dashConfig := configFake.NewMockDash(controller) dashConfig.EXPECT().CurrentContext().Return("foo-context") state := octantFake.NewMockState(controller) state.EXPECT().GetFilters().Return([]octant.Filter{{Key: "foo", Value: "bar"}}) state.EXPECT().GetNamespace().Return("foo-namespace") state.EXPECT().GetClientID().Return("foo-client") manager := api.NewActionRequestManager(dashConfig) payload := action.CreatePayload(api.RequestPerformAction, map[string]interface{}{ "foo": "bar", }) state.EXPECT(). Dispatch(gomock.Any(), api.RequestPerformAction, payload). Do(func(ctx context.Context, _ string, _ action.Payload) { clientState := ocontext.ClientStateFrom(ctx) require.Equal(t, "foo-namespace", clientState.Namespace) require.Equal(t, "foo", clientState.Filters[0].Key) require.Equal(t, "bar", clientState.Filters[0].Value) require.Equal(t, "foo-client", clientState.ClientID) require.Equal(t, "foo-context", clientState.ContextName) }). Return(nil) require.NoError(t, manager.PerformAction(state, payload)) }
MastodonC/cassandra-mesos
cassandra-mesos-scheduler/src/main/java/io/mesosphere/mesos/frameworks/cassandra/scheduler/api/ClusterRepairController.java
package io.mesosphere.mesos.frameworks.cassandra.scheduler.api; import com.fasterxml.jackson.core.JsonFactory; import io.mesosphere.mesos.frameworks.cassandra.CassandraFrameworkProtos; import io.mesosphere.mesos.frameworks.cassandra.scheduler.CassandraCluster; import io.mesosphere.mesos.frameworks.cassandra.scheduler.util.ClusterJobUtils; import org.jetbrains.annotations.NotNull; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; @Path("/cluster/repair") @Produces("application/json") public final class ClusterRepairController { @NotNull private final CassandraCluster cluster; @NotNull private final JsonFactory factory; public ClusterRepairController(@NotNull final CassandraCluster cluster, @NotNull final JsonFactory factory) { this.cluster = cluster; this.factory = factory; } /** * Starts a cluster-wide repair. * * Example: <pre>{@code { * "started" : true * }}</pre> */ @POST @Path("/start") public Response repairStart() { return ClusterJobUtils.startJob(cluster, factory, CassandraFrameworkProtos.ClusterJobType.REPAIR); } /** * Aborts a cluster-wide repair after the current node has finished. * * Example: <pre>{@code { * "aborted" : true * }}</pre> */ @POST @Path("/abort") public Response repairAbort() { return ClusterJobUtils.abortJob(cluster, factory, CassandraFrameworkProtos.ClusterJobType.REPAIR); } /** * Returns the status of the current repair. * * Example: <pre>{@code { * "running" : true, * "repair" : { * "type" : "REPAIR", * "started" : 1426686829672, * "finished" : null, * "aborted" : false, * "remainingNodes" : [ ], * "currentNode" : { * "executorId" : "cassandra.node.0.executor", * "taskId" : "cassandra.node.0.executor.REPAIR", * "hostname" : "127.0.0.2", * "ip" : "127.0.0.2", * "processedKeyspaces" : { }, * "remainingKeyspaces" : [ ] * }, * "completedNodes" : [ { * "executorId" : "cassandra.node.1.executor", * "taskId" : "cassandra.node.1.executor.REPAIR", * "hostname" : "localhost", * "ip" : "127.0.0.1", * "processedKeyspaces" : { * "system_traces" : { * "status" : "FINISHED", * "durationMillis" : 2490 * } * }, * "remainingKeyspaces" : [ ] * } ] * } * }}</pre> */ @GET @Path("/status") public Response repairStatus() { return ClusterJobUtils.jobStatus(cluster, factory, CassandraFrameworkProtos.ClusterJobType.REPAIR, "repair"); } /** * Returns the status of the last repair. * See {@link #repairStatus()} for an response example except that `running` field is exchanged with a field * called `present`. */ @GET @Path("/last") public Response lastRepair() { return ClusterJobUtils.lastJob(cluster, factory, CassandraFrameworkProtos.ClusterJobType.REPAIR, "repair"); } }
intel/pse-fw
services/fw_version/fw_version.c
<filename>services/fw_version/fw_version.c<gh_stars>0 /* * Copyright (c) 2021 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <zephyr.h> #include <init.h> #include <fw_version.h> void __weak fwver_user_print(void) { } static int fwver_print(const struct device *arg) { ARG_UNUSED(arg); printk("\nFW VERSION: %s.%s.%s\n", FWVER_MAJOR, FWVER_MINOR, FWVER_PATCH); printk("FW HW IP: %s\n", FWVER_HW_IP); printk("FW BUILD: DATE %s, TIME %s, BY %s@%s\n", FWVER_BUILD_DATE, FWVER_BUILD_TIME, FWVER_WHOAMI, FWVER_HOST_NAME); fwver_user_print(); printk("\n"); return 0; } SYS_INIT(fwver_print, APPLICATION, 0);
gorkem0606/moderasyon-botlari
Moderator 13/commands/unmute.js
<gh_stars>10-100 const db = require('quick.db'); const Discord = require('discord.js'); module.exports = { name: 'unmute', run: async(client, message, args) => { let embed = new Discord.MessageEmbed().setAuthor(message.member.displayName, message.author.avatarURL({ dynamic: true })).setTimestamp().setThumbnail(message.author.avatarURL).setFooter(client.config.fooder); if (!client.config.mods.some(id => message.member.roles.cache.has(id))&& (!message.member.hasPermission("ADMINISTRATOR"))) { return message.channel.send(embed.setDescription('Komutu kullanan kullanıcıda yetki bulunmamakta!')).then(x => x.delete({ timeout: 5000 })) } let member = message.mentions.members.first() || message.guild.members.cache.get(args[0]); if (!member) return message.channel.send(embed.setDescription("Lütfen Bir Kullanıcı Etiketle")).then(x => x.delete({ timeout: 5000 })) if (member.roles.highest.position >= message.member.roles.highest.position) { return message.channel.send(embed.setDescription("Belirttiğin kullanıcı seninle aynı yetkide veya senden üstün!")).then(x => x.delete({ timeout: 5000 })) } await message.guild.members.cache.get(member.id).roles.remove(client.config.muteRoles) await message.guild.members.cache.get(member.id).roles.remove(client.config.voicemuteRoles) message.channel.send(embed.setDescription("Kullanıcının olan chat ve ses mutesi açıldı!")).then(x => x.delete({ timeout: 5000 })) } }
DuCalixte/fake_library_dash
library-api/db/migrate/20200615060658_create_books.rb
class CreateBooks < ActiveRecord::Migration[6.0] def change create_table :books, id: :uuid do |t| t.string :title t.string :isbn t.string :description t.integer :quantity t.timestamps end end end
plyfe/conductor.js
test/fixtures/load_css_card.js
Conductor.requireCSS("load_css.css"); Conductor.card({ activate: function() { var lastCSSSheet = document.styleSheets[document.styleSheets.length-1]; // Test that the CSS has finished loading if (lastCSSSheet.cssRules) { ok(lastCSSSheet.cssRules[0].style.backgroundColor === "red", "background was set by CSS"); } else { // ie8 ok(/background-color: red/i.test(lastCSSSheet.cssText), "background was set by CSS"); } start(); } });
huntc/akka
akka-parsing/src/main/scala/akka/parboiled2/ParseError.scala
/* * Copyright (C) 2009-2013 <NAME>, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package akka.parboiled2 import CharUtils.escape case class ParseError(position: Position, traces: Seq[RuleTrace]) extends RuntimeException { def formatExpectedAsString: String = { val expected = formatExpectedAsSeq expected.size match { case 0 ⇒ "??" case 1 ⇒ expected.head case _ ⇒ expected.init.mkString(", ") + " or " + expected.last } } def formatExpectedAsSeq: Seq[String] = traces.map { trace ⇒ if (trace.frames.nonEmpty) { val exp = trace.frames.last.format val nonEmptyExp = if (exp.isEmpty) "?" else exp if (trace.isNegated) "!" + nonEmptyExp else nonEmptyExp } else "???" }.distinct def formatTraces: String = traces.map(_.format).mkString(traces.size + " rule" + (if (traces.size != 1) "s" else "") + " mismatched at error location:\n ", "\n ", "\n") } case class Position(index: Int, line: Int, column: Int) // outermost (i.e. highest-level) rule first case class RuleTrace(frames: Seq[RuleFrame]) { def format: String = frames.size match { case 0 ⇒ "<empty>" case 1 ⇒ frames.head.format case _ ⇒ // we don't want to show intermediate Sequence and RuleCall frames in the trace def show(frame: RuleFrame) = !(frame.isInstanceOf[RuleFrame.Sequence] || frame.isInstanceOf[RuleFrame.RuleCall]) frames.init.filter(show).map(_.format).mkString("", " / ", " / " + frames.last.format) } def isNegated: Boolean = (frames.count(_.anon == RuleFrame.NotPredicate) & 0x01) > 0 } sealed abstract class RuleFrame { import RuleFrame._ def anon: RuleFrame.Anonymous def format: String = this match { case Named(name, _) ⇒ name case Sequence(_) ⇒ "~" case FirstOf(_) ⇒ "|" case CharMatch(c) ⇒ "'" + escape(c) + '\'' case StringMatch(s) ⇒ '"' + escape(s) + '"' case MapMatch(m) ⇒ m.toString() case IgnoreCaseChar(c) ⇒ "'" + escape(c) + '\'' case IgnoreCaseString(s) ⇒ '"' + escape(s) + '"' case CharPredicateMatch(_, name) ⇒ if (name.nonEmpty) name else "<anon predicate>" case RuleCall(callee) ⇒ '(' + callee + ')' case AnyOf(s) ⇒ '[' + escape(s) + ']' case NoneOf(s) ⇒ s"[^${escape(s)}]" case Times(_, _) ⇒ "times" case CharRange(from, to) ⇒ s"'${escape(from)}'-'${escape(to)}'" case AndPredicate ⇒ "&" case NotPredicate ⇒ "!" case SemanticPredicate ⇒ "test" case ANY ⇒ "ANY" case _ ⇒ { val s = toString s.updated(0, s.charAt(0).toLower) } } } object RuleFrame { def apply(frame: Anonymous, name: String): RuleFrame = if (name.isEmpty) frame else Named(name, frame) case class Named(name: String, anon: Anonymous) extends RuleFrame sealed abstract class Anonymous extends RuleFrame { def anon: Anonymous = this } case class Sequence(subs: Int) extends Anonymous case class FirstOf(subs: Int) extends Anonymous case class CharMatch(char: Char) extends Anonymous case class StringMatch(string: String) extends Anonymous case class MapMatch(map: Map[String, Any]) extends Anonymous case class IgnoreCaseChar(char: Char) extends Anonymous case class IgnoreCaseString(string: String) extends Anonymous case class CharPredicateMatch(predicate: CharPredicate, name: String) extends Anonymous case class AnyOf(string: String) extends Anonymous case class NoneOf(string: String) extends Anonymous case class Times(min: Int, max: Int) extends Anonymous case class RuleCall(callee: String) extends Anonymous case class CharRange(from: Char, to: Char) extends Anonymous case object ANY extends Anonymous case object Optional extends Anonymous case object ZeroOrMore extends Anonymous case object OneOrMore extends Anonymous case object AndPredicate extends Anonymous case object NotPredicate extends Anonymous case object SemanticPredicate extends Anonymous case object Capture extends Anonymous case object Run extends Anonymous case object Push extends Anonymous case object Drop extends Anonymous case object Action extends Anonymous case object RunSubParser extends Anonymous }
Ashwanigupta9125/code-DS-ALGO
225-Days Coding Problem/Day-014.cpp
<gh_stars>10-100 /* * This problem was asked by Google. The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method. Hint: The basic equation of a circle is x2 + y2 = r2. */ /* * Monte Carlo is Randomized Algorithms. * Idea is to get PI from Probability. * * consider a circle of radius 1 unit circumscribed inside the rectangle (of course the length and breadth of rectangle will be 2) * * now probability of point generated inside circle is P(__)=AREA_OF_CIRCLE / AREA_OF_RECTANGLE * ==> P(__) = PI*(r*r) / 4(r*r) * ==> P(__) = PI/4 * ==> 4*P(__) = PI */ #include <bits/stdc++.h> using namespace std; int main(void){ srand(time(NULL)); double C{},R{}; // C = Point generated inside the Circle & R is point generated inside Rectangle for(int i=0;i<100000;++i){ double x = double((rand()%(100000+1))/100000.0f); double y = double((rand()%(100000+1))/100000.0f); if(x*x+y*y<=1.0f){ C++; } R++; } cout<<"Expected Value of PI = "<<fixed<<setprecision(3)<<double(4.0f*C)/R<<endl; return 0; }
junktionfet/alloy
libEs6/components/Identity/getIdentity/getIdentityOptionsValidator.js
/* Copyright 2020 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { objectOf, literal, arrayOf } from "../../../utils/validation"; /** * Verifies user provided event options. * @param {*} options The user event options to validate * @returns {*} Validated options */ export default (options => { const getIdentityOptionsValidator = objectOf({ namespaces: arrayOf(literal("ECID")).nonEmpty() }).noUnknownFields(); getIdentityOptionsValidator(options); // Return default options for now // To-Do: Accept namespace from given options return { namespaces: ["ECID"] }; });
m3Lith/site
src/components/pages/doc/DocsWrapper.js
import React from 'react' import ReactDOM from 'react-dom' import styled from 'styled-components' import { navigateTo } from 'gatsby-link' import { Column } from 'serverless-design-system' import LinkCatcher from './LinkCatcher' import redHighlighter from 'src/assets/images/red-highlighter.png' const Wrapper = styled(Column)` input:focus { outline: none; } h1, h2, h3, h4, h5, h6 { font-weight: normal; } h3 a { color: black; } p, li { font-family: 'Soleil'; font-size: 16px; font-weight: normal; font-style: normal; color: #5b5b5b; line-height: 1.33; } li { line-height: 1.5; } .docs-center { display: flex; flex-direction: column; align-items: center; p { text-align: center; } } blockquote { margin: 0; margin-top: 10px; position: relative; & > p { margin-top: 5px; font-family: Soleil; font-size: 24px; font-weight: normal; font-style: italic; line-height: 1.33; color: #000000; } &:before { content: ' '; position: absolute; height: 39px; top: 0; width: 20px; background: url(${redHighlighter}); background-size: cover; left: -40px; } } a { color: #5b5b5b; text-decoration: none; &:hover { color: #5b5b5b; } } .hljs { padding-left: 32px; padding-top: 32px; padding-bottom: 32px; &:before { width: 0px; } } /* Docs Content */ .content { display: block; flex-grow: 1; position: relative; padding-top: 32px; max-width: 82.5%; padding-bottom: 62px; overflow: hidden; padding-left: 104px; $copyWidth: 45px; table { display: block; overflow-x: scroll; } code { max-width: 82.5%; overflow-x: auto; } .docsSectionSubHeader h4 { font-size: 24px; line-height: 38px; letter-spacing: -0.38px; } p { margin-top: 32px; margin-bottom: 32px; line-height: 26px; letter-spacing: 0px; a { border-bottom: 1px solid #fd5750; &:hover { border-bottom: none; } } } h3 { font-size: 18px; font-family: 'Soleil'; } h1, h2, h4, h5, h6 { font-family: 'Soleil'; line-height: 44px; letter-spacing: -0.5px; color: #000000; &[id] { margin-top: 40px; } } .examples { display: flex; flex-wrap: wrap; .example { border: solid 1px #eaeaea; box-shadow: 2px 2px 8px 0 rgba(0, 0, 0, 0.08); flex-grow: 1; flex-shrink: 0; flex-basis: 30%; padding: 32px; margin-bottom: 62px; &:nth-child(3n + 2) { margin-left: 32px; margin-right: 32px; } .language { color: #8c8c8c; font-size: 12px; line-height: 16px; letter-spacing: 0; font-family: 'Soleil'; } .title { font-size: 18px; line-height: 24px; letter-spacing: -0.28px; font-family: 'Soleil'; font-weight: normal; margin-top: 8px; } .description { max-width: 100%; margin-top: 22px; margin-bottom: 22px; } .github { color: #fd5750; &:before { background-color: white; } } } } .phenomic-HeadingAnchor { display: inline-block; position: absolute !important; text-align: left; margin-right: 0; width: 130px; margin-left: -59px; /* line-height: 1.4rem; */ text-decoration: none; opacity: 1; line-height: inherit; color: transparent; transition: opacity 0.3s; border-bottom: none !important; &:before { content: '#'; transform: none; position: absolute; top: 0px; left: 30px; background-color: transparent; height: auto; color: #8c8c8c; visibility: visible; } &:hover:before { color: black; } &:after { opacity: 0.4; visibility: hidden; position: absolute; content: 'copy link'; text-align: center; height: 20px; transform: none; width: 55px; font-size: 11px; padding: 3px 5px; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; -ms-flex-pack: center; justify-content: center; color: white; background-color: #191919; top: 85%; left: 8px; border-radius: 3px; transition: 0.25s ease-in-out 0s; } &:hover { opacity: 1; } &:active:after { content: 'copied!' !important; background-color: #787878; } &:hover:after { visibility: visible; } } a { position: relative; &:hover:before { visibility: visible; transform: scaleX(1); } &:before { position: absolute; bottom: -1px; visibility: hidden; width: 100%; height: 1px; content: ''; transition: all 0.15s ease-in-out 0s; transition-delay: 0s; transform: scaleX(0); background-color: rgba(0, 0, 0, 0.5); } } h1, h2, h3, h4, h5, h6 { max-width: 100%; position: relative; } p { max-width: 800px; position: relative; } p, pre, code, ul, li { position: relative; } ul { padding-left: 25px; padding-right: 80px; } h1, h2, h3, h4, h5, h6 { &:before { display: block; content: ' '; visibility: hidden; } } h1 { font-size: 32px; &:first-of-type { margin-top: 0px; .phenomic-HeadingAnchor { display: none; } } } h2 { font-size: 32px; } h4 { font-size: 18px; } } .algolia-autocomplete .ds-dropdown-menu:before { width: 0px; height: 0px; } .algolia-autocomplete { width: 100%; } .algolia-autocomplete.algolia-autocomplete-right .ds-dropdown-menu { left: 0 !important; } .docsSections { display: flex; flex-direction: column; align-items: stretch; max-width: 80%; position: relative; z-index: 3; a { border: none !important; } > div { margin-right: 20px; padding: 10px !important; margin-top: 20px; ul { width: 100%; padding-right: 0px; padding-left: 30px; } } } .providersSections { display: flex; flex-direction: row; justify-content: center; align-items: center; flex-flow: row wrap; max-width: 100%; position: relative; z-index: 3; a { border: none !important; &:hover { box-shadow: 2px 7px 18px 0 rgba(0, 0, 0, 0.08); border: solid 1px rgba(234, 234, 234, 0.3); } &:before { background-color: white; } } > div { margin-right: 20px; padding: 10px !important; margin-top: 20px; ul { width: 100%; padding-right: 0px; padding-left: 30px; } } } .docsSection { width: 100%; } .docsProviderItems { column-count: 4; > ul { margin-top: 0; } } .providerSection { width: 280px; height: 213px; display: flex; justify-content: center; align-items: center; flex-basis: 30%; } .docsSectionHeader, .docsSectionHeader a { display: flex; align-items: center; justify-content: center; } .docsSectionHeader a { text-decoration: none; border-bottom: 0px; margin: 10px 0px; &:before { visibility: hidden !important; } } .docsSectionHeader img { width: 90%; border-radius: 6px; } .docsSection ul { padding-left: 30px; } .docsSection ul li { padding-bottom: 3px; } .providerSectionHeader, .providerSectionHeader a { display: flex; align-items: center; justify-content: center; } .providerSectionHeader a { text-decoration: none; border-bottom: 0px; margin: 10px 0px; &:before { visibility: hidden !important; } } .providerSectionHeader { img { width: 90%; border-radius: 6px; } .google-logo, .cloudflare-logo, .kubeless-logo { width: 75%; } .fn-logo { width: 60%; } } .providerSectionHeader:nth-child(2) img { width: 30%; border-radius: 6px; } .providerSection ul { padding-left: 30px; } .providerSection ul li { padding-bottom: 3px; } & { margin-top: 62px; padding-bottom: 0; margin-bottom: 0; } .docContainer { margin-top: 0px; } .docWrapper { display: flex; margin-top: 0px; } .breadcrumbs a { font-size: 14px; line-height: 24px; letter-spacing: 0.44px; color: #8c8c8c !important; font-family: 'Soleil' !important; } .current { a { color: white !important; } } .breadCrumbContainer { margin: 0 auto; display: flex; max-width: 1216px; justify-content: space-between; padding: 9px 0px 11px 0px; font-size: 15px; background: #000; a { } a:hover { opacity: 1; } .rightContent { width: 735px; } } .versionNumber { font-size: 14px; line-height: 16px; letter-spacing: 0.58px; color: #9b9b9b; } .sidebar { min-width: 296px; max-width: 296px; z-index: 5; background: #f6f6f6; } .sidebarBlock { margin-left: -10px; padding: 10px; padding-right: 0px; min-width: 296px; max-width: 296px; border: none; box-shadow: none; } .sidebarLinks { margin-bottom: 5px; a:hover { border-bottom: 1px dashed black; } } .searchBumper { min-height: 74px; background: #f6f6f6; min-width: 250px; max-width: 250px; } .searchWrapper { background: #f6f6f6; min-width: 250px; max-width: 250px; z-index: 600; padding: 15px; padding-top: 19px; padding-bottom: 20px; } .searchBox { min-width: 220px; } .sidebarInner { min-width: 250px; max-width: 250px; padding: 0px; background: #f6f6f6; } a.editLinkWrapper { border: none; display: inline-block; font-size: 13px; padding: 5px; /* padding-top: 1px; */ position: absolute; right: 20px; top: 5px; &:before { display: none; } } .editLink { position: absolute; right: 20px; top: 130px; z-index: 10; display: flex; justify-content: center; align-items: center; font-size: 13px; color: #555; cursor: pointer; .SVGInline { display: flex; height: 100%; } .text { margin-left: 5px; padding-top: 1px; } img { width: 17px; height: 17px; } } .currentURL a { font-weight: 600; &:after { content: '-'; position: absolute; color: #a5a5a5; left: -10px; transform: none; transition: none; } } .pageContext { text-transform: capitalize; font-weight: 600; padding: 0; margin: 0px 20px; margin-bottom: 5px; border-bottom: 1px solid rgba(0, 0, 0, 0.05); padding-bottom: 0px; padding-top: 0; font-size: 15px; line-height: 1.63; } .subPages { padding: 10px; margin: 0 10px; margin-top: 0px; padding-top: 0; padding-left: 15px; padding-right: 0px; ul { list-style: none; margin: 0; padding: 0; } } .forumCta { padding: 0 20px; margin-top: 20px; h2 { margin-bottom: 5px; font-size: 18px; font-weight: 500; letter-spacing: -0.015rem; line-height: 1.63; } p { font-size: 14px; margin-top: 0px; line-height: 1.63; } .forumLink { color: #6060e0; font-size: 15px; } } strong { font-weight: 600; } .subPageLinkHeading { font-weight: 600; display: block; margin-bottom: 5px; } .subPageLink { font-size: 14px; line-height: 2.3; cursor: pointer; a { text-decoration: none; border: none; position: relative; width: 100%; display: block; &:hover { color: #000; } &:hover:after { content: '-'; position: absolute; color: #a5a5a5; left: -10px; transform: none; transition: none; } } } @media (max-width: 1315px) { .breadCrumbContainer { .rightContent { width: 626px; } } } //small laptop @media (min-width: 1025px) and (max-width: 1398px) { .breadCrumbContainer { max-width: 76%; } .providerSection { width: 200px; height: 180px; } } //normal laptop @media (min-width: 1399px) and (max-width: 1599px) { .providerSection { width: 240px; height: 190px; } .breadCrumbContainer { max-width: 76%; } } //tablet @media (max-width: 1025px) { .sidebar { display: none; } .content { padding-left: 40px; padding-right: 40px; padding-top: 62px; max-width: 100%; pre code:global(.hljs) { margin-left: -30px !important; padding-left: 30px !important; padding-right: 30px !important; } h1, h2, h3, h4, h5, h6, p { max-width: 100%; padding-right: 25px; margin-top: 22px; margin-bottom: 22px; } .docsSections { width: 100%; max-width: 100%; } .docsSection { width: 95%; } .docsSection { margin-bottom: 20px; } .docsSectionHeader, .docsSectionHeader a { display: flex; align-items: center; justify-content: center; } .providersSections { max-width: 100%; } .providerSection { width: 95%; } .providerSection { margin-bottom: 20px; } } blockquote { & > p { padding-left: 40px; } &:before { left: 0; top: 0; } } iframe { width: 100%; height: 360px; } & { margin-top: calc(47px); } .sidebar { z-index: 9; } .sidebarInner { min-width: 100%; padding-top: 10px; background: #fff; } .breadCrumbContainer { flex-direction: column; font-size: 14px; } .breadCrumbContainer li:first-of-type { display: none; } .searchBumper { min-height: inherit; margin-bottom: 3px; margin-top: 8px; } .searchWrapper { margin-top: 0px; border-top: none; padding: 0px; } .searchBox { width: 90%; box-shadow: none; } a.editLinkWrapper { bottom: 0px; left: 15px; padding: 0px; margin-bottom: 25px; top: inherit; right: inherit; display: none; } .editLink { display: none; } .versionNumber { display: none; } .page, .sidebar, .searchBumper, .searchWrapper { max-width: 100%; min-width: 100%; } .sidebar { margin-bottom: 35px; } .docWrapper { flex-direction: column; flex-flow: column-reverse; } .content { font-size: 14px; pre code:global(.hljs) { font-size: 11px; line-height: 1.4; padding-top: 10px; padding-bottom: 10px; padding-left: 32px; } .phenomic-HeadingAnchor { display: none; } ol, ul { font-size: 13px; padding: 0px 20px; } li { margin-bottom: 5px; } h1, h2, h3, h4, h5, h6, p { padding-right: 20px; } h1, h2, h3, h4, h5, h6 { &:before { display: block; content: ' '; visibility: hidden; } } ul { padding-right: 10px; } } .subPageLink, .subPageLinkHeading { font-size: 16px; } } //mobile @media screen and (max-width: 415px) { iframe { width: 100%; height: auto; } .content { padding-left: 30px; padding-right: 30px; h1, h2 { font-size: 24px; line-height: 38px; letter-spacing: -0.38px; max-width: 90%; } p { max-width: 90%; } .providerSections { justify-content: space-between; } .providerSection { width: 128px; height: 97px; } .docsProviderItems { column-count: 2; } } } ` const Clipboard = typeof window !== 'undefined' ? require('clipboard') : null const preventDefault = e => e.preventDefault() export default class DocsWrapper extends React.Component { componentDidMount() { //TODO: hacky - find a better solution for offsetting anchor scroll if (typeof window !== 'undefined' && window.location.hash) { setTimeout(function() { window.scrollBy(0, -80) }, 1) } const domNode = ReactDOM.findDOMNode(this.ref) //eslint-disable-line this.linkCatcher = new LinkCatcher(domNode, navigateTo) const { origin, pathname } = window.location // disable anchor tags until they are removed this.attachHandlers() setTimeout(() => { this.clipboardInstance = new Clipboard('.phenomic-HeadingAnchor', { // eslint-disable-line text(trigger) { // eslint-disable-line return `${origin}${pathname.replace(/\/$/, '')}#${ trigger.parentNode.id }` }, }) }, 10) } componentDidUpdate(previousProps, _prevState) { if (previousProps.__url !== this.props.__url) { this.dettachHandlers() setTimeout(() => { this.attachHandlers() }, 0) } } componentWillUnmount() { if (this.clipboardInstance) { this.clipboardInstance.destroy() } // disable anchor tags until they are removed this.dettachHandlers() } attachHandlers = () => { // attach link handlers this.linkCatcher.add() const html = document.documentElement if (html && html.className.indexOf('safari') > -1) { // clipboard doesnt work in safari return false } const elements = document.getElementsByClassName('phenomic-HeadingAnchor') for (let i = 0; i < elements.length; i++) { elements[i].addEventListener('click', preventDefault, false) } } dettachHandlers = () => { // detach link handler this.linkCatcher.remove() const html = document.documentElement if (html && html.className.indexOf('safari') > -1) { return false } const elements = document.getElementsByClassName('phenomic-HeadingAnchor') for (let i = 0; i < elements.length; i++) { elements[i].removeEventListener('click', preventDefault, false) } } render() { return ( <Wrapper ref={ref => { this.ref = ref }} {...this.props} /> ) } }
stefanzilske/camunda-bpm-data
example/spin-type-detector/src/main/java/io/holunda/camunda/bpm/data/spin/SpinTypeDetectorConfigurator.java
package io.holunda.camunda.bpm.data.spin; import org.camunda.spin.impl.json.jackson.format.JacksonJsonDataFormat; import org.camunda.spin.spi.DataFormatConfigurator; /** * Spin configurator referenced in META-INF/services/org.camunda.spin.spi.DataFormatConfigurator. * Configures the {@link ErasedCollectionTypeDetector}. */ public class SpinTypeDetectorConfigurator implements DataFormatConfigurator<JacksonJsonDataFormat> { @Override public Class<JacksonJsonDataFormat> getDataFormatClass() { return JacksonJsonDataFormat.class; } @Override public void configure(JacksonJsonDataFormat dataFormat) { dataFormat.addTypeDetector(ErasedCollectionTypeDetector.INSTANCE); } }
xomachine/gabedit
src/Utils/Utils.h
/********************************************************************************************************** Copyright (c) 2002-2013 <NAME>. All rights reserved Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Gabedit), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************************************************/ #ifndef __GABEDIT_UTILS_H__ #define __GABEDIT_UTILS_H__ #define NHOSTMAX 5 #define LOGFILE 0 #define OUTFILE 1 #define MOLDENFILE 2 #define ALLFILES 3 typedef struct _Point { gdouble C[3]; }Point; typedef struct _DataTree { gchar *projectname; gchar *datafile; gchar *localdir; gchar *remotehost; gchar *remoteuser; gchar *remotepass; gchar *remotedir; GabEditNetWork netWorkProtocol; gint itype; gchar* command; GtkTreeIter* noeud; }DataTree; void timing(double* cpu,double *sys); #ifdef G_OS_WIN32 gboolean winsockCheck(FILE* ); void addUnitDisk(FILE* file, G_CONST_RETURN gchar* name); #endif /* G_OS_WIN32 */ void free_gaussian_commands(); void free_molpro_commands(); void free_mpqc_commands(); gchar* get_time_str(); gboolean this_is_a_backspace(gchar *st); void changeDInE(gchar *st); FILE* FOpen(const gchar *fileutf8, const gchar* type); void set_file_open(gchar* remotehost,gchar* remoteuser,gchar* remotedir, GabEditNetWork netWorkProtocol); gboolean this_is_an_object(GtkObject *obj); G_CONST_RETURN gchar *get_local_user(); void Waiting(gdouble tsecond); void Debug(char *fmt,...); void add_host(const gchar *hostname, const gchar* username, const gchar* password, const gchar* dir); gchar* get_line_chars(gchar c,gint n); gchar* cat_file(gchar* namefile,gboolean tabulation); gchar *run_command(gchar *command); void run_local_command(gchar *outfile,gchar *errfile,gchar* command,gboolean under); const gchar *gabedit_directory(void); void DeleteLastChar(gchar *); gchar *get_filename_without_ext(const gchar* allname); gchar *get_suffix_name_file(const gchar*); gchar *get_dir_file_name(G_CONST_RETURN gchar* dirname, G_CONST_RETURN gchar* filename); gchar *get_name_dir(const gchar* ); gchar *get_name_file(const gchar* ); Point get_produit_vectoriel(Point V1,Point V2); gchar *get_distance_points(Point P1,Point P2,gboolean f3); gdouble get_module(Point V); gdouble get_scalaire(Point V1,Point V2); gchar *get_angle_vectors(Point V1,Point V2); void create_hosts_file(); void create_ressource_file(); void read_ressource_file(); gchar *ang_to_bohr(gchar *); gchar *bohr_to_ang(gchar *); guint get_number_electrons(guint); gdouble get_value_variableZmat(gchar *); gdouble get_value_variableXYZ(gchar *); guint get_num_variableXYZ(gchar *); guint get_num_variableZmat(gchar *); gboolean geometry_with_medium_layer(); gboolean geometry_with_lower_layer(); void uppercase(gchar *); void lowercase(gchar *); void initialise_batch_commands(); void initialise_name_file(); void reset_name_files(); void initialise_global_variables(); void run_molden (gchar *); gboolean variable_name_valid(gchar *); gboolean testa(char ); gboolean test(const gchar *); gboolean testapointeE(char ); gboolean testpointeE(const gchar *); void create_commands_file(); void create_network_file(); void create_fonts_file(); void set_tab_size (GtkWidget *view, gint tab_size); void set_font (GtkWidget *view, gchar *fontname); void set_font_style (GtkStyle* style,gchar *fontname); GtkStyle *set_text_style(GtkWidget *text,gushort red,gushort green,gushort blue); GtkStyle *set_base_style(GtkWidget *text,gushort red,gushort green,gushort blue); GtkStyle *set_fg_style(GtkWidget *wid,gushort red,gushort green,gushort blue); GtkStyle *set_bg_style(GtkWidget *wid,gushort red,gushort green,gushort blue); gint numb_of_string_by_row(gchar *str); gint numb_of_reals_by_row(gchar *str); gchar** gab_split(gchar *str); void get_dipole_from_gamess_output_file(FILE* fd); void get_dipole_from_turbomole_output_file(FILE* fd); void get_dipole_from_gaussian_output_file(FILE* fd); void get_dipole_from_molpro_output_file(FILE* fd); void get_dipole_from_dalton_output_file(FILE* fd); void get_dipole_from_orca_output_file(FILE* fd); void get_dipole_from_nwchem_output_file(FILE* fd); void get_dipole_from_psicode_output_file(FILE* fd); void get_dipole_from_qchem_output_file(FILE* fd); void get_dipole_from_mopac_output_file(FILE* fd); void get_dipole_from_mopac_aux_file(FILE* fd); void set_dipole(GtkWidget* fp,gpointer data); void init_dipole(); void read_commands_file(); void read_network_file(); void set_path(); void read_hosts_file(); void read_fonts_file(); void delete_last_spaces(gchar* str); void delete_first_spaces(gchar* str); void delete_all_spaces(gchar* str); void str_delete_n(gchar* str); gchar* get_to_str(gchar* str,gchar* end); gboolean isInteger(gchar *t); gboolean isFloat(const gchar *t); void get_symb_type_charge(gchar* str,gchar symb[], gchar type[], gchar charge[]); gchar* get_font_label_name(); gint get_type_of_program(FILE* file); void gabedit_string_get_pixel_size(GtkWidget* parent, PangoFontDescription *font_desc, G_CONST_RETURN gchar* t, int *width, int* height); void gabedit_draw_string(GtkWidget* parent, GdkPixmap* pixmap, PangoFontDescription *font_desc, GdkGC* gc , gint x, gint y, G_CONST_RETURN gchar* t, gboolean centerX, gboolean centerY); void gabedit_save_image(GtkWidget* widget, gchar *fileName, gchar* type); G_CONST_RETURN gchar* get_open_babel_command(); gchar** get_one_block_from_aux_mopac_file(FILE* file, gchar* blockName, gint* n); gint get_num_orbitals_from_aux_mopac_file(FILE* file, gchar* blockName, gint* begin, gint* end); gchar** free_one_string_table(gchar** table, gint n); gboolean zmat_mopac_irc_output_file(gchar *FileName); gboolean zmat_mopac_scan_output_file(gchar *FileName); GabEditTypeFile get_type_output_file(gchar* fileName); GabEditTypeFile get_type_input_file(gchar* fileName); GabEditTypeFile get_type_file(gchar* filename); gchar * mystrcasestr(G_CONST_RETURN gchar *haystack, G_CONST_RETURN gchar *needle); gint get_one_int_from_fchk_gaussian_file(FILE* file, gchar* blockName); gdouble get_one_real_from_fchk_gaussian_file(FILE* file, gchar* blockName); gint* get_array_int_from_fchk_gaussian_file(FILE* file, gchar* blockName, gint* nElements); gdouble* get_array_real_from_fchk_gaussian_file(FILE* file, gchar* blockName, gint* nElements); gchar** get_array_string_from_fchk_gaussian_file(FILE* file, gchar* blockName, gint* nElements); void getvScaleBond(gdouble r, gdouble Center1[], gdouble Center2[], gdouble vScal[]); void getPositionsRadiusBond3(gdouble r, gdouble Orig[], gdouble Center1[], gdouble Center2[], gdouble C11[], gdouble C12[], gdouble C21[], gdouble C22[], gdouble C31[], gdouble C32[], gdouble radius[], gint type); void getPositionsRadiusBond2(gdouble r, gdouble Orig[], gdouble Center1[], gdouble Center2[], gdouble C11[], gdouble C12[], gdouble C21[], gdouble C22[], gdouble radius[], gint type); gdouble get_multipole_rank(); void getCoefsGradient(gint nBoundary, gdouble xh, gdouble yh, gdouble zh, gdouble* fcx, gdouble* fcy, gdouble* fcz); void getCoefsLaplacian(gint nBoundary, gdouble xh, gdouble yh, gdouble zh, gdouble* fcx, gdouble* fcy, gdouble* fcz, gdouble* cc); void swapDouble(gdouble* a, gdouble* b); #endif /* __GABEDIT_UTILS_H__ */
dmj/jing-trang
mod/schematron/src/main/com/thaiopensource/validate/schematron/NewSaxonSchemaReaderFactory.java
package com.thaiopensource.validate.schematron; import net.sf.saxon.lib.FeatureKeys; import net.sf.saxon.TransformerFactoryImpl; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXTransformerFactory; public class NewSaxonSchemaReaderFactory extends SchematronSchemaReaderFactory { public SAXTransformerFactory newTransformerFactory() { return new TransformerFactoryImpl(); } public void initTransformerFactory(TransformerFactory factory) { try { factory.setAttribute(FeatureKeys.XSLT_VERSION, "2.0"); } catch (IllegalArgumentException e) { // The old Saxon 9 (pre HE/PE/EE) throws this exception. } factory.setAttribute(FeatureKeys.LINE_NUMBERING, Boolean.TRUE); factory.setAttribute(FeatureKeys.VERSION_WARNING, Boolean.FALSE); } }
a13m/wsdl2c
src/org/codehaus/jam/visitor/JVisitor.java
/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.jam.visitor; import org.codehaus.jam.JAnnotation; import org.codehaus.jam.JClass; import org.codehaus.jam.JComment; import org.codehaus.jam.JConstructor; import org.codehaus.jam.JField; import org.codehaus.jam.JMethod; import org.codehaus.jam.JPackage; import org.codehaus.jam.JParameter; import org.codehaus.jam.JProperty; import org.codehaus.jam.JTag; //REVIEW I think this should be an interface /** * <p>To be implemented by classes which wish to traverse a JElement tree.</p> * * @author <NAME> &lt;email: pcal-at-bea-dot-com&gt; */ public abstract class JVisitor { public void visit(JPackage pkg) {} public void visit(JClass clazz) {} public void visit(JConstructor ctor) {} public void visit(JField field) {} public void visit(JMethod method) {} public void visit(JParameter param) {} public void visit(JAnnotation ann) {} public void visit(JComment comment) {} public void visit(JProperty property) {} public void visit(JTag tag) {} }
zwxbest/Demo
demo/src/main/java/com/tuowazi/demo/nio/src/main/java/buffer/NioWrap.java
package com.tuowazi.demo.nio.src.main.java.buffer; import java.nio.CharBuffer; /** * Created by zwxbest on 2018/7/17. */ public class NioWrap { public static void main(String[] args) { CharBuffer charBuffer=CharBuffer.wrap(new char[]{'l','e','t','g','o'}); System.out.println(charBuffer.position()); System.out.println(charBuffer.limit()); System.out.println(charBuffer.capacity()); CharBuffer charBuffer2=CharBuffer.wrap(new char[]{'l','e','t','g','o'},1,2); //pos=offset //limit=offset+length //capacity=char[].length System.out.println(charBuffer2.position()); System.out.println(charBuffer2.limit()); System.out.println(charBuffer2.capacity()); } }
iStig/iMeasure
Schneider.iPad/Schneider/iMeasure/MonitorValueCell.h
<filename>Schneider.iPad/Schneider/iMeasure/MonitorValueCell.h // // MonitorValueCell.h // Schneider // // Created by GongXuehan on 13-5-29. // Copyright (c) 2013年 xhgong. All rights reserved. // #import <UIKit/UIKit.h> @interface MonitorValueCell : UITableViewCell @end
realityforge/galdr
processor/src/test/fixtures/subsystem/input/com/example/world_ref/WorldRefInterface.java
package com.example.world_ref; import galdr.World; import galdr.annotations.WorldRef; public interface WorldRefInterface { @WorldRef World world(); }
geoffroyw/packing-list
app/models/item.rb
<filename>app/models/item.rb class Item < ApplicationRecord has_many :documents, foreign_key: 'item_id', class_name: "ItemDocument" has_many :package_items has_many :packages, through: :package_items validates_presence_of :name validates_numericality_of :quantity, :only_integer => true, :greater_than_or_equal_to => 1, :allow_blank => false, :allow_nil => false validate :bought_on_is_not_in_future scope :unpacked, -> {left_outer_joins(:packages).where(packages: {id: nil})} private def bought_on_is_not_in_future if bought_on.present? && bought_on > Date.today errors.add(:bought_on, "can't be in the future") end end end
ronsaldo/loden
core/GUI/FontManager.cpp
#include "Loden/GUI/FontManager.hpp" #include "Loden/JSON.hpp" #include "Loden/FileSystem.hpp" #include "FreeTypeFont.hpp" #include "LodenFont.hpp" namespace Loden { namespace GUI { FontManager::FontManager(Engine *engine) : engine(engine) { } FontManager::~FontManager() { } bool FontManager::initialize() { FontLoaderPtr fontLoader = std::make_shared<FreeTypeFontLoader>(engine); if (fontLoader->initialize()) fontLoaders.push_back(fontLoader); fontLoader = std::make_shared<LodenFontLoader>(engine); if (fontLoader->initialize()) fontLoaders.push_back(fontLoader); loadFontsFromFile("core-assets/fonts/fonts.json"); return true; } bool FontManager::loadFontsFromFile(const std::string &fontsDescriptionFileName) { rapidjson::Document document; if (!parseJsonFromFile(fontsDescriptionFileName, &document)) return false; // Load the referenced fonts first. auto basePath = dirname(fontsDescriptionFileName); if (document.HasMember("include")) { auto &inclusionValue = document["include"]; if (!inclusionValue.IsObject()) return false; for (auto it = inclusionValue.MemberBegin(); it != inclusionValue.MemberEnd(); ++it) { //auto name = it->name.GetString(); auto &fileNameValue = it->value; if (!fileNameValue.IsString()) return false; auto fileName = fileNameValue.GetString(); if (!loadFontsFromFile(joinPath(basePath, fileName))) return false; } } // Load the fonts. if (document.HasMember("fonts")) { auto &fontsDesc = document["fonts"]; if (!fontsDesc.IsObject()) return false; for (auto it = fontsDesc.MemberBegin(); it != fontsDesc.MemberEnd(); ++it) { auto fontName = it->name.GetString(); auto &fontDesc = it->value; if (!fontDesc.IsObject() || !fontDesc.HasMember("faces")) return false; // Create the font auto font = std::make_shared<Font> (); addFont(fontName, font); // Load the faces auto &facesDesc = fontDesc["faces"]; for (auto faceIt = facesDesc.MemberBegin(); faceIt != facesDesc.MemberEnd(); ++faceIt) { auto faceName = faceIt->name.GetString(); auto &faceDesc = faceIt->value; if (!faceDesc.IsObject() || !faceDesc.HasMember("file")) return false; auto &faceFileName = faceDesc["file"]; if (!faceFileName.IsString()) return false; auto face = loadFaceFromFile(joinPath(basePath, faceFileName.GetString())); if (face) font->addFace(faceName, face); } // Cache the special faces. font->loadSpecialFaces(); } } // Load the defaults. if (document.HasMember("default-font") && document["default-font"].IsString()) defaultFont = getFont(document["default-font"].GetString()); if (document.HasMember("default-mono-font") && document["default-mono-font"].IsString()) defaultMononospacedFont = getFont(document["default-mono-font"].GetString()); if (document.HasMember("default-sans-font") && document["default-sans-font"].IsString()) defaultSansFont = getFont(document["default-sans-font"].GetString()); if (document.HasMember("default-serif-font") && document["default-serif-font"].IsString()) defaultSerifFont = getFont(document["default-serif-font"].GetString()); return true; } FontFacePtr FontManager::loadFaceFromFile(const std::string &fileName) { for (auto &loader : fontLoaders) { if (loader->canLoadFaceFromFile(fileName)) return loader->loadFaceFromFile(fileName); } return nullptr; } void FontManager::shutdown() { for (auto &font : fonts) font.second->release(); fonts.clear(); for(auto &loader : fontLoaders) loader->shutdown(); fontLoaders.clear(); } void FontManager::addFont(const std::string &name, const FontPtr &font) { fonts.insert(std::make_pair(name, font)); } FontPtr FontManager::getFont(const std::string &name) { auto it = fonts.find(name); if (it != fonts.end()) return it->second; return nullptr; } FontPtr FontManager::getDefaultFont() const { return defaultFont; } FontPtr FontManager::getDefaultSansFont() const { return defaultSansFont; } FontPtr FontManager::getDefaultSerifFont() const { return defaultSerifFont; } FontPtr FontManager::getDefaultMonospaceFont() const { return defaultMononospacedFont; } } // End of namespace Loden } // End of namespace GUI
goodmind/FlowDefinitelyTyped
flow-types/types/gapi.client.datastore_vx.x.x/flow_v0.25.x-/gapi.client.datastore.js
declare module "gapi.client.datastore" { declare var npm$namespace$gapi: { client: typeof npm$namespace$gapi$client }; declare var npm$namespace$gapi$client: { load: typeof gapi$client$load, projects: typeof gapi$client$projects }; /** * Load Google Cloud Datastore API v1 */ declare function gapi$client$load( name: "datastore", version: "v1" ): PromiseLike<void>; declare function gapi$client$load( name: "datastore", version: "v1", callback: () => any ): void; declare var gapi$client$projects: datastore$ProjectsResource; declare interface gapi$client$datastore$AllocateIdsRequest { /** * A list of keys with incomplete key paths for which to allocate IDs. * No key may be reserved/read-only. */ keys?: datastore$Key[]; } declare interface gapi$client$datastore$AllocateIdsResponse { /** * The keys specified in the request (in the same order), each with * its key path completed with a newly allocated ID. */ keys?: datastore$Key[]; } declare interface gapi$client$datastore$ArrayValue { /** * Values in the array. * The order of this array may not be preserved if it contains a mix of * indexed and unindexed values. */ values?: datastore$Value[]; } declare interface gapi$client$datastore$BeginTransactionRequest { /** * Options for a new transaction. */ transactionOptions?: datastore$TransactionOptions; } declare interface gapi$client$datastore$BeginTransactionResponse { /** * The transaction identifier (always present). */ transaction?: string; } declare interface gapi$client$datastore$CommitRequest { /** * The type of commit to perform. Defaults to `TRANSACTIONAL`. */ mode?: string; /** * The mutations to perform. * * When mode is `TRANSACTIONAL`, mutations affecting a single entity are * applied in order. The following sequences of mutations affecting a single * entity are not permitted in a single `Commit` request: * * - `insert` followed by `insert` * - `update` followed by `insert` * - `upsert` followed by `insert` * - `delete` followed by `update` * * When mode is `NON_TRANSACTIONAL`, no two mutations may affect a single * entity. */ mutations?: datastore$Mutation[]; /** * The identifier of the transaction associated with the commit. A * transaction identifier is returned by a call to * Datastore.BeginTransaction. */ transaction?: string; } declare interface gapi$client$datastore$CommitResponse { /** * The number of index entries updated during the commit, or zero if none were * updated. */ indexUpdates?: number; /** * The result of performing the mutations. * The i-th mutation result corresponds to the i-th mutation in the request. */ mutationResults?: datastore$MutationResult[]; } declare interface gapi$client$datastore$CompositeFilter { /** * The list of filters to combine. * Must contain at least one filter. */ filters?: datastore$Filter[]; /** * The operator for combining multiple filters. */ op?: string; } declare interface gapi$client$datastore$Entity { /** * The entity's key. * * An entity must have a key, unless otherwise documented (for example, * an entity in `Value.entity_value` may have no key). * An entity's kind is its key path's last element's kind, * or null if it has no key. */ key?: datastore$Key; /** * The entity's properties. * The map's keys are property names. * A property name matching regex `__.&#42;__` is reserved. * A reserved property name is forbidden in certain documented contexts. * The name must not contain more than 500 characters. * The name cannot be `""`. */ properties?: Record<string, datastore$Value>; } declare interface gapi$client$datastore$EntityResult { /** * A cursor that points to the position after the result entity. * Set only when the `EntityResult` is part of a `QueryResultBatch` message. */ cursor?: string; /** * The resulting entity. */ entity?: gapi$client$datastore$Entity; /** * The version of the entity, a strictly positive number that monotonically * increases with changes to the entity. * * This field is set for `FULL` entity * results. * * For missing entities in `LookupResponse`, this * is the version of the snapshot that was used to look up the entity, and it * is always set except for eventually consistent reads. */ version?: string; } declare interface gapi$client$datastore$Filter { /** * A composite filter. */ compositeFilter?: gapi$client$datastore$CompositeFilter; /** * A filter on a property. */ propertyFilter?: datastore$PropertyFilter; } declare interface gapi$client$datastore$GoogleDatastoreAdminV1beta1CommonMetadata { /** * The time the operation ended, either successfully or otherwise. */ endTime?: string; /** * The client-assigned labels which were provided when the operation was * created. May also include additional labels. */ labels?: Record<string, string>; /** * The type of the operation. Can be used as a filter in * ListOperationsRequest. */ operationType?: string; /** * The time that work began on the operation. */ startTime?: string; /** * The current state of the Operation. */ state?: string; } declare interface gapi$client$datastore$GoogleDatastoreAdminV1beta1EntityFilter { /** * If empty, then this represents all kinds. */ kinds?: string[]; /** * An empty list represents all namespaces. This is the preferred * usage for projects that don't use namespaces. * * An empty string element represents the default namespace. This should be * used if the project has data in non-default namespaces, but doesn't want to * include them. * Each namespace in this list must be unique. */ namespaceIds?: string[]; } declare interface gapi$client$datastore$GoogleDatastoreAdminV1beta1ExportEntitiesMetadata { /** * Metadata common to all Datastore Admin operations. */ common?: gapi$client$datastore$GoogleDatastoreAdminV1beta1CommonMetadata; /** * Description of which entities are being exported. */ entityFilter?: gapi$client$datastore$GoogleDatastoreAdminV1beta1EntityFilter; /** * Location for the export metadata and data files. This will be the same * value as the * google.datastore.admin.v1beta1.ExportEntitiesRequest.output_url_prefix * field. The final output location is provided in * google.datastore.admin.v1beta1.ExportEntitiesResponse.output_url. */ outputUrlPrefix?: string; /** * An estimate of the number of bytes processed. */ progressBytes?: datastore$GoogleDatastoreAdminV1beta1Progress; /** * An estimate of the number of entities processed. */ progressEntities?: datastore$GoogleDatastoreAdminV1beta1Progress; } declare interface gapi$client$datastore$GoogleDatastoreAdminV1beta1ExportEntitiesResponse { /** * Location of the output metadata file. This can be used to begin an import * into Cloud Datastore (this project or another project). See * google.datastore.admin.v1beta1.ImportEntitiesRequest.input_url. * Only present if the operation completed successfully. */ outputUrl?: string; } declare interface gapi$client$datastore$GoogleDatastoreAdminV1beta1ImportEntitiesMetadata { /** * Metadata common to all Datastore Admin operations. */ common?: gapi$client$datastore$GoogleDatastoreAdminV1beta1CommonMetadata; /** * Description of which entities are being imported. */ entityFilter?: gapi$client$datastore$GoogleDatastoreAdminV1beta1EntityFilter; /** * The location of the import metadata file. This will be the same value as * the google.datastore.admin.v1beta1.ExportEntitiesResponse.output_url * field. */ inputUrl?: string; /** * An estimate of the number of bytes processed. */ progressBytes?: datastore$GoogleDatastoreAdminV1beta1Progress; /** * An estimate of the number of entities processed. */ progressEntities?: datastore$GoogleDatastoreAdminV1beta1Progress; } declare interface gapi$client$datastore$GoogleDatastoreAdminV1beta1Progress { /** * The amount of work that has been completed. Note that this may be greater * than work_estimated. */ workCompleted?: string; /** * An estimate of how much work needs to be performed. May be zero if the * work estimate is unavailable. */ workEstimated?: string; } declare interface gapi$client$datastore$GoogleLongrunningListOperationsResponse { /** * The standard List next-page token. */ nextPageToken?: string; /** * A list of operations that matches the specified filter in the request. */ operations?: datastore$GoogleLongrunningOperation[]; } declare interface gapi$client$datastore$GoogleLongrunningOperation { /** * If the value is `false`, it means the operation is still in progress. * If `true`, the operation is completed, and either `error` or `response` is * available. */ done?: boolean; /** * The error result of the operation in case of failure or cancellation. */ error?: datastore$Status; /** * Service-specific metadata associated with the operation. It typically * contains progress information and common metadata such as create time. * Some services might not provide such metadata. Any method that returns a * long-running operation should document the metadata type, if any. */ metadata?: Record<string, any>; /** * The server-assigned name, which is only unique within the same service that * originally returns it. If you use the default HTTP mapping, the * `name` should have the format of `operations/some/unique/name`. */ name?: string; /** * The normal response of the operation in case of success. If the original * method returns no data on success, such as `Delete`, the response is * `google.protobuf.Empty`. If the original method is standard * `Get`/`Create`/`Update`, the response should be the resource. For other * methods, the response should have the type `XxxResponse`, where `Xxx` * is the original method name. For example, if the original method name * is `TakeSnapshot()`, the inferred response type is * `TakeSnapshotResponse`. */ response?: Record<string, any>; } declare interface gapi$client$datastore$GqlQuery { /** * When false, the query string must not contain any literals and instead must * bind all values. For example, * `SELECT &#42; FROM Kind WHERE a = 'string literal'` is not allowed, while * `SELECT &#42; FROM Kind WHERE a = @value` is. */ allowLiterals?: boolean; /** * For each non-reserved named binding site in the query string, there must be * a named parameter with that name, but not necessarily the inverse. * * Key must match regex `A-Za-z_$&#42;`, must not match regex * `__.&#42;__`, and must not be `""`. */ namedBindings?: Record<string, datastore$GqlQueryParameter>; /** * Numbered binding site @1 references the first numbered parameter, * effectively using 1-based indexing, rather than the usual 0. * * For each binding site numbered i in `query_string`, there must be an i-th * numbered parameter. The inverse must also be true. */ positionalBindings?: datastore$GqlQueryParameter[]; /** * A string of the format described * [here](https://cloud.google.com/datastore/docs/apis/gql/gql_reference). */ queryString?: string; } declare interface gapi$client$datastore$GqlQueryParameter { /** * A query cursor. Query cursors are returned in query * result batches. */ cursor?: string; /** * A value parameter. */ value?: datastore$Value; } declare interface gapi$client$datastore$Key { /** * Entities are partitioned into subsets, currently identified by a project * ID and namespace ID. * Queries are scoped to a single partition. */ partitionId?: datastore$PartitionId; /** * The entity path. * An entity path consists of one or more elements composed of a kind and a * string or numerical identifier, which identify entities. The first * element identifies a _root entity_, the second element identifies * a _child_ of the root entity, the third element identifies a child of the * second entity, and so forth. The entities identified by all prefixes of * the path are called the element's _ancestors_. * * An entity path is always fully complete: &#42;all&#42; of the entity's ancestors * are required to be in the path along with the entity identifier itself. * The only exception is that in some documented cases, the identifier in the * last path element (for the entity) itself may be omitted. For example, * the last path element of the key of `Mutation.insert` may have no * identifier. * * A path can never be empty, and a path can have at most 100 elements. */ path?: datastore$PathElement[]; } declare interface gapi$client$datastore$KindExpression { /** * The name of the kind. */ name?: string; } declare interface gapi$client$datastore$LatLng { /** * The latitude in degrees. It must be in the range [-90.0, +90.0]. */ latitude?: number; /** * The longitude in degrees. It must be in the range [-180.0, +180.0]. */ longitude?: number; } declare interface gapi$client$datastore$LookupRequest { /** * Keys of entities to look up. */ keys?: gapi$client$datastore$Key[]; /** * The options for this lookup request. */ readOptions?: datastore$ReadOptions; } declare interface gapi$client$datastore$LookupResponse { /** * A list of keys that were not looked up due to resource constraints. The * order of results in this field is undefined and has no relation to the * order of the keys in the input. */ deferred?: gapi$client$datastore$Key[]; /** * Entities found as `ResultType.FULL` entities. The order of results in this * field is undefined and has no relation to the order of the keys in the * input. */ found?: gapi$client$datastore$EntityResult[]; /** * Entities not found as `ResultType.KEY_ONLY` entities. The order of results * in this field is undefined and has no relation to the order of the keys * in the input. */ missing?: gapi$client$datastore$EntityResult[]; } declare interface gapi$client$datastore$Mutation { /** * The version of the entity that this mutation is being applied to. If this * does not match the current version on the server, the mutation conflicts. */ baseVersion?: string; /** * The key of the entity to delete. The entity may or may not already exist. * Must have a complete key path and must not be reserved/read-only. */ delete?: gapi$client$datastore$Key; /** * The entity to insert. The entity must not already exist. * The entity key's final path element may be incomplete. */ insert?: gapi$client$datastore$Entity; /** * The entity to update. The entity must already exist. * Must have a complete key path. */ update?: gapi$client$datastore$Entity; /** * The entity to upsert. The entity may or may not already exist. * The entity key's final path element may be incomplete. */ upsert?: gapi$client$datastore$Entity; } declare interface gapi$client$datastore$MutationResult { /** * Whether a conflict was detected for this mutation. Always false when a * conflict detection strategy field is not set in the mutation. */ conflictDetected?: boolean; /** * The automatically allocated key. * Set only when the mutation allocated a key. */ key?: gapi$client$datastore$Key; /** * The version of the entity on the server after processing the mutation. If * the mutation doesn't change anything on the server, then the version will * be the version of the current entity or, if no entity is present, a version * that is strictly greater than the version of any previous entity and less * than the version of any possible future entity. */ version?: string; } declare interface gapi$client$datastore$PartitionId { /** * If not empty, the ID of the namespace to which the entities belong. */ namespaceId?: string; /** * The ID of the project to which the entities belong. */ projectId?: string; } declare interface gapi$client$datastore$PathElement { /** * The auto-allocated ID of the entity. * Never equal to zero. Values less than zero are discouraged and may not * be supported in the future. */ id?: string; /** * The kind of the entity. * A kind matching regex `__.&#42;__` is reserved/read-only. * A kind must not contain more than 1500 bytes when UTF-8 encoded. * Cannot be `""`. */ kind?: string; /** * The name of the entity. * A name matching regex `__.&#42;__` is reserved/read-only. * A name must not be more than 1500 bytes when UTF-8 encoded. * Cannot be `""`. */ name?: string; } declare interface gapi$client$datastore$Projection { /** * The property to project. */ property?: datastore$PropertyReference; } declare interface gapi$client$datastore$PropertyFilter { /** * The operator to filter by. */ op?: string; /** * The property to filter by. */ property?: datastore$PropertyReference; /** * The value to compare the property to. */ value?: datastore$Value; } declare interface gapi$client$datastore$PropertyOrder { /** * The direction to order by. Defaults to `ASCENDING`. */ direction?: string; /** * The property to order by. */ property?: datastore$PropertyReference; } declare interface gapi$client$datastore$PropertyReference { /** * The name of the property. * If name includes "."s, it may be interpreted as a property name path. */ name?: string; } declare interface gapi$client$datastore$Query { /** * The properties to make distinct. The query results will contain the first * result for each distinct combination of values for the given properties * (if empty, all results are returned). */ distinctOn?: gapi$client$datastore$PropertyReference[]; /** * An ending point for the query results. Query cursors are * returned in query result batches and * [can only be used to limit the same query](https://cloud.google.com/datastore/docs/concepts/queries#cursors_limits_and_offsets). */ endCursor?: string; /** * The filter to apply. */ filter?: gapi$client$datastore$Filter; /** * The kinds to query (if empty, returns entities of all kinds). * Currently at most 1 kind may be specified. */ kind?: gapi$client$datastore$KindExpression[]; /** * The maximum number of results to return. Applies after all other * constraints. Optional. * Unspecified is interpreted as no limit. * Must be >= 0 if specified. */ limit?: number; /** * The number of results to skip. Applies before limit, but after all other * constraints. Optional. Must be >= 0 if specified. */ offset?: number; /** * The order to apply to the query results (if empty, order is unspecified). */ order?: gapi$client$datastore$PropertyOrder[]; /** * The projection to return. Defaults to returning all properties. */ projection?: gapi$client$datastore$Projection[]; /** * A starting point for the query results. Query cursors are * returned in query result batches and * [can only be used to continue the same query](https://cloud.google.com/datastore/docs/concepts/queries#cursors_limits_and_offsets). */ startCursor?: string; } declare interface gapi$client$datastore$QueryResultBatch { /** * A cursor that points to the position after the last result in the batch. */ endCursor?: string; /** * The result type for every entity in `entity_results`. */ entityResultType?: string; /** * The results for this batch. */ entityResults?: gapi$client$datastore$EntityResult[]; /** * The state of the query after the current batch. */ moreResults?: string; /** * A cursor that points to the position after the last skipped result. * Will be set when `skipped_results` != 0. */ skippedCursor?: string; /** * The number of results skipped, typically because of an offset. */ skippedResults?: number; /** * The version number of the snapshot this batch was returned from. * This applies to the range of results from the query's `start_cursor` (or * the beginning of the query if no cursor was given) to this batch's * `end_cursor` (not the query's `end_cursor`). * * In a single transaction, subsequent query result batches for the same query * can have a greater snapshot version number. Each batch's snapshot version * is valid for all preceding batches. * The value will be zero for eventually consistent queries. */ snapshotVersion?: string; } declare interface gapi$client$datastore$ReadOptions { /** * The non-transactional read consistency to use. * Cannot be set to `STRONG` for global queries. */ readConsistency?: string; /** * The identifier of the transaction in which to read. A * transaction identifier is returned by a call to * Datastore.BeginTransaction. */ transaction?: string; } declare interface gapi$client$datastore$ReadWrite { /** * The transaction identifier of the transaction being retried. */ previousTransaction?: string; } declare interface gapi$client$datastore$RollbackRequest { /** * The transaction identifier, returned by a call to * Datastore.BeginTransaction. */ transaction?: string; } declare interface gapi$client$datastore$RunQueryRequest { /** * The GQL query to run. */ gqlQuery?: gapi$client$datastore$GqlQuery; /** * Entities are partitioned into subsets, identified by a partition ID. * Queries are scoped to a single partition. * This partition ID is normalized with the standard default context * partition ID. */ partitionId?: gapi$client$datastore$PartitionId; /** * The query to run. */ query?: gapi$client$datastore$Query; /** * The options for this query. */ readOptions?: gapi$client$datastore$ReadOptions; } declare interface gapi$client$datastore$RunQueryResponse { /** * A batch of query results (always present). */ batch?: gapi$client$datastore$QueryResultBatch; /** * The parsed form of the `GqlQuery` from the request, if it was set. */ query?: gapi$client$datastore$Query; } declare interface gapi$client$datastore$Status { /** * The status code, which should be an enum value of google.rpc.Code. */ code?: number; /** * A list of messages that carry the error details. There is a common set of * message types for APIs to use. */ details?: Array<Record<string, any>>; /** * A developer-facing error message, which should be in English. Any * user-facing error message should be localized and sent in the * google.rpc.Status.details field, or localized by the client. */ message?: string; } declare interface gapi$client$datastore$TransactionOptions { /** * The transaction should only allow reads. */ readOnly?: any; /** * The transaction should allow both reads and writes. */ readWrite?: gapi$client$datastore$ReadWrite; } declare interface gapi$client$datastore$Value { /** * An array value. * Cannot contain another array value. * A `Value` instance that sets field `array_value` must not set fields * `meaning` or `exclude_from_indexes`. */ arrayValue?: gapi$client$datastore$ArrayValue; /** * A blob value. * May have at most 1,000,000 bytes. * When `exclude_from_indexes` is false, may have at most 1500 bytes. * In JSON requests, must be base64-encoded. */ blobValue?: string; /** * A boolean value. */ booleanValue?: boolean; /** * A double value. */ doubleValue?: number; /** * An entity value. * * - May have no key. * - May have a key with an incomplete key path. * - May have a reserved/read-only key. */ entityValue?: gapi$client$datastore$Entity; /** * If the value should be excluded from all indexes including those defined * explicitly. */ excludeFromIndexes?: boolean; /** * A geo point value representing a point on the surface of Earth. */ geoPointValue?: gapi$client$datastore$LatLng; /** * An integer value. */ integerValue?: string; /** * A key value. */ keyValue?: gapi$client$datastore$Key; /** * The `meaning` field should only be populated for backwards compatibility. */ meaning?: number; /** * A null value. */ nullValue?: string; /** * A UTF-8 encoded string value. * When `exclude_from_indexes` is false (it is indexed) , may have at most 1500 bytes. * Otherwise, may be set to at least 1,000,000 bytes. */ stringValue?: string; /** * A timestamp value. * When stored in the Datastore, precise only to microseconds; * any additional precision is rounded down. */ timestampValue?: string; } declare interface gapi$client$datastore$OperationsResource { /** * Starts asynchronous cancellation on a long-running operation. The server * makes a best effort to cancel the operation, but success is not * guaranteed. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. Clients can use * Operations.GetOperation or * other methods to check whether the cancellation succeeded or whether the * operation completed despite cancellation. On successful cancellation, * the operation is not deleted; instead, it becomes an operation with * an Operation.error value with a google.rpc.Status.code of 1, * corresponding to `Code.CANCELLED`. */ cancel(request: { /** * V1 error format. */ "$.xgafv"?: string, /** * OAuth access token. */ access_token?: string, /** * Data format for response. */ alt?: string, /** * OAuth bearer token. */ bearer_token?: string, /** * JSONP */ callback?: string, /** * Selector specifying which fields to include in a partial response. */ fields?: string, /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** * The name of the operation resource to be cancelled. */ name: string, /** * OAuth 2.0 token for the current user. */ oauth_token?: string, /** * Pretty-print response. */ pp?: boolean, /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean, /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string }): Request<{}>; /** * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the * operation. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. */ delete(request: { /** * V1 error format. */ "$.xgafv"?: string, /** * OAuth access token. */ access_token?: string, /** * Data format for response. */ alt?: string, /** * OAuth bearer token. */ bearer_token?: string, /** * JSONP */ callback?: string, /** * Selector specifying which fields to include in a partial response. */ fields?: string, /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** * The name of the operation resource to be deleted. */ name: string, /** * OAuth 2.0 token for the current user. */ oauth_token?: string, /** * Pretty-print response. */ pp?: boolean, /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean, /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string }): Request<{}>; /** * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. */ get(request: { /** * V1 error format. */ "$.xgafv"?: string, /** * OAuth access token. */ access_token?: string, /** * Data format for response. */ alt?: string, /** * OAuth bearer token. */ bearer_token?: string, /** * JSONP */ callback?: string, /** * Selector specifying which fields to include in a partial response. */ fields?: string, /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** * The name of the operation resource. */ name: string, /** * OAuth 2.0 token for the current user. */ oauth_token?: string, /** * Pretty-print response. */ pp?: boolean, /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean, /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string }): Request<gapi$client$datastore$GoogleLongrunningOperation>; /** * Lists operations that match the specified filter in the request. If the * server doesn't support this method, it returns `UNIMPLEMENTED`. * * NOTE: the `name` binding allows API services to override the binding * to use different resource name schemes, such as `users/&#42;/operations`. To * override the binding, API services can add a binding such as * `"/v1/{name=users/&#42;}/operations"` to their service configuration. * For backwards compatibility, the default name includes the operations * collection id, however overriding users must ensure the name binding * is the parent resource, without the operations collection id. */ list(request: { /** * V1 error format. */ "$.xgafv"?: string, /** * OAuth access token. */ access_token?: string, /** * Data format for response. */ alt?: string, /** * OAuth bearer token. */ bearer_token?: string, /** * JSONP */ callback?: string, /** * Selector specifying which fields to include in a partial response. */ fields?: string, /** * The standard list filter. */ filter?: string, /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** * The name of the operation's parent resource. */ name: string, /** * OAuth 2.0 token for the current user. */ oauth_token?: string, /** * The standard list page size. */ pageSize?: number, /** * The standard list page token. */ pageToken?: string, /** * Pretty-print response. */ pp?: boolean, /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean, /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string }): Request<gapi$client$datastore$GoogleLongrunningListOperationsResponse>; } declare interface gapi$client$datastore$ProjectsResource { /** * Allocates IDs for the given keys, which is useful for referencing an entity * before it is inserted. */ allocateIds(request: { /** * V1 error format. */ "$.xgafv"?: string, /** * OAuth access token. */ access_token?: string, /** * Data format for response. */ alt?: string, /** * OAuth bearer token. */ bearer_token?: string, /** * JSONP */ callback?: string, /** * Selector specifying which fields to include in a partial response. */ fields?: string, /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** * OAuth 2.0 token for the current user. */ oauth_token?: string, /** * Pretty-print response. */ pp?: boolean, /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean, /** * The ID of the project against which to make the request. */ projectId: string, /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string }): Request<gapi$client$datastore$AllocateIdsResponse>; /** * Begins a new transaction. */ beginTransaction(request: { /** * V1 error format. */ "$.xgafv"?: string, /** * OAuth access token. */ access_token?: string, /** * Data format for response. */ alt?: string, /** * OAuth bearer token. */ bearer_token?: string, /** * JSONP */ callback?: string, /** * Selector specifying which fields to include in a partial response. */ fields?: string, /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** * OAuth 2.0 token for the current user. */ oauth_token?: string, /** * Pretty-print response. */ pp?: boolean, /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean, /** * The ID of the project against which to make the request. */ projectId: string, /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string }): Request<gapi$client$datastore$BeginTransactionResponse>; /** * Commits a transaction, optionally creating, deleting or modifying some * entities. */ commit(request: { /** * V1 error format. */ "$.xgafv"?: string, /** * OAuth access token. */ access_token?: string, /** * Data format for response. */ alt?: string, /** * OAuth bearer token. */ bearer_token?: string, /** * JSONP */ callback?: string, /** * Selector specifying which fields to include in a partial response. */ fields?: string, /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** * OAuth 2.0 token for the current user. */ oauth_token?: string, /** * Pretty-print response. */ pp?: boolean, /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean, /** * The ID of the project against which to make the request. */ projectId: string, /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string }): Request<gapi$client$datastore$CommitResponse>; /** * Looks up entities by key. */ lookup(request: { /** * V1 error format. */ "$.xgafv"?: string, /** * OAuth access token. */ access_token?: string, /** * Data format for response. */ alt?: string, /** * OAuth bearer token. */ bearer_token?: string, /** * JSONP */ callback?: string, /** * Selector specifying which fields to include in a partial response. */ fields?: string, /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** * OAuth 2.0 token for the current user. */ oauth_token?: string, /** * Pretty-print response. */ pp?: boolean, /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean, /** * The ID of the project against which to make the request. */ projectId: string, /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string }): Request<gapi$client$datastore$LookupResponse>; /** * Rolls back a transaction. */ rollback(request: { /** * V1 error format. */ "$.xgafv"?: string, /** * OAuth access token. */ access_token?: string, /** * Data format for response. */ alt?: string, /** * OAuth bearer token. */ bearer_token?: string, /** * JSONP */ callback?: string, /** * Selector specifying which fields to include in a partial response. */ fields?: string, /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** * OAuth 2.0 token for the current user. */ oauth_token?: string, /** * Pretty-print response. */ pp?: boolean, /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean, /** * The ID of the project against which to make the request. */ projectId: string, /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string }): Request<{}>; /** * Queries for entities. */ runQuery(request: { /** * V1 error format. */ "$.xgafv"?: string, /** * OAuth access token. */ access_token?: string, /** * Data format for response. */ alt?: string, /** * OAuth bearer token. */ bearer_token?: string, /** * JSONP */ callback?: string, /** * Selector specifying which fields to include in a partial response. */ fields?: string, /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** * OAuth 2.0 token for the current user. */ oauth_token?: string, /** * Pretty-print response. */ pp?: boolean, /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean, /** * The ID of the project against which to make the request. */ projectId: string, /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string }): Request<gapi$client$datastore$RunQueryResponse>; operations: gapi$client$datastore$OperationsResource; } }
madhuri7112/Singularity
SingularityService/src/main/java/com/hubspot/singularity/data/history/SingularityTaskHistoryPersister.java
<gh_stars>0 package com.hubspot.singularity.data.history; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.collect.Multimap; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import com.google.common.collect.TreeMultimap; import com.google.inject.Inject; import com.google.inject.name.Named; import com.hubspot.mesos.JavaUtils; import com.hubspot.singularity.SingularityDeleteResult; import com.hubspot.singularity.SingularityPendingDeploy; import com.hubspot.singularity.SingularityTaskHistory; import com.hubspot.singularity.SingularityTaskId; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.config.SingularityTaskMetadataConfiguration; import com.hubspot.singularity.data.DeployManager; import com.hubspot.singularity.data.TaskManager; @Singleton public class SingularityTaskHistoryPersister extends SingularityHistoryPersister<SingularityTaskId> { private static final Logger LOG = LoggerFactory.getLogger(SingularityTaskHistoryPersister.class); private final TaskManager taskManager; private final DeployManager deployManager; private final HistoryManager historyManager; private final SingularityTaskMetadataConfiguration taskMetadataConfiguration; @Inject public SingularityTaskHistoryPersister(SingularityConfiguration configuration, SingularityTaskMetadataConfiguration taskMetadataConfiguration, TaskManager taskManager, DeployManager deployManager, HistoryManager historyManager, @Named(SingularityHistoryModule.PERSISTER_LOCK) ReentrantLock persisterLock) { super(configuration, persisterLock); this.taskManager = taskManager; this.historyManager = historyManager; this.deployManager = deployManager; this.taskMetadataConfiguration = taskMetadataConfiguration; } @Override public void runActionOnPoll() { LOG.info("Attempting to grab persister lock"); persisterLock.lock(); try { LOG.info("Checking inactive task ids for task history persistence"); final long start = System.currentTimeMillis(); final List<SingularityTaskId> allTaskIds = taskManager.getAllTaskIds(); final Set<SingularityTaskId> activeTaskIds = Sets.newHashSet(taskManager.getActiveTaskIds()); final Set<SingularityTaskId> lbCleaningTaskIds = Sets.newHashSet(taskManager.getLBCleanupTasks()); final List<SingularityPendingDeploy> pendingDeploys = deployManager.getPendingDeploys(); int numTotal = 0; int numTransferred = 0; final Multimap<String, SingularityTaskId> eligibleTaskIdByRequestId = TreeMultimap.create(Ordering.natural(), SingularityTaskId.STARTED_AT_COMPARATOR_DESC); for (SingularityTaskId taskId : allTaskIds) { if (activeTaskIds.contains(taskId) || lbCleaningTaskIds.contains(taskId) || isPartOfPendingDeploy(pendingDeploys, taskId)) { continue; } eligibleTaskIdByRequestId.put(taskId.getRequestId(), taskId); } for (Map.Entry<String, Collection<SingularityTaskId>> entry : eligibleTaskIdByRequestId.asMap().entrySet()) { int i = 0; for (SingularityTaskId taskId : entry.getValue()) { final long age = start - taskId.getStartedAt(); if (age < configuration.getTaskPersistAfterStartupBufferMillis()) { LOG.debug("Not persisting {}, it has started up too recently {} (buffer: {}) - this prevents race conditions with ZK tx", taskId, JavaUtils.durationFromMillis(age), JavaUtils.durationFromMillis(configuration.getTaskPersistAfterStartupBufferMillis())); continue; } if (moveToHistoryOrCheckForPurge(taskId, i++)) { numTransferred++; } numTotal++; } } LOG.info("Transferred {} out of {} inactive task ids (total {}) in {}", numTransferred, numTotal, allTaskIds.size(), JavaUtils.duration(start)); } finally { persisterLock.unlock(); } } private boolean isPartOfPendingDeploy(List<SingularityPendingDeploy> pendingDeploys, SingularityTaskId taskId) { for (SingularityPendingDeploy pendingDeploy : pendingDeploys) { if (pendingDeploy.getDeployMarker().getDeployId().equals(taskId.getDeployId()) && pendingDeploy.getDeployMarker().getRequestId().equals(taskId.getRequestId())) { return true; } } return false; } @Override protected long getMaxAgeInMillisOfItem() { return TimeUnit.HOURS.toMillis(configuration.getDeleteTasksFromZkWhenNoDatabaseAfterHours()); } @Override protected Optional<Integer> getMaxNumberOfItems() { return configuration.getMaxStaleTasksPerRequestInZkWhenNoDatabase(); } @Override protected boolean moveToHistory(SingularityTaskId object) { final Optional<SingularityTaskHistory> taskHistory = taskManager.getTaskHistory(object); if (taskHistory.isPresent()) { if (!taskHistory.get().getTaskUpdates().isEmpty()) { final long lastUpdateAt = taskHistory.get().getLastTaskUpdate().get().getTimestamp(); final long timeSinceLastUpdate = System.currentTimeMillis() - lastUpdateAt; if (timeSinceLastUpdate < taskMetadataConfiguration.getTaskPersistAfterFinishBufferMillis()) { LOG.debug("Not persisting {} yet - lastUpdate only happened {} ago, buffer {}", JavaUtils.durationFromMillis(timeSinceLastUpdate), JavaUtils.durationFromMillis(taskMetadataConfiguration.getTaskPersistAfterFinishBufferMillis())); return false; } } LOG.debug("Moving {} to history", object); try { historyManager.saveTaskHistory(taskHistory.get()); } catch (Throwable t) { LOG.warn("Failed to persist task into History for task {}", object, t); return false; } } else { LOG.warn("Inactive task {} did not have a task to persist", object); } return true; } @Override protected SingularityDeleteResult purgeFromZk(SingularityTaskId object) { return taskManager.deleteTaskHistory(object); } }
alexanderpetrenko/job4j
chapter_002/src/main/java/ru/job4j/tracker/MenuTracker.java
<gh_stars>0 package ru.job4j.tracker; import java.util.HashMap; import java.util.List; import java.util.Map; /** * The {@code MenuTracker} realizes the executing of user's operations. * * @author <NAME> (<EMAIL>) * @version 1.0 * @since 1.0 */ public class MenuTracker { /** * This field stores an Input object reference */ private Input input; /** * This field stores a Tracker object reference */ private Tracker tracker; /** * Menu's constants and keys for user's actions. */ private static final int ADD = 0; private static final int SHOW = 1; private static final int EDIT = 2; private static final int DELETE = 3; private static final int FINDID = 4; private static final int FINDNAME = 5; private static final int EXIT = 6; /** * Array of user's actions. */ private HashMap<Integer, BaseAction> actions = new HashMap<>(); /** * The class constructor. * * @param input Input type object. * @param tracker Tracker type object. */ public MenuTracker(Input input, Tracker tracker) { this.input = input; this.tracker = tracker; } /** * This method fills an array with user's actions. */ public void fillActions(StartUI ui) { this.actions.put(ADD, new CreateItem(ADD, "Добавить новую заявку")); this.actions.put(SHOW, new ShowAllItems(SHOW, "Показать все заявки")); this.actions.put(EDIT, new EditItem(EDIT, "Редактировать заявку")); this.actions.put(DELETE, new DeleteItem(DELETE, "Удалить заявку")); this.actions.put(FINDID, new FindItemById(FINDID, "Поиск заявки по Id")); this.actions.put(FINDNAME, new FindItemByName(FINDNAME, "Поиск заявки по названию")); this.actions.put(EXIT, new Exit(EXIT, "Выход", ui)); } public int getActionsLength() { return this.actions.size(); } /** * The method performs the appropriate action depending on the specified key. * * @param key An action key. */ public void select(int key) { this.actions.get(key).execute(this.input, this.tracker); } /** * This method outputs menu items. */ public void show() { System.out.println("Меню:"); for (Map.Entry<Integer, BaseAction> action : this.actions.entrySet()) { System.out.println(action.getValue().info()); } } /** * The {@code CreateItem} class implements adding a new bid to the repository. */ private class CreateItem extends BaseAction { public CreateItem(int key, String name) { super(key, name); } @Override public void execute(Input input, Tracker tracker) { System.out.println("------------ Добавление новой заявки --------------"); String name = input.ask("Введите название заявки: "); String description = input.ask("Введите описание заявки: "); Item item = new Item(name, description); tracker.add(item); System.out.println("------------ Новая заявка с Id : " + item.getId() + "-----------"); System.out.println("----- Новая заявка с названием : " + item.getName() + "-----------"); System.out.println("----- Новая заявка с описанием : " + item.getDescription() + "-----------"); } } /** * The {@code ShowAllItems} class outputs all bid Items from the repository. */ private class ShowAllItems extends BaseAction { public ShowAllItems(int key, String name) { super(key, name); } @Override public void execute(Input input, Tracker tracker) { System.out.println("------------ Вывод всех заявок --------------------"); List<Item> items = tracker.findAll(); for (Item item : items) { System.out.println(item.toString()); } System.out.println("------------ Вывод всех заявок окончен ------------"); } } /** * The {@code EditItem} class implements editing an existing bid Item. */ private class EditItem extends BaseAction { public EditItem(int key, String name) { super(key, name); } @Override public void execute(Input input, Tracker tracker) { System.out.println("------------ Редактирование заявки ----------------"); String id = input.ask("Введите Id заявки для редактирования: "); String name = input.ask("Введите новое название заявки: "); String description = input.ask("Введите новое описание заявки: "); Item newItem = new Item(name, description); if (tracker.replace(id, newItem)) { System.out.println("------------ Заявка с Id " + newItem.getId() + " отредактирована -----------"); System.out.println("------------ Название заявки " + newItem.getName() + " -----------"); System.out.println("------------ Описание заявки " + newItem.getDescription() + " -----------"); } else { System.out.println("------------ Операция отклонена! Заявка не найдена ----"); } } } /** * The {@code DeleteItem} class implements delete operation of the existing bid from the repository. */ private class DeleteItem extends BaseAction { public DeleteItem(int key, String name) { super(key, name); } @Override public void execute(Input input, Tracker tracker) { System.out.println("------------ Удаление заявки ----------------------"); String id = input.ask("Введите Id заявки: "); if (tracker.delete(id)) { System.out.println("------------ Заявка удалена успешно -------------------"); } else { System.out.println("------------ Операция отклонена! Заявка не найдена ----"); } } } /** * The {@code FindItemById} class implements search a bid Item by Id. */ private class FindItemById extends BaseAction { public FindItemById(int key, String name) { super(key, name); } @Override public void execute(Input input, Tracker tracker) { System.out.println("------------ Поиск заявки по Id -------------------"); String id = input.ask("Введите Id заявки: "); Item item = tracker.findById(id); if (item != null) { System.out.println(item.toString()); } else { System.out.println("------------ Заявка " + id + " не найдена -------------"); } } } /** * The {@code FindItemById} class implements search a bid Item by its Name. */ private class FindItemByName extends BaseAction { public FindItemByName(int key, String name) { super(key, name); } @Override public void execute(Input input, Tracker tracker) { System.out.println("------------ Поиск заявки по названию ---------------"); String name = input.ask("Введите название заявки: "); List<Item> foundItems = tracker.findByName(name); if (foundItems.size() == 0) { System.out.println("------------ Заявки не найдены ------------------------"); } else { for (Item item : foundItems) { System.out.println(item.toString()); } } System.out.println("------------ Вывод найденных заявок окончен ---------------"); } } private class Exit extends BaseAction { private final StartUI ui; public Exit(int key, String name, StartUI ui) { super(key, name); this.ui = ui; } @Override public void execute(Input input, Tracker tracker) { System.out.println("------------------------ Выход ---------------------------"); this.ui.stop(); } } }
SebastianBoe/fw-nrfconnect-zephyr
drivers/timer/native_posix_timer.c
<reponame>SebastianBoe/fw-nrfconnect-zephyr<filename>drivers/timer/native_posix_timer.c /* * Copyright (c) 2017 <NAME> * * SPDX-License-Identifier: Apache-2.0 */ /** * Driver for the timer model of the POSIX native_posix board * It provides the interfaces required by the kernel and the sanity testcases * It also provides a custom k_busy_wait() which can be used with the * POSIX arch and InfClock SOC */ #include "zephyr/types.h" #include "irq.h" #include "device.h" #include "drivers/system_timer.h" #include "sys_clock.h" #include "timer_model.h" #include "soc.h" #include "posix_trace.h" #include "legacy_api.h" static u64_t tick_period; /* System tick period in number of hw cycles */ static s64_t silent_ticks; static s32_t _sys_idle_elapsed_ticks = 1; /** * Return the current HW cycle counter * (number of microseconds since boot in 32bits) */ u32_t _timer_cycle_get_32(void) { return hwm_get_time(); } #ifdef CONFIG_TICKLESS_IDLE /* * Do not raise another ticker interrupt until the sys_ticks'th one * e.g. if sys_ticks is 10, do not raise the next 9 ones * * if sys_ticks is K_FOREVER (or another negative number), * we will effectively silence the tick interrupts forever */ void _timer_idle_enter(s32_t sys_ticks) { if (silent_ticks > 0) { /* LCOV_EXCL_BR_LINE */ /* LCOV_EXCL_START */ posix_print_warning("native timer: Re-entering idle mode with " "%i ticks pending\n", silent_ticks); z_clock_idle_exit(); /* LCOV_EXCL_STOP */ } if (sys_ticks < 0) { silent_ticks = INT64_MAX; } else if (sys_ticks > 0) { silent_ticks = sys_ticks - 1; } else { silent_ticks = 0; } hwtimer_set_silent_ticks(silent_ticks); } /* * Exit from idle mode * * If we have been silent for a number of ticks, announce immediately to the * kernel how many silent ticks have passed. * If this is called due to the 1st non silent timer interrupt, sp_timer_isr() * will be called right away, which will announce that last (non silent) one. * * Note that we do not assume this function is called before the interrupt is * raised (the interrupt can handle it announcing all ticks) */ void z_clock_idle_exit(void) { silent_ticks -= hwtimer_get_pending_silent_ticks(); if (silent_ticks > 0) { _sys_idle_elapsed_ticks = silent_ticks; z_clock_announce(_sys_idle_elapsed_ticks); } silent_ticks = 0; hwtimer_set_silent_ticks(0); } #endif /** * Interrupt handler for the timer interrupt * Announce to the kernel that a tick has passed */ static void sp_timer_isr(void *arg) { ARG_UNUSED(arg); _sys_idle_elapsed_ticks = silent_ticks + 1; silent_ticks = 0; z_clock_announce(_sys_idle_elapsed_ticks); } /* * Enable the hw timer, setting its tick period, and setup its interrupt */ int z_clock_driver_init(struct device *device) { ARG_UNUSED(device); tick_period = 1000000ul / CONFIG_SYS_CLOCK_TICKS_PER_SEC; hwtimer_enable(tick_period); IRQ_CONNECT(TIMER_TICK_IRQ, 1, sp_timer_isr, 0, 0); irq_enable(TIMER_TICK_IRQ); return 0; } #if defined(CONFIG_ARCH_HAS_CUSTOM_BUSY_WAIT) /** * Replacement to the kernel k_busy_wait() * Will block this thread (and therefore the whole zephyr) during usec_to_wait * * Note that interrupts may be received in the meanwhile and that therefore this * thread may loose context */ void z_arch_busy_wait(u32_t usec_to_wait) { u64_t time_end = hwm_get_time() + usec_to_wait; while (hwm_get_time() < time_end) { /*There may be wakes due to other interrupts*/ hwtimer_wake_in_time(time_end); posix_halt_cpu(); } } #endif #if defined(CONFIG_SYSTEM_CLOCK_DISABLE) /** * * @brief Stop announcing sys ticks into the kernel * * Disable the system ticks generation * * @return N/A */ void sys_clock_disable(void) { irq_disable(TIMER_TICK_IRQ); hwtimer_set_silent_ticks(INT64_MAX); } #endif /* CONFIG_SYSTEM_CLOCK_DISABLE */
DarrenPaulWright/hafgufa
src/graphs/GraphBase.js
import { defer } from 'async-agent'; import { forOwn } from 'object-agent'; import { DockPoint, Enum, isObject, methodArray, methodElement, methodQueue, methodString, methodThickness, PIXELS, Thickness } from 'type-enforcer-ui'; import Control from '../Control.js'; import Tooltip from '../layout/Tooltip.js'; import ControlHeadingMixin from '../mixins/ControlHeadingMixin.js'; import IsWorkingMixin from '../mixins/IsWorkingMixin.js'; import Svg from '../svg/Svg.js'; import { HEIGHT, WIDTH } from '../utility/domConstants.js'; import setDefaults from '../utility/setDefaults.js'; import './GraphBase.less'; import Legend from './Legend.js'; const BREAK = '<br>'; const MAX_TOOLTIP_WIDTH = '20rem'; const DATA_TYPES = new Enum({ TWO_AXIS: 'twoAxis', THREE_AXIS: 'threeAxis', FOUR_AXIS: 'fourAxis', FOUR_AXIS_RANGE: 'fourAxisRange', TREE: 'tree', NETWORK: 'network', TIME_LINE: 'timeLine' }); const TOOLTIP = Symbol(); // const STORE_ON_CHANGE_IDS = Symbol(); const LEGEND = Symbol(); const calculateDataLimits = Symbol(); const buildTooltipText = Symbol(); /** * @class GraphBase * @mixes IsWorkingMixin * @mixes ControlHeadingMixin * @extends Control * * @param {object} settings */ export default class GraphBase extends IsWorkingMixin(ControlHeadingMixin(Control)) { constructor(settings = {}) { super(setDefaults({ isWorking: true }, settings)); const self = this; self.addClass('graph'); self.svgElement(new Svg().element); // self[STORE_ON_CHANGE_IDS] = []; self.onResize(() => { let legendWidth; let renderWidth = self.innerWidth() || self.element.offsetWidth; let renderHeight = self.innerHeight() || self.element.offsetHeight; if (self.getHeading()) { renderHeight -= self.getHeading().height(); } self.svgElement().setAttribute(WIDTH, renderWidth + PIXELS); self.svgElement().setAttribute(HEIGHT, renderHeight + PIXELS); if (self[LEGEND]) { legendWidth = self[LEGEND].width(); renderWidth -= legendWidth + 10; self[LEGEND].attr('transform', 'translate(' + renderWidth + ',' + self.graphPadding().top + ')'); } self.onUpdateSize().trigger(null, [renderWidth, renderHeight]); if (self.data().length !== 0) { self.onUpdateData().trigger(); } }); defer(() => { self.resize(); }); self.onRemove(() => { // self.dataSource([]); self.data([]); self.legendItems([]); self.svgElement(null); }); } [calculateDataLimits](data, dataType) { const limits = {}; const parseValue = (value) => parseFloat(value); const calculate = (model) => { forOwn(model, (itemKey, limitKey) => { limits['min' + limitKey] = data.length ? parseValue(data[0][itemKey]) : 0; limits['max' + limitKey] = data.length ? parseValue(data[0][itemKey]) : 0; }); data.forEach((item) => { forOwn(model, (itemKey, limitKey) => { limits['min' + limitKey] = Math.min(limits['min' + limitKey], parseValue(item[itemKey])); limits['max' + limitKey] = Math.max(limits['max' + limitKey], parseValue(item[itemKey])); }); }); }; switch (dataType) { case DATA_TYPES.TWO_AXIS: calculate({ Value: 'value', Label: 'label' }); break; case DATA_TYPES.THREE_AXIS: calculate({ Value: 'value', X: 'x', Y: 'y' }); break; case DATA_TYPES.FOUR_AXIS: calculate({ Value: 'value', X: 'x', Y: 'y', Z: 'z' }); break; case DATA_TYPES.FOUR_AXIS_RANGE: calculate({ Value: 'value', XMin: 'xMin', XMax: 'xMax', YMin: 'yMin', YMax: 'yMax', Z: 'z' }); break; } return limits; } [buildTooltipText](d, dataType) { const self = this; let output = ''; switch (dataType) { case DATA_TYPES.TWO_AXIS: output += d.label + BREAK; break; case DATA_TYPES.THREE_AXIS: if (self.xLabel()) { output += self.xLabel() + ': '; } output += d.x + BREAK; if (self.yLabel()) { output += self.yLabel() + ': '; } output += d.y + BREAK; break; case DATA_TYPES.FOUR_AXIS: if (d.title) { output += '<strong>' + d.title + '</strong>' + BREAK; } if (self.xLabel()) { output += self.xLabel() + ': '; } output += d.x + BREAK; if (self.yLabel()) { output += self.yLabel() + ': '; } output += d.y + BREAK; if (self.zLabel()) { output += self.zLabel() + ': '; } output += d.z + BREAK; break; case DATA_TYPES.FOUR_AXIS_RANGE: if (d.title) { output += '<strong>' + d.title + '</strong>' + BREAK; } if (self.xLabel()) { output += self.xLabel() + ': '; } output += d.xMin + ' - ' + d.xMax + BREAK; if (self.yLabel()) { output += self.yLabel() + ': '; } output += d.yMin + ' - ' + d.yMax + BREAK; if (self.zLabel()) { output += self.zLabel() + ': '; } output += d.z + BREAK; break; } output += 'Total: ' + d.value; return output; } } Object.assign(GraphBase.prototype, { svgElement: methodElement({ set(newValue) { if (newValue) { this.contentContainer.append(newValue); } }, other: null }), onUpdateSize: methodQueue(), onUpdateData: methodQueue(), graphPadding: methodThickness({ init: new Thickness(12), set: 'resize' }), color: methodString({ init: '#b24f26', set(newValue) { const self = this; self.onUpdateData().trigger(); if (self[LEGEND]) { self[LEGEND].color(newValue); } } }), data: methodArray({ set(newValue) { const self = this; if (!self.isRemoved) { newValue.forEach((dataObject) => { if (isObject(dataObject)) { dataObject.limits = self[calculateDataLimits](dataObject.data, dataObject.dataType); } }); self.onUpdateData().trigger(); self.isWorking(false); } } }), // dataSource: methodArray({ // init: undefined, // before(oldValue) { // if (oldValue && !isArray(oldValue)) { // oldValue = [oldValue]; // } // if (oldValue) { // oldValue.forEach((source, index) => { // if (source.store) { // source.store.offChange(self[STORE_ON_CHANGE_IDS][index]); // self[STORE_ON_CHANGE_IDS][index] = null; // } // }); // } // }, // set(newValue) { // const saveData = (data, index, dataType) => { // const currentData = clone(self.data()); // currentData[index] = { // data: data, // dataType: dataType // }; // self.data(currentData); // }; // // if (newValue && !isArray(newValue)) { // newValue = [newValue]; // } // // newValue.forEach((source, index) => { // if (source.store && source.valueKey) { // self[STORE_ON_CHANGE_IDS][index] = dataSource.twoAxisFromValueKey(source, (data) => { // saveData(data, index, DATA_TYPES.TWO_AXIS); // }); // } // else if (source.store && source.groupKey) { // self[STORE_ON_CHANGE_IDS][index] = dataSource.twoAxisFromGroupKey(source, (data) => { // saveData(data, index, DATA_TYPES.TWO_AXIS); // }); // } // else if (source.store && source.xKey && source.yKey && source.zKey) { // self[STORE_ON_CHANGE_IDS][index] = dataSource.fourAxisWithValue(source, (data) => { // saveData(data, index, DATA_TYPES.FOUR_AXIS); // }); // } // else if (source.store && source.xKey && source.yKey) { // self[STORE_ON_CHANGE_IDS][index] = dataSource.threeAxisWithValue(source, (data) => { // saveData(data, index, DATA_TYPES.THREE_AXIS); // }); // } // else if (source.store && source.xMinKey && source.xMaxKey && source.yMinKey && source.yMaxKey && source.zKey) { // self[STORE_ON_CHANGE_IDS][index] = dataSource.fourAxisWithRangeAndValue(source, (data) => { // saveData(data, index, DATA_TYPES.FOUR_AXIS_RANGE); // }); // } // }); // }, // other: Object // }), tooltip(anchor, datum, dataType) { const self = this; if (anchor) { self[TOOLTIP] = new Tooltip({ content: self[buildTooltipText](datum, dataType), anchor, anchorDockPoint: DockPoint.POINTS.TOP_CENTER, tooltipDockPoint: DockPoint.POINTS.BOTTOM_CENTER, maxWidth: MAX_TOOLTIP_WIDTH }); } else if (self[TOOLTIP]) { self[TOOLTIP].remove(); self[TOOLTIP] = null; } }, legendItems: methodArray({ set(newValue) { const self = this; if (newValue.length !== 0) { if (!self[LEGEND]) { self[LEGEND] = new Legend({ container: self.svgElement(), color: self.color() }); } self[LEGEND].items(newValue); self.resize(); } else { self[LEGEND].remove(); self[LEGEND] = null; } } }), legendItemColor(item) { return this[LEGEND] ? this[LEGEND].itemColor(item) : this.color(); }, legendOnMouseOverItem(callback) { return this[LEGEND] ? this[LEGEND].onMouseOverItem(callback) : undefined; }, legendOnMouseOutItem(callback) { return this[LEGEND] ? this[LEGEND].onMouseOutItem(callback) : undefined; }, legendOnSelectionChange(callback) { return this[LEGEND] ? this[LEGEND].onSelectionChange(callback) : undefined; } }); GraphBase.DATA_TYPES = DATA_TYPES;
cschladetsch/ChessClock
ChessClock/Source/SceneSplash.cpp
#include "ChessClock/SceneSplash.hpp" namespace ChessClock { bool SplashScene::Setup(Context& ctx) { //if (!ReadJson(_jsonConfig.c_str())) // return false; //ctx.MyValues = std::make_shared<MyValues>(); //LoadResources(ctx.Resources, ctx.TheRenderer, *ctx.MyValues); //AddStep(ctx, &SplashScene::RenderScene); //AddStep(ctx, &SplashScene::StepGame); //AddStep(ctx, &SplashScene::Present); return true; } }
tfoxy/futbol-app
src/app/data/seasonData.factory.js
<reponame>tfoxy/futbol-app<filename>src/app/data/seasonData.factory.js export default seasonDataFactory; function seasonDataFactory(DS) { 'ngInject'; return DS.defineResource({ name: 'seasonData', relations: { hasOne: { season: { localField: 'season', localKey: 'id' } }, hasMany: { division: { localField: 'divisions' }, round: { localField: 'rounds' }, match: { localField: 'matches' }, matchTeamStats: { localField: 'matchTeamStats' }, team: { localField: 'teams' }, player: { localField: 'players' }, goal: { localField: 'goals' }, card: { localField: 'cards' }, cardType: { localField: 'cardTypes' } } } }); }
Zoltan45/Mame-mkp119
src/mame/drivers/coinmstr.c
/* Coinmaster trivia games preliminary driver by <NAME> TODO: - finish video emulation (colors, missing banking bits) - where is palette ? - finish inputs - finish question roms reading - hook up all the PIAs Notes: - Some trivia seems to accept 2 type of eproms for question roms: 0x4000 or 0x8000 bytes long. This check is done with the 1st read from the rom (I think from offset 0) and if it's 0x10, it means a 0x4000 bytes eprom or if it's 0x20, it means a 0x8000 one. Also supnudg2 only tests 0x20 as 1st byte, so accepting only the 2nd type of eproms. */ #include "driver.h" #include "machine/6821pia.h" #include "video/crtc6845.h" #include "sound/ay8910.h" static UINT8 *attr_ram1, *attr_ram2; static tilemap *bg_tilemap; static UINT8 question_adr[4]; static WRITE8_HANDLER( quizmstr_bg_w ) { videoram[offset] = data; if(offset >= 0x0240) tilemap_mark_tile_dirty(bg_tilemap,offset - 0x0240); } static WRITE8_HANDLER( quizmstr_attr1_w ) { attr_ram1[offset] = data; if(offset >= 0x0240) tilemap_mark_tile_dirty(bg_tilemap,offset - 0x0240); } static WRITE8_HANDLER( quizmstr_attr2_w ) { attr_ram2[offset] = data; if(offset >= 0x0240) tilemap_mark_tile_dirty(bg_tilemap,offset - 0x0240); } static READ8_HANDLER( question_r ) { int address; UINT8 *questions = memory_region(REGION_USER1); switch(question_adr[2]) { case 0x38: address = 0x00000; break; // question_adr[3] == 7 case 0x39: address = 0x08000; break; // question_adr[3] == 7 case 0x3a: address = 0x10000; break; // question_adr[3] == 7 case 0x3b: address = 0x18000; break; // question_adr[3] == 7 case 0x3c: address = 0x20000; break; // question_adr[3] == 7 case 0x3d: address = 0x28000; break; // question_adr[3] == 7 case 0x3e: address = 0x30000; break; // question_adr[3] == 7 case 0x07: address = 0x38000; break; // question_adr[3] == 7 case 0x0f: address = 0x40000; break; // question_adr[3] == 7 case 0x17: address = 0x48000; break; // question_adr[3] == 7 case 0x1f: address = 0x50000; break; // question_adr[3] == 7 case 0x27: address = 0x58000; break; // question_adr[3] == 7 case 0x2f: address = 0x60000; break; // question_adr[3] == 7 case 0x37: address = 0x68000; break; // question_adr[3] == 7 case 0x3f: address = 0x70000 + question_adr[3] * 0x8000; break; default: address = 0; logerror("unknown question rom # = %02X\n",question_adr[2]); } if(question_adr[3] == 6 || question_adr[3] > 7) logerror("question_adr[3] = %02X\n",question_adr[3]); /* in these offsets they set 0x80... why? if( (question_adr[0] & 0x5f) == 0x00 || (question_adr[0] & 0x5f) == 0x01 || (question_adr[0] & 0x5f) == 0x0f || (question_adr[0] & 0x5f) == 0x56 ) */ // don't know... // address |= ((question_adr[0] & 0x7f) << 8) | question_adr[1]; address |= (question_adr[1] << 7) | (question_adr[0] & 0x7f); return questions[address]; } static WRITE8_HANDLER( question_w ) { if(data != question_adr[offset]) { logerror("offset = %d data = %02X\n",offset,data); } question_adr[offset] = data; } // Common memory map static ADDRESS_MAP_START( coinmstr_map, ADDRESS_SPACE_PROGRAM, 8 ) AM_RANGE(0x0000, 0xbfff) AM_ROM AM_RANGE(0xc000, 0xdfff) AM_RAM // supnudg2 writes here... AM_RANGE(0xe000, 0xe7ff) AM_RAM AM_WRITE(quizmstr_bg_w) AM_BASE(&videoram) AM_RANGE(0xe800, 0xefff) AM_RAM AM_WRITE(quizmstr_attr1_w) AM_BASE(&attr_ram1) AM_RANGE(0xf000, 0xf7ff) AM_RAM AM_WRITE(quizmstr_attr2_w) AM_BASE(&attr_ram2) AM_RANGE(0xf800, 0xffff) AM_RAM // supnudg2 writes here... ADDRESS_MAP_END // Different I/O mappping for every game static ADDRESS_MAP_START( quizmstr_io_map, ADDRESS_SPACE_IO, 8 ) ADDRESS_MAP_FLAGS( AMEF_ABITS(8) | AMEF_UNMAP(1) ) AM_RANGE(0x00, 0x00) AM_READ(question_r) AM_RANGE(0x00, 0x03) AM_WRITE(question_w) AM_RANGE(0x40, 0x40) AM_WRITE(AY8910_control_port_0_w) AM_RANGE(0x41, 0x41) AM_READWRITE(AY8910_read_port_0_r, AY8910_write_port_0_w) AM_RANGE(0x48, 0x4b) AM_READWRITE(pia_0_r, pia_0_w) AM_RANGE(0x50, 0x53) AM_READNOP AM_RANGE(0x50, 0x53) AM_WRITENOP AM_RANGE(0x58, 0x5b) AM_READWRITE(pia_2_r, pia_2_w) AM_RANGE(0x70, 0x70) AM_WRITE(crtc6845_address_w) AM_RANGE(0x71, 0x71) AM_WRITE(crtc6845_register_w) AM_RANGE(0xc0, 0xc3) AM_READNOP AM_RANGE(0xc0, 0xc3) AM_WRITENOP ADDRESS_MAP_END static ADDRESS_MAP_START( trailblz_io_map, ADDRESS_SPACE_IO, 8 ) ADDRESS_MAP_FLAGS( AMEF_ABITS(8) ) AM_RANGE(0x00, 0x00) AM_READ(question_r) AM_RANGE(0x00, 0x03) AM_WRITE(question_w) AM_RANGE(0x40, 0x40) AM_WRITE(crtc6845_address_w) AM_RANGE(0x41, 0x41) AM_WRITE(crtc6845_register_w) AM_RANGE(0x48, 0x48) AM_WRITE(AY8910_control_port_0_w) AM_RANGE(0x49, 0x49) AM_READWRITE(AY8910_read_port_0_r, AY8910_write_port_0_w) AM_RANGE(0x50, 0x53) AM_READWRITE(pia_0_r, pia_0_w) //? AM_RANGE(0x60, 0x63) AM_READWRITE(pia_1_r, pia_1_w) AM_RANGE(0x70, 0x73) AM_READWRITE(pia_2_r, pia_2_w) AM_RANGE(0xc1, 0xc3) AM_WRITENOP ADDRESS_MAP_END static ADDRESS_MAP_START( supnudg2_io_map, ADDRESS_SPACE_IO, 8 ) ADDRESS_MAP_FLAGS( AMEF_ABITS(8) | AMEF_UNMAP(1) ) AM_RANGE(0x00, 0x00) AM_READ(question_r) AM_RANGE(0x00, 0x03) AM_WRITE(question_w) AM_RANGE(0x40, 0x41) AM_READNOP AM_RANGE(0x40, 0x43) AM_WRITENOP AM_RANGE(0x43, 0x43) AM_READNOP AM_RANGE(0x48, 0x48) AM_WRITE(crtc6845_address_w) AM_RANGE(0x49, 0x49) AM_WRITE(crtc6845_register_w) AM_RANGE(0x50, 0x51) AM_READNOP AM_RANGE(0x50, 0x53) AM_WRITENOP AM_RANGE(0x53, 0x53) AM_READNOP AM_RANGE(0x68, 0x69) AM_READNOP AM_RANGE(0x68, 0x6b) AM_WRITENOP AM_RANGE(0x6b, 0x6b) AM_READNOP AM_RANGE(0x78, 0x78) AM_WRITE(AY8910_control_port_0_w) AM_RANGE(0x79, 0x79) AM_READWRITE(AY8910_read_port_0_r, AY8910_write_port_0_w) AM_RANGE(0xc0, 0xc1) AM_READNOP AM_RANGE(0xc0, 0xc3) AM_WRITENOP ADDRESS_MAP_END INPUT_PORTS_START( quizmstr ) PORT_START PORT_BIT ( 0x01, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT ( 0x02, IP_ACTIVE_LOW, IPT_SERVICE1) PORT_NAME("Bookkeeping") PORT_TOGGLE /* Button 2 for second page, Button 3 erases data */ PORT_BIT ( 0x04, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_BIT ( 0x08, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT ( 0x10, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT ( 0x20, IP_ACTIVE_LOW, IPT_SERVICE) PORT_TOGGLE PORT_BIT ( 0x40, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_BIT ( 0x80, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_START PORT_BIT ( 0x01, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_BIT ( 0x02, IP_ACTIVE_LOW, IPT_BUTTON5 ) PORT_BIT ( 0x04, IP_ACTIVE_LOW, IPT_BUTTON6 ) PORT_BIT ( 0x08, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT ( 0x10, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT ( 0x20, IP_ACTIVE_LOW, IPT_BUTTON1 ) /* If 0x40 is HIGH the DIP Test Mode does work but bookkeeping shows always 0's */ /* If 0x40 is LOW Bookkeeping does work, but the second page (selected categories) is missing */ PORT_BIT ( 0x40, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT ( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START PORT_DIPNAME( 0x01, 0x01, "2-01" ) PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START PORT_DIPNAME( 0x01, 0x01, "3-01" ) PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START PORT_DIPNAME( 0x01, 0x01, DEF_STR( Coin_A ) ) PORT_DIPSETTING( 0x00, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 1C_1C ) ) PORT_DIPNAME( 0x02, 0x02, "4-02" ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, "Test Mode" ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, "NVRAM Reset?" ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, "Self Test" ) PORT_DIPSETTING( 0x00, DEF_STR( No )) PORT_DIPSETTING( 0x80, DEF_STR( Yes )) INPUT_PORTS_END INPUT_PORTS_START( trailblz ) PORT_START PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN4 ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_SERVICE1 ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_SERVICE( 0x80, IP_ACTIVE_LOW ) PORT_START PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 ) PORT_DIPNAME( 0x02, 0x02, "1" ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_NAME("Cont") PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_NAME("Pass") PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_NAME("Sel") PORT_DIPNAME( 0x40, 0x40, "Show Refill" ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, "Show Stats" ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START PORT_DIPNAME( 0x01, 0x01, "2" ) PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START PORT_DIPNAME( 0x01, 0x01, "3" ) PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START PORT_DIPNAME( 0x01, 0x01, "4" ) PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, "Tests" ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, "NVRAM Reset?" ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) INPUT_PORTS_END INPUT_PORTS_START( supnudg2 ) PORT_START PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN4 ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_SERVICE1 ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_SERVICE( 0x80, IP_ACTIVE_HIGH ) PORT_START PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 ) PORT_DIPNAME( 0x02, 0x02, "1" ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_NAME("Cont") PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_NAME("Pass") PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_NAME("Sel") PORT_DIPNAME( 0x40, 0x40, "Show Refill?" ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, "Show Stats?" ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START PORT_DIPNAME( 0x01, 0x01, "2" ) PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START PORT_DIPNAME( 0x01, 0x01, "3" ) PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START PORT_DIPNAME( 0x01, 0x01, "4" ) PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, "Tests?" ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, "NVRAM Reset?" ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, "First Install (DIL 8)" ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) INPUT_PORTS_END static const gfx_layout charlayout = { 8,8, RGN_FRAC(1,2), 2, { RGN_FRAC(0,2), RGN_FRAC(1,2) }, { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 }, 8*8 }; static const gfx_decode gfxdecodeinfo[] = { { REGION_GFX1, 0, &charlayout, 0, 32 }, { -1 } }; static TILE_GET_INFO( get_bg_tile_info ) { int tile = videoram[tile_index + 0x0240]; int color = 0; tile |= (attr_ram1[tile_index + 0x0240] & 0x80) << 1; tile |= (attr_ram2[tile_index + 0x0240] & 0x80) << 2; SET_TILE_INFO(0,tile,color,0); } VIDEO_START( coinmstr ) { bg_tilemap = tilemap_create(get_bg_tile_info,tilemap_scan_rows,TILEMAP_TYPE_PEN, 8, 8, 46, 64); } VIDEO_UPDATE( coinmstr ) { tilemap_draw(bitmap,cliprect,bg_tilemap,0,0); return 0; } /* Declare PIA structure */ /* PIA 0 */ static const pia6821_interface quizmstr_pia_0_intf = { /*inputs : A/B,CA/B1,CA/B2 */ input_port_0_r, 0, 0, 0, 0, 0, /*outputs: A/B,CA/B2 */ 0, 0, 0, 0, /*irqs : A/B */ 0, 0 }; /* PIA 1 */ static const pia6821_interface quizmstr_pia_1_intf = { /*inputs : A/B,CA/B1,CA/B2 */ 0, 0, 0, 0, 0, 0, /*outputs: A/B,CA/B2 */ 0, 0, 0, 0, /*irqs : A/B */ 0, 0 }; /* PIA 2 */ static const pia6821_interface quizmstr_pia_2_intf = { /*inputs : A/B,CA/B1,CA/B2 */ input_port_1_r, 0, 0, 0, 0, 0, /*outputs: A/B,CA/B2 */ 0, 0, 0, 0, /*irqs : A/B */ 0, 0 }; /* PIA 0 */ static const pia6821_interface trailblz_pia_0_intf = { /*inputs : A/B,CA/B1,CA/B2 */ 0, 0, 0, 0, 0, 0, /*outputs: A/B,CA/B2 */ 0, 0, 0, 0, /*irqs : A/B */ 0, 0 }; /* PIA 1 */ static const pia6821_interface trailblz_pia_1_intf = { /*inputs : A/B,CA/B1,CA/B2 */ input_port_1_r, 0, 0, 0, 0, 0, /*outputs: A/B,CA/B2 */ 0, 0, 0, 0, /*irqs : A/B */ 0, 0 }; /* PIA 2 */ static const pia6821_interface trailblz_pia_2_intf = { /*inputs : A/B,CA/B1,CA/B2 */ input_port_0_r, 0, 0, 0, 0, 0, /*outputs: A/B,CA/B2 */ 0, 0, 0, 0, /*irqs : A/B */ 0, 0 }; static MACHINE_START( quizmstr ) { pia_config(0, &quizmstr_pia_0_intf); pia_config(1, &quizmstr_pia_1_intf); pia_config(2, &quizmstr_pia_2_intf); } static MACHINE_RESET( quizmstr ) { pia_reset(); } static MACHINE_START( trailblz ) { pia_config(0, &trailblz_pia_0_intf); pia_config(1, &trailblz_pia_1_intf); pia_config(2, &trailblz_pia_2_intf); } static MACHINE_RESET( trailblz ) { pia_reset(); } struct AY8910interface ay8912_interface = { input_port_4_r }; static MACHINE_DRIVER_START( coinmstr ) MDRV_CPU_ADD_TAG("cpu",Z80,8000000) // ? MDRV_CPU_PROGRAM_MAP(coinmstr_map,0) MDRV_CPU_VBLANK_INT(irq0_line_hold,1) MDRV_SCREEN_REFRESH_RATE(60) MDRV_SCREEN_VBLANK_TIME(DEFAULT_60HZ_VBLANK_DURATION) /* video hardware */ MDRV_VIDEO_ATTRIBUTES(VIDEO_TYPE_RASTER) MDRV_SCREEN_FORMAT(BITMAP_FORMAT_INDEXED16) MDRV_SCREEN_SIZE(64*8, 64*8) MDRV_SCREEN_VISIBLE_AREA(0*8, 46*8-1, 0*8, 32*8-1) MDRV_GFXDECODE(gfxdecodeinfo) MDRV_PALETTE_LENGTH(256) MDRV_VIDEO_START(coinmstr) MDRV_VIDEO_UPDATE(coinmstr) /* sound hardware */ MDRV_SPEAKER_STANDARD_MONO("mono") MDRV_SOUND_ADD(AY8910, 1500000) MDRV_SOUND_CONFIG(ay8912_interface) MDRV_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25) MACHINE_DRIVER_END static MACHINE_DRIVER_START( quizmstr ) MDRV_IMPORT_FROM(coinmstr) MDRV_CPU_MODIFY("cpu") MDRV_CPU_IO_MAP(quizmstr_io_map,0) MDRV_MACHINE_START(quizmstr) MDRV_MACHINE_RESET(quizmstr) MACHINE_DRIVER_END static MACHINE_DRIVER_START( trailblz ) MDRV_IMPORT_FROM(coinmstr) MDRV_CPU_MODIFY("cpu") MDRV_CPU_IO_MAP(trailblz_io_map,0) MDRV_MACHINE_START(trailblz) MDRV_MACHINE_RESET(trailblz) MACHINE_DRIVER_END static MACHINE_DRIVER_START( supnudg2 ) MDRV_IMPORT_FROM(coinmstr) MDRV_CPU_MODIFY("cpu") MDRV_CPU_IO_MAP(supnudg2_io_map,0) MDRV_MACHINE_START(quizmstr) MDRV_MACHINE_RESET(quizmstr) MACHINE_DRIVER_END /* Quizmaster Coinmaster, 1985 PCB Layout ---------- PCB 001-POK 5MBYTE MEMORY EXPANSION |--------------------------------------------------| |------------------------------| | ULN2803 6821 | | | | | | | | NPC_QM4_11.IC45 | |GESCHICH2.IC19 GESCHICH1.IC20| | ULN2003 6821 | | | | ULN2003 NPC_QM4_21.IC41 | | * GESCHICH3.IC18| | | | | |7 6821 | |POPMUSIK2.IC15 POPMUSIK1.IC16| |2 HD465055 | | | |W | | * * | |A | | | |Y AY3-8912 6116 | |SPORT2.IC11 SPORT1.IC12 | | | | | | | |SPORT4.IC9 SPORT3.IC10 | | BATTERY 6116 | | | | DSW1(8) NM_QM4_11.IC9 | |GEOGRAPH2.IC7 GEOGRAPH1.IC8 | | NE555 | | | | VOL NP_QM4_21.IC6 6116 | | * * | | LM380 PAL | | | | | |ALLGEME2.IC3 ALLGEME1.IC4 | | PAL | | | | | | * ALLGEME3.IC2 | | PAL | | | | 14MHz | | | | Z80 CN1 | | CN2 | | | | PAL | |--------------------------------------------------| |------------------------------| CN1/2 is connector for top ROM board * - unpopulated socket */ ROM_START( quizmstr ) ROM_REGION( 0x10000, REGION_CPU1, ROMREGION_ERASEFF ) ROM_LOAD( "nm_qm4_11.ic9", 0x0000, 0x4000, CRC(3a233bf0) SHA1(7b91b6f19093e67dd5513a000138421d4ef6f0af) ) ROM_LOAD( "np_qm4_21.ic6", 0x4000, 0x4000, CRC(a1cd39e4) SHA1(420b0726577471c762ae470bc2138c035f295ad9) ) /* 0x8000 - 0xbfff empty */ ROM_REGION( 0x4000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "npc_qm4_11.ic45", 0x0000, 0x2000, CRC(ed48582a) SHA1(0aa2434a43af2990b8ad1cd3fc9f2e5e962f99c7) ) ROM_LOAD( "npc_qm4_21.ic41", 0x2000, 0x2000, CRC(b67b0183) SHA1(018cabace593e795edfe914cdaedb9ebdf158567) ) ROM_REGION( 0xa0000, REGION_USER1, ROMREGION_ERASEFF ) /* Question roms */ /* empty ic1 */ ROM_LOAD( "allgeme3.ic2", 0x08000, 0x8000, CRC(e9ead7f0) SHA1(c0b8e4e7905f31b74c8d217f0afc91f73d52927b) ) ROM_LOAD( "allgeme2.ic3", 0x10000, 0x8000, CRC(ac4d2ee8) SHA1(3a64fba8a24ae2e8bfd9d1c27804342e1779bcf6) ) ROM_LOAD( "allgeme1.ic4", 0x18000, 0x8000, CRC(896e619b) SHA1(6f0faf0ae206f20387024a4a426b3e92429b3b1d) ) /* empty ic5 */ /* empty ic6 */ ROM_LOAD( "geograph2.ic7", 0x30000, 0x8000, CRC(d809eeb6) SHA1(c557cecd3dd641a9c293f1865a423dafcd71af82) ) ROM_LOAD( "geograph1.ic8", 0x38000, 0x8000, CRC(8984e83c) SHA1(d22c02e9297f804f8560e2e46793e4b6654d0785) ) ROM_LOAD( "sport4.ic9", 0x40000, 0x8000, CRC(3c37de48) SHA1(bee26e9b15cec0b8e81af59810db17a8f2bdc299) ) ROM_LOAD( "sport3.ic10", 0x48000, 0x8000, CRC(24abe1e7) SHA1(77373b1fafa4b117b3a1e4c6e8b530e0bb3b4f42) ) ROM_LOAD( "sport2.ic11", 0x50000, 0x8000, CRC(26645e8e) SHA1(4922dcd417f7d098aaaa6a0320ed1d3e488d3e63) ) ROM_LOAD( "sport1.ic12", 0x58000, 0x8000, CRC(7be41758) SHA1(8e6452fd902d25a73d3fa89bd7b4c5563669cc92) ) /* empty ic13 */ /* empty ic14 */ ROM_LOAD( "popmusik2.ic15", 0x70000, 0x8000, CRC(d3b9ea70) SHA1(0a92ecdc4e2ddd3c0f40682a46a88bc617829481) ) ROM_LOAD( "popmusik1.ic16", 0x78000, 0x8000, CRC(685f047e) SHA1(c0254130d57f60435a70effe6376e0cb3f50223f) ) /* empty ic17 */ ROM_LOAD( "geschich3.ic18", 0x88000, 0x8000, CRC(26c3ceec) SHA1(bf6fd24576c6159bf7730b04d2ac451bfcf3f757) ) ROM_LOAD( "geschich2.ic19", 0x90000, 0x8000, CRC(387d166e) SHA1(14edac9ef550ce64fd81567520f3009612aa7221) ) ROM_LOAD( "geschich1.ic20", 0x98000, 0x8000, CRC(bf4c097f) SHA1(eb14e7bad713d3b03fa3978a7f0087312517cf9e) ) ROM_END ROM_START( trailblz ) ROM_REGION( 0x10000, REGION_CPU1, ROMREGION_ERASEFF ) ROM_LOAD( "1-4.09", 0x0000, 0x4000, CRC(7c34749c) SHA1(3847188a734b32979f376f51f74dff050b610dfb) ) ROM_LOAD( "2-4.06", 0x4000, 0x4000, CRC(81a9809b) SHA1(4d2bfd5223713a9e2e15130a3176118d400ee63e) ) /* 0x8000 - 0xbfff empty */ ROM_REGION( 0x4000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "1-2.45", 0x0000, 0x2000, CRC(b4a807b1) SHA1(f00a4790adb0c25917a0dc8c98c9b65526304fd3) ) ROM_LOAD( "2-2.41", 0x2000, 0x2000, CRC(756dd230) SHA1(6d6f440bf1f48cc33d5e46cfc645809d5f8b1f3a) ) ROM_REGION( 0xa0000, REGION_USER1, ROMREGION_ERASEFF ) /* Question roms */ ROM_LOAD( "questions.bin", 0x00000, 0xa0000, NO_DUMP ) ROM_END ROM_START( supnudg2 ) ROM_REGION( 0x10000, REGION_CPU1, 0 ) ROM_LOAD( "u3.bin", 0x0000, 0x8000, CRC(ed04e2cc) SHA1(7d90a588cca2d113487710e897771f9d99e37e62) ) ROM_LOAD( "u4.bin", 0x8000, 0x8000, CRC(0551e859) SHA1(b71640097cc75b78f3013f0e77de328bf1a205b1) ) ROM_REGION( 0x10000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "u23.bin", 0x0000, 0x8000, CRC(726a48ac) SHA1(cd17840067294812edf5bfa88d71fc967388df8e) ) ROM_LOAD( "u25.bin", 0x8000, 0x8000, CRC(1f7cef5e) SHA1(3abc31d400a0f5dc29c70d8aac42fd6302290cc9) ) ROM_REGION( 0xa0000, REGION_USER1, 0 ) /* Question roms */ ROM_LOAD( "q1.bin", 0x00000, 0x8000, CRC(245d679a) SHA1(2d3fbed8c1b3d0bffe7f3bd9088e0a5d207654c7) ) ROM_LOAD( "q2.bin", 0x08000, 0x8000, CRC(e41ae8fb) SHA1(526c7b60e6ee4dfe05bbabf0e1e986e04ac2f544) ) ROM_LOAD( "q3.bin", 0x10000, 0x8000, CRC(692218a2) SHA1(b9548dd835d9f3fb3e09bd018c7f9cbecafaee28) ) ROM_LOAD( "q4.bin", 0x18000, 0x8000, CRC(ce4be482) SHA1(4fd8f24d22d3f1789fc728445cbc5339ed454bb4) ) ROM_LOAD( "q5.bin", 0x20000, 0x8000, CRC(805672bf) SHA1(0fa68cad0d1c2b11a04a364b5ff64facfa573bbc) ) ROM_LOAD( "q6.bin", 0x28000, 0x8000, CRC(b4405848) SHA1(5f8ca8b017966e6f358f603efde83f45897f3476) ) ROM_LOAD( "q7.bin", 0x30000, 0x8000, CRC(32329b78) SHA1(114f097678be734355b8f36f6af7f1cb75ece191) ) ROM_LOAD( "q8.bin", 0x38000, 0x8000, CRC(25c2aa26) SHA1(7f95553bf98381ced086b6606345bef62fe89a3a) ) ROM_LOAD( "q9.bin", 0x40000, 0x8000, CRC(c98cb15a) SHA1(7d12064c2bcb34668299cadae3072c7f8434c405) ) ROM_LOAD( "q10.bin", 0x48000, 0x8000, CRC(0c6c2df5) SHA1(49c92e498a0556032bb8ca56ff5afb9f69a80b3f) ) ROM_LOAD( "q11.bin", 0x50000, 0x8000, CRC(1c53a264) SHA1(c10cc32b032bd4f890497bdc942e7e8c75ea1d6f) ) ROM_LOAD( "q12.bin", 0x58000, 0x8000, CRC(c9535bff) SHA1(9c9873642c62971f805dc629f8d1006e35a675f9) ) ROM_LOAD( "q13.bin", 0x60000, 0x8000, CRC(7a9b9f61) SHA1(7e39fef67fc3c29604ae68358e01330cf5130c06) ) ROM_LOAD( "q14.bin", 0x68000, 0x8000, CRC(ec35e800) SHA1(0e0ca6fec760f31f464b282a1d7341cc4a29c064) ) ROM_LOAD( "q15.bin", 0x70000, 0x8000, CRC(9f3738eb) SHA1(e841958f37167e7f9adcd3c965d31e2b7e02f52c) ) ROM_LOAD( "q16.bin", 0x78000, 0x8000, CRC(af92277c) SHA1(093079fab28e3de443b640d2777cc2980b20af6c) ) ROM_LOAD( "q17.bin", 0x80000, 0x8000, CRC(522fd485) SHA1(6c2a2626c00015962c460eac0dcb46ea263a4a23) ) ROM_LOAD( "q18.bin", 0x88000, 0x8000, CRC(54d50510) SHA1(2a8ad2a2e1735f9c7d606b99b3653f823f09d1e8) ) ROM_LOAD( "q19.bin", 0x90000, 0x8000, CRC(30aa2ff5) SHA1(4a2b4fc9c0c5cab3d374ee4738152209589e0807) ) ROM_LOAD( "q20.bin", 0x98000, 0x8000, CRC(0845b450) SHA1(c373839ee1ad983e2df41cb22f625c14972372b0) ) ROM_END DRIVER_INIT( coinmstr ) { UINT8 *rom = memory_region(REGION_USER1); int length = memory_region_length(REGION_USER1); UINT8 *buf = malloc_or_die(length); int i; memcpy(buf,rom,length); for(i = 0; i < length; i++) { int adr = BITSWAP24(i, 23,22,21,20,19,18,17,16,15, 14,8,7,2,5,12,10,9,11,13,3,6,0,1,4); rom[i] = BITSWAP8(buf[adr],3,2,4,1,5,0,6,7); } free(buf); } GAME( 1985, quizmstr, 0, quizmstr, quizmstr, coinmstr, ROT0, "Loewen Spielautomaten", "Quizmaster (German)", GAME_WRONG_COLORS | GAME_UNEMULATED_PROTECTION ) GAME( 1987, trailblz, 0, trailblz, trailblz, coinmstr, ROT0, "Coinmaster", "Trail Blazer", GAME_WRONG_COLORS | GAME_UNEMULATED_PROTECTION | GAME_NOT_WORKING ) // or Trail Blazer 2 ? GAME( 1989, supnudg2, 0, supnudg2, supnudg2, coinmstr, ROT0, "Coinmaster", "Super Nudger II (Version 5.21)", GAME_WRONG_COLORS | GAME_UNEMULATED_PROTECTION | GAME_NOT_WORKING )
geovas01/cup2
docs/res/LRParserSerializer.java
<gh_stars>0 package edu.tum.cup2.io; import edu.tum.cup2.generator.LR1Generator; import edu.tum.cup2.generator.exceptions.GeneratorException; import edu.tum.cup2.parser.LRParser; import edu.tum.cup2.spec.CUPSpecification; /** * LRParserSerializer generates a parser for a given CUPSpecification and * serializes a LRParser (mainly the ParsingTable) * to a cup2 file. * * @author <NAME> */ @SuppressWarnings("unchecked") public final class LRParserSerializer { /** * @param arg[0]: CUPSpecification name * arg[1]: cup2 file name where to store serialization * @return 0: successful * !=0: error */ public static int main(String args[]) { if(args.length != 2) { System.err.println("== ERROR LRParserSerializer.main required 2 arguments: specifiaction name, file name =="); return -1; } String strSpecName = args[0]; String strFileName = args[1]; try { createSerialisation(strSpecName, strFileName); System.out.println("Parser successfully serialized."); } catch(ClassNotFoundException cnfe) { System.err.println("Could not find " + strSpecName); System.out.println("Parser NOT successfully serialized."); return 1; //createSerialisation failed } catch(InstantiationException ie) { System.err.println("Could not instantiate " + strSpecName); System.out.println("Parser NOT successfully serialized."); return 2; //createSerialisation failed } catch(Exception e) { System.err.println("Parser NOT successfully serialized."); System.out.println("Parser NOT successfully serialized."); return 3; //createSerialisation failed } return 0; //successfully serialized } private static void createSerialisation(String strSpecName, String strFileName) throws GeneratorException, InstantiationException, IllegalAccessException, ClassNotFoundException //createSerialisation failed { Class<CUPSpecification> c = null; CUPSpecification spec = null; LR1Generator generator = null; c = (Class<CUPSpecification>) Class.forName(strSpecName); spec = (CUPSpecification) c.newInstance(); generator = new LR1Generator(spec); LRParser parser = new LRParser(generator.getParsingTable()); //create LRParserSerialization object LRParserSerialization serial = new LRParserSerialization(strFileName); //serialize parser serial.saveParser(parser); //createSerialisation successful } /* end of createSerialisation */ } /*end of class*/
b93de3d/mantine-fork
src/mantine-demos/esm/demos/modals/multipleSteps.js
import React from 'react'; import { Group, Button, Text } from '@mantine/core'; import { useModals } from '@mantine/modals'; const code = ` import { Button, Text } from '@mantine/core'; import { useModals } from '@mantine/modals'; function Demo() { const modals = useModals(); const openMultiStepModal = () => modals.openConfirmModal({ title: 'Please confirm your action', closeOnConfirm: false, labels: { confirm: 'Next modal', cancel: 'Close modal' }, children: ( <Text size="sm"> This action is so important that you are required to confirm it with a modal. Please click one of these buttons to proceed. </Text> ), onConfirm: () => modals.openConfirmModal({ title: 'This is modal at second layer', labels: { confirm: 'Close modal', cancel: 'Back' }, closeOnConfirm: false, children: ( <Text size="sm">When this modal is closed modals state will revert to first modal</Text> ), onConfirm: () => modals.closeAll(), }), }); return <Button onClick={openMultiStepModal}>Open multiple steps modal</Button>; } `; function Demo() { const modals = useModals(); const openMultiStepModal = () => modals.openConfirmModal({ title: "Please confirm your action", closeOnConfirm: false, labels: { confirm: "Next modal", cancel: "Close modal" }, children: /* @__PURE__ */ React.createElement(Text, { size: "sm" }, "This action is so important that you are required to confirm it with a modal. Please click one of these buttons to proceed."), onConfirm: () => modals.openConfirmModal({ title: "This is modal at second layer", labels: { confirm: "Close modal", cancel: "Back" }, closeOnConfirm: false, children: /* @__PURE__ */ React.createElement(Text, { size: "sm" }, "When this modal is closed modals state will revert to first modal"), onConfirm: () => modals.closeAll() }) }); return /* @__PURE__ */ React.createElement(Group, { position: "center" }, /* @__PURE__ */ React.createElement(Button, { onClick: openMultiStepModal }, "Open multiple steps modal")); } const multipleSteps = { type: "demo", component: Demo, code }; export { multipleSteps }; //# sourceMappingURL=multipleSteps.js.map
super468/leetcode
java/src/PalindromePartitioning.java
<filename>java/src/PalindromePartitioning.java<gh_stars>0 import java.util.ArrayList; import java.util.List; /** * Creator : wts * Date : 7/2/18 * Title : 131. Palindrome Partitioning * Description : * Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. Example: Input: "aab" Output: [ ["aa","b"], ["a","a","b"] ] * Analysis : * * */ public class PalindromePartitioning { List<List<String>> list = new ArrayList<>(); List<String> row = new ArrayList<>(); public List<List<String>> partition(String s) { if(s.equals("")) { list.add(row); return list; } // if(s.length() == 1){ // row.add(s); // list.add(row); // return list; // } helper(s, row); return list; } public void helper(String s, List<String> row){ if(s.length() == 0){ list.add(new ArrayList<>(row)); return; } for(int i = 0; i < s.length(); i++){ if(ispalindrome(s.substring(0,i + 1))){ row.add(s.substring(0,i + 1)); helper(s.substring(i + 1), row); row.remove(row.size() - 1); } } } public boolean ispalindrome(String s){ for(int i = 0; i < s.length() / 2; i++){ if(s.charAt(i) != s.charAt(s.length() - 1 - i)){ return false; } } return true; } }
thinkerou/blb
internal/testblb/test_pack_failure.go
// Copyright (c) 2017 Western Digital Corporation or its affiliates. All rights reserved. // SPDX-License-Identifier: MIT package testblb import ( "fmt" "github.com/westerndigitalcorporation/blb/internal/core" ) // TestPackFailure tests that PackTracts fails if sources are corrupted. func (tc *TestCase) TestPackFailure() error { // Create a bunch of blobs with data. _, ts1, d1 := createAndFill1(tc, 3, 100000) _, ts2, d2 := createAndFill1(tc, 3, 20000) _, ts3, d3 := createAndFill1(tc, 3, 70000) // Corrupt all copies of the second blob. tc.corruptTract(ts2[0].Tract, tc.bc.FindByServiceAddress(ts2[0].Hosts[0]), 123) tc.corruptTract(ts2[0].Tract, tc.bc.FindByServiceAddress(ts2[0].Hosts[1]), 456) tc.corruptTract(ts2[0].Tract, tc.bc.FindByServiceAddress(ts2[0].Hosts[2]), 789) // Pick a tractserver and pack. t0 := tc.bc.Tractservers()[0].ServiceAddr() err := packTracts(t0, core.PackTractsReq{ Length: 200000, ChunkID: core.RSChunkID{Partition: 0x80000555, ID: 5555}, Tracts: []*core.PackTractSpec{ {ID: ts1[0].Tract, From: tiToAddrs(ts1[0]), Version: ts1[0].Version, Offset: 0, Length: len(d1)}, {ID: ts2[0].Tract, From: tiToAddrs(ts2[0]), Version: ts2[0].Version, Offset: len(d1), Length: len(d2)}, {ID: ts3[0].Tract, From: tiToAddrs(ts3[0]), Version: ts3[0].Version, Offset: len(d1) + len(d2), Length: len(d3)}, }, }) if err != core.ErrRPC { return fmt.Errorf("PackTracts should have failed") } return nil }
libogonek/ogonek
include/ogonek/error/replace_errors.h++
// Ogonek // // Written in 2012-2013 by <NAME> <<EMAIL>> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // Error handler that uses a replacement character #ifndef OGONEK_ERROR_REPLACE_ERRORS_HPP #define OGONEK_ERROR_REPLACE_ERRORS_HPP #include <ogonek/error/error_handler.h++> #include <ogonek/error/assume_valid.h++> #include <ogonek/types.h++> #include <ogonek/encoding/traits.h++> #include <wheels/meta.h++> #include <boost/range/sub_range.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <iterator> #include <type_traits> #include <tuple> namespace ogonek { //! {callable} //! Error handler that replaces invalid data with a replacement character struct replace_errors_t : error_handler { template <typename Sequence, typename EncodingForm> decode_correction<Sequence, EncodingForm> handle(decode_error<Sequence, EncodingForm> const& error) const { return std::make_tuple(error.source, error.state, U'\xFFFD'); } template <typename Sequence, typename EncodingForm> encode_correction<Sequence, EncodingForm> handle(encode_error<Sequence, EncodingForm> const& error) const { auto state = error.state; auto replacement = EncodingForm::encode_one(replacement_character<EncodingForm>(), state, assume_valid); return std::make_tuple(error.source, state, replacement); } template <typename EncodingForm, typename Range> static boost::sub_range<Range> apply_decode(boost::sub_range<Range> const& source, EncodingState<EncodingForm>&, code_point& out) { out = U'\xFFFD'; return { std::next(boost::begin(source)), boost::end(source) }; } template <typename EncodingForm> static detail::encoded_character<EncodingForm> apply_encode(code_point, EncodingState<EncodingForm>& s) { return EncodingForm::encode_one(replacement_character<EncodingForm>(), s, assume_valid); } }; //! {object} //! A default instance of [function:replace_errors_t]. constexpr replace_errors_t replace_errors = {}; } // namespace ogonek #endif // OGONEK_ERROR_REPLACE_ERRORS_HPP
Wolfmarsh/mpf
mpf/tests/test_StepStick.py
import asyncio from mpf.tests.MpfTestCase import MpfTestCase, MagicMock, patch class TestStepStick(MpfTestCase): def get_config_file(self): return 'config.yaml' def get_machine_path(self): return 'tests/machine_files/step_stick/' def get_platform(self): # no force platform. we are testing step stick return False def test_step_stick(self): direction = self.machine.digital_outputs["c_direction"].hw_driver step_enable = self.machine.digital_outputs["c_step"].hw_driver.enable = MagicMock() step_disable = self.machine.digital_outputs["c_step"].hw_driver.disable = MagicMock() enable = self.machine.digital_outputs["c_enable"].hw_driver self.assertEqual("enabled", direction.state) self.assertEqual("enabled", enable.state) self.advance_time_and_run(1) self.assertEqual(25, step_enable.call_count) self.assertEqual(25, step_disable.call_count) self.hit_switch_and_run("s_home", .1) step_enable = self.machine.digital_outputs["c_step"].hw_driver.enable = MagicMock() step_disable = self.machine.digital_outputs["c_step"].hw_driver.disable = MagicMock() self.advance_time_and_run(1) self.assertEqual(0, step_enable.call_count) self.assertEqual(0, step_disable.call_count) self.post_event("test_01") self.advance_time_and_run(1) self.assertEqual("enabled", direction.state) self.assertEqual(20, step_enable.call_count) self.assertEqual(20, step_disable.call_count) step_enable = self.machine.digital_outputs["c_step"].hw_driver.enable = MagicMock() step_disable = self.machine.digital_outputs["c_step"].hw_driver.disable = MagicMock() self.post_event("test_00") self.advance_time_and_run(1) self.assertEqual("disabled", direction.state) self.assertEqual(10, step_enable.call_count) self.assertEqual(10, step_disable.call_count) step_enable = self.machine.digital_outputs["c_step"].hw_driver.enable = MagicMock() step_disable = self.machine.digital_outputs["c_step"].hw_driver.disable = MagicMock() self.post_event("test_10") self.advance_time_and_run(2) self.assertEqual("enabled", direction.state) self.assertEqual(40, step_enable.call_count) self.assertEqual(40, step_disable.call_count)
Jgorsick/Advocacy_Angular
openstates/openstates-master/openstates/de/__init__.py
import lxml.html from billy.scrape.utils import url_xpath from .bills import DEBillScraper from .legislators import DELegislatorScraper from .committees import DECommitteeScraper from .events import DEEventScraper import logging logging.basicConfig(level=logging.DEBUG) metadata = { 'name': 'Delaware', 'abbreviation': 'de', 'legislature_name': 'Delaware General Assembly', 'legislature_url': 'http://legis.delaware.gov/', 'capitol_timezone': 'America/New_York', 'chambers': { 'upper': {'name': 'Senate', 'title': 'Senator'}, 'lower': {'name': 'House', 'title': 'Representative'}, }, 'terms': [ { 'name': '2011-2012', 'start_year': 2011, 'end_year': 2012, 'sessions': ['146'], }, { 'name': '2013-2014', 'start_year': 2013, 'end_year': 2014, 'sessions': ['147'], }, { 'name': '2015-2016', 'start_year': 2015, 'end_year': 2016, 'sessions': ['148'], }, ], 'session_details': { '146': { 'display_name': '146th General Assembly (2011-2012)', '_scraped_name': 'GA 146', }, '147': { 'display_name': '147th General Assembly (2013-2014)', '_scraped_name': 'GA 147', }, '148': { 'display_name': '148th General Assembly (2015-2016)', '_scraped_name': 'GA 148', }, }, 'feature_flags': ['events', 'influenceexplorer'], '_ignored_scraped_sessions': [ 'GA 145', 'GA 144', 'GA 143', 'GA 142', 'GA 141', 'GA 140', 'GA 139', 'GA 138', ], } def session_list(): url = 'http://legis.delaware.gov/Legislature.nsf/7CD69CCAB66992B285256EE0'\ '005E0727/78346509610C835385257F2B004F2590?OpenDocument' sessions = url_xpath(url, '//select[@name="gSession"]/option/text()') sessions = [session.strip() for session in sessions if session.strip()] return sessions def extract_text(doc, data): if doc['mimetype'] == 'text/html': doc = lxml.html.fromstring(data) return ' '.join(x.text_content() for x in doc.xpath('//p[@class: "MsoNormal"]'))
jaslou/flink-project
user-behavior-analysis/src/main/java/com/jaslou/logAnalysis/domain/LogViewCount.java
<filename>user-behavior-analysis/src/main/java/com/jaslou/logAnalysis/domain/LogViewCount.java package com.jaslou.logAnalysis.domain; public class LogViewCount { public String accessURL; public long windowEnd; public long viewCount; public LogViewCount(String accessURL, long windowEnd, long viewCount) { this.accessURL = accessURL; this.windowEnd = windowEnd; this.viewCount = viewCount; } public String getAccessURL() { return accessURL; } public void setAccessURL(String accessURL) { this.accessURL = accessURL; } public long getWindowEnd() { return windowEnd; } public void setWindowEnd(long windowEnd) { this.windowEnd = windowEnd; } public long getViewCount() { return viewCount; } public void setViewCount(long viewCount) { this.viewCount = viewCount; } }
gabrielferreiraa/showmethecode-web
src/components/Button/index.js
import React from "react" import styled from "styled-components" import { darken } from "polished" import PropTypes from "prop-types" import global from "config/global" const StyledButton = styled.button` background-color: ${global.colors.primaryColor}; border-radius: ${global.layout.borderRadius}; color: #fff; outline: none; border: 2px solid ${global.colors.primaryColor}; cursor: pointer; padding: 0 30px; transition: background-color 200ms ease; font-size: 1.1em; display: flex; align-items: center; justify-content: center; height: 50px; &:hover { background-color: ${darken(0.05, global.colors.primaryColor)}; } ` export default function Button({ children, onClick, ...rest }) { return ( <StyledButton onClick={onClick} {...rest}> {children} </StyledButton> ) } Button.defaultProps = { onClick: () => {}, } Button.propTypes = { children: PropTypes.node.isRequired, onClick: PropTypes.func, }
DanielLaborda/proyecto
src/components/pages/users.js
<reponame>DanielLaborda/proyecto import React, { Component } from "react"; import Register from "../users/register"; import Login from "../users/login"; class Users extends Component { constructor(props) { super(props); this.state = { show: "Login" }; this.showLogin = this.showLogin.bind(this); this.showRegister = this.showRegister.bind(this); this.handleSuccessfulLogin = this.handleSuccessfulLogin.bind(this); this.handleUnsuccessfulLogin = this.handleSuccessfulLogin.bind(this); } showLogin() { this.setState({ show: "Login" }); } showRegister() { this.setState({ show: "register" }); } handleSuccessfulLogin() { this.props.handleSuccessfulLogin(); } handleUnsuccessfulLogin() { this.props.handleUnsuccessfulLogin(); } render() { return ( <div className='users'> <ul> <li onClick={this.showLogin}>Login in</li> <li onClick={this.showRegister}>register</li> </ul> {(this.state.show === 'Login') ? <Login handleSuccessfulLogin={this.handleSuccessfulLogin} handleUnsuccessfulLogin={this.handleUnsuccessfulLogin}/> : <Register /> } </div> ); } } export default Users;
tinours/PCSim2
src/gov/nist/javax/sip/header/ProxyAuthorizationList.java
<reponame>tinours/PCSim2 /******************************************************************************* * Product of NIST/ITL Advanced Networking Technologies Division (ANTD). * *******************************************************************************/ package gov.nist.javax.sip.header; import javax.sip.header.*; /** * List of ProxyAuthorization headers. * @version JAIN-SIP-1.1 $Revision: 1.1 $ $Date: 2005/02/24 15:52:21 $ * * @author <NAME> <<EMAIL>> <br/> * * <a href="{@docRoot}/uncopyright.html">This code is in the public domain.</a> * */ public class ProxyAuthorizationList extends SIPHeaderList { private static final long serialVersionUID = 1L; /** Default constructor */ public ProxyAuthorizationList() { super(ProxyAuthorization.class, ProxyAuthorizationHeader.NAME); } }
Bloombox/Java
src/main/java/io/bloombox/schema/telemetry/stats/SessionTelemetry.java
/* * Copyright 2019, Momentum Ideas, Co. All rights reserved. * * Source and object computer code contained herein is the private intellectual * property of Momentum Ideas Co., a Delaware Corporation. Use of this * code in source form requires permission in writing before use or the * assembly, distribution, or publishing of derivative works, for commercial * purposes or any other purpose, from a duly authorized officer of Momentum * Ideas Co. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: analytics/stats/SessionStats.proto package io.bloombox.schema.telemetry.stats; public final class SessionTelemetry { private SessionTelemetry() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } public interface SessionStatsOrBuilder extends // @@protoc_insertion_point(interface_extends:bloombox.analytics.stats.SessionStats) com.google.protobuf.MessageOrBuilder { /** * <pre> * Original ID of the session. * </pre> * * <code>string sid = 1 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Original ID of the session."];</code> */ java.lang.String getSid(); /** * <pre> * Original ID of the session. * </pre> * * <code>string sid = 1 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Original ID of the session."];</code> */ com.google.protobuf.ByteString getSidBytes(); /** * <pre> * Partner scope seen as associated with this session. * </pre> * * <code>string partner_scope = 2 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Partner scope seen as associated with this session."];</code> */ java.lang.String getPartnerScope(); /** * <pre> * Partner scope seen as associated with this session. * </pre> * * <code>string partner_scope = 2 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Partner scope seen as associated with this session."];</code> */ com.google.protobuf.ByteString getPartnerScopeBytes(); /** * <pre> * Count of total events seen in this session. * </pre> * * <code>uint32 event_count = 3 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Count of total events seen in this session."];</code> */ int getEventCount(); /** * <pre> * Timestamp representing the first event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant begin = 4 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the first event seen in this session."];</code> */ boolean hasBegin(); /** * <pre> * Timestamp representing the first event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant begin = 4 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the first event seen in this session."];</code> */ io.opencannabis.schema.temporal.TemporalInstant.Instant getBegin(); /** * <pre> * Timestamp representing the first event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant begin = 4 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the first event seen in this session."];</code> */ io.opencannabis.schema.temporal.TemporalInstant.InstantOrBuilder getBeginOrBuilder(); /** * <pre> * Timestamp representing the last event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant end = 5 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the last event seen in this session."];</code> */ boolean hasEnd(); /** * <pre> * Timestamp representing the last event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant end = 5 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the last event seen in this session."];</code> */ io.opencannabis.schema.temporal.TemporalInstant.Instant getEnd(); /** * <pre> * Timestamp representing the last event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant end = 5 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the last event seen in this session."];</code> */ io.opencannabis.schema.temporal.TemporalInstant.InstantOrBuilder getEndOrBuilder(); /** * <pre> * Device ID seen as associated with this session. * </pre> * * <code>string device_id = 6 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Device ID seen as associated with this session."];</code> */ java.lang.String getDeviceId(); /** * <pre> * Device ID seen as associated with this session. * </pre> * * <code>string device_id = 6 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Device ID seen as associated with this session."];</code> */ com.google.protobuf.ByteString getDeviceIdBytes(); /** * <pre> * User ID seen as associated with this session. * </pre> * * <code>string user_id = 7 [(.gen_bq_schema.description) = "User ID seen as associated with this session."];</code> */ java.lang.String getUserId(); /** * <pre> * User ID seen as associated with this session. * </pre> * * <code>string user_id = 7 [(.gen_bq_schema.description) = "User ID seen as associated with this session."];</code> */ com.google.protobuf.ByteString getUserIdBytes(); } /** * <pre> * Specifies a set of basic calculated statistics, computed at the level of an entire user session. * </pre> * * Protobuf type {@code bloombox.analytics.stats.SessionStats} */ public static final class SessionStats extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:bloombox.analytics.stats.SessionStats) SessionStatsOrBuilder { private static final long serialVersionUID = 0L; // Use SessionStats.newBuilder() to construct. private SessionStats(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SessionStats() { sid_ = ""; partnerScope_ = ""; deviceId_ = ""; userId_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private SessionStats( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); sid_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); partnerScope_ = s; break; } case 24: { eventCount_ = input.readUInt32(); break; } case 34: { io.opencannabis.schema.temporal.TemporalInstant.Instant.Builder subBuilder = null; if (begin_ != null) { subBuilder = begin_.toBuilder(); } begin_ = input.readMessage(io.opencannabis.schema.temporal.TemporalInstant.Instant.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(begin_); begin_ = subBuilder.buildPartial(); } break; } case 42: { io.opencannabis.schema.temporal.TemporalInstant.Instant.Builder subBuilder = null; if (end_ != null) { subBuilder = end_.toBuilder(); } end_ = input.readMessage(io.opencannabis.schema.temporal.TemporalInstant.Instant.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(end_); end_ = subBuilder.buildPartial(); } break; } case 50: { java.lang.String s = input.readStringRequireUtf8(); deviceId_ = s; break; } case 58: { java.lang.String s = input.readStringRequireUtf8(); userId_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.bloombox.schema.telemetry.stats.SessionTelemetry.internal_static_bloombox_analytics_stats_SessionStats_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return io.bloombox.schema.telemetry.stats.SessionTelemetry.internal_static_bloombox_analytics_stats_SessionStats_fieldAccessorTable .ensureFieldAccessorsInitialized( io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats.class, io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats.Builder.class); } public static final int SID_FIELD_NUMBER = 1; private volatile java.lang.Object sid_; /** * <pre> * Original ID of the session. * </pre> * * <code>string sid = 1 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Original ID of the session."];</code> */ public java.lang.String getSid() { java.lang.Object ref = sid_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sid_ = s; return s; } } /** * <pre> * Original ID of the session. * </pre> * * <code>string sid = 1 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Original ID of the session."];</code> */ public com.google.protobuf.ByteString getSidBytes() { java.lang.Object ref = sid_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sid_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PARTNER_SCOPE_FIELD_NUMBER = 2; private volatile java.lang.Object partnerScope_; /** * <pre> * Partner scope seen as associated with this session. * </pre> * * <code>string partner_scope = 2 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Partner scope seen as associated with this session."];</code> */ public java.lang.String getPartnerScope() { java.lang.Object ref = partnerScope_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); partnerScope_ = s; return s; } } /** * <pre> * Partner scope seen as associated with this session. * </pre> * * <code>string partner_scope = 2 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Partner scope seen as associated with this session."];</code> */ public com.google.protobuf.ByteString getPartnerScopeBytes() { java.lang.Object ref = partnerScope_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); partnerScope_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int EVENT_COUNT_FIELD_NUMBER = 3; private int eventCount_; /** * <pre> * Count of total events seen in this session. * </pre> * * <code>uint32 event_count = 3 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Count of total events seen in this session."];</code> */ public int getEventCount() { return eventCount_; } public static final int BEGIN_FIELD_NUMBER = 4; private io.opencannabis.schema.temporal.TemporalInstant.Instant begin_; /** * <pre> * Timestamp representing the first event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant begin = 4 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the first event seen in this session."];</code> */ public boolean hasBegin() { return begin_ != null; } /** * <pre> * Timestamp representing the first event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant begin = 4 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the first event seen in this session."];</code> */ public io.opencannabis.schema.temporal.TemporalInstant.Instant getBegin() { return begin_ == null ? io.opencannabis.schema.temporal.TemporalInstant.Instant.getDefaultInstance() : begin_; } /** * <pre> * Timestamp representing the first event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant begin = 4 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the first event seen in this session."];</code> */ public io.opencannabis.schema.temporal.TemporalInstant.InstantOrBuilder getBeginOrBuilder() { return getBegin(); } public static final int END_FIELD_NUMBER = 5; private io.opencannabis.schema.temporal.TemporalInstant.Instant end_; /** * <pre> * Timestamp representing the last event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant end = 5 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the last event seen in this session."];</code> */ public boolean hasEnd() { return end_ != null; } /** * <pre> * Timestamp representing the last event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant end = 5 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the last event seen in this session."];</code> */ public io.opencannabis.schema.temporal.TemporalInstant.Instant getEnd() { return end_ == null ? io.opencannabis.schema.temporal.TemporalInstant.Instant.getDefaultInstance() : end_; } /** * <pre> * Timestamp representing the last event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant end = 5 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the last event seen in this session."];</code> */ public io.opencannabis.schema.temporal.TemporalInstant.InstantOrBuilder getEndOrBuilder() { return getEnd(); } public static final int DEVICE_ID_FIELD_NUMBER = 6; private volatile java.lang.Object deviceId_; /** * <pre> * Device ID seen as associated with this session. * </pre> * * <code>string device_id = 6 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Device ID seen as associated with this session."];</code> */ public java.lang.String getDeviceId() { java.lang.Object ref = deviceId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); deviceId_ = s; return s; } } /** * <pre> * Device ID seen as associated with this session. * </pre> * * <code>string device_id = 6 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Device ID seen as associated with this session."];</code> */ public com.google.protobuf.ByteString getDeviceIdBytes() { java.lang.Object ref = deviceId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); deviceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int USER_ID_FIELD_NUMBER = 7; private volatile java.lang.Object userId_; /** * <pre> * User ID seen as associated with this session. * </pre> * * <code>string user_id = 7 [(.gen_bq_schema.description) = "User ID seen as associated with this session."];</code> */ public java.lang.String getUserId() { java.lang.Object ref = userId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); userId_ = s; return s; } } /** * <pre> * User ID seen as associated with this session. * </pre> * * <code>string user_id = 7 [(.gen_bq_schema.description) = "User ID seen as associated with this session."];</code> */ public com.google.protobuf.ByteString getUserIdBytes() { java.lang.Object ref = userId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); userId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getSidBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, sid_); } if (!getPartnerScopeBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, partnerScope_); } if (eventCount_ != 0) { output.writeUInt32(3, eventCount_); } if (begin_ != null) { output.writeMessage(4, getBegin()); } if (end_ != null) { output.writeMessage(5, getEnd()); } if (!getDeviceIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 6, deviceId_); } if (!getUserIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 7, userId_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getSidBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, sid_); } if (!getPartnerScopeBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, partnerScope_); } if (eventCount_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(3, eventCount_); } if (begin_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, getBegin()); } if (end_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(5, getEnd()); } if (!getDeviceIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, deviceId_); } if (!getUserIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(7, userId_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats)) { return super.equals(obj); } io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats other = (io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats) obj; if (!getSid() .equals(other.getSid())) return false; if (!getPartnerScope() .equals(other.getPartnerScope())) return false; if (getEventCount() != other.getEventCount()) return false; if (hasBegin() != other.hasBegin()) return false; if (hasBegin()) { if (!getBegin() .equals(other.getBegin())) return false; } if (hasEnd() != other.hasEnd()) return false; if (hasEnd()) { if (!getEnd() .equals(other.getEnd())) return false; } if (!getDeviceId() .equals(other.getDeviceId())) return false; if (!getUserId() .equals(other.getUserId())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SID_FIELD_NUMBER; hash = (53 * hash) + getSid().hashCode(); hash = (37 * hash) + PARTNER_SCOPE_FIELD_NUMBER; hash = (53 * hash) + getPartnerScope().hashCode(); hash = (37 * hash) + EVENT_COUNT_FIELD_NUMBER; hash = (53 * hash) + getEventCount(); if (hasBegin()) { hash = (37 * hash) + BEGIN_FIELD_NUMBER; hash = (53 * hash) + getBegin().hashCode(); } if (hasEnd()) { hash = (37 * hash) + END_FIELD_NUMBER; hash = (53 * hash) + getEnd().hashCode(); } hash = (37 * hash) + DEVICE_ID_FIELD_NUMBER; hash = (53 * hash) + getDeviceId().hashCode(); hash = (37 * hash) + USER_ID_FIELD_NUMBER; hash = (53 * hash) + getUserId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Specifies a set of basic calculated statistics, computed at the level of an entire user session. * </pre> * * Protobuf type {@code bloombox.analytics.stats.SessionStats} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:bloombox.analytics.stats.SessionStats) io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStatsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.bloombox.schema.telemetry.stats.SessionTelemetry.internal_static_bloombox_analytics_stats_SessionStats_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return io.bloombox.schema.telemetry.stats.SessionTelemetry.internal_static_bloombox_analytics_stats_SessionStats_fieldAccessorTable .ensureFieldAccessorsInitialized( io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats.class, io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats.Builder.class); } // Construct using io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); sid_ = ""; partnerScope_ = ""; eventCount_ = 0; if (beginBuilder_ == null) { begin_ = null; } else { begin_ = null; beginBuilder_ = null; } if (endBuilder_ == null) { end_ = null; } else { end_ = null; endBuilder_ = null; } deviceId_ = ""; userId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return io.bloombox.schema.telemetry.stats.SessionTelemetry.internal_static_bloombox_analytics_stats_SessionStats_descriptor; } @java.lang.Override public io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats getDefaultInstanceForType() { return io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats.getDefaultInstance(); } @java.lang.Override public io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats build() { io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats buildPartial() { io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats result = new io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats(this); result.sid_ = sid_; result.partnerScope_ = partnerScope_; result.eventCount_ = eventCount_; if (beginBuilder_ == null) { result.begin_ = begin_; } else { result.begin_ = beginBuilder_.build(); } if (endBuilder_ == null) { result.end_ = end_; } else { result.end_ = endBuilder_.build(); } result.deviceId_ = deviceId_; result.userId_ = userId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats) { return mergeFrom((io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats other) { if (other == io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats.getDefaultInstance()) return this; if (!other.getSid().isEmpty()) { sid_ = other.sid_; onChanged(); } if (!other.getPartnerScope().isEmpty()) { partnerScope_ = other.partnerScope_; onChanged(); } if (other.getEventCount() != 0) { setEventCount(other.getEventCount()); } if (other.hasBegin()) { mergeBegin(other.getBegin()); } if (other.hasEnd()) { mergeEnd(other.getEnd()); } if (!other.getDeviceId().isEmpty()) { deviceId_ = other.deviceId_; onChanged(); } if (!other.getUserId().isEmpty()) { userId_ = other.userId_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object sid_ = ""; /** * <pre> * Original ID of the session. * </pre> * * <code>string sid = 1 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Original ID of the session."];</code> */ public java.lang.String getSid() { java.lang.Object ref = sid_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sid_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Original ID of the session. * </pre> * * <code>string sid = 1 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Original ID of the session."];</code> */ public com.google.protobuf.ByteString getSidBytes() { java.lang.Object ref = sid_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sid_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Original ID of the session. * </pre> * * <code>string sid = 1 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Original ID of the session."];</code> */ public Builder setSid( java.lang.String value) { if (value == null) { throw new NullPointerException(); } sid_ = value; onChanged(); return this; } /** * <pre> * Original ID of the session. * </pre> * * <code>string sid = 1 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Original ID of the session."];</code> */ public Builder clearSid() { sid_ = getDefaultInstance().getSid(); onChanged(); return this; } /** * <pre> * Original ID of the session. * </pre> * * <code>string sid = 1 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Original ID of the session."];</code> */ public Builder setSidBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); sid_ = value; onChanged(); return this; } private java.lang.Object partnerScope_ = ""; /** * <pre> * Partner scope seen as associated with this session. * </pre> * * <code>string partner_scope = 2 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Partner scope seen as associated with this session."];</code> */ public java.lang.String getPartnerScope() { java.lang.Object ref = partnerScope_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); partnerScope_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Partner scope seen as associated with this session. * </pre> * * <code>string partner_scope = 2 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Partner scope seen as associated with this session."];</code> */ public com.google.protobuf.ByteString getPartnerScopeBytes() { java.lang.Object ref = partnerScope_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); partnerScope_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Partner scope seen as associated with this session. * </pre> * * <code>string partner_scope = 2 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Partner scope seen as associated with this session."];</code> */ public Builder setPartnerScope( java.lang.String value) { if (value == null) { throw new NullPointerException(); } partnerScope_ = value; onChanged(); return this; } /** * <pre> * Partner scope seen as associated with this session. * </pre> * * <code>string partner_scope = 2 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Partner scope seen as associated with this session."];</code> */ public Builder clearPartnerScope() { partnerScope_ = getDefaultInstance().getPartnerScope(); onChanged(); return this; } /** * <pre> * Partner scope seen as associated with this session. * </pre> * * <code>string partner_scope = 2 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Partner scope seen as associated with this session."];</code> */ public Builder setPartnerScopeBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); partnerScope_ = value; onChanged(); return this; } private int eventCount_ ; /** * <pre> * Count of total events seen in this session. * </pre> * * <code>uint32 event_count = 3 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Count of total events seen in this session."];</code> */ public int getEventCount() { return eventCount_; } /** * <pre> * Count of total events seen in this session. * </pre> * * <code>uint32 event_count = 3 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Count of total events seen in this session."];</code> */ public Builder setEventCount(int value) { eventCount_ = value; onChanged(); return this; } /** * <pre> * Count of total events seen in this session. * </pre> * * <code>uint32 event_count = 3 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Count of total events seen in this session."];</code> */ public Builder clearEventCount() { eventCount_ = 0; onChanged(); return this; } private io.opencannabis.schema.temporal.TemporalInstant.Instant begin_; private com.google.protobuf.SingleFieldBuilderV3< io.opencannabis.schema.temporal.TemporalInstant.Instant, io.opencannabis.schema.temporal.TemporalInstant.Instant.Builder, io.opencannabis.schema.temporal.TemporalInstant.InstantOrBuilder> beginBuilder_; /** * <pre> * Timestamp representing the first event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant begin = 4 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the first event seen in this session."];</code> */ public boolean hasBegin() { return beginBuilder_ != null || begin_ != null; } /** * <pre> * Timestamp representing the first event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant begin = 4 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the first event seen in this session."];</code> */ public io.opencannabis.schema.temporal.TemporalInstant.Instant getBegin() { if (beginBuilder_ == null) { return begin_ == null ? io.opencannabis.schema.temporal.TemporalInstant.Instant.getDefaultInstance() : begin_; } else { return beginBuilder_.getMessage(); } } /** * <pre> * Timestamp representing the first event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant begin = 4 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the first event seen in this session."];</code> */ public Builder setBegin(io.opencannabis.schema.temporal.TemporalInstant.Instant value) { if (beginBuilder_ == null) { if (value == null) { throw new NullPointerException(); } begin_ = value; onChanged(); } else { beginBuilder_.setMessage(value); } return this; } /** * <pre> * Timestamp representing the first event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant begin = 4 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the first event seen in this session."];</code> */ public Builder setBegin( io.opencannabis.schema.temporal.TemporalInstant.Instant.Builder builderForValue) { if (beginBuilder_ == null) { begin_ = builderForValue.build(); onChanged(); } else { beginBuilder_.setMessage(builderForValue.build()); } return this; } /** * <pre> * Timestamp representing the first event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant begin = 4 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the first event seen in this session."];</code> */ public Builder mergeBegin(io.opencannabis.schema.temporal.TemporalInstant.Instant value) { if (beginBuilder_ == null) { if (begin_ != null) { begin_ = io.opencannabis.schema.temporal.TemporalInstant.Instant.newBuilder(begin_).mergeFrom(value).buildPartial(); } else { begin_ = value; } onChanged(); } else { beginBuilder_.mergeFrom(value); } return this; } /** * <pre> * Timestamp representing the first event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant begin = 4 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the first event seen in this session."];</code> */ public Builder clearBegin() { if (beginBuilder_ == null) { begin_ = null; onChanged(); } else { begin_ = null; beginBuilder_ = null; } return this; } /** * <pre> * Timestamp representing the first event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant begin = 4 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the first event seen in this session."];</code> */ public io.opencannabis.schema.temporal.TemporalInstant.Instant.Builder getBeginBuilder() { onChanged(); return getBeginFieldBuilder().getBuilder(); } /** * <pre> * Timestamp representing the first event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant begin = 4 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the first event seen in this session."];</code> */ public io.opencannabis.schema.temporal.TemporalInstant.InstantOrBuilder getBeginOrBuilder() { if (beginBuilder_ != null) { return beginBuilder_.getMessageOrBuilder(); } else { return begin_ == null ? io.opencannabis.schema.temporal.TemporalInstant.Instant.getDefaultInstance() : begin_; } } /** * <pre> * Timestamp representing the first event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant begin = 4 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the first event seen in this session."];</code> */ private com.google.protobuf.SingleFieldBuilderV3< io.opencannabis.schema.temporal.TemporalInstant.Instant, io.opencannabis.schema.temporal.TemporalInstant.Instant.Builder, io.opencannabis.schema.temporal.TemporalInstant.InstantOrBuilder> getBeginFieldBuilder() { if (beginBuilder_ == null) { beginBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< io.opencannabis.schema.temporal.TemporalInstant.Instant, io.opencannabis.schema.temporal.TemporalInstant.Instant.Builder, io.opencannabis.schema.temporal.TemporalInstant.InstantOrBuilder>( getBegin(), getParentForChildren(), isClean()); begin_ = null; } return beginBuilder_; } private io.opencannabis.schema.temporal.TemporalInstant.Instant end_; private com.google.protobuf.SingleFieldBuilderV3< io.opencannabis.schema.temporal.TemporalInstant.Instant, io.opencannabis.schema.temporal.TemporalInstant.Instant.Builder, io.opencannabis.schema.temporal.TemporalInstant.InstantOrBuilder> endBuilder_; /** * <pre> * Timestamp representing the last event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant end = 5 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the last event seen in this session."];</code> */ public boolean hasEnd() { return endBuilder_ != null || end_ != null; } /** * <pre> * Timestamp representing the last event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant end = 5 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the last event seen in this session."];</code> */ public io.opencannabis.schema.temporal.TemporalInstant.Instant getEnd() { if (endBuilder_ == null) { return end_ == null ? io.opencannabis.schema.temporal.TemporalInstant.Instant.getDefaultInstance() : end_; } else { return endBuilder_.getMessage(); } } /** * <pre> * Timestamp representing the last event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant end = 5 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the last event seen in this session."];</code> */ public Builder setEnd(io.opencannabis.schema.temporal.TemporalInstant.Instant value) { if (endBuilder_ == null) { if (value == null) { throw new NullPointerException(); } end_ = value; onChanged(); } else { endBuilder_.setMessage(value); } return this; } /** * <pre> * Timestamp representing the last event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant end = 5 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the last event seen in this session."];</code> */ public Builder setEnd( io.opencannabis.schema.temporal.TemporalInstant.Instant.Builder builderForValue) { if (endBuilder_ == null) { end_ = builderForValue.build(); onChanged(); } else { endBuilder_.setMessage(builderForValue.build()); } return this; } /** * <pre> * Timestamp representing the last event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant end = 5 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the last event seen in this session."];</code> */ public Builder mergeEnd(io.opencannabis.schema.temporal.TemporalInstant.Instant value) { if (endBuilder_ == null) { if (end_ != null) { end_ = io.opencannabis.schema.temporal.TemporalInstant.Instant.newBuilder(end_).mergeFrom(value).buildPartial(); } else { end_ = value; } onChanged(); } else { endBuilder_.mergeFrom(value); } return this; } /** * <pre> * Timestamp representing the last event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant end = 5 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the last event seen in this session."];</code> */ public Builder clearEnd() { if (endBuilder_ == null) { end_ = null; onChanged(); } else { end_ = null; endBuilder_ = null; } return this; } /** * <pre> * Timestamp representing the last event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant end = 5 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the last event seen in this session."];</code> */ public io.opencannabis.schema.temporal.TemporalInstant.Instant.Builder getEndBuilder() { onChanged(); return getEndFieldBuilder().getBuilder(); } /** * <pre> * Timestamp representing the last event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant end = 5 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the last event seen in this session."];</code> */ public io.opencannabis.schema.temporal.TemporalInstant.InstantOrBuilder getEndOrBuilder() { if (endBuilder_ != null) { return endBuilder_.getMessageOrBuilder(); } else { return end_ == null ? io.opencannabis.schema.temporal.TemporalInstant.Instant.getDefaultInstance() : end_; } } /** * <pre> * Timestamp representing the last event seen in this session. * </pre> * * <code>.opencannabis.temporal.Instant end = 5 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Timestamp representing the last event seen in this session."];</code> */ private com.google.protobuf.SingleFieldBuilderV3< io.opencannabis.schema.temporal.TemporalInstant.Instant, io.opencannabis.schema.temporal.TemporalInstant.Instant.Builder, io.opencannabis.schema.temporal.TemporalInstant.InstantOrBuilder> getEndFieldBuilder() { if (endBuilder_ == null) { endBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< io.opencannabis.schema.temporal.TemporalInstant.Instant, io.opencannabis.schema.temporal.TemporalInstant.Instant.Builder, io.opencannabis.schema.temporal.TemporalInstant.InstantOrBuilder>( getEnd(), getParentForChildren(), isClean()); end_ = null; } return endBuilder_; } private java.lang.Object deviceId_ = ""; /** * <pre> * Device ID seen as associated with this session. * </pre> * * <code>string device_id = 6 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Device ID seen as associated with this session."];</code> */ public java.lang.String getDeviceId() { java.lang.Object ref = deviceId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); deviceId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Device ID seen as associated with this session. * </pre> * * <code>string device_id = 6 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Device ID seen as associated with this session."];</code> */ public com.google.protobuf.ByteString getDeviceIdBytes() { java.lang.Object ref = deviceId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); deviceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Device ID seen as associated with this session. * </pre> * * <code>string device_id = 6 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Device ID seen as associated with this session."];</code> */ public Builder setDeviceId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } deviceId_ = value; onChanged(); return this; } /** * <pre> * Device ID seen as associated with this session. * </pre> * * <code>string device_id = 6 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Device ID seen as associated with this session."];</code> */ public Builder clearDeviceId() { deviceId_ = getDefaultInstance().getDeviceId(); onChanged(); return this; } /** * <pre> * Device ID seen as associated with this session. * </pre> * * <code>string device_id = 6 [(.gen_bq_schema.require) = true, (.gen_bq_schema.description) = "Device ID seen as associated with this session."];</code> */ public Builder setDeviceIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); deviceId_ = value; onChanged(); return this; } private java.lang.Object userId_ = ""; /** * <pre> * User ID seen as associated with this session. * </pre> * * <code>string user_id = 7 [(.gen_bq_schema.description) = "User ID seen as associated with this session."];</code> */ public java.lang.String getUserId() { java.lang.Object ref = userId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); userId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * User ID seen as associated with this session. * </pre> * * <code>string user_id = 7 [(.gen_bq_schema.description) = "User ID seen as associated with this session."];</code> */ public com.google.protobuf.ByteString getUserIdBytes() { java.lang.Object ref = userId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); userId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * User ID seen as associated with this session. * </pre> * * <code>string user_id = 7 [(.gen_bq_schema.description) = "User ID seen as associated with this session."];</code> */ public Builder setUserId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } userId_ = value; onChanged(); return this; } /** * <pre> * User ID seen as associated with this session. * </pre> * * <code>string user_id = 7 [(.gen_bq_schema.description) = "User ID seen as associated with this session."];</code> */ public Builder clearUserId() { userId_ = getDefaultInstance().getUserId(); onChanged(); return this; } /** * <pre> * User ID seen as associated with this session. * </pre> * * <code>string user_id = 7 [(.gen_bq_schema.description) = "User ID seen as associated with this session."];</code> */ public Builder setUserIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); userId_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:bloombox.analytics.stats.SessionStats) } // @@protoc_insertion_point(class_scope:bloombox.analytics.stats.SessionStats) private static final io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats(); } public static io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SessionStats> PARSER = new com.google.protobuf.AbstractParser<SessionStats>() { @java.lang.Override public SessionStats parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new SessionStats(input, extensionRegistry); } }; public static com.google.protobuf.Parser<SessionStats> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SessionStats> getParserForType() { return PARSER; } @java.lang.Override public io.bloombox.schema.telemetry.stats.SessionTelemetry.SessionStats getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_bloombox_analytics_stats_SessionStats_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_bloombox_analytics_stats_SessionStats_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\"analytics/stats/SessionStats.proto\022\030bl" + "oombox.analytics.stats\032\016bq_field.proto\032\026" + "temporal/Instant.proto\"\310\004\n\014SessionStats\022" + ".\n\003sid\030\001 \001(\tB!\360?\001\212@\033Original ID of the s" + "ession.\022P\n\rpartner_scope\030\002 \001(\tB9\360?\001\212@3Pa" + "rtner scope seen as associated with this" + " session.\022F\n\013event_count\030\003 \001(\rB1\360?\001\212@+Co" + "unt of total events seen in this session" + ".\022q\n\005begin\030\004 \001(\0132\036.opencannabis.temporal" + ".InstantBB\360?\001\212@<Timestamp representing t" + "he first event seen in this session.\022n\n\003" + "end\030\005 \001(\0132\036.opencannabis.temporal.Instan" + "tBA\360?\001\212@;Timestamp representing the last" + " event seen in this session.\022H\n\tdevice_i" + "d\030\006 \001(\tB5\360?\001\212@/Device ID seen as associa" + "ted with this session.\022A\n\007user_id\030\007 \001(\tB" + "0\212@-User ID seen as associated with this" + " session.B@\n\"io.bloombox.schema.telemetr" + "y.statsB\020SessionTelemetryH\001P\000\242\002\003BBSb\006pro" + "to3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { gen_bq_schema.BqField.getDescriptor(), io.opencannabis.schema.temporal.TemporalInstant.getDescriptor(), }, assigner); internal_static_bloombox_analytics_stats_SessionStats_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_bloombox_analytics_stats_SessionStats_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_bloombox_analytics_stats_SessionStats_descriptor, new java.lang.String[] { "Sid", "PartnerScope", "EventCount", "Begin", "End", "DeviceId", "UserId", }); com.google.protobuf.ExtensionRegistry registry = com.google.protobuf.ExtensionRegistry.newInstance(); registry.add(gen_bq_schema.BqField.description); registry.add(gen_bq_schema.BqField.require); com.google.protobuf.Descriptors.FileDescriptor .internalUpdateFileDescriptor(descriptor, registry); gen_bq_schema.BqField.getDescriptor(); io.opencannabis.schema.temporal.TemporalInstant.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
ryanmdoyle/class-karma
web/src/components/GridView/GridView.js
import GroupGridCell from 'src/components/cells/GroupGridCell/GroupGridCell' const GridView = ({ groupId }) => { return <GroupGridCell id={groupId} /> } export default GridView
Sammyuel/VisChess
node_modules/heroku-cli-status/node_modules/cli-engine-command/lib/parser.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.RequiredFlagError = undefined; require('./arg'); require('./flags'); class Parse { constructor(input) { this.input = input; input.args = input.args || []; input.flags = input.flags || {}; } async parse(output = {}) { let argv = output.argv || []; output.flags = output.flags || {}; output.argv = []; output.args = {}; let parseFlag = arg => { let long = arg.startsWith('--'); let name = long ? findLongFlag(arg) : findShortFlag(arg); if (!name) { const i = arg.indexOf('='); if (i !== -1) { let sliced = arg.slice(i + 1); argv.unshift(sliced); let equalsParsed = parseFlag(arg.slice(0, i)); if (!equalsParsed) { argv.shift(); } return equalsParsed; } return false; } let flag = this.input.flags[name]; let cur = output.flags[name]; if (flag.parse) { // TODO: handle multiple flags if (cur) throw new Error(`Flag --${name} already provided`); let input; if (long || arg.length < 3) input = argv.shift();else input = arg.slice(arg[2] === '=' ? 3 : 2); if (!input) throw new Error(`Flag --${name} expects a value`); output.flags[name] = input; } else { if (!cur) output.flags[name] = true; // push the rest of the short characters back on the stack if (!long && arg.length > 2) argv.unshift(`-${arg.slice(2)}`); } return true; }; let findLongFlag = arg => { let name = arg.slice(2); if (this.input.flags[name]) return name; }; let findShortFlag = arg => { for (let k of Object.keys(this.input.flags)) { if (this.input.flags[k].char === arg[1]) return k; } }; let parsingFlags = true; let maxArgs = this.input.args.length; let minArgs = this.input.args.filter(a => a.required !== false && !a.optional).length; while (argv.length) { let arg = argv.shift(); if (parsingFlags && arg.startsWith('-')) { // attempt to parse as flag if (arg === '--') { parsingFlags = false;continue; } if (parseFlag(arg)) continue; // not actually a flag if it reaches here so parse as an arg } // not a flag, parse as arg let argDefinition = this.input.args[output.argv.length]; if (argDefinition) output.args[argDefinition.name] = arg; output.argv.push(arg); } if (!this.input.variableArgs && output.argv.length > maxArgs) throw new Error(`Unexpected argument ${output.argv[maxArgs]}`); if (output.argv.length < minArgs) throw new Error(new Error(`Missing required argument ${this.input.args[output.argv.length].name}`)); for (let name of Object.keys(this.input.flags)) { const flag = this.input.flags[name]; if (flag.parse) { output.flags[name] = await flag.parse(output.flags[name], this.input.cmd, name); flag.required = flag.required || flag.optional === false; if (flag.required && !output.flags[name]) throw new RequiredFlagError(name); } } return output; } } exports.default = Parse; class RequiredFlagError extends Error { constructor(name) { super(`Missing required flag --${name}`); } } exports.RequiredFlagError = RequiredFlagError;
Searchlight2/Searchlight2
software/misc/get_all_samples.py
<filename>software/misc/get_all_samples.py def get_all_samples(global_variables): samples_by_sample_groups = global_variables["samples_by_sample_groups"] order_list = global_variables["order_list"] all_samples = [] for key, value in samples_by_sample_groups.iteritems(): if key in order_list: for v in value: all_samples.append(v) return all_samples
harsha-simhadri/sbsched
src/HR1Scheduler.hh
<reponame>harsha-simhadri/sbsched // This code is part of the project "Experimental Analysis of Space-Bounded // Schedulers", presented at Symposium on Parallelism in Algorithms and // Architectures, 2014. // Copyright (c) 2014 <NAME>, <NAME>, <NAME>, // <NAME>, <NAME>. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights (to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef __HR1SCHEDULER_HH #define __HR1SCHEDULER_HH #include "Scheduler.hh" class HR_Scheduler : public Scheduler { typedef struct TaskSet { friend class HR_Scheduler; volatile int _clusters_needed; volatile int _clusters_attached; bool _complete; // Is this task complete? lluint _parent_job_id; Fork * _parent_fork; Mutex _lock; std::deque<SizedJob*> _task_queue; TaskSet (Fork * parent_fork, lluint parent_job_id, int num) : _parent_fork (parent_fork), _parent_job_id (parent_job_id), _clusters_needed (num), _clusters_attached (0), _complete (false) {} int change_clusters_needed(int delta) { return __sync_add_and_fetch(&_clusters_needed, delta); } int change_clusters_attached(int delta) { return __sync_add_and_fetch(&_clusters_attached, delta); } void lock () {_lock.lock();} void unlock () {_lock.unlock();} } TaskSet; struct Cluster; typedef struct Cluster { friend class TreeOfCaches; const lluint _size; // In Bytes const uint _block_size; // In Bytes int _num_children; // No. of subclusters Cluster * _parent; Cluster ** _children; lluint _occupied; // Occupied size in byes TaskSet * _active_set; // A cluster can execute tasks only from this set TaskSet * _spawned_set; // Set of tasks pinned to a cluster // In other words, tasks can be executed only under this cluster // Sublcusters point to this set using their _active_set pointers. Mutex _lock; Cluster (const lluint size, const int block_size, int num_children, Cluster * parent=NULL, Cluster ** children=NULL); Cluster * create_tree ( Cluster * root, Cluster ** leaf_array, int num_levels, uint * fan_outs, lluint * sizes, uint * block_sizes); void lock () {_lock.lock();} void unlock () {_lock.unlock();} bool is_locked () {return _lock.is_locked();} std::vector<TaskSet*> _spawned_set_vector; // List of spawned sets that are currently active on subclusters // Need lock on cluster to access // Added by Aapo int _locked_thread_id; // Thread that locked this cluster void set_active_set(TaskSet * a, int thrid) { assert(thrid == _locked_thread_id); _active_set = a; } } Cluster; class TreeOfCaches { friend class HR_Scheduler; int _num_levels; int _num_leaves; Cluster * _root; Cluster ** _leaf_array; int * _num_locks_held; // #locks held by the thread Cluster *** _locked_clusters; // There is one list for each thread, // in the order in which they were obtained. lluint * _sizes; uint * _block_sizes; uint * _fan_outs; }; protected: TreeOfCaches * _tree; lluint _num_jobs; int _type; // 0(def): Spawned set statically alocated to subclusters // 1 : Active_set link can move to other spawned set under parent Cluster * find_active_set (int thread_id, SizedJob* sized_job); // Search from the leaves of the tree up until you // find an active set to which sized_job is pinned // and return it. Lock up all nodes till there. void release_active_set (Cluster *node, int thrid); // Require that node's active_set be locked, // and that the active_set be completed. void insert_task_in_queue (std::deque<SizedJob*> &task_queue, SizedJob *job, lluint block_size); // Insert task in to the task queue of an active set public: HR_Scheduler (int num_threads, // Threads are logically numbered left to right. int num_levels, int * fan_outs, // num levels including top level RAM, f_{}, lluint * sizes, int * block_sizes,// M_{}, B_{}; M_0 is neglected int type=0); ~HR_Scheduler (); int allocate (lluint size, lluint lower_cache_size, // Set this to 0, if this is processor and upper is L1 lluint upper_cache_size, int fan_out) { #define MIN(A, B) ((A<B)?A:B) return (lower_cache_size == 0 ? fan_out : MIN (fan_out, (int)ceil (((double)size)/((double)lower_cache_size)))); //: (int)ceil (fan_out*(((double)size)/((double)upper_cache_size)))); } void add (Job *job, int thread_id ); void done (Job *job, int thread_id, bool deactivate ); Job* get (int thread_id=-1); bool more (int thread_id=-1); void print_scheduler_stats() {}; Job* find_job (int thread_id, Cluster *node=NULL); void check_lock_consistency (int thread_id); void lock (Cluster* node, int thread_id); bool has_lock (Cluster* node, int thread_id); void unlock (Cluster* node, int thread_id); void print_locks (int thread_id); void release_locks (int thread_id); Mutex _print_lock; void print_tree( Cluster * root, int num_levels, int total_levels=-1); void print_job ( SizedJob *job); void print_info (int thread_id, SizedJob* sized_job, int deactivate); }; #endif
faisal-bhatti/pos-retail
config/initializers/app_config.rb
<filename>config/initializers/app_config.rb require 'yaml' YAML::ENGINE.yamler = 'syck' ActionController::Renderers.add :csv do |csv,options| csv = csv.respond_to?(:to_csv) ? csv.to_csv : csv self.content_type ||= Mime::CSV self.response_body = csv end class Array def to_csv(options = Hash.new) out = self.first.as_csv.keys.join("\t") + "\n" self.each do |el| out << el.as_csv.values.join("\t") + "\n" end return out end end class Hash def get_name return self[:name] end def get_path return self[:path] end end
Yobin123/POCCms
app/src/main/java/com/st/cms/fragment/SignsBrokenLineFragment.java
package com.st.cms.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.st.cms.activity.TreatmentMainActivity; import com.st.cms.entity.Prioritise; import com.st.cms.entity.VitalSign; import com.st.cms.widget.BPMView; import com.st.cms.widget.Spo2View; import java.util.List; import cms.st.com.poccms.R; /** * Created by jt on 2016/9/5. */ public class SignsBrokenLineFragment extends TreatmentBaseFragment{ private static SignsBrokenLineFragment fragment; private static String title = ""; private BPMView bpm_view; private Spo2View spo2_view; private List<VitalSign> signs; private int preIndex = -1; private MyBackListener myBackListener; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_broken_line, container, false); bpm_view = (BPMView)view.findViewById(R.id.bpm_view); spo2_view = (Spo2View)view.findViewById(R.id.spo2_view); treatmentMainActivity = (TreatmentMainActivity)getActivity(); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LogHistoryFragment fragment = LogHistoryFragment.newInstance(prioritise, "LogHistory", signs, treatmentMainActivity.currentIndex); jumpAction(fragment); } }); bpm_view.setSigns(signs); spo2_view.setSigns(signs); bpm_view.invalidate(); spo2_view.invalidate(); treatmentMainActivity.tv_title.setText(prioritise.getTagId()); myBackListener = new MyBackListener(preIndex); treatmentMainActivity.iv_back.setOnClickListener(myBackListener); return view; } @Override public void onHiddenChanged(boolean hidden) { if(!hidden) { bpm_view.setSigns(signs); spo2_view.setSigns(signs); bpm_view.invalidate(); spo2_view.invalidate(); if(myBackListener != null) { myBackListener.setPreIndex(preIndex); } else { myBackListener = new MyBackListener(preIndex); } treatmentMainActivity.iv_back.setOnClickListener(new MyBackListener(preIndex)); bpm_view.setSigns(signs); spo2_view.setSigns(signs); bpm_view.invalidate(); spo2_view.invalidate(); treatmentMainActivity.tv_title.setText(prioritise.getTagId()); } // else if(hidden) // { // signs = null; // } super.onHiddenChanged(hidden); } public static SignsBrokenLineFragment newInstance(Prioritise prioritise, List<VitalSign> signs, int preIndex) { if(fragment == null) { fragment = new SignsBrokenLineFragment(); } fragment.prioritise = prioritise; // fragment.title = title; fragment.signs = signs; fragment.preIndex = preIndex; return fragment; } }
zshnb/qiangdongserver
src/main/java/com/qiangdong/reader/common/NovelConstant.java
<gh_stars>1-10 package com.qiangdong.reader.common; public class NovelConstant { public static Integer COIN_TO_TICKET_THRESHOLD = 10000; public static String KEY_TOP_SUBSCRIBE_NOVEL = "novel-top-subscribe"; public static String KEY_TOP_RECOMMEND_NOVEL = "novel-top-recommend"; public static String KEY_TOP_REWARD_NOVEL = "novel-top-reward"; public static String KEY_TOP_UPDATE_NOVEL = "novel-top-update"; public static String KEY_TOP_COLLECTION_NOVEL = "novel-top-collection"; }
alassetter/qui
stories/components/QTag.stories.js
<gh_stars>100-1000 import QTag from '../../src/qComponents/QTag'; export default { title: 'Components/QTag', component: QTag }; export const QTagStory = (_, { argTypes }) => ({ props: Object.keys(argTypes), data() { return { tags: ['Tag 1', 'Tag 2', 'Tag 3', 'Tag 4', 'Tag 5'] }; }, methods: { handleCloseClick(clickedTag) { console.log('Close tag clicked'); this.tags = this.tags.filter(tag => tag !== clickedTag); } }, template: ` <div> <q-tag v-for="tag in tags" :key="tag" :closable="closable" @close="handleCloseClick(tag)" > {{ tag }} </q-tag> </div> ` }); QTagStory.storyName = 'Default';
nitinbarai777/dateprog
db/migrate/20150818201010_add_level_type_to_course_level.rb
class AddLevelTypeToCourseLevel < ActiveRecord::Migration def change add_column :course_levels, :level_type, :integer, default: 0 end end
PascalGuenther/gecko_sdk
protocol/z-wave/Components/Utils/SizeOf.h
<gh_stars>10-100 /** * @file * @brief Header file containing various 'sizeof' macros * @copyright 2019 Silicon Laboratories Inc. */ #ifndef _SIZEOF_H_ #define _SIZEOF_H_ /** * Macro returns the number of ELEMENTS an array can hold. * Purpose of macro is increased readability in source code. */ #define sizeof_array(ARRAY) ((sizeof ARRAY) / (sizeof *ARRAY)) /** * Macro returns the size of a struct member from type (no actual instantiated * struct or pointer to struct needed). Use stadnard sizeof if you have an * instantiation or pointer to the struct. * Usage: as offsetoff, sizeof_structmember(MyStructType, MyStructMember) */ #define sizeof_structmember(TYPE, MEMBER) (sizeof(((TYPE *)0)->MEMBER)) #endif // _SIZEOF_H_
78182648/blibli-go
app/service/main/push/service/setting.go
<filename>app/service/main/push/service/setting.go package service import ( "context" "go-common/app/service/main/push/dao" "go-common/app/service/main/push/model" "go-common/library/log" ) // Setting gets user notify setting. func (s *Service) Setting(c context.Context, mid int64) (st map[int]int, err error) { st, err = s.dao.Setting(c, mid) if err != nil { log.Error("s.dao.Setting(%d) error(%v)", mid, err) return } if st == nil { st = make(map[int]int, len(model.Settings)) for k, v := range model.Settings { st[k] = v } } return } // SetSetting saves setting. func (s *Service) SetSetting(c context.Context, mid int64, typ, val int) (err error) { st, err := s.dao.Setting(c, mid) if err != nil { log.Error("s.dao.Setting(%d) error(%v)", mid, err) return } if st == nil { st = make(map[int]int, len(model.Settings)) for k, v := range model.Settings { st[k] = v } } st[typ] = val if err = s.dao.SetSetting(c, mid, st); err != nil { log.Error("s.dao.AddSetting(%d,%v) error(%v)", mid, st, err) dao.PromError("setting:保存设置") } return }
unboxed/bops
spec/system/planning_applications/validation_banner_display_spec.rb
# frozen_string_literal: true RSpec.describe "Validation banners", type: :system do context "Validation request banners are displayed correctly when open request is overdue" do let!(:assessor) { create :user, :assessor, local_authority: @default_local_authority } let!(:planning_application) { create :planning_application, local_authority: @default_local_authority } let!(:description_change_validation_request) do create :description_change_validation_request, planning_application: planning_application, state: "open" end before do sign_in assessor end it "shows the correct count for 1 overdue request validation" do travel 2.months visit planning_application_path(planning_application) expect(page).to have_content("1 validation request now overdue") end it "shows the correct count for 2 overdue request validations" do create(:replacement_document_validation_request, planning_application: planning_application, state: "open") travel 2.months visit planning_application_path(planning_application) expect(page).to have_content("2 validation requests now overdue") end end context "Validation warning banner is not displayed when request is closed" do let!(:assessor) { create :user, :assessor, local_authority: @default_local_authority } let!(:planning_application) { create :planning_application, local_authority: @default_local_authority } let!(:description_change_validation_request) do create :description_change_validation_request, planning_application: planning_application, state: "closed" end let!(:replacement_document_validation_request) do create :replacement_document_validation_request, planning_application: planning_application, state: "closed" end before do travel 2.months sign_in assessor visit planning_application_path(planning_application) end it "does not display the overdue validation request banner" do expect(page).not_to have_content("now overdue.") end it "displays the resolved validation request banner" do expect(page).to have_content("2 new responses to a validation request.") end end end
katemihalikova/test262
test/intl402/RelativeTimeFormat/prototype/formatToParts/value-symbol.js
// Copyright 2018 Igalia, S.L. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-Intl.RelativeTimeFormat.prototype.formatToParts description: Checks the handling of invalid value arguments to Intl.RelativeTimeFormat.prototype.formatToParts(). info: | Intl.RelativeTimeFormat.prototype.formatToParts( value, unit ) 3. Let value be ? ToNumber(value). features: [Intl.RelativeTimeFormat] ---*/ const rtf = new Intl.RelativeTimeFormat("en-US"); assert.sameValue(typeof rtf.formatToParts, "function", "formatToParts should be supported"); const symbol = Symbol(); assert.throws(TypeError, () => rtf.formatToParts(symbol, "second"));
shihab4t/Competitive-Programming
Online-Judges/CodeForces/800/34A.Reconnaissance_2.cpp
<reponame>shihab4t/Competitive-Programming #include <bits/stdc++.h> using namespace std; typedef long long int lli; typedef long double ld; #define endn "\n" #define faststdio ios_base::sync_with_stdio(false); #define fastcincout cin.tie(NULL); cout.tie(NULL); #define fastio faststdio fastcincout // Solve void test(void) { int num_of_soilders; cin >>num_of_soilders; int height[num_of_soilders]; for (int i = 0; i < num_of_soilders; i++) { cin >> height[i]; } int min = 1e3+5, temp, indx; for (int i = 0; i < num_of_soilders-1; i++) { temp = abs(height[i]-height[i+1]); if (temp < min) { indx = i; min = temp; } } temp = abs(height[0] - height[num_of_soilders-1]); if (temp < min) cout <<num_of_soilders <<" " <<1 <<endn; else cout <<indx+1 <<" " <<indx+2 <<endn; } int main(void) { fastio; test(); return 0; } // by: shihab4t // Monday, June 14, 2021 | 02:09:01 PM (+06)
theapache64/RetroKit
app/src/main/java/com/theah64/retrokitexample/model/data/GetUserProfileData.java
<reponame>theapache64/RetroKit<filename>app/src/main/java/com/theah64/retrokitexample/model/data/GetUserProfileData.java package com.theah64.retrokitexample.model.data; import com.google.gson.annotations.SerializedName; import com.theah64.retrokitexample.model.User; /** * Created by theapache64 on 25/8/17. */ public class GetUserProfileData { @SerializedName("user") private final User user; public GetUserProfileData(User user) { this.user = user; } public User getUser() { return user; } }
shreyasvj25/turicreate
deps/src/boost_1_65_1/boost/python/detail/map_entry.hpp
<gh_stars>1000+ // Copyright <NAME> 2002. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef MAP_ENTRY_DWA2002118_HPP # define MAP_ENTRY_DWA2002118_HPP namespace boost { namespace python { namespace detail { // A trivial type that works well as the value_type of associative // vector maps template <class Key, class Value> struct map_entry { map_entry() {} map_entry(Key k) : key(k), value() {} map_entry(Key k, Value v) : key(k), value(v) {} bool operator<(map_entry const& rhs) const { return this->key < rhs.key; } Key key; Value value; }; template <class Key, class Value> bool operator<(map_entry<Key,Value> const& e, Key const& k) { return e.key < k; } template <class Key, class Value> bool operator<(Key const& k, map_entry<Key,Value> const& e) { return k < e.key; } }}} // namespace boost::python::detail #endif // MAP_ENTRY_DWA2002118_HPP
George-Freedland/bookstore-app
application/backend/migrations/20200315211524-create-product.js
<reponame>George-Freedland/bookstore-app 'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Products', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER, }, photo: { type: Sequelize.STRING, }, categoryId: { type: Sequelize.INTEGER, allowNull: false, }, description: { type: Sequelize.STRING, }, productName: { type: Sequelize.STRING, }, sellerId: { type: Sequelize.INTEGER, allowNull: false, }, startDate: { type: Sequelize.DATE, }, endDate: { type: Sequelize.DATE, }, bidding: { type: Sequelize.BOOLEAN, }, price: { type: Sequelize.DECIMAL, }, approved: { type: Sequelize.BOOLEAN, }, sold: { type: Sequelize.BOOLEAN, }, createdAt: { allowNull: false, type: Sequelize.DATE, }, updatedAt: { allowNull: false, type: Sequelize.DATE, }, }); }, down: (queryInterface, Sequelize) => { return queryInterface.dropTable('Products'); }, };
TheFleksisCekcu/LiquidBounce-b62-deobfed
jdk/nashorn/internal/codegen/types/IntType.java
// // Decompiled by Procyon v0.5.36 // package jdk.nashorn.internal.codegen.types; import jdk.nashorn.internal.runtime.JSType; import jdk.internal.org.objectweb.asm.MethodVisitor; import jdk.nashorn.internal.codegen.CompilerConstants; class IntType extends BitwiseType { private static final long serialVersionUID = 1L; private static final CompilerConstants.Call TO_STRING; private static final CompilerConstants.Call VALUE_OF; protected IntType() { super("int", Integer.TYPE, 2, 1); } @Override public Type nextWider() { return IntType.NUMBER; } @Override public Class<?> getBoxedType() { return Integer.class; } @Override public char getBytecodeStackType() { return 'I'; } @Override public Type ldc(final MethodVisitor method, final Object c) { assert c instanceof Integer; final int value = (int)c; switch (value) { case -1: { method.visitInsn(2); break; } case 0: { method.visitInsn(3); break; } case 1: { method.visitInsn(4); break; } case 2: { method.visitInsn(5); break; } case 3: { method.visitInsn(6); break; } case 4: { method.visitInsn(7); break; } case 5: { method.visitInsn(8); break; } default: { if (value == (byte)value) { method.visitIntInsn(16, value); break; } if (value == (short)value) { method.visitIntInsn(17, value); break; } method.visitLdcInsn(c); break; } } return Type.INT; } @Override public Type convert(final MethodVisitor method, final Type to) { if (to.isEquivalentTo(this)) { return to; } if (to.isNumber()) { method.visitInsn(135); } else if (to.isLong()) { method.visitInsn(133); } else if (!to.isBoolean()) { if (to.isString()) { Type.invokestatic(method, IntType.TO_STRING); } else { if (!to.isObject()) { throw new UnsupportedOperationException("Illegal conversion " + this + " -> " + to); } Type.invokestatic(method, IntType.VALUE_OF); } } return to; } @Override public Type add(final MethodVisitor method, final int programPoint) { if (programPoint == -1) { method.visitInsn(96); } else { method.visitInvokeDynamicInsn("iadd", "(II)I", IntType.MATHBOOTSTRAP, programPoint); } return IntType.INT; } @Override public Type shr(final MethodVisitor method) { method.visitInsn(124); return IntType.INT; } @Override public Type sar(final MethodVisitor method) { method.visitInsn(122); return IntType.INT; } @Override public Type shl(final MethodVisitor method) { method.visitInsn(120); return IntType.INT; } @Override public Type and(final MethodVisitor method) { method.visitInsn(126); return IntType.INT; } @Override public Type or(final MethodVisitor method) { method.visitInsn(128); return IntType.INT; } @Override public Type xor(final MethodVisitor method) { method.visitInsn(130); return IntType.INT; } @Override public Type load(final MethodVisitor method, final int slot) { assert slot != -1; method.visitVarInsn(21, slot); return IntType.INT; } @Override public void store(final MethodVisitor method, final int slot) { assert slot != -1; method.visitVarInsn(54, slot); } @Override public Type sub(final MethodVisitor method, final int programPoint) { if (programPoint == -1) { method.visitInsn(100); } else { method.visitInvokeDynamicInsn("isub", "(II)I", IntType.MATHBOOTSTRAP, programPoint); } return IntType.INT; } @Override public Type mul(final MethodVisitor method, final int programPoint) { if (programPoint == -1) { method.visitInsn(104); } else { method.visitInvokeDynamicInsn("imul", "(II)I", IntType.MATHBOOTSTRAP, programPoint); } return IntType.INT; } @Override public Type div(final MethodVisitor method, final int programPoint) { if (programPoint == -1) { JSType.DIV_ZERO.invoke(method); } else { method.visitInvokeDynamicInsn("idiv", "(II)I", IntType.MATHBOOTSTRAP, programPoint); } return IntType.INT; } @Override public Type rem(final MethodVisitor method, final int programPoint) { if (programPoint == -1) { JSType.REM_ZERO.invoke(method); } else { method.visitInvokeDynamicInsn("irem", "(II)I", IntType.MATHBOOTSTRAP, programPoint); } return IntType.INT; } @Override public Type neg(final MethodVisitor method, final int programPoint) { if (programPoint == -1) { method.visitInsn(116); } else { method.visitInvokeDynamicInsn("ineg", "(I)I", IntType.MATHBOOTSTRAP, programPoint); } return IntType.INT; } @Override public void _return(final MethodVisitor method) { method.visitInsn(172); } @Override public Type loadUndefined(final MethodVisitor method) { method.visitLdcInsn(0); return IntType.INT; } @Override public Type loadForcedInitializer(final MethodVisitor method) { method.visitInsn(3); return IntType.INT; } @Override public Type cmp(final MethodVisitor method, final boolean isCmpG) { throw new UnsupportedOperationException("cmp" + (isCmpG ? 'g' : 'l')); } @Override public Type cmp(final MethodVisitor method) { throw new UnsupportedOperationException("cmp"); } static { TO_STRING = CompilerConstants.staticCallNoLookup(Integer.class, "toString", String.class, Integer.TYPE); VALUE_OF = CompilerConstants.staticCallNoLookup(Integer.class, "valueOf", Integer.class, Integer.TYPE); } }
NYULibraries/getit
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base protect_from_forgery helper :institutions include InstitutionsHelper # Override rails url_for to add institution parameter # This has to be defined in the controller so that controller logic # in Umlaut sees the override functionality. # # Ex. # => url_for({controller: 'resolve'}) === 'http://test.host/resolve?umlaut.insitution=#{current_institution}' # => url_for(http://test.host/resolve?rft.object_id=1234) === 'http://test.host/resolve?rft.object_id=1234&umlaut.insitution=#{current_institution}' def url_for(options={}) if institution_param.present? if options.is_a?(Hash) options[institution_param_name] ||= institution_param elsif options.is_a?(String) current_host = URI.parse(request.url).host url_host = URI.parse(options).host # Only do it for internal requests if current_host == url_host options = append_parameter_to_url(options, institution_param_name, institution_param) end end end super(options) rescue URI::InvalidURIError => e super(options) end def append_parameter_to_url(url, key, value) if url.include?('?') url += '&' else url += '?' end url += "#{key}=#{URI.encode(value.to_s)}" end private :append_parameter_to_url def current_user_dev # Assuming you have a dev user on your local environment @current_user ||= User.where(institution_code: :NYU).first end alias_method :current_user, :current_user_dev if Rails.env.development? prepend_before_filter :passive_login def passive_login if !cookies[:_check_passive_login] cookies[:_check_passive_login] = true redirect_to passive_login_url end end def url_for_request(request) url_for(controller: :resolve, action: :index, only_path: false, 'umlaut.request_id' => request.id) end helper_method :url_for_request # Alias new_session_path as login_path for default devise config def new_session_path(scope) login_path end def after_sign_in_path_for(resource) request.env['omniauth.origin'] || stored_location_for(resource) || root_path end # After signing out from the local application, # redirect to the logout path for the Login app def after_sign_out_path_for(resource_or_scope) if logout_path.present? logout_path else super(resource_or_scope) end end private def logout_path if ENV['LOGIN_URL'].present? && ENV['SSO_LOGOUT_PATH'].present? "#{ENV['LOGIN_URL']}#{ENV['SSO_LOGOUT_PATH']}" end end def passive_login_url "#{ENV['LOGIN_URL']}#{ENV['PASSIVE_LOGIN_PATH']}?client_id=#{ENV['APP_ID']}&return_uri=#{request_url_escaped}" end def request_url_escaped CGI::escape(request.url) end end
TimCook1/trident
storage_drivers/ontap/api/rest/models/account.go
// Code generated by go-swagger; DO NOT EDIT. package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "encoding/json" "strconv" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) // Account account // // swagger:model account type Account struct { // links Links *AccountLinks `json:"_links,omitempty"` // applications Applications []*AccountApplication `json:"applications,omitempty"` // Optional comment for the user account. Comment string `json:"comment,omitempty"` // Locked status of the account. Locked *bool `json:"locked,omitempty"` // User or group account name // Example: joe.smith // Max Length: 64 // Min Length: 3 Name string `json:"name,omitempty"` // owner Owner *AccountOwner `json:"owner,omitempty"` // Password for the account. The password can contain a mix of lower and upper case alphabetic characters, digits, and special characters. // Max Length: 128 // Min Length: 8 // Format: password Password strfmt.Password `json:"password,omitempty"` // role Role *AccountRole `json:"role,omitempty"` // Scope of the entity. Set to "cluster" for cluster owned objects and to "svm" for SVM owned objects. // Read Only: true // Enum: [cluster svm] Scope string `json:"scope,omitempty"` } // Validate validates this account func (m *Account) Validate(formats strfmt.Registry) error { var res []error if err := m.validateLinks(formats); err != nil { res = append(res, err) } if err := m.validateApplications(formats); err != nil { res = append(res, err) } if err := m.validateName(formats); err != nil { res = append(res, err) } if err := m.validateOwner(formats); err != nil { res = append(res, err) } if err := m.validatePassword(formats); err != nil { res = append(res, err) } if err := m.validateRole(formats); err != nil { res = append(res, err) } if err := m.validateScope(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *Account) validateLinks(formats strfmt.Registry) error { if swag.IsZero(m.Links) { // not required return nil } if m.Links != nil { if err := m.Links.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("_links") } return err } } return nil } func (m *Account) validateApplications(formats strfmt.Registry) error { if swag.IsZero(m.Applications) { // not required return nil } for i := 0; i < len(m.Applications); i++ { if swag.IsZero(m.Applications[i]) { // not required continue } if m.Applications[i] != nil { if err := m.Applications[i].Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("applications" + "." + strconv.Itoa(i)) } return err } } } return nil } func (m *Account) validateName(formats strfmt.Registry) error { if swag.IsZero(m.Name) { // not required return nil } if err := validate.MinLength("name", "body", m.Name, 3); err != nil { return err } if err := validate.MaxLength("name", "body", m.Name, 64); err != nil { return err } return nil } func (m *Account) validateOwner(formats strfmt.Registry) error { if swag.IsZero(m.Owner) { // not required return nil } if m.Owner != nil { if err := m.Owner.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("owner") } return err } } return nil } func (m *Account) validatePassword(formats strfmt.Registry) error { if swag.IsZero(m.Password) { // not required return nil } if err := validate.MinLength("password", "body", m.Password.String(), 8); err != nil { return err } if err := validate.MaxLength("password", "body", m.Password.String(), 128); err != nil { return err } if err := validate.FormatOf("password", "body", "password", m.Password.String(), formats); err != nil { return err } return nil } func (m *Account) validateRole(formats strfmt.Registry) error { if swag.IsZero(m.Role) { // not required return nil } if m.Role != nil { if err := m.Role.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("role") } return err } } return nil } var accountTypeScopePropEnum []interface{} func init() { var res []string if err := json.Unmarshal([]byte(`["cluster","svm"]`), &res); err != nil { panic(err) } for _, v := range res { accountTypeScopePropEnum = append(accountTypeScopePropEnum, v) } } const ( // BEGIN DEBUGGING // account // Account // scope // Scope // cluster // END DEBUGGING // AccountScopeCluster captures enum value "cluster" AccountScopeCluster string = "cluster" // BEGIN DEBUGGING // account // Account // scope // Scope // svm // END DEBUGGING // AccountScopeSvm captures enum value "svm" AccountScopeSvm string = "svm" ) // prop value enum func (m *Account) validateScopeEnum(path, location string, value string) error { if err := validate.EnumCase(path, location, value, accountTypeScopePropEnum, true); err != nil { return err } return nil } func (m *Account) validateScope(formats strfmt.Registry) error { if swag.IsZero(m.Scope) { // not required return nil } // value enum if err := m.validateScopeEnum("scope", "body", m.Scope); err != nil { return err } return nil } // ContextValidate validate this account based on the context it is used func (m *Account) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error if err := m.contextValidateLinks(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateApplications(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateOwner(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateRole(ctx, formats); err != nil { res = append(res, err) } if err := m.contextValidateScope(ctx, formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *Account) contextValidateLinks(ctx context.Context, formats strfmt.Registry) error { if m.Links != nil { if err := m.Links.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("_links") } return err } } return nil } func (m *Account) contextValidateApplications(ctx context.Context, formats strfmt.Registry) error { for i := 0; i < len(m.Applications); i++ { if m.Applications[i] != nil { if err := m.Applications[i].ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("applications" + "." + strconv.Itoa(i)) } return err } } } return nil } func (m *Account) contextValidateOwner(ctx context.Context, formats strfmt.Registry) error { if m.Owner != nil { if err := m.Owner.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("owner") } return err } } return nil } func (m *Account) contextValidateRole(ctx context.Context, formats strfmt.Registry) error { if m.Role != nil { if err := m.Role.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("role") } return err } } return nil } func (m *Account) contextValidateScope(ctx context.Context, formats strfmt.Registry) error { if err := validate.ReadOnly(ctx, "scope", "body", string(m.Scope)); err != nil { return err } return nil } // MarshalBinary interface implementation func (m *Account) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *Account) UnmarshalBinary(b []byte) error { var res Account if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil } // AccountLinks account links // // swagger:model AccountLinks type AccountLinks struct { // self Self *Href `json:"self,omitempty"` } // Validate validates this account links func (m *AccountLinks) Validate(formats strfmt.Registry) error { var res []error if err := m.validateSelf(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *AccountLinks) validateSelf(formats strfmt.Registry) error { if swag.IsZero(m.Self) { // not required return nil } if m.Self != nil { if err := m.Self.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("_links" + "." + "self") } return err } } return nil } // ContextValidate validate this account links based on the context it is used func (m *AccountLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error if err := m.contextValidateSelf(ctx, formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *AccountLinks) contextValidateSelf(ctx context.Context, formats strfmt.Registry) error { if m.Self != nil { if err := m.Self.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("_links" + "." + "self") } return err } } return nil } // MarshalBinary interface implementation func (m *AccountLinks) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *AccountLinks) UnmarshalBinary(b []byte) error { var res AccountLinks if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil } // AccountOwner Owner name and UUID that uniquely identifies the user account. // // swagger:model AccountOwner type AccountOwner struct { // links Links *AccountOwnerLinks `json:"_links,omitempty"` // The name of the SVM. // // Example: svm1 Name string `json:"name,omitempty"` // The unique identifier of the SVM. // // Example: 02c9e252-41be-11e9-81d5-00a0986138f7 UUID string `json:"uuid,omitempty"` } // Validate validates this account owner func (m *AccountOwner) Validate(formats strfmt.Registry) error { var res []error if err := m.validateLinks(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *AccountOwner) validateLinks(formats strfmt.Registry) error { if swag.IsZero(m.Links) { // not required return nil } if m.Links != nil { if err := m.Links.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("owner" + "." + "_links") } return err } } return nil } // ContextValidate validate this account owner based on the context it is used func (m *AccountOwner) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error if err := m.contextValidateLinks(ctx, formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *AccountOwner) contextValidateLinks(ctx context.Context, formats strfmt.Registry) error { if m.Links != nil { if err := m.Links.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("owner" + "." + "_links") } return err } } return nil } // MarshalBinary interface implementation func (m *AccountOwner) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *AccountOwner) UnmarshalBinary(b []byte) error { var res AccountOwner if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil } // AccountOwnerLinks account owner links // // swagger:model AccountOwnerLinks type AccountOwnerLinks struct { // self Self *Href `json:"self,omitempty"` } // Validate validates this account owner links func (m *AccountOwnerLinks) Validate(formats strfmt.Registry) error { var res []error if err := m.validateSelf(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *AccountOwnerLinks) validateSelf(formats strfmt.Registry) error { if swag.IsZero(m.Self) { // not required return nil } if m.Self != nil { if err := m.Self.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("owner" + "." + "_links" + "." + "self") } return err } } return nil } // ContextValidate validate this account owner links based on the context it is used func (m *AccountOwnerLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error if err := m.contextValidateSelf(ctx, formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *AccountOwnerLinks) contextValidateSelf(ctx context.Context, formats strfmt.Registry) error { if m.Self != nil { if err := m.Self.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("owner" + "." + "_links" + "." + "self") } return err } } return nil } // MarshalBinary interface implementation func (m *AccountOwnerLinks) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *AccountOwnerLinks) UnmarshalBinary(b []byte) error { var res AccountOwnerLinks if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil } // AccountRole account role // // swagger:model AccountRole type AccountRole struct { // links Links *AccountRoleLinks `json:"_links,omitempty"` // Role name // Example: admin Name string `json:"name,omitempty"` } // Validate validates this account role func (m *AccountRole) Validate(formats strfmt.Registry) error { var res []error if err := m.validateLinks(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *AccountRole) validateLinks(formats strfmt.Registry) error { if swag.IsZero(m.Links) { // not required return nil } if m.Links != nil { if err := m.Links.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("role" + "." + "_links") } return err } } return nil } // ContextValidate validate this account role based on the context it is used func (m *AccountRole) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error if err := m.contextValidateLinks(ctx, formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *AccountRole) contextValidateLinks(ctx context.Context, formats strfmt.Registry) error { if m.Links != nil { if err := m.Links.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("role" + "." + "_links") } return err } } return nil } // MarshalBinary interface implementation func (m *AccountRole) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *AccountRole) UnmarshalBinary(b []byte) error { var res AccountRole if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil } // AccountRoleLinks account role links // // swagger:model AccountRoleLinks type AccountRoleLinks struct { // self Self *Href `json:"self,omitempty"` } // Validate validates this account role links func (m *AccountRoleLinks) Validate(formats strfmt.Registry) error { var res []error if err := m.validateSelf(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *AccountRoleLinks) validateSelf(formats strfmt.Registry) error { if swag.IsZero(m.Self) { // not required return nil } if m.Self != nil { if err := m.Self.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("role" + "." + "_links" + "." + "self") } return err } } return nil } // ContextValidate validate this account role links based on the context it is used func (m *AccountRoleLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error { var res []error if err := m.contextValidateSelf(ctx, formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *AccountRoleLinks) contextValidateSelf(ctx context.Context, formats strfmt.Registry) error { if m.Self != nil { if err := m.Self.ContextValidate(ctx, formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("role" + "." + "_links" + "." + "self") } return err } } return nil } // MarshalBinary interface implementation func (m *AccountRoleLinks) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *AccountRoleLinks) UnmarshalBinary(b []byte) error { var res AccountRoleLinks if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
pabru/libgdx
extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btSphereBoxCollisionAlgorithm.java
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 3.0.11 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package com.badlogic.gdx.physics.bullet.collision; import com.badlogic.gdx.physics.bullet.BulletBase; import com.badlogic.gdx.physics.bullet.linearmath.*; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Matrix3; import com.badlogic.gdx.math.Matrix4; public class btSphereBoxCollisionAlgorithm extends btActivatingCollisionAlgorithm { private long swigCPtr; protected btSphereBoxCollisionAlgorithm(final String className, long cPtr, boolean cMemoryOwn) { super(className, CollisionJNI.btSphereBoxCollisionAlgorithm_SWIGUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } /** Construct a new btSphereBoxCollisionAlgorithm, normally you should not need this constructor it's intended for low-level usage. */ public btSphereBoxCollisionAlgorithm(long cPtr, boolean cMemoryOwn) { this("btSphereBoxCollisionAlgorithm", cPtr, cMemoryOwn); construct(); } @Override protected void reset(long cPtr, boolean cMemoryOwn) { if (!destroyed) destroy(); super.reset(CollisionJNI.btSphereBoxCollisionAlgorithm_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn); } public static long getCPtr(btSphereBoxCollisionAlgorithm obj) { return (obj == null) ? 0 : obj.swigCPtr; } @Override protected void finalize() throws Throwable { if (!destroyed) destroy(); super.finalize(); } @Override protected synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; CollisionJNI.delete_btSphereBoxCollisionAlgorithm(swigCPtr); } swigCPtr = 0; } super.delete(); } public btSphereBoxCollisionAlgorithm(btPersistentManifold mf, btCollisionAlgorithmConstructionInfo ci, btCollisionObjectWrapper body0Wrap, btCollisionObjectWrapper body1Wrap, boolean isSwapped) { this(CollisionJNI.new_btSphereBoxCollisionAlgorithm(btPersistentManifold.getCPtr(mf), mf, btCollisionAlgorithmConstructionInfo.getCPtr(ci), ci, btCollisionObjectWrapper.getCPtr(body0Wrap), body0Wrap, btCollisionObjectWrapper.getCPtr(body1Wrap), body1Wrap, isSwapped), true); } public boolean getSphereDistance(btCollisionObjectWrapper boxObjWrap, Vector3 v3PointOnBox, Vector3 normal, SWIGTYPE_p_float penetrationDepth, Vector3 v3SphereCenter, float fRadius, float maxContactDistance) { return CollisionJNI.btSphereBoxCollisionAlgorithm_getSphereDistance(swigCPtr, this, btCollisionObjectWrapper.getCPtr(boxObjWrap), boxObjWrap, v3PointOnBox, normal, SWIGTYPE_p_float.getCPtr(penetrationDepth), v3SphereCenter, fRadius, maxContactDistance); } public float getSpherePenetration(Vector3 boxHalfExtent, Vector3 sphereRelPos, Vector3 closestPoint, Vector3 normal) { return CollisionJNI.btSphereBoxCollisionAlgorithm_getSpherePenetration(swigCPtr, this, boxHalfExtent, sphereRelPos, closestPoint, normal); } static public class CreateFunc extends btCollisionAlgorithmCreateFunc { private long swigCPtr; protected CreateFunc(final String className, long cPtr, boolean cMemoryOwn) { super(className, CollisionJNI.btSphereBoxCollisionAlgorithm_CreateFunc_SWIGUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } /** Construct a new CreateFunc, normally you should not need this constructor it's intended for low-level usage. */ public CreateFunc(long cPtr, boolean cMemoryOwn) { this("CreateFunc", cPtr, cMemoryOwn); construct(); } @Override protected void reset(long cPtr, boolean cMemoryOwn) { if (!destroyed) destroy(); super.reset(CollisionJNI.btSphereBoxCollisionAlgorithm_CreateFunc_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn); } public static long getCPtr(CreateFunc obj) { return (obj == null) ? 0 : obj.swigCPtr; } @Override protected void finalize() throws Throwable { if (!destroyed) destroy(); super.finalize(); } @Override protected synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; CollisionJNI.delete_btSphereBoxCollisionAlgorithm_CreateFunc(swigCPtr); } swigCPtr = 0; } super.delete(); } public CreateFunc() { this(CollisionJNI.new_btSphereBoxCollisionAlgorithm_CreateFunc(), true); } } }
davideschiavone/pulpissimo
boot_code/include/archi/pwm/v1/pwm_v1_structs.h
<filename>boot_code/include/archi/pwm/v1/pwm_v1_structs.h /* THIS FILE HAS BEEN GENERATED, DO NOT MODIFY IT. */ /* * Copyright (C) 2018 ETH Zurich, University of Bologna * and GreenWaves Technologies * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __INCLUDE_ARCHI_PWM_V1_PWM_V1_STRUCTS_H__ #define __INCLUDE_ARCHI_PWM_V1_PWM_V1_STRUCTS_H__ #if !defined(LANGUAGE_ASSEMBLY) && !defined(__ASSEMBLER__) #include <stdint.h> #include "archi/utils.h" #endif // // REGISTERS STRUCTS // #if !defined(LANGUAGE_ASSEMBLY) && !defined(__ASSEMBLER__) typedef union { struct { unsigned int start :1 ; // ADV_TIMER0 start command bitfield. unsigned int stop :1 ; // ADV_TIMER0 stop command bitfield. unsigned int update :1 ; // ADV_TIMER0 update command bitfield. unsigned int reset :1 ; // ADV_TIMER0 reset command bitfield. unsigned int arm :1 ; // ADV_TIMER0 arm command bitfield. }; unsigned int raw; } __attribute__((packed)) pwm_t0_cmd_t; typedef union { struct { unsigned int insel :8 ; // ADV_TIMER0 input source configuration bitfield: - 0-31: GPIO[0] to GPIO[31] - 32-35: Channel 0 to 3 of ADV_TIMER0 - 36-39: Channel 0 to 3 of ADV_TIMER1 - 40-43: Channel 0 to 3 of ADV_TIMER2 - 44-47: Channel 0 to 3 of ADV_TIMER3 unsigned int mode :3 ; // ADV_TIMER0 trigger mode configuration bitfield: - 3'h0: trigger event at each clock cycle. - 3'h1: trigger event if input source is 0 - 3'h2: trigger event if input source is 1 - 3'h3: trigger event on input source rising edge - 3'h4: trigger event on input source falling edge - 3'h5: trigger event on input source falling or rising edge - 3'h6: trigger event on input source rising edge when armed - 3'h7: trigger event on input source falling edge when armed unsigned int clksel :1 ; // ADV_TIMER0 clock source configuration bitfield: - 1'b0: FLL - 1'b1: reference clock at 32kHz unsigned int updownsel :1 ; // ADV_TIMER0 center-aligned mode configuration bitfield: - 1'b0: The counter counts up and down alternatively. - 1'b1: The counter counts up and resets to 0 when reach threshold. unsigned int padding0:3 ; unsigned int presc :8 ; // ADV_TIMER0 prescaler value configuration bitfield. }; unsigned int raw; } __attribute__((packed)) pwm_t0_config_t; typedef union { struct { unsigned int th_lo :16; // ADV_TIMER0 threshold low part configuration bitfield. It defines start counter value. unsigned int th_hi :16; // ADV_TIMER0 threshold high part configuration bitfield. It defines end counter value. }; unsigned int raw; } __attribute__((packed)) pwm_t0_threshold_t; typedef union { struct { unsigned int th :16; // ADV_TIMER0 channel 0 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER0 channel 0 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t0_th_channel0_t; typedef union { struct { unsigned int th :16; // ADV_TIMER0 channel 1 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER0 channel 1 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t0_th_channel1_t; typedef union { struct { unsigned int th :16; // ADV_TIMER0 channel 2 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER0 channel 2 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t0_th_channel2_t; typedef union { struct { unsigned int th :16; // ADV_TIMER0 channel 3 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER0 channel 3 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t0_th_channel3_t; typedef union { struct { }; unsigned int raw; } __attribute__((packed)) pwm_t0_counter_t; typedef union { struct { unsigned int start :1 ; // ADV_TIMER1 start command bitfield. unsigned int stop :1 ; // ADV_TIMER1 stop command bitfield. unsigned int update :1 ; // ADV_TIMER1 update command bitfield. unsigned int reset :1 ; // ADV_TIMER1 reset command bitfield. unsigned int arm :1 ; // ADV_TIMER1 arm command bitfield. }; unsigned int raw; } __attribute__((packed)) pwm_t1_cmd_t; typedef union { struct { unsigned int insel :8 ; // ADV_TIMER1 input source configuration bitfield: - 0-31: GPIO[0] to GPIO[31] - 32-35: Channel 0 to 3 of ADV_TIMER0 - 36-39: Channel 0 to 3 of ADV_TIMER1 - 40-43: Channel 0 to 3 of ADV_TIMER2 - 44-47: Channel 0 to 3 of ADV_TIMER3 unsigned int mode :3 ; // ADV_TIMER1 trigger mode configuration bitfield: - 3'h0: trigger event at each clock cycle. - 3'h1: trigger event if input source is 0 - 3'h2: trigger event if input source is 1 - 3'h3: trigger event on input source rising edge - 3'h4: trigger event on input source falling edge - 3'h5: trigger event on input source falling or rising edge - 3'h6: trigger event on input source rising edge when armed - 3'h7: trigger event on input source falling edge when armed unsigned int clksel :1 ; // ADV_TIMER1 clock source configuration bitfield: - 1'b0: FLL - 1'b1: reference clock at 32kHz unsigned int updownsel :1 ; // ADV_TIMER1 center-aligned mode configuration bitfield: - 1'b0: The counter counts up and down alternatively. - 1'b1: The counter counts up and resets to 0 when reach threshold. unsigned int padding0:3 ; unsigned int presc :8 ; // ADV_TIMER1 prescaler value configuration bitfield. }; unsigned int raw; } __attribute__((packed)) pwm_t1_config_t; typedef union { struct { unsigned int th_lo :16; // ADV_TIMER1 threshold low part configuration bitfield. It defines start counter value. unsigned int th_hi :16; // ADV_TIMER1 threshold high part configuration bitfield. It defines end counter value. }; unsigned int raw; } __attribute__((packed)) pwm_t1_threshold_t; typedef union { struct { unsigned int th :16; // ADV_TIMER1 channel 0 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER1 channel 0 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t1_th_channel0_t; typedef union { struct { unsigned int th :16; // ADV_TIMER1 channel 1 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER1 channel 1 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t1_th_channel1_t; typedef union { struct { unsigned int th :16; // ADV_TIMER1 channel 2 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER1 channel 2 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t1_th_channel2_t; typedef union { struct { unsigned int th :16; // ADV_TIMER1 channel 3 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER1 channel 3 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t1_th_channel3_t; typedef union { struct { }; unsigned int raw; } __attribute__((packed)) pwm_t1_counter_t; typedef union { struct { unsigned int start :1 ; // ADV_TIMER2 start command bitfield. unsigned int stop :1 ; // ADV_TIMER2 stop command bitfield. unsigned int update :1 ; // ADV_TIMER2 update command bitfield. unsigned int reset :1 ; // ADV_TIMER2 reset command bitfield. unsigned int arm :1 ; // ADV_TIMER2 arm command bitfield. }; unsigned int raw; } __attribute__((packed)) pwm_t2_cmd_t; typedef union { struct { unsigned int insel :8 ; // ADV_TIMER2 input source configuration bitfield: - 0-31: GPIO[0] to GPIO[31] - 32-35: Channel 0 to 3 of ADV_TIMER0 - 36-39: Channel 0 to 3 of ADV_TIMER1 - 40-43: Channel 0 to 3 of ADV_TIMER2 - 44-47: Channel 0 to 3 of ADV_TIMER3 unsigned int mode :3 ; // ADV_TIMER2 trigger mode configuration bitfield: - 3'h0: trigger event at each clock cycle. - 3'h1: trigger event if input source is 0 - 3'h2: trigger event if input source is 1 - 3'h3: trigger event on input source rising edge - 3'h4: trigger event on input source falling edge - 3'h5: trigger event on input source falling or rising edge - 3'h6: trigger event on input source rising edge when armed - 3'h7: trigger event on input source falling edge when armed unsigned int clksel :1 ; // ADV_TIMER2 clock source configuration bitfield: - 1'b0: FLL - 1'b1: reference clock at 32kHz unsigned int updownsel :1 ; // ADV_TIMER2 center-aligned mode configuration bitfield: - 1'b0: The counter counts up and down alternatively. - 1'b1: The counter counts up and resets to 0 when reach threshold. unsigned int padding0:3 ; unsigned int presc :8 ; // ADV_TIMER2 prescaler value configuration bitfield. }; unsigned int raw; } __attribute__((packed)) pwm_t2_config_t; typedef union { struct { unsigned int th_lo :16; // ADV_TIMER2 threshold low part configuration bitfield. It defines start counter value. unsigned int th_hi :16; // ADV_TIMER2 threshold high part configuration bitfield. It defines end counter value. }; unsigned int raw; } __attribute__((packed)) pwm_t2_threshold_t; typedef union { struct { unsigned int th :16; // ADV_TIMER2 channel 0 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER2 channel 0 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t2_th_channel0_t; typedef union { struct { unsigned int th :16; // ADV_TIMER2 channel 1 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER2 channel 1 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t2_th_channel1_t; typedef union { struct { unsigned int th :16; // ADV_TIMER2 channel 2 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER2 channel 2 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t2_th_channel2_t; typedef union { struct { unsigned int th :16; // ADV_TIMER2 channel 3 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER2 channel 3 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t2_th_channel3_t; typedef union { struct { }; unsigned int raw; } __attribute__((packed)) pwm_t2_counter_t; typedef union { struct { unsigned int start :1 ; // ADV_TIMER3 start command bitfield. unsigned int stop :1 ; // ADV_TIMER3 stop command bitfield. unsigned int update :1 ; // ADV_TIMER3 update command bitfield. unsigned int reset :1 ; // ADV_TIMER3 reset command bitfield. unsigned int arm :1 ; // ADV_TIMER3 arm command bitfield. }; unsigned int raw; } __attribute__((packed)) pwm_t3_cmd_t; typedef union { struct { unsigned int insel :8 ; // ADV_TIMER3 input source configuration bitfield: - 0-31: GPIO[0] to GPIO[31] - 32-35: Channel 0 to 3 of ADV_TIMER0 - 36-39: Channel 0 to 3 of ADV_TIMER1 - 40-43: Channel 0 to 3 of ADV_TIMER2 - 44-47: Channel 0 to 3 of ADV_TIMER3 unsigned int mode :3 ; // ADV_TIMER3 trigger mode configuration bitfield: - 3'h0: trigger event at each clock cycle. - 3'h1: trigger event if input source is 0 - 3'h2: trigger event if input source is 1 - 3'h3: trigger event on input source rising edge - 3'h4: trigger event on input source falling edge - 3'h5: trigger event on input source falling or rising edge - 3'h6: trigger event on input source rising edge when armed - 3'h7: trigger event on input source falling edge when armed unsigned int clksel :1 ; // ADV_TIMER3 clock source configuration bitfield: - 1'b0: FLL - 1'b1: reference clock at 32kHz unsigned int updownsel :1 ; // ADV_TIMER3 center-aligned mode configuration bitfield: - 1'b0: The counter counts up and down alternatively. - 1'b1: The counter counts up and resets to 0 when reach threshold. unsigned int padding0:3 ; unsigned int presc :8 ; // ADV_TIMER3 prescaler value configuration bitfield. }; unsigned int raw; } __attribute__((packed)) pwm_t3_config_t; typedef union { struct { unsigned int th_lo :16; // ADV_TIMER3 threshold low part configuration bitfield. It defines start counter value. unsigned int th_hi :16; // ADV_TIMER3 threshold high part configuration bitfield. It defines end counter value. }; unsigned int raw; } __attribute__((packed)) pwm_t3_threshold_t; typedef union { struct { unsigned int th :16; // ADV_TIMER3 channel 0 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER3 channel 0 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t3_th_channel0_t; typedef union { struct { unsigned int th :16; // ADV_TIMER3 channel 1 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER3 channel 1 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t3_th_channel1_t; typedef union { struct { unsigned int th :16; // ADV_TIMER3 channel 2 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER3 channel 2 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t3_th_channel2_t; typedef union { struct { unsigned int th :16; // ADV_TIMER3 channel 3 threshold configuration bitfield. unsigned int mode :3 ; // ADV_TIMER3 channel 3 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. }; unsigned int raw; } __attribute__((packed)) pwm_t3_th_channel3_t; typedef union { struct { }; unsigned int raw; } __attribute__((packed)) pwm_t3_counter_t; typedef union { struct { unsigned int sel0 :4 ; // ADV_TIMER output event 0 source configuration bitfiled: - 4'h0: ADV_TIMER0 channel 0. - 4'h1: ADV_TIMER0 channel 1. - 4'h2: ADV_TIMER0 channel 2. - 4'h3: ADV_TIMER0 channel 3. - 4'h4: ADV_TIMER1 channel 0. - 4'h5: ADV_TIMER1 channel 1. - 4'h6: ADV_TIMER1 channel 2. - 4'h7: ADV_TIMER1 channel 3. - 4'h8: ADV_TIMER2 channel 0. - 4'h9: ADV_TIMER2 channel 1. - 4'hA: ADV_TIMER2 channel 2. - 4'hB: ADV_TIMER2 channel 3. - 4'hC: ADV_TIMER3 channel 0. - 4'hD: ADV_TIMER3 channel 1. - 4'hE: ADV_TIMER3 channel 2. - 4'hF: ADV_TIMER3 channel 3. unsigned int sel1 :4 ; // ADV_TIMER output event 1 source configuration bitfiled: - 4'h0: ADV_TIMER0 channel 0. - 4'h1: ADV_TIMER0 channel 1. - 4'h2: ADV_TIMER0 channel 2. - 4'h3: ADV_TIMER0 channel 3. - 4'h4: ADV_TIMER1 channel 0. - 4'h5: ADV_TIMER1 channel 1. - 4'h6: ADV_TIMER1 channel 2. - 4'h7: ADV_TIMER1 channel 3. - 4'h8: ADV_TIMER2 channel 0. - 4'h9: ADV_TIMER2 channel 1. - 4'hA: ADV_TIMER2 channel 2. - 4'hB: ADV_TIMER2 channel 3. - 4'hC: ADV_TIMER3 channel 0. - 4'hD: ADV_TIMER3 channel 1. - 4'hE: ADV_TIMER3 channel 2. - 4'hF: ADV_TIMER3 channel 3. unsigned int sel2 :4 ; // ADV_TIMER output event 2 source configuration bitfiled: - 4'h0: ADV_TIMER0 channel 0. - 4'h1: ADV_TIMER0 channel 1. - 4'h2: ADV_TIMER0 channel 2. - 4'h3: ADV_TIMER0 channel 3. - 4'h4: ADV_TIMER1 channel 0. - 4'h5: ADV_TIMER1 channel 1. - 4'h6: ADV_TIMER1 channel 2. - 4'h7: ADV_TIMER1 channel 3. - 4'h8: ADV_TIMER2 channel 0. - 4'h9: ADV_TIMER2 channel 1. - 4'hA: ADV_TIMER2 channel 2. - 4'hB: ADV_TIMER2 channel 3. - 4'hC: ADV_TIMER3 channel 0. - 4'hD: ADV_TIMER3 channel 1. - 4'hE: ADV_TIMER3 channel 2. - 4'hF: ADV_TIMER3 channel 3. unsigned int sel3 :4 ; // ADV_TIMER output event 3 source configuration bitfiled: - 4'h0: ADV_TIMER0 channel 0. - 4'h1: ADV_TIMER0 channel 1. - 4'h2: ADV_TIMER0 channel 2. - 4'h3: ADV_TIMER0 channel 3. - 4'h4: ADV_TIMER1 channel 0. - 4'h5: ADV_TIMER1 channel 1. - 4'h6: ADV_TIMER1 channel 2. - 4'h7: ADV_TIMER1 channel 3. - 4'h8: ADV_TIMER2 channel 0. - 4'h9: ADV_TIMER2 channel 1. - 4'hA: ADV_TIMER2 channel 2. - 4'hB: ADV_TIMER2 channel 3. - 4'hC: ADV_TIMER3 channel 0. - 4'hD: ADV_TIMER3 channel 1. - 4'hE: ADV_TIMER3 channel 2. - 4'hF: ADV_TIMER3 channel 3. unsigned int ena :4 ; // ADV_TIMER output event enable configuration bitfield. ENA[i]=1 enables output event i generation. }; unsigned int raw; } __attribute__((packed)) pwm_event_cfg_t; typedef union { struct { unsigned int ena :16; // ADV_TIMER clock gating configuration bitfield. - ENA[i]=0: clock gate ADV_TIMERi. - ENA[i]=1: enable ADV_TIMERi. }; unsigned int raw; } __attribute__((packed)) pwm_cg_t; #endif #endif
kabootit/data-sutra
_ds_AC_access_control/datasources/sutra/sutra_access_user_calculations.js
/** * * @properties={type:12,typeid:36,uuid:"05610bdd-f149-4594-8623-9abb600f840c"} */ function display_login_expiration() { var html = '<html><head>' //css html += '<style type="text/css" media="screen"><!--' html += '.red { color: red; font-weight: bold; }' html += '.blue { color: blue; font-weight: bold; }' html += '.green { color: green; }' html += '--></style></head>' //body html += '<body>' //no password if (!user_password) { html += '<span class="red">BLANK PASSWORD</span>' } //account disabled else if (account_disabled) { html += 'Account <span class="red">disabled</span>' } //password never expires else if (pass_never_expires) { html += 'Password <span class="blue">never</span> expires' } //expiration in effect else if (ac_access_user_to_access_rules.expire_flag) { var expireDays = ac_access_user_to_access_rules.expire_days var today = new Date(new Date().getFullYear(),new Date().getMonth(),new Date().getDate()) var startDate = (date_password_changed) ? new Date(date_password_changed.getFullYear(),date_password_changed.getMonth(),date_password_changed.getDate()) : new Date() var expire = expireDays - Math.floor(((today - startDate) / 864E5)) if (expire > 0) { html += 'Password expires in <span class="green">' + expire + ' days</span>' } else { html += 'Password <span class="red">expired</span>' } } //close body html += '</body></html>' return html } /** * * @properties={type:12,typeid:36,uuid:"a8080d60-b261-4c27-8c5b-06a8b1612e69"} */ function display_user_name() { if (id_user) { var itemName = (user_name) ? user_name : 'UNKNOWN' var height = (solutionPrefs.config.webClient) ? '16px' : '20' var html = '<html><head><style type="text/css" media="screen"><!--' html += 'table.sutra { table-layout: fixed; width: 100%; border-spacing: 0px; border: 0px; }' html += 'table.sutra td { text-indent: 5px; white-space: nowrap; overflow: hidden; border: 0px; padding: 2px; height: ' + height + '; line-height: ' + height + '; }' html += '.table.sutra rowSelected { color: white; text-decoration: none; font-weight: bold; background-image: url("media:///row_selected.png"); }' html += 'table.sutra td.rowSelected a { color: white; text-decoration: none; }' html += '--></style></head>' if (globals.AC_user_selected == id_user) { html += '<table class = "sutra"><tr>' html += '<td class = "rowSelected">' + itemName + '</td>' html += '</tr></table></html>' } else { html += '<table class = "sutra"><tr>' html += '<td>' + itemName + '</td>' html += '</tr></table></html>' } return html } } /** * * @properties={type:12,typeid:36,uuid:"42ae180d-7adb-4501-8cfa-010e68c36ed5"} */ function row_background() { //white/tan with medium blue highlighter var index = arguments[0] var selected = arguments[1] if (selected) { return '#BED7F7' } else { if (index % 2 == 0) { return '#F7F8EF' } else { return '#FFFFFF' } } }
blueswhisper/athena
athena-core/src/main/java/me/ele/jarch/athena/allinone/AllInOneMonitor.java
<reponame>blueswhisper/athena package me.ele.jarch.athena.allinone; import me.ele.jarch.athena.DecryptorSpi; import me.ele.jarch.athena.constant.Constants; import me.ele.jarch.athena.scheduler.DBChannelDispatcher; import me.ele.jarch.athena.server.pool.ServerSessionPool; import me.ele.jarch.athena.sql.seqs.SeqsCache; import me.ele.jarch.athena.util.deploy.dalgroupcfg.DalGroupConfig; import me.ele.jarch.athena.util.etrace.MetricFactory; import org.apache.commons.io.Charsets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; public class AllInOneMonitor { private static final Logger logger = LoggerFactory.getLogger(AllInOneMonitor.class); private final DecryptorSpi decryptor; // store the db info for dbGroup private volatile List<DBConnectionInfo> dbConnectionInfos; // store the db info for $dal_sequences_user_xxx private volatile List<DBConnectionInfo> seqDbConnectionInfos; // store the db info for mysqlDBGroup private volatile Map<String, DBRole> mysqlDBGroup = new ConcurrentHashMap<>(); // store the db info for pgDBGroup private volatile Map<String, DBRole> pgDBGroup = new ConcurrentHashMap<>(); private List<ServerSessionPool> inactiveServers = new ArrayList<ServerSessionPool>(); private static AllInOneMonitor INSTANCE = new AllInOneMonitor(); public static AllInOneMonitor getInstance() { return AllInOneMonitor.INSTANCE; } private AllInOneMonitor() { dbConnectionInfos = new ArrayList<>(); seqDbConnectionInfos = new ArrayList<>(); mysqlDBGroup = new HashMap<>(); pgDBGroup = new HashMap<>(); decryptor = loadDecryptor(); } private DecryptorSpi loadDecryptor() { String decryptorSpiProvider = System .getProperty("athena.decryptorspi.provider", "me.ele.jarch.athena.Base64Decryptor"); for (DecryptorSpi decryptorSpi : ServiceLoader.load(DecryptorSpi.class)) { if (decryptorSpiProvider.equals(decryptorSpi.getClass().getName())) { decryptorSpi.init(); return decryptorSpi; } } return null; } public List<DBConnectionInfo> getDbConnectionInfos() { return dbConnectionInfos; } public List<DBConnectionInfo> getSeqDbConnectionInfos() { return seqDbConnectionInfos; } public Map<String, DBRole> getMysqlDBGroup() { return mysqlDBGroup; } public Map<String, DBRole> getPgDBGroup() { return pgDBGroup; } public synchronized void loadConfig(String configFilePath) { try { // load db-connection doLoadConfig(configFilePath); } catch (Exception e) { logger.error("Error occur during run AllInOneMonitor", e); MetricFactory.newCounter("config.error").once(); } } private void doLoadConfig(String configFilePath) throws Exception { MetricFactory.newCounter("config.load").once(); logger.info("Load new allinone DB connection info"); Map<DBConfType, List<DBConnectionInfo>> newDBInfosMap = parseFromFile(configFilePath); updateNormalDbCfgs(newDBInfosMap.getOrDefault(DBConfType.NORMAL, Collections.emptyList())); // load $dal_sequence_user config updateSeqDbCfgsFromFile( newDBInfosMap.getOrDefault(DBConfType.SEQUENCE, Collections.emptyList())); } private Map<DBConfType, List<DBConnectionInfo>> parseFromFile(String path) throws IOException { Map<DBConfType, List<DBConnectionInfo>> result = new HashMap<>(); try (BufferedReader reader = Files.newBufferedReader(Paths.get(path), Charsets.UTF_8)) { reader.lines().forEach(line -> { line = line.trim(); DBConfType confType = DBConfType.getType(line); if (confType == DBConfType.NONE) { return; } DBConnectionInfo info = DBConnectionInfo.parseDBConnectionString(line); if (info == null) { return; } List<DBConnectionInfo> dbInfos = result.computeIfAbsent(confType, (key) -> new ArrayList<DBConnectionInfo>()); dbInfos.add(info); }); } return result; } private void updateNormalDbCfgs(List<DBConnectionInfo> newDbInfos) { if (newDbInfos.size() <= 0) { logger.warn("No element is contained in the ALLInOne DB Connection File"); } this.dbConnectionInfos = newDbInfos; DBChannelDispatcher.TEMP_DAL_GROUP_CONFIGS.forEach((t, u) -> { u.updateDBInfos(); }); } private void updateSeqDbCfgsFromFile(List<DBConnectionInfo> newSeqDBcfgs) { DalGroupConfig dummy = DBChannelDispatcher.TEMP_DAL_GROUP_CONFIGS .computeIfAbsent(Constants.DUMMY, DalGroupConfig::new); updateDbInfoPerType(dummy, newSeqDBcfgs, DBConfType.SEQUENCE); } private void updateDbInfoPerType(DalGroupConfig dalGroupConfig, List<DBConnectionInfo> dbInfos, DBConfType dbConfType) { dalGroupConfig.getDbInfos() .removeIf(db -> db.getGroup().startsWith(dbConfType.getSymbol())); dalGroupConfig.getDbInfos().addAll(dbInfos); dalGroupConfig.write2File(); } private void updateSeqDbCfgs(List<DBConnectionInfo> newSeqDBcfgs) { if (Objects.isNull(newSeqDBcfgs)) { seqDbConnectionInfos.clear(); return; } newSeqDBcfgs.forEach(newCfg -> { if (!seqDbConnectionInfos.contains(newCfg)) { logger.info("new dal_sequence_user config: " + newCfg); } }); if (seqDbConnectionInfos.equals(newSeqDBcfgs)) { logger.info("no dal_sequence_user $xxx changed"); return; } seqDbConnectionInfos = newSeqDBcfgs; SeqsCache.clearAll(); } public void updateSeqDbs(List<DBConnectionInfo> newSeqDBcfgs) { Map<DBConfType, List<DBConnectionInfo>> newDBInfosMap = newSeqDBcfgs.stream() .collect(Collectors.groupingBy(db -> DBConfType.getType(db.getGroup()))); this.updateSeqDbCfgs(newDBInfosMap.get(DBConfType.SEQUENCE)); } public void updateDBGroupPerDalGroup(List<DBConnectionInfo> newDbInfos) { if (newDbInfos.isEmpty()) { logger.warn("No element is contained in the ALLInOne DB Connection File"); } for (DBConnectionInfo newDbInfo : newDbInfos) { switch (newDbInfo.getDBVendor()) { case MYSQL: if (mysqlDBGroup.getOrDefault(newDbInfo.getGroup(), DBRole.SLAVE) != DBRole.MASTER) { this.mysqlDBGroup.put(newDbInfo.getGroup(), newDbInfo.getDefaultRole()); } break; case PG: if (pgDBGroup.getOrDefault(newDbInfo.getGroup(), DBRole.SLAVE) != DBRole.MASTER) { this.pgDBGroup.put(newDbInfo.getGroup(), newDbInfo.getDefaultRole()); } break; default: logger.warn("Unknown db vendor {}, skip updating DBGroup", newDbInfo.getDBVendor()); } } } public String dec(String txt) { return decryptor.decrypt(txt); } public void cleanInactiveDBConnection() { try { this.cleanInavtiveServers(); } catch (Exception e) { logger.error("Error occur during process clean inactive db connection", e); } } synchronized public void attachInavtiveServer(ServerSessionPool pool) { inactiveServers.add(pool); } synchronized public void cleanInavtiveServers() { List<ServerSessionPool> servers = this.inactiveServers; this.inactiveServers = new ArrayList<>(); for (ServerSessionPool pool : servers) { pool.closePoolConnections(); } } }
Pennsieve/upload-service
src/main/scala/com/blackfynn/upload/UploadPorts.scala
// Copyright (c) 2018 Blackfynn, Inc. All Rights Reserved. package com.blackfynn.upload import akka.http.scaladsl.model.{ HttpRequest, HttpResponse } import akka.stream.alpakka.s3.impl.MultipartUpload import akka.stream.scaladsl.Source import cats.data.NonEmptyList import com.amazonaws.services.s3.model.PartListing import com.blackfynn.upload.ChunkPorts.{ CacheHash, SendChunk } import com.blackfynn.upload.CompletePorts._ import com.blackfynn.upload.HashPorts.GetChunkHashes import com.blackfynn.upload.PreviewPorts.{ CachePreview, InitiateUpload } import com.blackfynn.upload.UploadPorts._ import com.blackfynn.upload.model.Eventual.Eventual import com.blackfynn.upload.model._ final case class UploadPorts( chunk: ChunkPorts, preview: PreviewPorts, complete: CompletePorts, status: StatusPorts, hash: HashPorts ) object UploadPorts { type ListParts = HttpRequest => Eventual[Option[PartListing]] type GetPreview = ImportId => Eventual[PackagePreview] type CheckFileExists = HttpRequest => Eventual[Boolean] def apply( chunk: ChunkPorts, preview: PreviewPorts, complete: CompletePorts, hash: HashPorts ): UploadPorts = UploadPorts(chunk, preview, complete, StatusPorts(complete), hash) } final case class CompletePorts( listParts: ListParts, completeUpload: CompleteUpload, getPreview: GetPreview, sendComplete: SendComplete, checkFileExists: CheckFileExists ) object CompletePorts { type CompleteUpload = HttpRequest => Eventual[Unit] type SendComplete = HttpRequest => Eventual[HttpResponse] } final case class PreviewPorts(cachePreview: CachePreview, initiateUpload: InitiateUpload) object PreviewPorts { type CachePreview = PackagePreview => Eventual[Unit] type InitiateUpload = HttpRequest => Eventual[MultipartUpload] } final case class StatusPorts( listParts: ListParts, getPreview: GetPreview, checkFileExists: CheckFileExists ) object StatusPorts { def apply(complete: CompletePorts): StatusPorts = StatusPorts(complete.listParts, complete.getPreview, complete.checkFileExists) } final case class ChunkPorts(sendChunk: SendChunk, cacheHash: CacheHash) object ChunkPorts { type CacheHash = ChunkHash => Eventual[Unit] type SendChunk = HttpRequest => Eventual[Unit] } case class HashPorts(getChunkHashes: GetChunkHashes, getPreview: GetPreview) object HashPorts { type GetChunkHashes = (NonEmptyList[ChunkHashId], ImportId) => Source[Either[Throwable, ChunkHash], _] }
manifoldco/heighliner
apis/v1alpha1/doc.go
<reponame>manifoldco/heighliner // +k8s:deepcopy-gen=package // Package v1alpha1 contains data types for Heighliner components v1alpha1. package v1alpha1
blackjyn/flex-sdk
modules/thirdparty/batik/sources/org/apache/flex/forks/batik/anim/values/AnimatableValue.java
<filename>modules/thirdparty/batik/sources/org/apache/flex/forks/batik/anim/values/AnimatableValue.java /* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.flex.forks.batik.anim.values; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; import org.apache.flex.forks.batik.dom.anim.AnimationTarget; /** * An abstract class for values in the animation engine. * * @author <a href="mailto:cam%40mcc%2eid%2eau"><NAME></a> * @version $Id: AnimatableValue.java 475477 2006-11-15 22:44:28Z cam $ */ public abstract class AnimatableValue { /** * A formatting object to get CSS compatible float strings. */ protected static DecimalFormat decimalFormat = new DecimalFormat ("0.0###########################################################", new DecimalFormatSymbols(Locale.ENGLISH)); /** * The target of the animation. */ protected AnimationTarget target; /** * Whether this value has changed since the last call to * {@link #hasChanged()}. This must be updated within {@link #interpolate} * in descendant classes. */ protected boolean hasChanged = true; /** * Creates a new AnimatableValue. */ protected AnimatableValue(AnimationTarget target) { this.target = target; } /** * Returns a CSS compatible string version of the specified float. */ public static String formatNumber(float f) { return decimalFormat.format(f); } /** * Performs interpolation to the given value. * @param result the object in which to store the result of the * interpolation, or null if a new object should be created * @param to the value this value should be interpolated towards, or null * if no actual interpolation should be performed * @param interpolation the interpolation distance, 0 &lt;= interpolation * &lt;= 1 * @param accumulation an accumulation to add to the interpolated value * @param multiplier an amount the accumulation values should be multiplied * by before being added to the interpolated value */ public abstract AnimatableValue interpolate(AnimatableValue result, AnimatableValue to, float interpolation, AnimatableValue accumulation, int multiplier); /** * Returns whether two values of this type can have their distance * computed, as needed by paced animation. */ public abstract boolean canPace(); /** * Returns the absolute distance between this value and the specified other * value. */ public abstract float distanceTo(AnimatableValue other); /** * Returns a zero value of this AnimatableValue's type. */ public abstract AnimatableValue getZeroValue(); /** * Returns the CSS text representation of the value. */ public String getCssText() { return null; } /** * Returns whether the value in this AnimatableValue has been modified. */ public boolean hasChanged() { boolean ret = hasChanged; hasChanged = false; return ret; } /** * Returns a string representation of this object. This should be * overridden in classes that do not have a CSS representation. */ public String toStringRep() { return getCssText(); } /** * Returns a string representation of this object prefixed with its * class name. */ public String toString() { return getClass().getName() + "[" + toStringRep() + "]"; } }
koraygulcu/bitmovin-python
bitmovin/resources/models/encodings/__init__.py
from .muxings import Muxing, FMP4Muxing, MP4Muxing, TSMuxing, WebMMuxing, ProgressiveTSMuxing, MuxingStream, \ ByteRange, MuxingInformationAudioTrack, MuxingInformationVideoTrack, ProgressiveTSInformation, \ MP4MuxingInformation, ProgressiveMOVMuxing, TimeCode from .muxings.broadcast_ts import BroadcastTsMuxing, BroadcastTsAudioStreamConfiguration, \ BroadcastTsVideoStreamConfiguration, BroadcastTsProgramConfiguration, BroadcastTsTransportConfiguration, \ BroadcastTsMuxingConfiguration, BroadcastTsInputStreamConfiguration from .drms import DRM, DRMStatus, AESDRM, ClearKeyDRM, FairPlayDRM, MarlinDRM, PlayReadyDRM, PrimeTimeDRM, \ WidevineDRM, CENCDRM, CENCPlayReadyEntry, CENCWidevineEntry from .acl_entry import ACLEntry from .infrastructure import Infrastructure from .encoding import Encoding from .encoding_output import EncodingOutput from .encoding_status import EncodingStatus from .stream import Stream from .stream_input import StreamInput from .encoding_live_details import EncodingLiveDetails from .live import LiveHlsManifest, LiveDashManifest, LiveStreamConfiguration from .thumbnail import Thumbnail from .sprite import Sprite from .stream_filter import StreamFilter from .keyframe import Keyframe from .id3 import ID3Tag, RawID3Tag, FrameIdID3Tag, PlainTextID3Tag from .ignored_by_type import IgnoredByType from .ignored_by import IgnoredBy from .start import StartEncodingRequest, StartEncodingTrimming, Scheduling, Tweaks from .conditions import ConditionType, Condition, AndConjunction, OrConjunction from .stream_metadata import StreamMetadata from .pertitle import PerTitle, PerTitleConfiguration, H264PerTitleConfiguration, AutoRepresentation
dalexa10/puma
gui/src/MaterialProperties/thermalcond.h
#ifndef THERMALCOND_H #define THERMALCOND_H #include <QDialog> #include <QDebug> #include <QTextEdit> #include "../src/Utilities/q_debugstream.h" #include "puma.h" #include <QThread> #include <QProcess> #include <QTextBrowser> #include "../src/Utilities/viewer.h" namespace Ui { class ThermalCond; } class ThermalCond : public QDialog { Q_OBJECT public: explicit ThermalCond(QWidget *parent = 0); void setViewer(Viewer *view); ~ThermalCond(); // QMessage /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ static void QMessageOutput(QtMsgType , const QMessageLogContext &, const QString &msg); /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ private slots: void on_CalculateButton_clicked(); void on_comboBox_currentIndexChanged(int index); void on_vtkButton_clicked(); void on_binaryButton_clicked(); private: Ui::ThermalCond *ui; puma::Workspace *workspace; Viewer *view; void Calculate(); // MessageHandler for display and ThreadLogStream for redirecting cout /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ MessageHandler *msgHandler = Q_NULLPTR; ThreadLogStream* m_qd; puma::Matrix<double> Tx; puma::Matrix<double> Ty; puma::Matrix<double> Tz; /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ }; #endif // THERMALCOND_H
SilverPineSoftware/UUAndroid
UUAndroid/src/main/java/uu/toolbox/bluetooth/UUClassicBluetoothScanner.java
<gh_stars>0 package uu.toolbox.bluetooth; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import androidx.annotation.NonNull; import androidx.annotation.Nullable; @SuppressWarnings("unused") public class UUClassicBluetoothScanner extends UUBluetoothDeviceScanner { private enum ScannerState { Idle, Discovery, StoppingDiscovery, } private BroadcastReceiver broadcastReceiver; private ScannerState currentState = ScannerState.Idle; public UUClassicBluetoothScanner(final Context context) { super(context); initBroadcastReceiver(); context.registerReceiver(broadcastReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); context.registerReceiver(broadcastReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)); } private void initBroadcastReceiver() { broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action != null) { switch (action) { case BluetoothAdapter.ACTION_DISCOVERY_FINISHED: handleDiscoveryFinished(intent); break; case BluetoothDevice.ACTION_FOUND: handleDeviceFound(intent); break; } } } }; } private void handleDiscoveryFinished(final Intent intent) { switch (currentState) { case Discovery: internalStartScanning(); break; case StoppingDiscovery: changeState(ScannerState.Idle); break; } } private void handleDeviceFound(final Intent intent) { BluetoothDevice device = safeGetDevice(intent); if (device != null) { // Throw out immediately any LE only device objects if (!isClassicDevice(device)) { return; } debugLog("handleDeviceFound", intent); debugLog("handleDeviceFound", "Device discovered: " + device.getName() + ", " + device.getAddress() + ", BondState: " + UUBluetooth.bondStateToString(device.getBondState()) + ", Type:" + UUBluetooth.deviceTypeToString(device.getType()) + ", BluetoothClass: " + device.getBluetoothClass() + ", State: " + currentState); processScannedDevice(device); } } private boolean isClassicDevice(@NonNull final BluetoothDevice device) { switch (device.getType()) { case BluetoothDevice.DEVICE_TYPE_CLASSIC: case BluetoothDevice.DEVICE_TYPE_DUAL: { return true; } default: { return false; } } } @Nullable private BluetoothDevice safeGetDevice(@Nullable final Intent intent) { BluetoothDevice device = null; if (intent != null) { if (intent.hasExtra(BluetoothDevice.EXTRA_DEVICE)) { device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); } } return device; } @Override protected void internalStartScanning() { boolean discoveryStarted = false; try { discoveryStarted = bluetoothAdapter.startDiscovery(); debugLog("internalStartScanning", "bluetoothAdapter.startDiscovery() returned " + discoveryStarted); } catch (Exception ex) { debugLog("internalStartScanning", ex); discoveryStarted = false; } finally { if (discoveryStarted) { changeState(ScannerState.Discovery); } else { changeState(ScannerState.Idle); } } } @Override protected void internalStopScanning() { try { changeState(ScannerState.StoppingDiscovery); boolean result = bluetoothAdapter.cancelDiscovery(); debugLog("internalStopScanning", "bluetoothAdapter.cancelDiscovery() returned " + result); } catch (Exception ex) { debugLog("internalStopScanning", ex); } } private void changeState(ScannerState state) { if (currentState != state) { currentState = state; debugLog("changeState", "New State: " + state); } } }
nbur4556/issue_reporter
controllers/index.js
module.exports = { issueController: require('./issueController.js'), projectController: require('./projectController.js'), userController: require('./userController.js') }
peynman/press-vue-core
src/crud/Page/Api/create.js
import { getCreateFormBindings, getFormValidationsAlert, getFormSubmitAction } from '../../../utils/crudForm' import SchemaCrud from '../../PageSchema' import { crudLoaderFunction } from '../../../mixins/CrudTable' import ExtraJsonTypes from '../extraJsonTypes' import { imageUploadProperty } from '../../../utils/schemaHelpers' export default function ($component) { return { to: '/admin/pages/create', permission: 'pages.store', bindings: [ { name: 'body', type: 'default', default: { }, }, { name: 'options', type: 'default', default: { }, }, ...getCreateFormBindings(), ], autoValidate: true, formTabs: [ { value: 'general', text: $component.$t('components.admin.crud.tabs.general'), }, { value: 'options', text: $component.$t('components.admin.crud.tabs.options'), }, { value: 'customCodes', text: $component.$t('components.admin.crud.tabs.customCodes'), }, ], form: [ getFormValidationsAlert($component), { key: 'slug', rules: [ $component.getRequiredRule(), ], component: { tag: 'VTextField', props: { label: $component.$t('components.admin.crud.labels.path'), hint: $component.$t('components.admin.crud.hints.path'), }, }, }, { key: 'name', rules: [ $component.getRequiredRule(), ], component: { tag: 'VTextField', props: { label: $component.$t('components.admin.crud.labels.name'), hint: $component.$t('components.admin.crud.hints.name'), }, }, }, { key: 'body.title', rules: [ $component.getRequiredRule(), ], component: { tag: 'VTextField', props: { label: $component.$t('components.admin.crud.labels.title'), }, }, }, { key: 'publish_at', tab: 'options', component: { tag: 'VTimestampInput', props: { label: $component.$t('components.admin.crud.labels.publishAt'), }, }, }, { key: 'unpublish_at', tab: 'options', component: { tag: 'VTimestampInput', props: { label: $component.$t('components.admin.crud.labels.expiresAt'), }, }, }, { key: 'zorder', component: { tag: 'VTextField', props: { label: $component.$t('components.admin.crud.labels.order'), type: 'number', }, }, }, { key: 'options.author', tab: 'options', component: { tag: 'VTextField', props: { label: $component.$t('components.admin.crud.labels.author'), clearable: true, }, }, }, { key: 'options.description', tab: 'options', component: { tag: 'VTextField', props: { label: $component.$t('components.admin.crud.labels.description'), clearable: true, }, }, }, { key: 'options.schemaId', tab: 'options', rules: [ $component.getNumericRule(), ], component: { tag: 'VCrudObjectPicker', props: { crud: SchemaCrud($component, 'user', 0), crudLoaderFunction: crudLoaderFunction($component), decorateLabel: '#:id :title', decorateMap: { id: 'id', title: 'schema.title', }, label: $component.$t('components.admin.crud.labels.pageSchema'), hint: $component.$t('components.admin.crud.hints.pageSchema'), chips: true, smallChips: true, }, }, }, { key: 'options.report_visits', tab: 'options', component: { tag: 'VCheckbox', props: { label: $component.$t('components.admin.crud.labels.reportVisits'), }, }, }, { key: 'options.report_filter', tab: 'options', component: { tag: 'VTextField', props: { label: $component.$t('components.admin.crud.labels.reportFilter'), }, }, }, { key: 'options.report_parameter', tab: 'options', component: { tag: 'VTextField', props: { label: $component.$t('components.admin.crud.labels.reportParamter'), }, }, }, { key: 'options.sources', tab: 'options', component: { tag: 'PageSourcesInput', props: { label: $component.$t('components.admin.crud.labels.pageSources'), }, factory: () => $component.$press?.importAsyncComponent('PageSourcesInput'), }, }, { key: 'options.metas', tab: 'options', component: { tag: 'VJsonEditor', props: { label: $component.$t('components.admin.crud.labels.metas'), startType: 'array', canChangeRootType: false, hideDefaultTypes: true, extraTypes: ExtraJsonTypes($component), }, }, }, { key: 'options.js', tab: 'customCodes', component: { tag: 'CodeEditor', props: { label: $component.$t('components.admin.crud.labels.jsCode'), }, factory: () => $component.$press?.importAsyncComponent('CodeEditor'), }, }, { key: 'options.html', tab: 'customCodes', component: { tag: 'CodeEditor', props: { label: $component.$t('components.admin.crud.labels.htmlCode'), }, factory: () => $component.$press?.importAsyncComponent('CodeEditor'), }, }, { key: 'body.content', component: { tag: 'VSchemaBuilder', props: { label: $component.$t('components.admin.crud.labels.content'), extraTypes: $component.$press?.getRendererComponentsList($component), customPropertyResolver: imageUploadProperty, rendererPreProcessor: $component.preProcessWidget, }, }, }, ], actions: [ getFormSubmitAction($component, values => { return $component.$store.dispatch('apiCall', { method: 'POST', url: '/api/pages', body: { body: values.body, options: values.options, slug: values.slug, name: values.name, publish_at: values.publish_at, unpublish_at: values.unpublish_at, zorder: values.zorder, }, }) }), ], } }
LehighRacing/gollum
testing/integration/pipelines_test.go
// +build integration package integration import ( "testing" "time" "github.com/trivago/tgo/ttesting" ) const ( testPipelineDistributeConfig = "test_pipeline_distribute.conf" testPipelineJoinConfig = "test_pipeline_join.conf" testPipelineDropConfig = "test_pipeline_drop.conf" testPipelineWildcardConfig = "test_pipeline_wildcard.conf" ) func TestPipelineDistribute(t *testing.T) { expect := ttesting.NewExpect(t) cmd, err := StartGollum(testPipelineDistributeConfig, DefaultStartIndicator, "-ll=2") expect.NoError(err) err = cmd.SendStdIn(100*time.Millisecond, "### fu") expect.NoError(err) err = cmd.Stop() expect.NoError(err) out := cmd.ReadStdOut() expect.ContainsN(out, "### fu", 2) } func TestPipelineJoin(t *testing.T) { expect := ttesting.NewExpect(t) cmd, err := StartGollum(testPipelineJoinConfig, DefaultStartIndicator, "-ll=2") expect.NoError(err) err = cmd.SendStdIn(100*time.Millisecond, "### fu") expect.NoError(err) err = cmd.Stop() expect.NoError(err) out := cmd.ReadStdOut() expect.ContainsN(out, "### fu", 2) } func TestPipelineDrop(t *testing.T) { expect := ttesting.NewExpect(t) cmd, err := StartGollum(testPipelineDropConfig, DefaultStartIndicator, "-ll=2") expect.NoError(err) err = cmd.SendStdIn(100*time.Millisecond, "### fu") expect.NoError(err) err = cmd.Stop() expect.NoError(err) out := cmd.ReadStdOut() expect.ContainsN(out, "STREAM-A", 1) expect.ContainsN(out, "STREAM-B", 1) expect.ContainsN(out, "### fu", 2) } func TestPipelineWildcard(t *testing.T) { expect := ttesting.NewExpect(t) cmd, err := StartGollum(testPipelineWildcardConfig, DefaultStartIndicator, "-ll=2") expect.NoError(err) err = cmd.SendStdIn(100*time.Millisecond, "### fu") expect.NoError(err) err = cmd.Stop() expect.NoError(err) out := cmd.ReadStdOut() expect.ContainsN(out, "### fu", 2) }
mcodegeeks/OpenKODE-Framework
07_Project/MonsterBattleCasino/Source/Unit/UI/MobCasinoStatus.cpp
/* ----------------------------------------------------------------------------------- * * File MobCasinoStatus.cpp * Ported By <NAME> * Contact <EMAIL> * * ----------------------------------------------------------------------------------- * * Copyright (c) 2010-2013 XMSoft * Copyright (c) 2011 FOWCOM. All rights reserved. * * ----------------------------------------------------------------------------------- * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * ----------------------------------------------------------------------------------- */ #include "Precompiled.h" #include "MobCasinoStatus.h" #include "MyData/MyData.h" cMobCasinoStatus::cMobCasinoStatus ( Node* pNode, const std::vector<cUnit*>& rMobs, eModeType eMode, KDint nBetSeatIndex ) : m_pNode ( pNode ) , m_pLabels ( new cLabels ( pNode ) ) , m_eModeType ( eMode ) { // loop for ( KDint i = 0; i < 5; i++ ) { // label parameters sLabelInt tLabelIntHp; sLabelInt tLabelIntAtk; sLabelInt tLabelIntDef; sLabelInt tLabelIntAgl; sLabelInt tLabelIntCrt; if ( rMobs [ i ] == nullptr ) { tLabelIntHp .nSub = 0; tLabelIntAtk.nSub = 0; tLabelIntDef.nSub = 0; tLabelIntAgl.nSub = 0; tLabelIntCrt.nSub = 0; } else { tLabelIntHp .nSub = rMobs [ i ]->getUseHp ( ); tLabelIntAtk.nSub = rMobs [ i ]->getUseAtk ( ); tLabelIntDef.nSub = rMobs [ i ]->getUseDef ( ); tLabelIntAgl.nSub = rMobs [ i ]->getUseAgl ( ); tLabelIntCrt.nSub = rMobs [ i ]->getUseCrt ( ); } if ( rMobs [ i ] == nullptr ) { Rect tRectHP = Rect ( 0, 0, 0, 0 ); Rect tRectATK = Rect ( 0, 0, 0, 0 ); Rect tRectDEF = Rect ( 0, 0, 0, 0 ); Rect tRectAGL = Rect ( 0, 0, 0, 0 ); Rect tRectCRT = Rect ( 0, 0, 0, 0 ); switch ( i ) { case 0 : tRectHP = Rect ( 94, 277, 100, 20 ); tRectATK = Rect ( 56, 263, 50, 20 ); tRectDEF = Rect ( 99 , 263, 45, 20 ); tRectAGL = Rect ( 56, 248, 50, 20); tRectCRT = Rect ( 99 , 248, 45, 20 ); break; case 1 : tRectHP = Rect ( 189, 277, 100, 20 ); tRectATK = Rect ( 151, 263, 50, 20 ); tRectDEF = Rect ( 194.5f, 263, 45, 20 ); tRectAGL = Rect (151, 248, 50, 20); tRectCRT = Rect ( 194.5f, 248, 45, 20 ); break; case 2 : tRectHP = Rect ( 284, 277, 100, 20 ); tRectATK = Rect ( 246, 263, 50, 20 ); tRectDEF = Rect ( 289.5f, 263, 45, 20 ); tRectAGL = Rect (246, 248, 50, 20); tRectCRT = Rect ( 289.5f, 248, 45, 20 ); break; case 3 : tRectHP = Rect ( 379, 277, 100, 20 ); tRectATK = Rect ( 341, 263, 50, 20 ); tRectDEF = Rect ( 384 , 263, 45, 20 ); tRectAGL = Rect (341, 248, 50, 20); tRectCRT = Rect ( 384 , 248, 45, 20 ); break; case 4 : tRectHP = Rect ( 474, 277, 100, 20 ); tRectATK = Rect ( 436, 263, 50, 20 ); tRectDEF = Rect ( 479 , 263, 45, 20 ); tRectAGL = Rect (436, 248, 50, 20); tRectCRT = Rect ( 479 , 248, 45, 20 ); break; } tLabelIntHp .pLabel = m_pLabels->add ( "gaeul9.ttf", 12, TextHAlignment::LEFT, tRectHP , "", LAYER_GAMEVIEW_INFO ); tLabelIntAtk.pLabel = m_pLabels->add ( "gaeul9.ttf", 12, TextHAlignment::LEFT, tRectATK, "", LAYER_GAMEVIEW_INFO ); tLabelIntDef.pLabel = m_pLabels->add ( "gaeul9.ttf", 12, TextHAlignment::LEFT, tRectDEF, "", LAYER_GAMEVIEW_INFO ); tLabelIntAgl.pLabel = m_pLabels->add ( "gaeul9.ttf", 12, TextHAlignment::LEFT, tRectAGL, "", LAYER_GAMEVIEW_INFO ); tLabelIntCrt.pLabel = m_pLabels->add ( "gaeul9.ttf", 12, TextHAlignment::LEFT, tRectCRT, "", LAYER_GAMEVIEW_INFO ); m_pLabels->setColor ( tLabelIntAtk.pLabel, 255, 255, 255 ); m_pLabels->setColor ( tLabelIntDef.pLabel, 255, 255, 255 ); m_pLabels->setColor ( tLabelIntAgl.pLabel, 255, 255, 255 ); m_pLabels->setColor ( tLabelIntCrt.pLabel, 255, 255, 255 ); } else { const KDchar* szHP = ccszf ( "%02d / %02d", rMobs [ i ]->getUseHp ( ), rMobs [ i ]->getHP ( ) ); const KDchar* szATK = ccszf ( "%02d", rMobs [ i ]->getUseAtk ( ) ); const KDchar* szDEF = ccszf ( "%02d", rMobs [ i ]->getUseDef ( ) ); const KDchar* szAGL = ccszf ( "%02d", rMobs [ i ]->getUseAgl ( ) ); const KDchar* szCRT = ccszf ( "%02d", rMobs [ i ]->getUseCrt ( ) ); Rect tRectHP = Rect ( 0, 0, 0, 0 ); Rect tRectATK = Rect ( 0, 0, 0, 0 ); Rect tRectDEF = Rect ( 0, 0, 0, 0 ); Rect tRectAGL = Rect ( 0, 0, 0, 0 ); Rect tRectCRT = Rect ( 0, 0, 0, 0 ); switch ( i ) { case 0 : tRectHP = Rect ( 94, 277, 100, 20 ); tRectATK = Rect ( 56, 263, 50, 20); tRectDEF = Rect ( 99 , 263, 45, 20 ); tRectAGL = Rect ( 56, 248, 50, 20 ); tRectCRT = Rect ( 99 , 248, 45, 20 ); break; case 1 : tRectHP = Rect ( 189, 277, 100, 20 ); tRectATK = Rect (151, 263, 50, 20); tRectDEF = Rect ( 194 , 263, 45, 20 ); tRectAGL = Rect ( 151, 248, 50, 20 ); tRectCRT = Rect ( 194 , 248, 45, 20 ); break; case 2 : tRectHP = Rect ( 284, 277, 100, 20 ); tRectATK = Rect (246, 263, 50, 20); tRectDEF = Rect ( 289.5f , 263, 45, 20 ); tRectAGL = Rect ( 246, 248, 50, 20 ); tRectCRT = Rect ( 289.5f, 248, 45, 20 ); break; case 3 : tRectHP = Rect ( 379, 277, 100, 20 ); tRectATK = Rect (341, 263, 50, 20); tRectDEF = Rect ( 384 , 263, 45, 20 ); tRectAGL = Rect ( 341, 248, 50, 20 ); tRectCRT = Rect ( 384 , 248, 45, 20 ); break; case 4 : tRectHP = Rect ( 474, 277, 100, 20 ); tRectATK = Rect (436, 263, 50, 20); tRectDEF = Rect ( 479 , 263, 45, 20 ); tRectAGL = Rect ( 436, 248, 50, 20 ); tRectCRT = Rect ( 479 , 248, 45, 20 ); break; } tLabelIntHp .pLabel = m_pLabels->add ( "gaeul9.ttf", 12, TextHAlignment::LEFT, tRectHP , szHP , LAYER_GAMEVIEW_INFO ); tLabelIntAtk.pLabel = m_pLabels->add ( "gaeul9.ttf", 12, TextHAlignment::LEFT, tRectATK, szATK, LAYER_GAMEVIEW_INFO ); tLabelIntDef.pLabel = m_pLabels->add ( "gaeul9.ttf", 12, TextHAlignment::LEFT, tRectDEF, szDEF, LAYER_GAMEVIEW_INFO ); tLabelIntAgl.pLabel = m_pLabels->add ( "gaeul9.ttf", 12, TextHAlignment::LEFT, tRectAGL, szAGL, LAYER_GAMEVIEW_INFO ); tLabelIntCrt.pLabel = m_pLabels->add ( "gaeul9.ttf", 12, TextHAlignment::LEFT, tRectCRT, szCRT, LAYER_GAMEVIEW_INFO ); if ( rMobs [ i ]->getUseAtk ( ) == rMobs [ i ]->getATK ( ) ) m_pLabels->setColor ( tLabelIntAtk.pLabel, 255, 255, 255 ); else if ( rMobs [ i ]->getUseAtk ( ) < rMobs [ i ]->getATK ( ) ) m_pLabels->setColor ( tLabelIntAtk.pLabel, 189, 29, 12 ); else m_pLabels->setColor ( tLabelIntAtk.pLabel, 12, 187, 37 ); if ( rMobs [ i ]->getUseDef ( ) == rMobs [ i ]->getDEF ( ) ) m_pLabels->setColor ( tLabelIntDef.pLabel, 255, 255, 255 ); else if ( rMobs [ i ]->getUseDef ( ) < rMobs [ i ]->getDEF ( ) ) m_pLabels->setColor ( tLabelIntDef.pLabel, 189, 29, 12 ); else m_pLabels->setColor ( tLabelIntDef.pLabel, 12, 187, 37 ); if ( rMobs [ i ]->getUseAgl ( ) == rMobs [ i ]->getAGL ( ) ) m_pLabels->setColor ( tLabelIntAgl.pLabel, 255, 255, 255 ); else if ( rMobs [ i ]->getUseAgl ( ) < rMobs [ i ]->getAGL ( ) ) m_pLabels->setColor ( tLabelIntAgl.pLabel, 189, 29, 12 ); else m_pLabels->setColor ( tLabelIntAgl.pLabel, 12, 187, 37 ); if ( rMobs [ i ]->getUseCrt ( ) == rMobs [ i ]->getCRT ( ) ) m_pLabels->setColor ( tLabelIntCrt.pLabel, 255, 255, 255 ); else if ( rMobs [ i ]->getUseCrt ( ) < rMobs [ i ]->getCRT ( ) ) m_pLabels->setColor ( tLabelIntCrt.pLabel, 189, 29, 12 ); else m_pLabels->setColor ( tLabelIntCrt.pLabel, 12, 187, 37 ); } m_aLabelHPs .push_back ( tLabelIntHp ); m_aLabelATKs.push_back ( tLabelIntAtk ); m_aLabelDEFs.push_back ( tLabelIntDef ); m_aLabelAGLs.push_back ( tLabelIntAgl ); m_aLabelCRTs.push_back ( tLabelIntCrt ); // status icons cStatusIcons* pStatusIcons = new cStatusIcons ( ); Point tPoint = Point::ZERO; switch ( i ) { case 0 : tPoint = Point ( 6, 228 ); break; case 1 : tPoint = Point ( 101, 228 ); break; case 2 : tPoint = Point ( 196, 228 ); break; case 3 : tPoint = Point ( 291, 228 ); break; case 4 : tPoint = Point ( 386, 228 ); break; } for ( KDint a = 0; a < 5; a++ ) { cSprAni* pAni = new cSprAni ( m_pNode, "Game/status_icons.png", LAYER_GAMEVIEW_INFO, Point ( tPoint.x + a * 18, tPoint.y ) ); pAni->addFrame ( Rect ( 0, 0, 15, 15), 80, false, false, Point::ZERO, Rect::ZERO, Rect::ZERO ); pAni->addFrame ( Rect ( 15, 0, 15, 15), 80, false, false, Point::ZERO, Rect::ZERO, Rect::ZERO ); pAni->addFrame ( Rect ( 30, 0, 15, 15), 80, false, false, Point::ZERO, Rect::ZERO, Rect::ZERO ); pAni->addFrame ( Rect ( 45, 0, 15, 15), 80, false, false, Point::ZERO, Rect::ZERO, Rect::ZERO ); pAni->addFrame ( Rect ( 60, 0, 15, 15), 80, false, false, Point::ZERO, Rect::ZERO, Rect::ZERO ); pAni->addFrame ( Rect ( 0, 15, 15, 15), 80, false, false, Point::ZERO, Rect::ZERO, Rect::ZERO ); pAni->addFrame ( Rect ( 15, 15, 15, 15), 80, false, false, Point::ZERO, Rect::ZERO, Rect::ZERO ); pAni->addFrame ( Rect ( 30, 15, 15, 15), 80, false, false, Point::ZERO, Rect::ZERO, Rect::ZERO ); pAni->addFrame ( Rect ( 45, 15, 15, 15), 80, false, false, Point::ZERO, Rect::ZERO, Rect::ZERO ); pAni->addFrame ( Rect ( 60, 15, 15, 15), 80, false, false, Point::ZERO, Rect::ZERO, Rect::ZERO ); pAni->setVisible ( false ); pAni->setFrameInit ( 0 ); pAni->setLoop ( false ); pAni->stop ( ); pStatusIcons->aIcons.push_back ( pAni ); } m_aStatusIcons.push_back ( pStatusIcons ); if ( m_eModeType == eModeType_Casino || m_eModeType == eModeType_MyRoom_Casino100 || m_eModeType == eModeType_MyRoom_Casino1000 ) { // status cover color layer if ( nBetSeatIndex != i ) { Color4B tColor; tColor.r = 0; tColor.g = 0; tColor.b = 0; tColor.a = 255; LayerColor* pColorLayer = LayerColor::create ( tColor, 91, 56 ); pColorLayer->setVisible ( false ); switch ( i ) { case 0 : pColorLayer->setPosition ( Point ( 4, 235 ) ); break; case 1 : pColorLayer->setPosition ( Point ( 99, 235 ) ); break; case 2 : pColorLayer->setPosition ( Point ( 194, 235 ) ); break; case 3 : pColorLayer->setPosition ( Point ( 289, 235 ) ); break; case 4 : pColorLayer->setPosition ( Point ( 385, 235 ) ); break; } m_pNode->addChild ( pColorLayer, LAYER_GAMEVIEW_INFO2 ); m_aColorStatusCovers.push_back ( pColorLayer ); // portrait cSprAnis* pAnis = nullptr; switch ( i ) { case 0 : pAnis = new cSprAnis ( m_pNode, rMobs [ i ]->getAniFileName ( ), LAYER_GAMEVIEW_INFO2, Point ( 17, 288 ) ); break; case 1 : pAnis = new cSprAnis ( m_pNode, rMobs [ i ]->getAniFileName ( ), LAYER_GAMEVIEW_INFO2, Point ( 112, 288 ) ); break; case 2 : pAnis = new cSprAnis ( m_pNode, rMobs [ i ]->getAniFileName ( ), LAYER_GAMEVIEW_INFO2, Point ( 207, 288 ) ); break; case 3 : pAnis = new cSprAnis ( m_pNode, rMobs [ i ]->getAniFileName ( ), LAYER_GAMEVIEW_INFO2, Point ( 302, 288 ) ); break; case 4 : pAnis = new cSprAnis ( m_pNode, rMobs [ i ]->getAniFileName ( ), LAYER_GAMEVIEW_INFO2, Point ( 397, 288 ) ); break; } pAnis->texLoad ( eUnitAniType_Portrait ); pAnis->changeAni ( eUnitAniType_Portrait ); pAnis->setVisible ( false ); pAnis->stop ( ); m_aSprPortraits.push_back ( pAnis ); // UI mob dividend magnifications const KDchar* pStr1 = ccszf ( "%d", (KDint) rMobs [ i ]->getDividendMagnification ( ) ); const KDchar* pStr2 = ccszf ( "%d", (KDint) ( ( rMobs [ i ]->getDividendMagnification ( ) - (KDint) rMobs [ i ]->getDividendMagnification ( ) ) * 10 ) ); Point tPoint = Point (0, 0); cLabelAtlas* pLabel1 = new cLabelAtlas ( m_pNode, pStr1, "Game/battle_multiple_num.png" , 18, 19, '0', LAYER_GAMEVIEW_INFO2, Point::ZERO ); cLabelAtlas* pLabel2 = new cLabelAtlas ( m_pNode, pStr2, "Game/battle_multiple_num2.png", 12, 13, '0', LAYER_GAMEVIEW_INFO2, Point::ZERO ); cSprite* pLabel3 = new cSprite ( m_pNode, "Game/battle_multiple_num3.png", LAYER_GAMEVIEW_INFO2, Point ( 0, 0 ), Point::ZERO ); cSprite* pLabel4 = new cSprite ( m_pNode, "Game/battle_multiple.png" , LAYER_GAMEVIEW_INFO2, Point ( 0, 0 ), Point::ZERO ); switch ( i ) { case 0 : tPoint = Point ( 50 - ( 20 + pLabel1->getSize ( ).width + 5 + pLabel2->getSize ( ).width ) / 2, 240 ); break; case 1 : tPoint = Point ( 145 - ( 20 + pLabel1->getSize ( ).width + 5 + pLabel2->getSize ( ).width ) / 2, 240 ); break; case 2 : tPoint = Point ( 240 - ( 20 + pLabel1->getSize ( ).width + 5 + pLabel2->getSize ( ).width ) / 2, 240 ); break; case 3 : tPoint = Point ( 335 - ( 20 + pLabel1->getSize ( ).width + 5 + pLabel2->getSize ( ).width ) / 2, 240 ); break; case 4 : tPoint = Point ( 430 - ( 20 + pLabel1->getSize ( ).width + 5 + pLabel2->getSize ( ).width ) / 2, 240 ); break; } pLabel1->setPoint ( Point ( tPoint.x + 20 , tPoint.y ) ); pLabel2->setPoint ( Point ( tPoint.x + 20 + pLabel1->getSize ( ).width + 5, tPoint.y ) ); pLabel3->get ( )->setPosition ( Point ( tPoint.x + 20 + pLabel1->getSize ( ).width, tPoint.y ) ); pLabel4->get ( )->setPosition ( tPoint ); pLabel1->setVisible ( false ); pLabel2->setVisible ( false ); pLabel3->get ( )->setVisible ( false ); pLabel4->get ( )->setVisible ( false ); m_pUIMobBarMagnifications .push_back ( pLabel1 ); m_pUIMobBarMagnifications2.push_back ( pLabel2 ); m_pUIMobBarMagnifications3.push_back ( pLabel3 ); m_pUIMobBarMagnifications4.push_back ( pLabel4 ); } } } // active sprite m_aActiveBars.push_back ( new cSprite ( m_pNode, "Game/game_mob_active_bar.png", LAYER_GAMEVIEW_ACTIVE, Point ( 0, 0 ), Point ( 7, 236 ) ) ); m_aActiveBars.push_back ( new cSprite ( m_pNode, "Game/game_mob_active_bar.png", LAYER_GAMEVIEW_ACTIVE, Point ( 0, 0 ), Point ( 102, 236 ) ) ); m_aActiveBars.push_back ( new cSprite ( m_pNode, "Game/game_mob_active_bar.png", LAYER_GAMEVIEW_ACTIVE, Point ( 0, 0 ), Point ( 197, 236 ) ) ); m_aActiveBars.push_back ( new cSprite ( m_pNode, "Game/game_mob_active_bar.png", LAYER_GAMEVIEW_ACTIVE, Point ( 0, 0 ), Point ( 292, 236 ) ) ); m_aActiveBars.push_back ( new cSprite ( m_pNode, "Game/game_mob_active_bar.png", LAYER_GAMEVIEW_ACTIVE, Point ( 0, 0 ), Point ( 387, 236 ) ) ); m_aActiveBarEnds.push_back ( new cSprite ( m_pNode, "Game/game_mob_active_bar_end.png", LAYER_GAMEVIEW_ACTIVE, Point ( 0, 0 ), Point ( 7, 236 ) ) ); m_aActiveBarEnds.push_back ( new cSprite ( m_pNode, "Game/game_mob_active_bar_end.png", LAYER_GAMEVIEW_ACTIVE, Point ( 0, 0 ), Point ( 102, 236 ) ) ); m_aActiveBarEnds.push_back ( new cSprite ( m_pNode, "Game/game_mob_active_bar_end.png", LAYER_GAMEVIEW_ACTIVE, Point ( 0, 0 ), Point ( 197, 236 ) ) ); m_aActiveBarEnds.push_back ( new cSprite ( m_pNode, "Game/game_mob_active_bar_end.png", LAYER_GAMEVIEW_ACTIVE, Point ( 0, 0 ), Point ( 292, 236 ) ) ); m_aActiveBarEnds.push_back ( new cSprite ( m_pNode, "Game/game_mob_active_bar_end.png", LAYER_GAMEVIEW_ACTIVE, Point ( 0, 0 ), Point ( 387, 236 ) ) ); for ( auto pNode : m_aActiveBars ) pNode->get ( )->setTextureRect ( Rect ( 0, 0, 0, 8 ) ); for ( auto pNode : m_aActiveBarEnds ) pNode->get ( )->setVisible ( false ); // kill m_pUIKillFont = new cSprite ( m_pNode, "Game/survival_kill_font.png", LAYER_GAMEVIEW_INFO2, Point ( 0, 0 ), Point ( 423, 13 ) ); m_pUIKillNum = new cLabelAtlasCustom ( m_pNode, "Game/survival_kill_num.png", 19, LAYER_GAMEVIEW_INFO2 ); m_pUIKillNum->addCharInfo ( '1', 11 ); m_pUIKillNum->addCharInfo ( '2', 15 ); m_pUIKillNum->addCharInfo ( '3', 15 ); m_pUIKillNum->addCharInfo ( '4', 15 ); m_pUIKillNum->addCharInfo ( '5', 15 ); m_pUIKillNum->addCharInfo ( '6', 15 ); m_pUIKillNum->addCharInfo ( '7', 15 ); m_pUIKillNum->addCharInfo ( '8', 15 ); m_pUIKillNum->addCharInfo ( '9', 15 ); m_pUIKillNum->addCharInfo ( '0', 15 ); m_pUIKillFont->get ( )->setVisible ( false ); m_pUIKillNum->setVisible ( false ); } cMobCasinoStatus::~cMobCasinoStatus ( KDvoid ) { // sprites for ( auto pNode : m_aActiveBars ) { CC_SAFE_RELEASE ( pNode ); } for ( auto pNode : m_aActiveBarEnds ) { CC_SAFE_RELEASE ( pNode ); } m_aActiveBars .clear ( ); m_aActiveBarEnds.clear ( ); // label parameters m_aLabelHPs .clear ( ); m_aLabelATKs.clear ( ); m_aLabelDEFs.clear ( ); m_aLabelAGLs.clear ( ); m_aLabelCRTs.clear ( ); // status icons for ( auto pNode : m_aStatusIcons ) { CC_SAFE_RELEASE ( pNode ); } m_aStatusIcons.clear ( ); // labels CC_SAFE_RELEASE ( m_pLabels ); // status cover color layer for ( auto pNode : m_aColorStatusCovers ) { m_pNode->removeChild ( pNode, true ); pNode = nullptr; } m_aColorStatusCovers.clear ( ); // portrait for ( auto pNode : m_aSprPortraits ) { CC_SAFE_RELEASE ( pNode ); } m_aSprPortraits.clear ( ); //UI mob dividend magnifications for ( auto pNode : m_pUIMobBarMagnifications ) { CC_SAFE_RELEASE ( pNode ); } for ( auto pNode : m_pUIMobBarMagnifications2 ) { CC_SAFE_RELEASE ( pNode ); } for ( auto pNode : m_pUIMobBarMagnifications3 ) { CC_SAFE_RELEASE ( pNode ); } for ( auto pNode : m_pUIMobBarMagnifications4 ) { CC_SAFE_RELEASE ( pNode ); } m_pUIMobBarMagnifications .clear ( ); m_pUIMobBarMagnifications2.clear ( ); m_pUIMobBarMagnifications3.clear ( ); m_pUIMobBarMagnifications4.clear ( ); // kill CC_SAFE_RELEASE ( m_pUIKillFont ); CC_SAFE_RELEASE ( m_pUIKillNum ); } KDvoid cMobCasinoStatus::update ( const std::vector<cUnit*>& rMobs, const std::vector<KDfloat>& rActiveGages ) { // status icons clear--------------------------------------------- for ( auto pStatusIcons : m_aStatusIcons ) { for ( auto pIcon : pStatusIcons->aIcons ) { pIcon->setVisible ( false ); } } // loop for ( KDuint i = 0; i < rMobs.size ( ); i++ ) { // get mob cUnit* pMob = rMobs [ i ]; // check if ( pMob == nullptr ) { continue; } // seat index KDint nSeatIndex = pMob->getSeatIndex ( ); // parameters------------------------------------------------- // hp if ( pMob->getDie ( ) == true ) { m_pLabels->setStr ( m_aLabelHPs [ nSeatIndex ].pLabel, "" ); m_pLabels->setStr ( m_aLabelATKs [ nSeatIndex ].pLabel, "" ); m_pLabels->setStr ( m_aLabelDEFs [ nSeatIndex ].pLabel, "" ); m_pLabels->setStr ( m_aLabelAGLs [ nSeatIndex ].pLabel, "" ); m_pLabels->setStr ( m_aLabelCRTs [ nSeatIndex ].pLabel, "" ); } else { if ( m_aLabelHPs [ nSeatIndex ].nSub != pMob->getUseHp ( ) ) { auto pLabelID = m_aLabelHPs [ nSeatIndex ].pLabel; m_aLabelHPs [ nSeatIndex ].nSub = pMob->getUseHp ( ); m_pLabels->setStr ( pLabelID, ccszf ( "%02d / %02d", pMob->getUseHp ( ), pMob->getHP ( ) ) ); } // atk if ( m_aLabelATKs [ nSeatIndex ].nSub != pMob->getUseAtk ( ) ) { m_aLabelATKs [ nSeatIndex ].nSub = pMob->getUseAtk ( ); m_pLabels->setStr ( m_aLabelATKs [ nSeatIndex ].pLabel, ccszf ( "%02d", m_aLabelATKs [ nSeatIndex ].nSub ) ); if ( pMob->getUseAtk ( ) == pMob->getATK ( ) ) m_pLabels->setColor ( m_aLabelATKs [ nSeatIndex ].pLabel, 255, 255, 255 ); else if ( pMob->getUseAtk ( ) < pMob->getATK ( ) ) m_pLabels->setColor ( m_aLabelATKs [ nSeatIndex ].pLabel, 189, 29, 12 ); else m_pLabels->setColor ( m_aLabelATKs [ nSeatIndex ].pLabel, 12, 187, 37 ); } // def if( m_aLabelDEFs [ nSeatIndex ].nSub != pMob->getUseDef ( ) ) { m_aLabelDEFs [ nSeatIndex ].nSub = pMob->getUseDef ( ); m_pLabels->setStr ( m_aLabelDEFs [ nSeatIndex ].pLabel, ccszf ( "%02d", m_aLabelDEFs [ nSeatIndex ].nSub ) ); if ( pMob->getUseDef ( ) == pMob->getDEF ( ) ) m_pLabels->setColor ( m_aLabelDEFs [ nSeatIndex ].pLabel, 255, 255, 255 ); else if ( pMob->getUseDef ( ) < pMob->getDEF ( ) ) m_pLabels->setColor ( m_aLabelDEFs [ nSeatIndex ].pLabel, 189, 29, 12 ); else m_pLabels->setColor ( m_aLabelDEFs [ nSeatIndex ].pLabel, 12, 187, 37 ); } // agl if ( m_aLabelAGLs [ nSeatIndex ].nSub != pMob->getUseAgl ( ) ) { m_aLabelAGLs [ nSeatIndex ].nSub = pMob->getUseAgl ( ); m_pLabels->setStr ( m_aLabelAGLs [ nSeatIndex ].pLabel, ccszf ( "%02d", m_aLabelAGLs [ nSeatIndex ].nSub ) ); if ( pMob->getUseAgl ( ) == pMob->getAGL ( ) ) m_pLabels->setColor ( m_aLabelAGLs [ nSeatIndex ].pLabel, 255, 255, 255 ); else if ( pMob->getUseAgl ( ) < pMob->getAGL ( ) ) m_pLabels->setColor ( m_aLabelAGLs [ nSeatIndex ].pLabel, 189, 29, 12 ); else m_pLabels->setColor ( m_aLabelAGLs [ nSeatIndex ].pLabel, 12, 187, 37 ); } // crt if ( m_aLabelCRTs [ nSeatIndex ].nSub != pMob->getUseCrt ( ) ) { m_aLabelCRTs [ nSeatIndex ].nSub = pMob->getUseCrt ( ); m_pLabels->setStr ( m_aLabelCRTs [ nSeatIndex ].pLabel, ccszf ( "%02d", m_aLabelCRTs [ nSeatIndex ].nSub ) ); if ( pMob->getUseCrt ( ) == pMob->getCRT ( ) ) m_pLabels->setColor ( m_aLabelCRTs [ nSeatIndex ].pLabel, 255, 255, 255 ); else if ( pMob->getUseCrt ( ) < pMob->getCRT ( ) ) m_pLabels->setColor ( m_aLabelCRTs [ nSeatIndex ].pLabel, 189, 29, 12 ); else m_pLabels->setColor ( m_aLabelCRTs [ nSeatIndex ].pLabel, 12, 187, 37 ); } } // status icons set------------------------------------------- const std::vector<cParaAdd>& rParaAdds = pMob->getUseParaAdd ( ); cStatusIcons* pStatusIcons = m_aStatusIcons [ nSeatIndex ]; std::vector<cParaAdd>::const_iterator pParaAddNode = rParaAdds.begin ( ); std::vector<cSprAni*>::iterator pIconNode = pStatusIcons->aIcons.begin ( ); while ( pParaAddNode != rParaAdds.end ( ) && pIconNode != pStatusIcons->aIcons.end ( ) ) { const cParaAdd& pParaAdd = *pParaAddNode; cSprAni* pSprIcon = *pIconNode; pSprIcon->setVisible ( true ); if ( pParaAdd.nHp > 0 ) pSprIcon->setFrameInit ( eStatusIcon_Regene ); else if ( pParaAdd.nHp < 0 ) pSprIcon->setFrameInit ( eStatusIcon_poison ); else if ( pParaAdd.nAtk > 0 ) pSprIcon->setFrameInit ( eStatusIcon_AtkUp ); else if ( pParaAdd.nAtk < 0 ) pSprIcon->setFrameInit ( eStatusIcon_AtkDown ); else if ( pParaAdd.nDef > 0 ) pSprIcon->setFrameInit ( eStatusIcon_DefUp ); else if ( pParaAdd.nDef < 0 ) pSprIcon->setFrameInit ( eStatusIcon_DefDown ); else if ( pParaAdd.nAgl > 0 ) pSprIcon->setFrameInit ( eStatusIcon_AglUp ); else if ( pParaAdd.nAgl < 0 ) pSprIcon->setFrameInit ( eStatusIcon_AglDown ); else if ( pParaAdd.nCrt > 0 ) pSprIcon->setFrameInit ( eStatusIcon_CrtUp ); else if ( pParaAdd.nCrt < 0 ) pSprIcon->setFrameInit ( eStatusIcon_CrtDown ); ++pParaAddNode; ++pIconNode; } } // active gages--------------------------------------------------- for ( KDuint i = 0; i < rActiveGages.size ( ); i++ ) { if ( rActiveGages [ i ] < 100 ) m_aActiveBarEnds [ i ]->get ( )->setVisible ( false ); else m_aActiveBarEnds [ i ]->get ( )->setVisible ( true ); KDfloat fWidth = ( rActiveGages [ i ] * 86 ) / 100; m_aActiveBars [ i ]->get ( )->setTextureRect ( Rect ( 0, 0, fWidth, 8 ) ); } // kill----------------------------------------------------------- if ( m_eModeType == eModeType_MyRoom_Survival ) { m_pUIKillFont->get ( )->setVisible ( true ); m_pUIKillNum->setString ( ccszf ( "%d", cMyData::getObj ( )->m_nGamingKillCount ) ); m_pUIKillNum->setPosition ( Point ( 418 - m_pUIKillNum->getSize ( ).width, 13 ) ); m_pUIKillNum->setVisible ( true ); } } KDvoid cMobCasinoStatus::setParaSub ( cUnit* pMob ) { // checi if ( pMob->getSeatIndex ( ) < 0 || pMob->getSeatIndex ( ) >= (KDint) m_aLabelHPs.size ( ) ) { return; } // init KDint nSeatIndex = pMob->getSeatIndex ( ); // set sub m_aLabelHPs [ nSeatIndex ].nSub = pMob->getHP ( ); m_aLabelATKs [ nSeatIndex ].nSub = pMob->getATK ( ); m_aLabelDEFs [ nSeatIndex ].nSub = pMob->getDEF ( ); m_aLabelAGLs [ nSeatIndex ].nSub = pMob->getAGL ( ); m_aLabelCRTs [ nSeatIndex ].nSub = pMob->getCRT ( ); // parameters // hp m_pLabels->setStr ( m_aLabelHPs [ nSeatIndex ].pLabel, ccszf ( "%02d / %02d", m_aLabelHPs [ nSeatIndex ].nSub, m_aLabelHPs [ nSeatIndex ].nSub ) ); m_pLabels->setColor ( m_aLabelHPs [ nSeatIndex ].pLabel, 255, 255, 255 ); // atk m_pLabels->setStr ( m_aLabelATKs [ nSeatIndex ].pLabel, ccszf ( "%02d / %02d", m_aLabelATKs [ nSeatIndex ].nSub, m_aLabelATKs [ nSeatIndex ].nSub ) ); m_pLabels->setColor ( m_aLabelATKs [ nSeatIndex ].pLabel, 255, 255, 255 ); // def m_pLabels->setStr ( m_aLabelDEFs [ nSeatIndex ].pLabel, ccszf ( "%02d / %02d", m_aLabelDEFs [ nSeatIndex ].nSub, m_aLabelDEFs [ nSeatIndex ].nSub ) ); m_pLabels->setColor ( m_aLabelDEFs [ nSeatIndex ].pLabel, 255, 255, 255 ); // agl m_pLabels->setStr ( m_aLabelAGLs [ nSeatIndex ].pLabel, ccszf ( "%02d / %02d", m_aLabelAGLs [ nSeatIndex ].nSub, m_aLabelAGLs [ nSeatIndex ].nSub ) ); m_pLabels->setColor ( m_aLabelAGLs [ nSeatIndex ].pLabel, 255, 255, 255 ); // crt m_pLabels->setStr ( m_aLabelCRTs [ nSeatIndex ].pLabel, ccszf ( "%02d / %02d", m_aLabelCRTs [ nSeatIndex ].nSub, m_aLabelCRTs [ nSeatIndex ].nSub ) ); m_pLabels->setColor ( m_aLabelCRTs [ nSeatIndex ].pLabel, 255, 255, 255 ); } KDvoid cMobCasinoStatus::setModeStatus ( KDvoid ) { // check if ( m_eModeType != eModeType_Casino && m_eModeType != eModeType_MyRoom_Casino100 && m_eModeType != eModeType_MyRoom_Casino1000 ) { return; } // cover for ( auto pNode : m_aColorStatusCovers ) { pNode->setVisible ( false ); } // portrait for ( auto pNode : m_aSprPortraits ) { pNode->setVisible ( false ); } // label magnifications for ( auto pNode : m_pUIMobBarMagnifications ) pNode->setVisible ( false ); for ( auto pNode : m_pUIMobBarMagnifications2 ) pNode->setVisible ( false ); for ( auto pNode : m_pUIMobBarMagnifications3 ) pNode->get ( )->setVisible ( false ); for ( auto pNode : m_pUIMobBarMagnifications4 ) pNode->get ( )->setVisible ( false ); } KDvoid cMobCasinoStatus::setModeMagnification ( KDvoid ) { // check if ( m_eModeType != eModeType_Casino && m_eModeType != eModeType_MyRoom_Casino100 && m_eModeType != eModeType_MyRoom_Casino1000 ) { return; } // cover for ( auto pNode : m_aColorStatusCovers ) { pNode->setVisible ( true ); } // portrait for ( auto pNode : m_aSprPortraits ) { pNode->setVisible ( true ); } // label magnifications for ( auto pNode : m_pUIMobBarMagnifications ) pNode->setVisible ( true ); for ( auto pNode : m_pUIMobBarMagnifications2 ) pNode->setVisible ( true ); for ( auto pNode : m_pUIMobBarMagnifications3 ) pNode->get ( )->setVisible ( true ); for ( auto pNode : m_pUIMobBarMagnifications4 ) pNode->get ( )->setVisible ( true ); }
peterahrens/FillEstimationIPDPS2017
oski-1.0.1h/include/oski/GCSR/format.h
/** * \defgroup MATTYPE_GCSR Generalized Compressed Sparse Row (GCSR) Format * \ingroup MATTYPES * * Generalized compressed sparse row (GCSR) format augments the * traditional CSR with an optional list of row indices, allowing * entire rows to be sparse. However, unlike the OSKI CSR * implementation, only a subset of semantic features are * supported: * - Indices are 0-based. * - Symmetric/Hermitian storage is not currently supported. * - Indices are assumed to be unsorted. * * A matrix with \f$m\f$ rows and \f$m_z\f$ structurally zero * rows requires less total storage in GCSR than in CSR when * \f$m_z > \frac{m}{2}\f$. * * For a detailed description of the data structure and its fields, * see #oski_matGCSR_t. */ /** * \file oski/GCSR/format.h * \ingroup MATTYPE_GCSR * \brief Generalized compressed sparse row data structure. * * For an overview, see \ref MATTYPE_GCSR. */ /** \ingroup MATTYPE_GCSR */ /*@{*/ #if !defined(INC_OSKI_GCSR_FORMAT_H) /** oski/GCSR/format.h included. */ #define INC_OSKI_GCSR_FORMAT_H #include <oski/common.h> #include <oski/matrix.h> #if defined(DO_NAME_MANGLING) /** \name Name mangling. */ /*@{*/ /** GCSR matrix representation */ #define oski_matGCSR_t MANGLE_(oski_matGCSR_t) /*@}*/ #endif /** * \brief Generalized compressed sparse row (GCSR) format. * * This data structure is similar to CSR except that there * is an additional array, rind, which stores row indices. */ typedef struct { oski_index_t num_stored_rows; /**< Number of stored rows */ oski_index_t *ptr; /**< Row pointers. */ oski_index_t *rind; /**< Row indices. */ oski_index_t *cind; /**< Column indices. */ oski_value_t *val; /**< Stored values. */ } oski_matGCSR_t; /*@}*/ #endif /* eof */
WangZhuo2000/libecc
src/utils/print_keys.c
/* * Copyright (C) 2017 - This file is part of libecc project * * Authors: * <NAME> <<EMAIL>> * <NAME> <<EMAIL>> * <NAME> <<EMAIL>> * * Contributors: * <NAME> <<EMAIL>> * <NAME> <<EMAIL>> * * This software is licensed under a dual BSD and GPL v2 license. * See LICENSE file at the root folder of the project. */ #include "print_keys.h" void priv_key_print(const char *msg, const ec_priv_key *priv) { nn_print(msg, &(priv->x)); } void pub_key_print(const char *msg, const ec_pub_key *pub) { ec_point_print(msg, &(pub->y)); }
broadinstitute/str-analysis
str_analysis/utils/strling_info_for_locus.py
def parse_strling_info_for_locus(strling_genotype_df, locus_chrom, locus_start, locus_end, margin=700): """Extract info related to a specific locus from the STRling genotype table. See https://strling.readthedocs.io/en/latest/outputs.html for more details. Args: strling_genotype_df (pd.DataFrame): parsed STRling genotype table locus_chrom (str): locus chromosome locus_start (int): locus start coord locus_end (int): locus end coord margin (int): when looking for matching STRling results, include calls this many base pairs away from the locus. This should be approximately the fragment-length or slightly larger (700 is a reasonable value for Illumina short read data). """ locus_chrom = locus_chrom.replace("chr", "") strling_results_for_locus = strling_genotype_df[ (strling_genotype_df.chrom.str.replace("chr", "") == locus_chrom) & (strling_genotype_df.start_1based < locus_end + margin) & (strling_genotype_df.end_1based > locus_start - margin) ] """ Example row: {'allele1_est': 0.0, 'allele2_est': 22.09, 'anchored_reads': 8, 'chrom': 'chr4', 'depth': 32.0, 'expected_spanning_pairs': 57.83, 'left': 39348477, 'left_clips': 5, 'repeatunit': 'AAGGG', 'right': 39348477, 'right_clips': 0, 'spanning_pairs': 0, 'spanning_pairs_pctl': 0.0, 'spanning_reads': 0, 'sum_str_counts': 265, 'unplaced_pairs': 0} """ return [row.to_dict() for _, row in strling_results_for_locus.iterrows()]
tan9/spring-security
acl/src/main/java/org/springframework/security/acls/domain/EhCacheBasedAclCache.java
<reponame>tan9/spring-security /* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import java.io.Serializable; import net.sf.ehcache.CacheException; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import org.springframework.security.acls.model.AclCache; import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.PermissionGrantingStrategy; import org.springframework.security.util.FieldUtils; import org.springframework.util.Assert; /** * Simple implementation of {@link AclCache} that delegates to EH-CACHE. * <p> * Designed to handle the transient fields in {@link AclImpl}. Note that this * implementation assumes all {@link AclImpl} instances share the same * {@link PermissionGrantingStrategy} and {@link AclAuthorizationStrategy} instances. * * @author <NAME> */ public class EhCacheBasedAclCache implements AclCache { // ~ Instance fields // ================================================================================================ private final Ehcache cache; private PermissionGrantingStrategy permissionGrantingStrategy; private AclAuthorizationStrategy aclAuthorizationStrategy; // ~ Constructors // =================================================================================================== public EhCacheBasedAclCache(Ehcache cache, PermissionGrantingStrategy permissionGrantingStrategy, AclAuthorizationStrategy aclAuthorizationStrategy) { Assert.notNull(cache, "Cache required"); Assert.notNull(permissionGrantingStrategy, "PermissionGrantingStrategy required"); Assert.notNull(aclAuthorizationStrategy, "AclAuthorizationStrategy required"); this.cache = cache; this.permissionGrantingStrategy = permissionGrantingStrategy; this.aclAuthorizationStrategy = aclAuthorizationStrategy; } // ~ Methods // ======================================================================================================== public void evictFromCache(Serializable pk) { Assert.notNull(pk, "Primary key (identifier) required"); MutableAcl acl = getFromCache(pk); if (acl != null) { cache.remove(acl.getId()); cache.remove(acl.getObjectIdentity()); } } public void evictFromCache(ObjectIdentity objectIdentity) { Assert.notNull(objectIdentity, "ObjectIdentity required"); MutableAcl acl = getFromCache(objectIdentity); if (acl != null) { cache.remove(acl.getId()); cache.remove(acl.getObjectIdentity()); } } public MutableAcl getFromCache(ObjectIdentity objectIdentity) { Assert.notNull(objectIdentity, "ObjectIdentity required"); Element element = null; try { element = cache.get(objectIdentity); } catch (CacheException ignored) { } if (element == null) { return null; } return initializeTransientFields((MutableAcl) element.getValue()); } public MutableAcl getFromCache(Serializable pk) { Assert.notNull(pk, "Primary key (identifier) required"); Element element = null; try { element = cache.get(pk); } catch (CacheException ignored) { } if (element == null) { return null; } return initializeTransientFields((MutableAcl) element.getValue()); } public void putInCache(MutableAcl acl) { Assert.notNull(acl, "Acl required"); Assert.notNull(acl.getObjectIdentity(), "ObjectIdentity required"); Assert.notNull(acl.getId(), "ID required"); if (this.aclAuthorizationStrategy == null) { if (acl instanceof AclImpl) { this.aclAuthorizationStrategy = (AclAuthorizationStrategy) FieldUtils .getProtectedFieldValue("aclAuthorizationStrategy", acl); this.permissionGrantingStrategy = (PermissionGrantingStrategy) FieldUtils .getProtectedFieldValue("permissionGrantingStrategy", acl); } } if ((acl.getParentAcl() != null) && (acl.getParentAcl() instanceof MutableAcl)) { putInCache((MutableAcl) acl.getParentAcl()); } cache.put(new Element(acl.getObjectIdentity(), acl)); cache.put(new Element(acl.getId(), acl)); } private MutableAcl initializeTransientFields(MutableAcl value) { if (value instanceof AclImpl) { FieldUtils.setProtectedFieldValue("aclAuthorizationStrategy", value, this.aclAuthorizationStrategy); FieldUtils.setProtectedFieldValue("permissionGrantingStrategy", value, this.permissionGrantingStrategy); } if (value.getParentAcl() != null) { initializeTransientFields((MutableAcl) value.getParentAcl()); } return value; } public void clearCache() { cache.removeAll(); } }
pSCANNER/SCANNER
network/services/registry/src/main/java/edu/isi/misd/scanner/network/registry/data/service/RegistryServiceImpl.java
/* * Copyright 2013 University of Southern California * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.isi.misd.scanner.network.registry.data.service; import edu.isi.misd.scanner.network.registry.data.domain.AnalysisInstance; import edu.isi.misd.scanner.network.registry.data.domain.AnalysisResult; import edu.isi.misd.scanner.network.registry.data.domain.AnalysisTool; import edu.isi.misd.scanner.network.registry.data.domain.DataSetDefinition; import edu.isi.misd.scanner.network.registry.data.domain.DataSetInstance; import edu.isi.misd.scanner.network.registry.data.domain.ScannerUser; import edu.isi.misd.scanner.network.registry.data.domain.Site; import edu.isi.misd.scanner.network.registry.data.domain.SitePolicy; import edu.isi.misd.scanner.network.registry.data.domain.StandardRole; import edu.isi.misd.scanner.network.registry.data.domain.Study; import edu.isi.misd.scanner.network.registry.data.domain.StudyManagementPolicy; import edu.isi.misd.scanner.network.registry.data.domain.StudyRole; import edu.isi.misd.scanner.network.registry.data.domain.ToolLibrary; import edu.isi.misd.scanner.network.registry.data.domain.UserRole; import edu.isi.misd.scanner.network.registry.data.repository.*; import edu.isi.misd.scanner.network.registry.web.errors.ForbiddenException; import edu.isi.misd.scanner.network.registry.web.errors.ResourceNotFoundException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.Executor; import org.apache.commons.exec.PumpStreamHandler; /** * Registry Service implementation. * * @author <NAME> */ @Service("registryService") public class RegistryServiceImpl implements RegistryService { public static final String ROOT_STUDY_NAME = "SCANNER"; @Autowired private DataSetDefinitionRepository dataSetDefinitionRepository; @Autowired private ToolLibraryRepository toolLibraryRepository; @Autowired private StudyRepository studyRepository; @Autowired private StudyRoleRepository studyRoleRepository; @Autowired private StudyManagementPolicyRepository studyManagementPolicyRepository; @Autowired private UserRoleRepository userRoleRepository; @Autowired private StandardRoleRepository standardRoleRepository; @Autowired private ScannerUserRepository scannerUserRepository; @Autowired private SiteRepository siteRepository; @Autowired private SitePolicyRepository sitePolicyRepository; @Autowired private AnalysisInstanceRepository analysisInstanceRepository; /** * Checks if the userName specified has the superuser flag set. * @param userName * @return true if the user is a superuser, false otherwise * @exception ForbiddenException if the userName is unknown (does not exist) */ @Override public boolean userIsSuperuser(String userName) throws ForbiddenException { ScannerUser user = scannerUserRepository.findByUserName(userName); if (user == null) { throw new ForbiddenException( userName,RegistryServiceConstants.MSG_UNKNOWN_USER_NAME); } return user.getIsSuperuser(); } /** * Checks if the userName specified can manage the studyId specified. * @param userName * @param studyId * @return true if the user can manage the study, false otherwise * @exception ForbiddenException if the userName is unknown (does not exist) */ @Override public boolean userCanManageStudy(String userName, Integer studyId) throws ForbiddenException { if (userIsSuperuser(userName)) { return true; } Integer count = userRoleRepository.countByUserUserNameAndStudyRoleStudyStudyId( userName,studyId); return (count > 0) ? true : false; } /** * Checks if the userName specified can manage the siteId specified. * @param userName * @param siteId * @return true if the user can manage the site, false otherwise * @exception ForbiddenException if the userName is unknown (does not exist) */ @Override public boolean userCanManageSite(String userName, Integer siteId) throws ForbiddenException { if (userIsSuperuser(userName)) { return true; } Integer count = userRoleRepository. countByUserUserNameAndStudyRoleSitePoliciesSiteSiteId( userName,siteId); return (count > 0) ? true : false; } /** * Checks if the userName specified can manage the nodeId specified. * @param userName * @param nodeId * @return true if the user can manage the node, false otherwise * @exception ForbiddenException if the userName is unknown (does not exist) */ @Override public boolean userCanManageNode(String userName, Integer nodeId) throws ForbiddenException { if (userIsSuperuser(userName)) { return true; } Integer count = userRoleRepository. countByUserUserNameAndStudyRoleSitePoliciesSiteNodesNodeId( userName,nodeId); return (count > 0) ? true : false; } /** * Checks if the userName specified can manage the dataSetInstanceId specified. * @param userName * @param dataSetInstanceId * @return true if the user can manage the dataSetInstance, false otherwise * @exception ForbiddenException if the userName is unknown (does not exist) */ @Override public boolean userCanManageDataSetInstance(String userName, Integer dataSetInstanceId) throws ForbiddenException { if (userIsSuperuser(userName)) { return true; } Integer count = userRoleRepository. countByUserUserNameAndStudyRoleSitePoliciesSiteNodesDataSetInstancesDataSetInstanceId( userName,dataSetInstanceId); return (count > 0) ? true : false; } /** * Creates or updates a single ToolLibrary, with optional creation of * AnalysisTool child relations. * @param library */ @Override @Transactional public ToolLibrary saveToolLibrary(ToolLibrary library) { List<AnalysisTool> toolList = library.getAnalysisTools(); if ((toolList != null) && (!toolList.isEmpty())) { library.setAnalysisTools(null); toolLibraryRepository.save(library); for (AnalysisTool tool : toolList) { tool.setToolParentLibrary(library); } library.setAnalysisTools(toolList); } return toolLibraryRepository.save(library); } /** * Creates or updates a single DataSetDefinition, with optional creation of * DataSetInstance child relations. * @param dataSet */ @Override @Transactional public DataSetDefinition saveDataSetDefinition(DataSetDefinition dataSet) { Set<DataSetInstance> dataSetInstances = dataSet.getDataSetInstances(); if ((dataSetInstances != null) && (!dataSetInstances.isEmpty())) { dataSet.setDataSetInstances(dataSetInstances); dataSetDefinitionRepository.save(dataSet); for (DataSetInstance instance : dataSetInstances) { instance.setDataSetDefinition(dataSet); } dataSet.setDataSetInstances(dataSetInstances); } return dataSetDefinitionRepository.save(dataSet); } /** * Creates a single Study and creates default StudyRoles for the Study based * on the existing StandardRoles. Also assigns the Study creator to * the created StudyRoles, and adds flagged StandardRoles to the * StudyManagementPolicy table. * @param study */ @Override @Transactional public Study createStudy(Study study) { // default role assignment lists based on StandardRole configuration ArrayList<StudyRole> defaultStudyManagementRoles = new ArrayList<StudyRole>(); ArrayList<StudyRole> defaultStudyRolesToUserRoles = new ArrayList<StudyRole>(); /** * 1. Create the Study */ Study createdStudy = studyRepository.save(study); /** * 2. Create the default StudyRoles based on the predefined * StandardRoles. Also store (in a separate list) any StandardRoles * that have AddToStudyPolicyByDefault set, as they will then be * saved later to the StudyManagementPolicy table. Same applies to * default UserRole creation based on getAddToUserRoleByDefault. */ ArrayList<StudyRole> studyRoles = new ArrayList<StudyRole>(); for (StandardRole standardRole : standardRoleRepository.findAll()) { StudyRole studyRole = new StudyRole(); studyRole.setRoleWithinStudy(standardRole.getStandardRoleName()); studyRole.setStudy(createdStudy); studyRoles.add(studyRole); if (standardRole.getAddToStudyPolicyByDefault()) { defaultStudyManagementRoles.add(studyRole); } if (standardRole.getAddToUserRoleByDefault()) { defaultStudyRolesToUserRoles.add(studyRole); } } studyRoleRepository.save(studyRoles); /** * 3. Add any of the flagged StudyManagement default roles to the * StudyManagementPolicy table */ ArrayList<StudyManagementPolicy> studyManagementPolicies = new ArrayList<StudyManagementPolicy>(); for (StudyRole studyManagementRole : defaultStudyManagementRoles) { StudyManagementPolicy studyManagementPolicy = new StudyManagementPolicy(); studyManagementPolicy.setStudyRoleId(studyManagementRole); studyManagementPolicy.setStudy(createdStudy); studyManagementPolicies.add(studyManagementPolicy); } studyManagementPolicyRepository.save(studyManagementPolicies); /** * 4. Add UserRole-to-StudyRole mappings for the Study creator for the * newly created StudyRoles */ ScannerUser owner = createdStudy.getStudyOwner(); ArrayList<UserRole> userRoles = new ArrayList<UserRole>(); for (StudyRole studyRole : defaultStudyRolesToUserRoles) { UserRole userRole = new UserRole(); userRole.setUser(owner); userRole.setStudyRole(studyRole); userRoles.add(userRole); } userRoleRepository.save(userRoles); return createdStudy; } /** * Updates a single Study, altering UserRole references (where required). * @param study */ @Override @Transactional public void updateStudy(Study study) { ArrayList<StudyRole> defaultStudyRolesToUserRoles = new ArrayList<StudyRole>(); List<StudyRole> studyRoles = studyRoleRepository.findByStudyStudyId(study.getStudyId()); /* * Find the set of default study roles that need to have corresponding * user roles automatically created. */ for (StandardRole standardRole : standardRoleRepository.findAll()) { if (standardRole.getAddToUserRoleByDefault()) { for (StudyRole studyRole : studyRoles) { if (studyRole.getRoleWithinStudy().equalsIgnoreCase( standardRole.getStandardRoleName())) defaultStudyRolesToUserRoles.add(studyRole); } } } /* * Create default user roles for the (potentially) new owner of the * study, if those roles do not exist already. If the owner has not * changed, then the roles will exist already and no UserRole update * will take place. */ ArrayList<UserRole> newUserRoles = new ArrayList<UserRole>(); List<StudyRole> studyRolesForUser = studyRoleRepository.findByStudyStudyIdAndScannerUsersUserName( study.getStudyId(), study.getStudyOwner().getUserName()); for (StudyRole studyRole : defaultStudyRolesToUserRoles) { if (studyRolesForUser.contains(studyRole)) { continue; } UserRole userRole = new UserRole(); userRole.setUser(study.getStudyOwner()); userRole.setStudyRole(studyRole); newUserRoles.add(userRole); } if (!newUserRoles.isEmpty()) { userRoleRepository.save(newUserRoles); } studyRepository.save(study); } /** * Deletes a single Study by Id, deleting references first (where * explicity required). * @param studyId */ @Override @Transactional public void deleteStudy(Integer studyId) { List<UserRole> userRoles = userRoleRepository.findByStudyRoleStudyStudyId(studyId); userRoleRepository.delete(userRoles); studyRepository.delete(studyId); } /** * Creates a single Site with associated roles and role permissions. * * 1. Creates the site table entry for the new site. * 2. Creates a role for the administrator at that site. * The way we've set things up, roles are associated with studies; * we use a study called "SCANNER" for this role, * and we call the role something like "SiteX Site Administrator". * 3. Creates an entry in the site_policy table giving the * "SiteX Site Administrator" role permission to administer SiteX policy. * 4. Optionally assigns a user (if specified) the new site admin role. * * @param site the site to create * @param defaultSiteAdmin the user to assign as the default site admin * @return the created site */ @Override @Transactional public Site createSite(Site site, ScannerUser defaultSiteAdmin) { /* 1. Create the site table entry for the new site. */ Site createdSite = siteRepository.save(site); /* 2. Create a role for the administrator at the new site. */ // First we have to find the correct root Study to associate the site // with. In this version, it is basically hard-coded to "SCANNER" // which is of course hacky, but will have to suffice. Study scannerStudy = studyRepository.findByStudyName(ROOT_STUDY_NAME); if (scannerStudy == null) { throw new RuntimeException( String.format( "Unable to locate the root administrative study. " + "New sites cannot be created unless a study named %s " + "already exsists.", ROOT_STUDY_NAME)); } // Now initialize the StudyRole for the site admin and associate it // with the root study, then try to create it. StudyRole siteAdminRole = new StudyRole(); siteAdminRole.setStudy(scannerStudy); siteAdminRole.setRoleWithinStudy( String.format("%s Site Administrator", site.getSiteName())); StudyRole createdSiteAdminRole = studyRoleRepository.save(siteAdminRole); /* 3. Create an entry in the SitePolicy table giving the * newly created role permission to administer the new site's policy. */ SitePolicy sitePolicy = new SitePolicy(); sitePolicy.setSite(createdSite); sitePolicy.setStudyRole(createdSiteAdminRole); sitePolicyRepository.save(sitePolicy); /* 4. If a default user was specifed, create a new UserRole for that * user and map it to the new SiteAdminRole. */ if (defaultSiteAdmin != null) { UserRole siteAdminUserRole = new UserRole(); siteAdminUserRole.setUser(defaultSiteAdmin); siteAdminUserRole.setStudyRole(createdSiteAdminRole); userRoleRepository.save(siteAdminUserRole); } return createdSite; } /** * See {@link #createSite(Site,ScannerUser) createSite}. * @param site the site to create * @return the created Site object */ @Override @Transactional public Site createSite(Site site) { return createSite(site,null); } /** * Deletes a single Site, removing any roles and privileges * associated with the Site. * @param site */ @Override @Transactional public void deleteSite(Site site) { for (SitePolicy sitePolicy : sitePolicyRepository.findBySiteSiteId(site.getSiteId())) { StudyRole studyRole = sitePolicy.getStudyRole(); List<UserRole> userRoles = userRoleRepository.findByStudyRoleRoleId(studyRole.getRoleId()); userRoleRepository.delete(userRoles); // this is hacky but it is the only way to remove the built-in Site // Administrator role without deleting other delegated study roles // which could still be valid in the context of the related study if (studyRole.getRoleWithinStudy().endsWith("Site Administrator")) { studyRoleRepository.delete(studyRole); } } siteRepository.delete(site); } /** * Creates or updates a single AnalysisInstance, with optional creation of * AnalysisResult child relations. * @param instance */ @Override @Transactional public AnalysisInstance saveAnalysisInstance(AnalysisInstance instance) { List<AnalysisResult> resultList = instance.getAnalysisResults(); if ((resultList != null) && (!resultList.isEmpty())) { instance.setAnalysisResults(null); Date now = Calendar.getInstance().getTime(); if (instance.getCreated() == null) { instance.setCreated(now); } instance.setUpdated(now); analysisInstanceRepository.save(instance); for (AnalysisResult result : resultList) { result.setAnalysisInstance(instance); } instance.setAnalysisResults(resultList); } return analysisInstanceRepository.save(instance); } @Override public String convertDataProcessingSpecification(String workingDir, String execName, String args, String input, Integer dataSetId) throws Exception { Executor exec = new DefaultExecutor(); exec.setWorkingDirectory(new File(workingDir)); CommandLine cl = new CommandLine(execName); cl.addArgument(args); ByteArrayInputStream in = new ByteArrayInputStream(input.getBytes("UTF-8")); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(out,err,in); exec.setStreamHandler(streamHandler); try { exec.execute(cl); } catch (Exception e) { throw new Exception(e.toString() + "\n\n" + err.toString("UTF-8")); } String output = out.toString("UTF-8"); if (dataSetId != null) { DataSetDefinition dataSet = dataSetDefinitionRepository.findOne(dataSetId); if (dataSet == null) { throw new ResourceNotFoundException(dataSetId); } dataSet.setDataProcessingSpecification(input); dataSet.setDataProcessingProgram(output); dataSetDefinitionRepository.save(dataSet); } return output; } }
blueboxd/chromium-legacy
content/browser/renderer_host/render_widget_host_view_android.cc
<reponame>blueboxd/chromium-legacy // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/render_widget_host_view_android.h" #include <android/bitmap.h> #include <limits> #include <utility> #include "base/android/build_info.h" #include "base/android/callback_android.h" #include "base/android/jni_string.h" #include "base/auto_reset.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "base/command_line.h" #include "base/files/file_util.h" #include "base/location.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/metrics/histogram_macros.h" #include "base/strings/utf_string_conversions.h" #include "base/system/sys_info.h" #include "base/task/single_thread_task_runner.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/thread_task_runner_handle.h" #include "cc/base/math_util.h" #include "cc/layers/layer.h" #include "cc/layers/surface_layer.h" #include "cc/trees/latency_info_swap_promise.h" #include "cc/trees/layer_tree_host.h" #include "components/viz/common/features.h" #include "components/viz/common/quads/compositor_frame.h" #include "components/viz/common/surfaces/frame_sink_id_allocator.h" #include "components/viz/common/surfaces/parent_local_surface_id_allocator.h" #include "content/browser/accessibility/browser_accessibility_manager_android.h" #include "content/browser/accessibility/web_contents_accessibility_android.h" #include "content/browser/android/gesture_listener_manager.h" #include "content/browser/android/ime_adapter_android.h" #include "content/browser/android/overscroll_controller_android.h" #include "content/browser/android/selection/selection_popup_controller.h" #include "content/browser/android/synchronous_compositor_host.h" #include "content/browser/android/text_suggestion_host_android.h" #include "content/browser/bad_message.h" #include "content/browser/compositor/surface_utils.h" #include "content/browser/devtools/render_frame_devtools_agent_host.h" #include "content/browser/gpu/gpu_process_host.h" #include "content/browser/renderer_host/compositor_impl_android.h" #include "content/browser/renderer_host/delegated_frame_host_client_android.h" #include "content/browser/renderer_host/input/input_router.h" #include "content/browser/renderer_host/input/synthetic_gesture_target_android.h" #include "content/browser/renderer_host/input/touch_selection_controller_client_manager_android.h" #include "content/browser/renderer_host/input/web_input_event_builders_android.h" #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_view_host_delegate_view.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/renderer_host/render_widget_host_input_event_router.h" #include "content/browser/renderer_host/ui_events_helper.h" #include "content/common/content_switches_internal.h" #include "content/public/android/content_jni_headers/RenderWidgetHostViewImpl_jni.h" #include "content/public/browser/android/compositor.h" #include "content/public/browser/android/synchronous_compositor_client.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_widget_host_iterator.h" #include "content/public/common/content_client.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/use_zoom_for_dsf_policy.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "ui/android/view_android_observer.h" #include "ui/android/window_android.h" #include "ui/android/window_android_compositor.h" #include "ui/base/layout.h" #include "ui/base/ui_base_types.h" #include "ui/display/display_util.h" #include "ui/events/android/gesture_event_android.h" #include "ui/events/android/gesture_event_type.h" #include "ui/events/android/motion_event_android.h" #include "ui/events/blink/blink_event_util.h" #include "ui/events/blink/blink_features.h" #include "ui/events/blink/did_overscroll_params.h" #include "ui/events/blink/web_input_event_traits.h" #include "ui/events/event_utils.h" #include "ui/events/gesture_detection/gesture_provider_config_helper.h" #include "ui/gfx/android/view_configuration.h" #include "ui/gfx/codec/jpeg_codec.h" #include "ui/gfx/geometry/dip_util.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/touch_selection/selection_event_type.h" #include "ui/touch_selection/touch_selection_controller.h" namespace content { namespace { static const char kAsyncReadBackString[] = "Compositing.CopyFromSurfaceTime"; static const base::TimeDelta kClickCountInterval = base::Seconds(0.5); static const float kClickCountRadiusSquaredDIP = 25; std::unique_ptr<ui::TouchSelectionController> CreateSelectionController( ui::TouchSelectionControllerClient* client, bool has_view_tree) { DCHECK(client); DCHECK(has_view_tree); ui::TouchSelectionController::Config config; config.max_tap_duration = base::Milliseconds(gfx::ViewConfiguration::GetLongPressTimeoutInMs()); config.tap_slop = gfx::ViewConfiguration::GetTouchSlopInDips(); config.enable_adaptive_handle_orientation = base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableAdaptiveSelectionHandleOrientation); config.enable_longpress_drag_selection = base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableLongpressDragSelection); config.hide_active_handle = base::android::BuildInfo::GetInstance()->sdk_int() >= base::android::SDK_VERSION_P; return std::make_unique<ui::TouchSelectionController>(client, config); } gfx::RectF GetSelectionRect(const ui::TouchSelectionController& controller) { // When the touch handles are on the same line, the rect may become simply a // one-dimensional rect, and still need to union the handle rect to avoid the // context menu covering the touch handle. See detailed comments in // TouchSelectionController::GetRectBetweenBounds(). Ensure that the |rect| is // not empty by adding a pixel width or height to avoid the wrong menu // position. gfx::RectF rect = controller.GetVisibleRectBetweenBounds(); if (rect.IsEmpty()) { gfx::SizeF size = rect.size(); size.SetToMax(gfx::SizeF(1.0f, 1.0f)); rect.set_size(size); } rect.Union(controller.GetStartHandleRect()); rect.Union(controller.GetEndHandleRect()); return rect; } void RecordToolTypeForActionDown(const ui::MotionEventAndroid& event) { ui::MotionEventAndroid::Action action = event.GetAction(); if (action == ui::MotionEventAndroid::Action::DOWN || action == ui::MotionEventAndroid::Action::POINTER_DOWN || action == ui::MotionEventAndroid::Action::BUTTON_PRESS) { UMA_HISTOGRAM_ENUMERATION( "Event.AndroidActionDown.ToolType", static_cast<int>(event.GetToolType(0)), static_cast<int>(ui::MotionEventAndroid::ToolType::LAST) + 1); } } void WakeUpGpu(GpuProcessHost* host) { if (host && host->gpu_host()->wake_up_gpu_before_drawing()) { host->gpu_service()->WakeUpGpu(); } } std::string CompressAndSaveBitmap(const std::string& dir, const SkBitmap& bitmap) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); std::vector<unsigned char> data; if (!gfx::JPEGCodec::Encode(bitmap, 85, &data)) { LOG(ERROR) << "Failed to encode bitmap to JPEG"; return std::string(); } base::FilePath screenshot_dir(dir); if (!base::DirectoryExists(screenshot_dir)) { if (!base::CreateDirectory(screenshot_dir)) { LOG(ERROR) << "Failed to create screenshot directory"; return std::string(); } } base::FilePath screenshot_path; base::ScopedFILE out_file(base::CreateAndOpenTemporaryStreamInDir( screenshot_dir, &screenshot_path)); if (!out_file) { LOG(ERROR) << "Failed to create temporary screenshot file"; return std::string(); } unsigned int bytes_written = fwrite(reinterpret_cast<const char*>(data.data()), 1, data.size(), out_file.get()); out_file.reset(); // Explicitly close before a possible Delete below. // If there were errors, don't leave a partial file around. if (bytes_written != data.size()) { base::DeleteFile(screenshot_path); LOG(ERROR) << "Error writing screenshot file to disk"; return std::string(); } return screenshot_path.value(); } } // namespace RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid( RenderWidgetHostImpl* widget_host, gfx::NativeView parent_native_view) : RenderWidgetHostViewBase(widget_host), is_showing_(!widget_host->is_hidden()), is_window_visible_(true), is_window_activity_started_(true), is_in_vr_(false), ime_adapter_android_(nullptr), selection_popup_controller_(nullptr), text_suggestion_host_(nullptr), gesture_listener_manager_(nullptr), view_(ui::ViewAndroid::LayoutType::MATCH_PARENT), gesture_provider_( ui::GetGestureProviderConfig( ui::GestureProviderConfigType::CURRENT_PLATFORM, content::GetUIThreadTaskRunner({BrowserTaskType::kUserInput})), this), stylus_text_selector_(this), using_browser_compositor_(CompositorImpl::IsInitialized()), synchronous_compositor_client_(nullptr), observing_root_window_(false), prev_top_shown_pix_(0.f), prev_top_controls_pix_(0.f), prev_top_controls_translate_(0.f), prev_top_controls_min_height_offset_pix_(0.f), prev_bottom_shown_pix_(0.f), prev_bottom_controls_translate_(0.f), prev_bottom_controls_min_height_offset_pix_(0.f), page_scale_(1.f), min_page_scale_(1.f), max_page_scale_(1.f), mouse_wheel_phase_handler_(this), is_surface_sync_throttling_(features::IsSurfaceSyncThrottling()) { // Set the layer which will hold the content layer for this view. The content // layer is managed by the DelegatedFrameHost. view_.SetLayer(cc::Layer::Create()); view_.set_event_handler(this); // If we're showing at creation time, we won't get a visibility change, so // generate our initial LocalSurfaceId here. if (is_showing_) local_surface_id_allocator_.GenerateId(); delegated_frame_host_client_ = std::make_unique<DelegatedFrameHostClientAndroid>(this); delegated_frame_host_ = std::make_unique<ui::DelegatedFrameHostAndroid>( &view_, GetHostFrameSinkManager(), delegated_frame_host_client_.get(), host()->GetFrameSinkId()); if (is_showing_) { delegated_frame_host_->WasShown( local_surface_id_allocator_.GetCurrentLocalSurfaceId(), GetCompositorViewportPixelSize(), host()->delegate()->IsFullscreen()); } // Let the page-level input event router know about our frame sink ID // for surface-based hit testing. if (ShouldRouteEvents()) { host()->delegate()->GetInputEventRouter()->AddFrameSinkIdOwner( GetFrameSinkId(), this); } host()->SetView(this); touch_selection_controller_client_manager_ = std::make_unique<TouchSelectionControllerClientManagerAndroid>( this, GetHostFrameSinkManager()); UpdateNativeViewTree(parent_native_view); // This RWHVA may have been created speculatively. We should give any // existing RWHVAs priority for receiving input events, otherwise a // speculative RWHVA could be sent input events intended for the currently // showing RWHVA. if (parent_native_view) parent_native_view->MoveToBack(&view_); CreateOverscrollControllerIfPossible(); if (GetTextInputManager()) GetTextInputManager()->AddObserver(this); host()->render_frame_metadata_provider()->AddObserver(this); } RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() { UpdateNativeViewTree(nullptr); view_.set_event_handler(nullptr); DCHECK(!ime_adapter_android_); DCHECK(!delegated_frame_host_); if (obj_) { Java_RenderWidgetHostViewImpl_clearNativePtr( base::android::AttachCurrentThread(), obj_); obj_.Reset(); } } void RenderWidgetHostViewAndroid::AddDestructionObserver( DestructionObserver* observer) { destruction_observers_.AddObserver(observer); } void RenderWidgetHostViewAndroid::RemoveDestructionObserver( DestructionObserver* observer) { destruction_observers_.RemoveObserver(observer); } base::CallbackListSubscription RenderWidgetHostViewAndroid::SubscribeToSurfaceIdChanges( const SurfaceIdChangedCallback& callback) { return surface_id_changed_callbacks_.Add(callback); } void RenderWidgetHostViewAndroid::OnSurfaceIdChanged() { surface_id_changed_callbacks_.Notify(GetCurrentSurfaceId()); } void RenderWidgetHostViewAndroid::InitAsChild(gfx::NativeView parent_view) { NOTIMPLEMENTED(); } void RenderWidgetHostViewAndroid::InitAsPopup( RenderWidgetHostView* parent_host_view, const gfx::Rect& pos, const gfx::Rect& anchor_rect) { NOTIMPLEMENTED(); } void RenderWidgetHostViewAndroid::NotifyVirtualKeyboardOverlayRect( const gfx::Rect& keyboard_rect) { RenderFrameHostImpl* frame_host = RenderViewHostImpl::From(host())->GetMainRenderFrameHost(); if (!frame_host || !frame_host->ShouldVirtualKeyboardOverlayContent()) return; gfx::Rect keyboard_rect_with_scale; if (!keyboard_rect.IsEmpty()) { float scale = IsUseZoomForDSFEnabled() ? 1 / view_.GetDipScale() : 1.f; keyboard_rect_with_scale = ScaleToEnclosedRect(keyboard_rect, scale); // Intersect the keyboard rect with the `this` bounds which will be sent // to the renderer. keyboard_rect_with_scale.Intersect(GetViewBounds()); } frame_host->NotifyVirtualKeyboardOverlayRect(keyboard_rect_with_scale); } bool RenderWidgetHostViewAndroid::ShouldVirtualKeyboardOverlayContent() { RenderFrameHostImpl* frame_host = RenderViewHostImpl::From(host())->GetMainRenderFrameHost(); return frame_host && frame_host->ShouldVirtualKeyboardOverlayContent(); } bool RenderWidgetHostViewAndroid::SynchronizeVisualProperties( const cc::DeadlinePolicy& deadline_policy, const absl::optional<viz::LocalSurfaceId>& child_local_surface_id) { if (!CanSynchronizeVisualProperties()) return false; if (child_local_surface_id) { local_surface_id_allocator_.UpdateFromChild(*child_local_surface_id); } else { local_surface_id_allocator_.GenerateId(); // When a rotation begins while hidden, the Renderer will report the amount // of time spent performing layout of the incremental surfaces. We cache the // first viz::LocalSurfaceId sent, and then update |hidden_rotation_time_| // for all subsequent cc::RenderFrameMetadata reported until the rotation // completes. if (!is_showing_ && in_rotation_ && !first_hidden_local_surface_id_.is_valid()) { hidden_rotation_time_ = base::TimeDelta(); first_hidden_local_surface_id_ = local_surface_id_allocator_.GetCurrentLocalSurfaceId(); } } // If we still have an invalid viz::LocalSurfaceId, then we are hidden and // evicted. This will have been triggered by a child acknowledging a previous // synchronization message via DidUpdateVisualProperties. The child has not // prompted any further property changes, so we do not need to continue // syncrhonization. Nor do we want to embed an invalid surface. if (!local_surface_id_allocator_.HasValidLocalSurfaceId()) return false; if (delegated_frame_host_) { delegated_frame_host_->EmbedSurface( local_surface_id_allocator_.GetCurrentLocalSurfaceId(), GetCompositorViewportPixelSize(), deadline_policy, host()->delegate()->IsFullscreen()); } return host()->SynchronizeVisualProperties(); } void RenderWidgetHostViewAndroid::SetSize(const gfx::Size& size) { // Ignore the given size as only the Java code has the power to // resize the view on Android. default_bounds_ = gfx::Rect(default_bounds_.origin(), size); } void RenderWidgetHostViewAndroid::SetBounds(const gfx::Rect& rect) { default_bounds_ = rect; } bool RenderWidgetHostViewAndroid::HasValidFrame() const { if (!delegated_frame_host_) return false; if (!view_.parent()) return false; if (current_surface_size_.IsEmpty()) return false; return delegated_frame_host_->HasSavedFrame(); } gfx::NativeView RenderWidgetHostViewAndroid::GetNativeView() { return &view_; } gfx::NativeViewAccessible RenderWidgetHostViewAndroid::GetNativeViewAccessible() { NOTIMPLEMENTED(); return NULL; } void RenderWidgetHostViewAndroid::GotFocus() { host()->GotFocus(); OnFocusInternal(); } void RenderWidgetHostViewAndroid::LostFocus() { host()->LostFocus(); LostFocusInternal(); } void RenderWidgetHostViewAndroid::OnRenderFrameMetadataChangedBeforeActivation( const cc::RenderFrameMetadata& metadata) { // If we began Surface Synchronization while hidden, the Renderer will report // the time spent performing the incremental layouts. The record those here, // to be included with the final time spend completing rotation in // OnRenderFrameMetadataChangedAfterActivation. if (first_hidden_local_surface_id_.is_valid() && metadata.local_surface_id->is_valid()) { auto local_surface_id = metadata.local_surface_id.value(); // We stop recording layout times once the surface is expected as the final // one for rotation. For that surface we are interested in the full time // until activation. Which will include layout and rendering. if (!rotation_metrics_.empty() && local_surface_id.IsSameOrNewerThan(rotation_metrics_.front().second)) { first_hidden_local_surface_id_ = viz::LocalSurfaceId(); } else if (metadata.local_surface_id->IsSameOrNewerThan( first_hidden_local_surface_id_)) { hidden_rotation_time_ += metadata.visual_properties_update_duration; } } bool is_transparent = metadata.has_transparent_background; SkColor root_background_color = metadata.root_background_color; if (!using_browser_compositor_) { // DevTools ScreenCast support for Android WebView. last_render_frame_metadata_ = metadata; // Android WebView ignores transparent background. is_transparent = false; } gesture_provider_.SetDoubleTapSupportForPageEnabled( !metadata.is_mobile_optimized); float dip_scale = view_.GetDipScale(); gfx::SizeF root_layer_size_dip = metadata.root_layer_size; gfx::SizeF scrollable_viewport_size_dip = metadata.scrollable_viewport_size; gfx::Vector2dF root_scroll_offset_dip = metadata.root_scroll_offset.value_or(gfx::Vector2dF()); if (IsUseZoomForDSFEnabled()) { float pix_to_dip = 1 / dip_scale; root_layer_size_dip.Scale(pix_to_dip); scrollable_viewport_size_dip.Scale(pix_to_dip); root_scroll_offset_dip.Scale(pix_to_dip); } float to_pix = IsUseZoomForDSFEnabled() ? 1.f : dip_scale; // Note that the height of browser control is not affected by page scale // factor. Thus, |top_content_offset| in CSS pixels is also in DIPs. float top_content_offset = metadata.top_controls_height * metadata.top_controls_shown_ratio; float top_shown_pix = top_content_offset * to_pix; if (ime_adapter_android_) { ime_adapter_android_->UpdateFrameInfo(metadata.selection.start, dip_scale, top_shown_pix); } if (!gesture_listener_manager_) return; UpdateTouchSelectionController(metadata.selection, metadata.page_scale_factor, metadata.top_controls_height, metadata.top_controls_shown_ratio, scrollable_viewport_size_dip); // ViewAndroid::content_offset() must be in dip. float top_content_offset_dip = IsUseZoomForDSFEnabled() ? top_content_offset / dip_scale : top_content_offset; view_.UpdateFrameInfo({scrollable_viewport_size_dip, top_content_offset_dip}); bool controls_changed = UpdateControls( view_.GetDipScale(), metadata.top_controls_height, metadata.top_controls_shown_ratio, metadata.top_controls_min_height_offset, metadata.bottom_controls_height, metadata.bottom_controls_shown_ratio, metadata.bottom_controls_min_height_offset); SetContentBackgroundColor(is_transparent ? SK_ColorTRANSPARENT : root_background_color); if (overscroll_controller_) { overscroll_controller_->OnFrameMetadataUpdated( metadata.page_scale_factor, metadata.device_scale_factor, metadata.scrollable_viewport_size, metadata.root_layer_size, metadata.root_scroll_offset.value_or(gfx::Vector2dF()), metadata.root_overflow_y_hidden); } // All offsets and sizes except |top_shown_pix| are in dip. gesture_listener_manager_->UpdateScrollInfo( root_scroll_offset_dip, metadata.page_scale_factor, metadata.min_page_scale_factor, metadata.max_page_scale_factor, root_layer_size_dip, scrollable_viewport_size_dip, top_content_offset_dip, top_shown_pix, controls_changed); // This needs to be called after GestureListenerManager::UpdateScrollInfo, as // it depends on frame info being updated during the UpdateScrollInfo call. auto* wcax = GetWebContentsAccessibilityAndroid(); if (wcax) wcax->UpdateFrameInfo(metadata.page_scale_factor); page_scale_ = metadata.page_scale_factor; min_page_scale_ = metadata.min_page_scale_factor; max_page_scale_ = metadata.max_page_scale_factor; current_surface_size_ = metadata.viewport_size_in_pixels; // With SurfaceSync we no longer call evict frame on every metadata change. We // must still call UpdateWebViewBackgroundColorIfNecessary to maintain the // associated background color changes. UpdateWebViewBackgroundColorIfNecessary(); if (metadata.new_vertical_scroll_direction != viz::VerticalScrollDirection::kNull) { bool can_scroll = metadata.root_layer_size.height() - metadata.viewport_size_in_pixels.height() > std::numeric_limits<float>::epsilon(); float scroll_ratio = 0.f; if (can_scroll && metadata.root_scroll_offset) { scroll_ratio = metadata.root_scroll_offset.value().y() / (metadata.root_layer_size.height() - metadata.viewport_size_in_pixels.height()); } view_.OnVerticalScrollDirectionChanged( metadata.new_vertical_scroll_direction == viz::VerticalScrollDirection::kUp, scroll_ratio); } } base::android::ScopedJavaLocalRef<jobject> RenderWidgetHostViewAndroid::GetJavaObject() { if (!obj_) { JNIEnv* env = base::android::AttachCurrentThread(); obj_.Reset(env, Java_RenderWidgetHostViewImpl_create( env, reinterpret_cast<intptr_t>(this)) .obj()); } return base::android::ScopedJavaLocalRef<jobject>(obj_); } bool RenderWidgetHostViewAndroid::IsReady( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj) { return HasValidFrame(); } void RenderWidgetHostViewAndroid::DismissTextHandles( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj) { DismissTextHandles(); } jint RenderWidgetHostViewAndroid::GetBackgroundColor( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj) { absl::optional<SkColor> color = RenderWidgetHostViewAndroid::GetCachedBackgroundColor(); if (!color) return SK_ColorTRANSPARENT; return *color; } void RenderWidgetHostViewAndroid::ShowContextMenuAtTouchHandle( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, jint x, jint y) { if (GetTouchSelectionControllerClientManager()) { GetTouchSelectionControllerClientManager()->ShowContextMenu( gfx::Point(x, y)); } } void RenderWidgetHostViewAndroid::OnViewportInsetBottomChanged( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj) { SynchronizeVisualProperties(cc::DeadlinePolicy::UseDefaultDeadline(), absl::nullopt); } void RenderWidgetHostViewAndroid::WriteContentBitmapToDiskAsync( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, jint width, jint height, const base::android::JavaParamRef<jstring>& jpath, const base::android::JavaParamRef<jobject>& jcallback) { base::OnceCallback<void(const SkBitmap&)> result_callback = base::BindOnce( &RenderWidgetHostViewAndroid::OnFinishGetContentBitmap, weak_ptr_factory_.GetWeakPtr(), base::android::ScopedJavaGlobalRef<jobject>(env, obj), base::android::ScopedJavaGlobalRef<jobject>(env, jcallback), base::android::ConvertJavaStringToUTF8(env, jpath)); CopyFromSurface(gfx::Rect(), gfx::Size(width, height), std::move(result_callback)); } void RenderWidgetHostViewAndroid::OnRenderFrameMetadataChangedAfterActivation( base::TimeTicks activation_time) { const cc::RenderFrameMetadata& metadata = host()->render_frame_metadata_provider()->LastRenderFrameMetadata(); auto activated_local_surface_id = metadata.local_surface_id.value_or(viz::LocalSurfaceId()); if (activated_local_surface_id.is_valid()) { // We have received content, ensure that any subsequent navigation allocates // a new surface. pre_navigation_content_ = true; while (!rotation_metrics_.empty()) { auto rotation_target = rotation_metrics_.front(); // Activation from a previous surface before the new rotation has set a // viz::LocalSurfaceId. if (!rotation_target.second.is_valid()) break; // In most cases the viz::LocalSurfaceId will be the same. // // However, if there are two cases where this does not occur. // // Firstly the Renderer may increment the |child_sequence_number| if it // needs to also alter visual properties. If so the newer surface would // denote the first visual update of the rotation. So its activation time // is correct. // // Otherwise there may be two rotations in close proximity, and one takes // too long to present. When this occurs the initial rotation does not // display. This newer surface will be the first displayed. Use its // activation time for the rotation, as the user would have been blocked // on visual updates for that long. // // We want to know of these long tail rotation times. if (activated_local_surface_id.IsSameOrNewerThan( rotation_target.second)) { // The duration for a rotation encompasses two separate spans of time, // depending on whether or not we were `is_showing_` at the start of // rotation. // // For a visible rotation `rotation_target.first` denotes the start of // the rotation event handled in BeginRotationBatching. // // For a hidden rotation we ignore this initial event, as the Renderer // can continue to be hidden for a long time. In these cases the // `rotation_target.first` denotes when ShowInternal is called. // // From these, until `activation_time`, we can determine the length of // time that the Renderer is visible, until the post rotation surface is // first displayed. // // For hidden rotations, the Renderer may be doing additional, partial, // layouts. This is tracked in `hidden_rotation_time_`. This extra work // will be removed once `is_surface_sync_throttling_` is the default. auto duration = activation_time - rotation_target.first + hidden_rotation_time_; TRACE_EVENT_NESTABLE_ASYNC_END_WITH_TIMESTAMP1( "viz", "RenderWidgetHostViewAndroid::RotationEmbed", TRACE_ID_LOCAL(rotation_target.second.hash()), activation_time, "duration(ms)", duration.InMillisecondsF()); // Report the total time from the first notification of rotation // beginning, until the Renderer has submitted and activated a // corresponding surface. UMA_HISTOGRAM_TIMES("Android.Rotation.BeginToRendererFrameActivation", duration); hidden_rotation_time_ = base::TimeDelta(); rotation_metrics_.pop_front(); } else { // The embedded surface may have updated the // LocalSurfaceId::child_sequence_number while we were updating the // parent_sequence_number for `rotation_target`. For example starting // from (6, 2) the child advances to (6, 3), and the parent advances to // (7, 2). viz::LocalSurfaceId::IsNewerThan will return false in these // mixed sequence advancements. // // Subsequently we would merge the two into (7, 3) which will become the // actually submitted surface to Viz. // // As such we have now received a surface that is not for our target, so // we break here and await the next frame from the child. break; } } if (rotation_metrics_.empty()) in_rotation_ = false; } if (ime_adapter_android_) { // We need to first wait for Blink's viewport size to change such that we // can correctly scroll to the currently focused input. // On Clank, only visible viewport size changes and device viewport size or // viewport_size_in_pixels do not change according to the window/view size /// change. Only scrollable viewport size changes both for Chrome and // WebView. ime_adapter_android_->OnRenderFrameMetadataChangedAfterActivation( metadata.scrollable_viewport_size); } } void RenderWidgetHostViewAndroid::OnRootScrollOffsetChanged( const gfx::Vector2dF& root_scroll_offset) { if (!gesture_listener_manager_) return; gfx::Vector2dF root_scroll_offset_dip = root_scroll_offset; if (IsUseZoomForDSFEnabled()) root_scroll_offset_dip.Scale(1 / view_.GetDipScale()); gesture_listener_manager_->OnRootScrollOffsetChanged(root_scroll_offset_dip); } void RenderWidgetHostViewAndroid::Focus() { if (view_.HasFocus()) GotFocus(); else view_.RequestFocus(); } void RenderWidgetHostViewAndroid::OnFocusInternal() { if (overscroll_controller_) overscroll_controller_->Enable(); } void RenderWidgetHostViewAndroid::LostFocusInternal() { if (overscroll_controller_) overscroll_controller_->Disable(); } bool RenderWidgetHostViewAndroid::HasFocus() { return view_.HasFocus(); } bool RenderWidgetHostViewAndroid::IsSurfaceAvailableForCopy() { return !using_browser_compositor_ || (delegated_frame_host_ && delegated_frame_host_->CanCopyFromCompositingSurface()); } void RenderWidgetHostViewAndroid::Show() { if (is_showing_) return; is_showing_ = true; ShowInternal(); } void RenderWidgetHostViewAndroid::Hide() { if (!is_showing_) return; is_showing_ = false; HideInternal(); } bool RenderWidgetHostViewAndroid::IsShowing() { // |view_.parent()| being NULL means that it is not attached // to the View system yet, so we treat this RWHVA as hidden. return is_showing_ && view_.parent(); } void RenderWidgetHostViewAndroid::SelectWordAroundCaretAck(bool did_select, int start_adjust, int end_adjust) { if (!selection_popup_controller_) return; selection_popup_controller_->OnSelectWordAroundCaretAck( did_select, start_adjust, end_adjust); } gfx::Rect RenderWidgetHostViewAndroid::GetViewBounds() { if (!view_.parent()) return default_bounds_; gfx::Size size(view_.GetSize()); return gfx::Rect(size); } gfx::Size RenderWidgetHostViewAndroid::GetVisibleViewportSize() { int pinned_bottom_adjust_dps = std::max(0, (int)(view_.GetViewportInsetBottom() / view_.GetDipScale())); gfx::Rect requested_rect(GetRequestedRendererSize()); requested_rect.Inset(gfx::Insets(0, 0, pinned_bottom_adjust_dps, 0)); return requested_rect.size(); } void RenderWidgetHostViewAndroid::SetInsets(const gfx::Insets& insets) { NOTREACHED(); } gfx::Size RenderWidgetHostViewAndroid::GetCompositorViewportPixelSize() { if (!view_.parent()) { if (default_bounds_.IsEmpty()) return gfx::Size(); float scale_factor = view_.GetDipScale(); return gfx::Size(default_bounds_.right() * scale_factor, default_bounds_.bottom() * scale_factor); } return view_.GetPhysicalBackingSize(); } int RenderWidgetHostViewAndroid::GetMouseWheelMinimumGranularity() const { auto* window = view_.GetWindowAndroid(); if (!window) return 0; // On Android, mouse wheel MotionEvents specify the number of ticks and how // many pixels each tick scrolls. This multiplier is specified by device // metrics (See WindowAndroid.getMouseWheelScrollFactor) so the minimum // granularity will be the size of this tick multiplier. return window->mouse_wheel_scroll_factor() / view_.GetDipScale(); } void RenderWidgetHostViewAndroid::UpdateCursor(const WebCursor& webcursor) { view_.OnCursorChanged(webcursor.cursor()); } void RenderWidgetHostViewAndroid::SetIsLoading(bool is_loading) { // Do nothing. The UI notification is handled through ContentViewClient which // is TabContentsDelegate. } // ----------------------------------------------------------------------------- // TextInputManager::Observer implementations. void RenderWidgetHostViewAndroid::OnUpdateTextInputStateCalled( TextInputManager* text_input_manager, RenderWidgetHostViewBase* updated_view, bool did_change_state) { if (!ime_adapter_android_) return; DCHECK_EQ(text_input_manager_, text_input_manager); if (GetTextInputManager()->GetActiveWidget()) { ime_adapter_android_->UpdateState( *GetTextInputManager()->GetTextInputState()); } else { // If there are no active widgets, the TextInputState.type should be // reported as none. ime_adapter_android_->UpdateState(ui::mojom::TextInputState()); } } void RenderWidgetHostViewAndroid::OnImeCompositionRangeChanged( TextInputManager* text_input_manager, RenderWidgetHostViewBase* updated_view) { DCHECK_EQ(text_input_manager_, text_input_manager); const TextInputManager::CompositionRangeInfo* info = text_input_manager_->GetCompositionRangeInfo(); if (!info) return; std::vector<gfx::RectF> character_bounds; for (const gfx::Rect& rect : info->character_bounds) character_bounds.emplace_back(rect); if (ime_adapter_android_) ime_adapter_android_->SetCharacterBounds(character_bounds); } void RenderWidgetHostViewAndroid::OnImeCancelComposition( TextInputManager* text_input_manager, RenderWidgetHostViewBase* updated_view) { DCHECK_EQ(text_input_manager_, text_input_manager); if (ime_adapter_android_) ime_adapter_android_->CancelComposition(); } void RenderWidgetHostViewAndroid::OnTextSelectionChanged( TextInputManager* text_input_manager, RenderWidgetHostViewBase* updated_view) { DCHECK_EQ(text_input_manager_, text_input_manager); if (!selection_popup_controller_) return; RenderWidgetHostImpl* focused_widget = GetFocusedWidget(); if (!focused_widget || !focused_widget->GetView()) return; const TextInputManager::TextSelection& selection = *text_input_manager_->GetTextSelection(focused_widget->GetView()); selection_popup_controller_->OnSelectionChanged( base::UTF16ToUTF8(selection.selected_text())); } viz::FrameSinkId RenderWidgetHostViewAndroid::GetRootFrameSinkId() { if (sync_compositor_) return sync_compositor_->GetFrameSinkId(); if (view_.GetWindowAndroid() && view_.GetWindowAndroid()->GetCompositor()) return view_.GetWindowAndroid()->GetCompositor()->GetFrameSinkId(); return viz::FrameSinkId(); } viz::SurfaceId RenderWidgetHostViewAndroid::GetCurrentSurfaceId() const { if (sync_compositor_) return sync_compositor_->GetSurfaceId(); return delegated_frame_host_ ? delegated_frame_host_->SurfaceId() : viz::SurfaceId(); } bool RenderWidgetHostViewAndroid::TransformPointToCoordSpaceForView( const gfx::PointF& point, RenderWidgetHostViewBase* target_view, gfx::PointF* transformed_point) { if (target_view == this) { *transformed_point = point; return true; } viz::SurfaceId surface_id = GetCurrentSurfaceId(); if (!surface_id.is_valid()) return false; // In TransformPointToLocalCoordSpace() there is a Point-to-Pixel conversion, // but it is not necessary here because the final target view is responsible // for converting before computing the final transform. return target_view->TransformPointToLocalCoordSpace(point, surface_id, transformed_point); } void RenderWidgetHostViewAndroid::SetGestureListenerManager( GestureListenerManager* manager) { gesture_listener_manager_ = manager; UpdateReportAllRootScrolls(); } void RenderWidgetHostViewAndroid::UpdateReportAllRootScrolls() { if (!host()) return; host()->render_frame_metadata_provider()->ReportAllRootScrolls( ShouldReportAllRootScrolls()); } base::WeakPtr<RenderWidgetHostViewAndroid> RenderWidgetHostViewAndroid::GetWeakPtrAndroid() { return weak_ptr_factory_.GetWeakPtr(); } bool RenderWidgetHostViewAndroid::OnGestureEvent( const ui::GestureEventAndroid& event) { std::unique_ptr<blink::WebGestureEvent> web_event; if (event.scale() < 0.f) { // Negative scale indicates zoom reset. float delta = min_page_scale_ / page_scale_; web_event = ui::CreateWebGestureEventFromGestureEventAndroid( ui::GestureEventAndroid(event.type(), event.location(), event.screen_location(), event.time(), delta, 0, 0, 0, 0, /*target_viewport*/ false, /*synthetic_scroll*/ false, /*prevent_boosting*/ false)); } else { web_event = ui::CreateWebGestureEventFromGestureEventAndroid(event); } if (!web_event) return false; SendGestureEvent(*web_event); return true; } bool RenderWidgetHostViewAndroid::OnTouchEvent( const ui::MotionEventAndroid& event) { RecordToolTypeForActionDown(event); if (event.GetAction() == ui::MotionEventAndroid::Action::DOWN) { if (ime_adapter_android_) ime_adapter_android_->UpdateOnTouchDown(); if (gesture_listener_manager_) gesture_listener_manager_->UpdateOnTouchDown(); } if (event.for_touch_handle()) return OnTouchHandleEvent(event); if (!host() || !host()->delegate()) return false; ComputeEventLatencyOSTouchHistograms(event); // Receiving any other touch event before the double-tap timeout expires // cancels opening the spellcheck menu. if (text_suggestion_host_) text_suggestion_host_->StopSuggestionMenuTimer(); // If a browser-based widget consumes the touch event, it's critical that // touch event interception be disabled. This avoids issues with // double-handling for embedder-detected gestures like side swipe. if (OnTouchHandleEvent(event)) { RequestDisallowInterceptTouchEvent(); return true; } if (stylus_text_selector_.OnTouchEvent(event)) { RequestDisallowInterceptTouchEvent(); return true; } ui::FilteredGestureProvider::TouchHandlingResult result = gesture_provider_.OnTouchEvent(event); if (!result.succeeded) return false; blink::WebTouchEvent web_event = ui::CreateWebTouchEventFromMotionEvent( event, result.moved_beyond_slop_region /* may_cause_scrolling */, false /* hovering */); if (web_event.GetType() == blink::WebInputEvent::Type::kUndefined) return false; ui::LatencyInfo latency_info(ui::SourceEventType::TOUCH); latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_UI_COMPONENT); if (ShouldRouteEvents()) { host()->delegate()->GetInputEventRouter()->RouteTouchEvent(this, &web_event, latency_info); } else { host()->ForwardTouchEventWithLatencyInfo(web_event, latency_info); } // Send a proactive BeginFrame for this vsync to reduce scroll latency for // scroll-inducing touch events. Note that Android's Choreographer ensures // that BeginFrame requests made during Action::MOVE dispatch will be honored // in the same vsync phase. if (observing_root_window_ && result.moved_beyond_slop_region) { if (sync_compositor_) sync_compositor_->RequestOneBeginFrame(); } return true; } bool RenderWidgetHostViewAndroid::OnTouchHandleEvent( const ui::MotionEvent& event) { return touch_selection_controller_ && touch_selection_controller_->WillHandleTouchEvent(event); } int RenderWidgetHostViewAndroid::GetTouchHandleHeight() { if (!touch_selection_controller_) return 0; return static_cast<int>(touch_selection_controller_->GetTouchHandleHeight()); } void RenderWidgetHostViewAndroid::ResetGestureDetection() { const ui::MotionEvent* current_down_event = gesture_provider_.GetCurrentDownEvent(); if (!current_down_event) { // A hard reset ensures prevention of any timer-based events that might fire // after a touch sequence has ended. gesture_provider_.ResetDetection(); return; } std::unique_ptr<ui::MotionEvent> cancel_event = current_down_event->Cancel(); if (gesture_provider_.OnTouchEvent(*cancel_event).succeeded) { bool causes_scrolling = false; ui::LatencyInfo latency_info(ui::SourceEventType::TOUCH); latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_UI_COMPONENT); blink::WebTouchEvent web_event = ui::CreateWebTouchEventFromMotionEvent( *cancel_event, causes_scrolling /* may_cause_scrolling */, false /* hovering */); if (ShouldRouteEvents()) { host()->delegate()->GetInputEventRouter()->RouteTouchEvent( this, &web_event, latency_info); } else { host()->ForwardTouchEventWithLatencyInfo(web_event, latency_info); } } } void RenderWidgetHostViewAndroid::OnDidNavigateMainFrameToNewPage() { // Move to front only if we are the primary page (we don't want to receive // events in the Prerender). GetMainRenderFrameHost() may be null in // tests. if (view_.parent() && RenderViewHostImpl::From(host())->GetMainRenderFrameHost() && RenderViewHostImpl::From(host()) ->GetMainRenderFrameHost() ->GetLifecycleState() == RenderFrameHost::LifecycleState::kActive) { view_.parent()->MoveToFront(&view_); } ResetGestureDetection(); if (delegated_frame_host_) delegated_frame_host_->OnNavigateToNewPage(); } void RenderWidgetHostViewAndroid::SetDoubleTapSupportEnabled(bool enabled) { gesture_provider_.SetDoubleTapSupportForPlatformEnabled(enabled); } void RenderWidgetHostViewAndroid::SetMultiTouchZoomSupportEnabled( bool enabled) { gesture_provider_.SetMultiTouchZoomSupportEnabled(enabled); } void RenderWidgetHostViewAndroid::FocusedNodeChanged( bool is_editable_node, const gfx::Rect& node_bounds_in_screen) { if (ime_adapter_android_) ime_adapter_android_->FocusedNodeChanged(is_editable_node); } void RenderWidgetHostViewAndroid::RenderProcessGone() { Destroy(); } void RenderWidgetHostViewAndroid::Destroy() { host()->render_frame_metadata_provider()->RemoveObserver(this); host()->ViewDestroyed(); UpdateNativeViewTree(nullptr); delegated_frame_host_.reset(); if (GetTextInputManager() && GetTextInputManager()->HasObserver(this)) GetTextInputManager()->RemoveObserver(this); for (auto& observer : destruction_observers_) observer.RenderWidgetHostViewDestroyed(this); destruction_observers_.Clear(); RenderWidgetHostViewBase::Destroy(); delete this; } void RenderWidgetHostViewAndroid::UpdateTooltipUnderCursor( const std::u16string& tooltip_text) { // Tooltips don't make sense on Android. } void RenderWidgetHostViewAndroid::UpdateTooltipFromKeyboard( const std::u16string& tooltip_text, const gfx::Rect& bounds) { // Tooltips don't make sense on Android. } void RenderWidgetHostViewAndroid::ClearKeyboardTriggeredTooltip() { // Tooltips don't make sense on Android. } void RenderWidgetHostViewAndroid::UpdateBackgroundColor() { DCHECK(RenderWidgetHostViewBase::GetBackgroundColor()); SkColor color = *RenderWidgetHostViewBase::GetBackgroundColor(); view_.OnBackgroundColorChanged(color); } bool RenderWidgetHostViewAndroid::HasFallbackSurface() const { return delegated_frame_host_ && delegated_frame_host_->HasFallbackSurface(); } void RenderWidgetHostViewAndroid::CopyFromSurface( const gfx::Rect& src_subrect, const gfx::Size& output_size, base::OnceCallback<void(const SkBitmap&)> callback) { TRACE_EVENT0("cc", "RenderWidgetHostViewAndroid::CopyFromSurface"); if (!IsSurfaceAvailableForCopy()) { std::move(callback).Run(SkBitmap()); return; } base::TimeTicks start_time = base::TimeTicks::Now(); if (!using_browser_compositor_) { SynchronousCopyContents(src_subrect, output_size, std::move(callback)); return; } DCHECK(delegated_frame_host_); delegated_frame_host_->CopyFromCompositingSurface( src_subrect, output_size, base::BindOnce( [](base::OnceCallback<void(const SkBitmap&)> callback, base::TimeTicks start_time, const SkBitmap& bitmap) { TRACE_EVENT0( "cc", "RenderWidgetHostViewAndroid::CopyFromSurface finished"); // TODO(crbug/1110301): Make the Compositing.CopyFromSurfaceTime // histogram obsolete. UMA_HISTOGRAM_TIMES(kAsyncReadBackString, base::TimeTicks::Now() - start_time); std::move(callback).Run(bitmap); }, std::move(callback), start_time)); } void RenderWidgetHostViewAndroid::EnsureSurfaceSynchronizedForWebTest() { ++latest_capture_sequence_number_; SynchronizeVisualProperties(cc::DeadlinePolicy::UseInfiniteDeadline(), absl::nullopt); } uint32_t RenderWidgetHostViewAndroid::GetCaptureSequenceNumber() const { return latest_capture_sequence_number_; } void RenderWidgetHostViewAndroid::OnInterstitialPageAttached() { if (view_.parent()) view_.parent()->MoveToFront(&view_); } void RenderWidgetHostViewAndroid::OnInterstitialPageGoingAway() { ResetSynchronousCompositor(); } bool RenderWidgetHostViewAndroid::CanSynchronizeVisualProperties() { // When a rotation begins, the new visual properties are not all notified to // RenderWidgetHostViewAndroid at the same time. The process begins when // OnSynchronizedDisplayPropertiesChanged is called, and ends with // OnPhysicalBackingSizeChanged. // // During this time there can be upwards of three calls to // SynchronizeVisualProperties. Sending each of these separately to the // Renderer causes three full re-layouts of the page to occur. // // We should instead wait for the full set of new visual properties to be // available, and deliver them to the Renderer in one single update. if (in_rotation_ && is_surface_sync_throttling_) return false; return true; } std::unique_ptr<SyntheticGestureTarget> RenderWidgetHostViewAndroid::CreateSyntheticGestureTarget() { return std::unique_ptr<SyntheticGestureTarget>( new SyntheticGestureTargetAndroid(host(), &view_)); } bool RenderWidgetHostViewAndroid::ShouldRouteEvents() const { DCHECK(host()); return host()->delegate() && host()->delegate()->GetInputEventRouter(); } void RenderWidgetHostViewAndroid::UpdateWebViewBackgroundColorIfNecessary() { // Android WebView had a bug the BG color was always set to black when // fullscreen (see https://crbug.com/961223#c5). As applications came to rely // on this behavior, preserve it here. if (!using_browser_compositor_ && host()->delegate()->IsFullscreen()) { SetContentBackgroundColor(SK_ColorBLACK); } } void RenderWidgetHostViewAndroid::ResetFallbackToFirstNavigationSurface() { if (delegated_frame_host_) delegated_frame_host_->ResetFallbackToFirstNavigationSurface(); } bool RenderWidgetHostViewAndroid::RequestRepaintForTesting() { return SynchronizeVisualProperties(cc::DeadlinePolicy::UseDefaultDeadline(), absl::nullopt); } void RenderWidgetHostViewAndroid::FrameTokenChangedForSynchronousCompositor( uint32_t frame_token, const gfx::Vector2dF& root_scroll_offset) { if (!viz::FrameTokenGT(frame_token, sync_compositor_last_frame_token_)) return; sync_compositor_last_frame_token_ = frame_token; if (host() && frame_token) { DCHECK(!using_browser_compositor_); // DevTools ScreenCast support for Android WebView. Don't call this if // we're currently in SynchronousCopyContents, as this can lead to // redundant copies. if (!in_sync_copy_contents_) { RenderFrameHostImpl* frame_host = RenderViewHostImpl::From(host())->GetMainRenderFrameHost(); if (frame_host && last_render_frame_metadata_) { // Update our |root_scroll_offset|, as changes to this value do not // trigger a new RenderFrameMetadata, and it may be out of date. This // is needed for devtools DOM node selection. cc::RenderFrameMetadata updated_metadata = *last_render_frame_metadata_; updated_metadata.root_scroll_offset = root_scroll_offset; RenderFrameDevToolsAgentHost::SignalSynchronousSwapCompositorFrame( frame_host, updated_metadata); } } } } void RenderWidgetHostViewAndroid::SetSynchronousCompositorClient( SynchronousCompositorClient* client) { synchronous_compositor_client_ = client; MaybeCreateSynchronousCompositor(); } void RenderWidgetHostViewAndroid::MaybeCreateSynchronousCompositor() { if (!sync_compositor_ && synchronous_compositor_client_) { sync_compositor_ = SynchronousCompositorHost::Create( this, host()->GetFrameSinkId(), GetHostFrameSinkManager()); view_.SetCopyOutputCallback(sync_compositor_->GetCopyViewCallback()); if (renderer_widget_created_) sync_compositor_->InitMojo(); } } void RenderWidgetHostViewAndroid::ResetSynchronousCompositor() { if (sync_compositor_) { view_.SetCopyOutputCallback(ui::ViewAndroid::CopyViewCallback()); sync_compositor_.reset(); } } void RenderWidgetHostViewAndroid::OnOverscrollRefreshHandlerAvailable() { DCHECK(!overscroll_controller_); CreateOverscrollControllerIfPossible(); } bool RenderWidgetHostViewAndroid::SupportsAnimation() const { // The synchronous (WebView) compositor does not have a proper browser // compositor with which to drive animations. return using_browser_compositor_; } void RenderWidgetHostViewAndroid::SetNeedsAnimate() { DCHECK(view_.GetWindowAndroid()); DCHECK(using_browser_compositor_); view_.GetWindowAndroid()->SetNeedsAnimate(); } void RenderWidgetHostViewAndroid::MoveCaret(const gfx::PointF& position) { MoveCaret(gfx::Point(position.x(), position.y())); } void RenderWidgetHostViewAndroid::MoveRangeSelectionExtent( const gfx::PointF& extent) { if (!selection_popup_controller_) return; selection_popup_controller_->MoveRangeSelectionExtent(extent); } void RenderWidgetHostViewAndroid::SelectBetweenCoordinates( const gfx::PointF& base, const gfx::PointF& extent) { if (!selection_popup_controller_) return; selection_popup_controller_->SelectBetweenCoordinates(base, extent); } void RenderWidgetHostViewAndroid::OnSelectionEvent( ui::SelectionEventType event) { if (!selection_popup_controller_) return; DCHECK(touch_selection_controller_); // If a selection drag has started, it has taken over the active touch // sequence. Immediately cancel gesture detection and any downstream touch // listeners (e.g., web content) to communicate this transfer. if (event == ui::SELECTION_HANDLES_SHOWN && gesture_provider_.GetCurrentDownEvent()) { ResetGestureDetection(); } selection_popup_controller_->OnSelectionEvent( event, GetSelectionRect(*touch_selection_controller_)); } void RenderWidgetHostViewAndroid::OnDragUpdate( const ui::TouchSelectionDraggable::Type type, const gfx::PointF& position) { if (!selection_popup_controller_) return; selection_popup_controller_->OnDragUpdate(type, position); } ui::TouchSelectionControllerClient* RenderWidgetHostViewAndroid::GetSelectionControllerClientManagerForTesting() { return touch_selection_controller_client_manager_.get(); } void RenderWidgetHostViewAndroid::SetSelectionControllerClientForTesting( std::unique_ptr<ui::TouchSelectionControllerClient> client) { touch_selection_controller_client_for_test_.swap(client); touch_selection_controller_ = CreateSelectionController( touch_selection_controller_client_for_test_.get(), !!view_.parent()); } std::unique_ptr<ui::TouchHandleDrawable> RenderWidgetHostViewAndroid::CreateDrawable() { if (!using_browser_compositor_) { if (!sync_compositor_) return nullptr; return std::unique_ptr<ui::TouchHandleDrawable>( sync_compositor_->client()->CreateDrawable()); } if (!selection_popup_controller_) return nullptr; return selection_popup_controller_->CreateTouchHandleDrawable(); } void RenderWidgetHostViewAndroid::DidScroll() {} void RenderWidgetHostViewAndroid::ShowTouchSelectionContextMenu( const gfx::Point& location) { host()->ShowContextMenuAtPoint(location, ui::MENU_SOURCE_TOUCH_HANDLE); } void RenderWidgetHostViewAndroid::SynchronousCopyContents( const gfx::Rect& src_subrect_dip, const gfx::Size& dst_size_in_pixel, base::OnceCallback<void(const SkBitmap&)> callback) { // Track that we're in this function to avoid repeatedly calling DevTools // capture logic. base::AutoReset<bool> in_sync_copy_contents(&in_sync_copy_contents_, true); // Note: When |src_subrect| is empty, a conversion from the view size must // be made instead of using |current_frame_size_|. The latter sometimes also // includes extra height for the toolbar UI, which is not intended for // capture. gfx::Rect valid_src_subrect_in_dips = src_subrect_dip; if (valid_src_subrect_in_dips.IsEmpty()) valid_src_subrect_in_dips = gfx::Rect(GetVisibleViewportSize()); const gfx::Rect src_subrect_in_pixel = gfx::ToEnclosingRect( gfx::ConvertRectToPixels(valid_src_subrect_in_dips, view_.GetDipScale())); // TODO(crbug/698974): [BUG] Current implementation does not support read-back // of regions that do not originate at (0,0). const gfx::Size& input_size_in_pixel = src_subrect_in_pixel.size(); DCHECK(!input_size_in_pixel.IsEmpty()); gfx::Size output_size_in_pixel; if (dst_size_in_pixel.IsEmpty()) output_size_in_pixel = input_size_in_pixel; else output_size_in_pixel = dst_size_in_pixel; int output_width = output_size_in_pixel.width(); int output_height = output_size_in_pixel.height(); if (!sync_compositor_) { std::move(callback).Run(SkBitmap()); return; } SkBitmap bitmap; bitmap.allocPixels(SkImageInfo::MakeN32Premul(output_width, output_height)); SkCanvas canvas(bitmap); canvas.scale( (float)output_width / (float)input_size_in_pixel.width(), (float)output_height / (float)input_size_in_pixel.height()); sync_compositor_->DemandDrawSw(&canvas, /*software_canvas=*/true); std::move(callback).Run(bitmap); } WebContentsAccessibilityAndroid* RenderWidgetHostViewAndroid::GetWebContentsAccessibilityAndroid() const { return web_contents_accessibility_; } void RenderWidgetHostViewAndroid::UpdateTouchSelectionController( const viz::Selection<gfx::SelectionBound>& selection, float page_scale_factor, float top_controls_height, float top_controls_shown_ratio, const gfx::SizeF& scrollable_viewport_size_dip) { if (!touch_selection_controller_) return; DCHECK(touch_selection_controller_client_manager_); touch_selection_controller_client_manager_->UpdateClientSelectionBounds( selection.start, selection.end, this, nullptr); OnUpdateScopedSelectionHandles(); // Set parameters for adaptive handle orientation. gfx::SizeF viewport_size(scrollable_viewport_size_dip); viewport_size.Scale(page_scale_factor); gfx::RectF viewport_rect(0.0f, top_controls_height * top_controls_shown_ratio, viewport_size.width(), viewport_size.height()); touch_selection_controller_->OnViewportChanged(viewport_rect); } bool RenderWidgetHostViewAndroid::UpdateControls( float dip_scale, float top_controls_height, float top_controls_shown_ratio, float top_controls_min_height_offset, float bottom_controls_height, float bottom_controls_shown_ratio, float bottom_controls_min_height_offset) { float to_pix = IsUseZoomForDSFEnabled() ? 1.f : dip_scale; float top_controls_pix = top_controls_height * to_pix; // |top_content_offset| is in physical pixels if --use-zoom-for-dsf is // enabled. Otherwise, it is in DIPs. // Note that the height of browser control is not affected by page scale // factor. Thus, |top_content_offset| in CSS pixels is also in DIPs. float top_content_offset = top_controls_height * top_controls_shown_ratio; float top_shown_pix = top_content_offset * to_pix; float top_translate = top_shown_pix - top_controls_pix; bool top_changed = !cc::MathUtil::IsFloatNearlyTheSame(top_shown_pix, prev_top_shown_pix_); float top_min_height_offset_pix = top_controls_min_height_offset * to_pix; top_changed |= !cc::MathUtil::IsFloatNearlyTheSame( top_min_height_offset_pix, prev_top_controls_min_height_offset_pix_); top_changed |= !cc::MathUtil::IsFloatNearlyTheSame(top_controls_pix, prev_top_controls_pix_); if (top_changed || !controls_initialized_) view_.OnTopControlsChanged(top_translate, top_shown_pix, top_min_height_offset_pix); prev_top_shown_pix_ = top_shown_pix; prev_top_controls_pix_ = top_controls_pix; prev_top_controls_translate_ = top_translate; prev_top_controls_min_height_offset_pix_ = top_min_height_offset_pix; float bottom_controls_pix = bottom_controls_height * to_pix; float bottom_shown_pix = bottom_controls_pix * bottom_controls_shown_ratio; bool bottom_changed = !cc::MathUtil::IsFloatNearlyTheSame( bottom_shown_pix, prev_bottom_shown_pix_); float bottom_translate = bottom_controls_pix - bottom_shown_pix; float bottom_min_height_offset_pix = bottom_controls_min_height_offset * to_pix; bottom_changed |= !cc::MathUtil::IsFloatNearlyTheSame( bottom_min_height_offset_pix, prev_bottom_controls_min_height_offset_pix_); if (bottom_changed || !controls_initialized_) view_.OnBottomControlsChanged(bottom_translate, bottom_min_height_offset_pix); prev_bottom_shown_pix_ = bottom_shown_pix; prev_bottom_controls_translate_ = bottom_translate; prev_bottom_controls_min_height_offset_pix_ = bottom_min_height_offset_pix; controls_initialized_ = true; return top_changed || bottom_changed; } void RenderWidgetHostViewAndroid::OnDidUpdateVisualPropertiesComplete( const cc::RenderFrameMetadata& metadata) { // If the Renderer is updating visual properties, do not block merging and // updating on rotation. base::AutoReset<bool> in_rotation(&in_rotation_, false); SynchronizeVisualProperties(cc::DeadlinePolicy::UseDefaultDeadline(), metadata.local_surface_id); if (delegated_frame_host_) { delegated_frame_host_->SetTopControlsVisibleHeight( metadata.top_controls_height * metadata.top_controls_shown_ratio); } } void RenderWidgetHostViewAndroid::OnFinishGetContentBitmap( const base::android::JavaRef<jobject>& obj, const base::android::JavaRef<jobject>& callback, const std::string& path, const SkBitmap& bitmap) { JNIEnv* env = base::android::AttachCurrentThread(); if (!bitmap.drawsNothing()) { auto task_runner = base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); base::PostTaskAndReplyWithResult( task_runner.get(), FROM_HERE, base::BindOnce(&CompressAndSaveBitmap, path, bitmap), base::BindOnce( &base::android::RunStringCallbackAndroid, base::android::ScopedJavaGlobalRef<jobject>(env, callback.obj()))); return; } // If readback failed, call empty callback base::android::RunStringCallbackAndroid(callback, std::string()); } void RenderWidgetHostViewAndroid::ShowInternal() { bool show = is_showing_ && is_window_activity_started_ && is_window_visible_; if (!show) return; if (!host() || !host()->is_hidden()) return; // Whether evicted or not, we stop batching for rotation in order to get // content ready for the new orientation. bool rotation_override = in_rotation_; base::AutoReset<bool> in_rotation(&in_rotation_, false); view_.GetLayer()->SetHideLayerAndSubtree(false); if (overscroll_controller_) overscroll_controller_->Enable(); if ((delegated_frame_host_ && delegated_frame_host_->IsPrimarySurfaceEvicted()) || !local_surface_id_allocator_.HasValidLocalSurfaceId()) { ui::WindowAndroidCompositor* compositor = view_.GetWindowAndroid() ? view_.GetWindowAndroid()->GetCompositor() : nullptr; SynchronizeVisualProperties( compositor && compositor->IsDrawingFirstVisibleFrame() ? cc::DeadlinePolicy::UseSpecifiedDeadline( ui::DelegatedFrameHostAndroid::FirstFrameTimeoutFrames()) : cc::DeadlinePolicy::UseDefaultDeadline(), absl::nullopt); // If we navigated while hidden, we need to update the fallback surface only // after we've completed navigation, and embedded the new surface. The // |delegated_frame_host_| is always valid when |navigation_while_hidden_| // is set to true. if (navigation_while_hidden_) { navigation_while_hidden_ = false; delegated_frame_host_->DidNavigate(); } } else if (rotation_override && is_surface_sync_throttling_) { // If a rotation occurred while this was not visible, we need to allocate a // new viz::LocalSurfaceId and send the current visual properties to the // Renderer. Otherwise there will be no content at all to display. // // The rotation process will complete after this first surface is displayed. SynchronizeVisualProperties(cc::DeadlinePolicy::UseDefaultDeadline(), absl::nullopt); } auto content_to_visible_start_state = TakeRecordContentToVisibleTimeRequest(); // Only when page is restored from back-forward cache, record content to // visible time and for this case no need to check for saved frames to // record ContentToVisibleTime. bool show_reason_bfcache_restore = content_to_visible_start_state ? content_to_visible_start_state->show_reason_bfcache_restore : false; host()->WasShown(show_reason_bfcache_restore ? std::move(content_to_visible_start_state) : blink::mojom::RecordContentToVisibleTimeRequestPtr()); if (delegated_frame_host_) { delegated_frame_host_->WasShown( local_surface_id_allocator_.GetCurrentLocalSurfaceId(), GetCompositorViewportPixelSize(), host()->delegate()->IsFullscreen()); } if (view_.parent() && view_.GetWindowAndroid()) { StartObservingRootWindow(); if (sync_compositor_) sync_compositor_->RequestOneBeginFrame(); } if (rotation_override) { // It's possible that several rotations were all enqueued while this view // has hidden. We skip those and update to just the final state. size_t skipped_rotations = rotation_metrics_.size() - 1; if (skipped_rotations) { rotation_metrics_.erase(rotation_metrics_.begin(), rotation_metrics_.begin() + skipped_rotations); } // If a rotation occurred while we were hidden, we do not want to include // all of that idle time in the rotation metrics. However we do want to have // the "RotationBegin" tracing event. So end the tracing event, before // setting the starting time of the rotation. EndRotationBatching(); rotation_metrics_.begin()->first = base::TimeTicks::Now(); BeginRotationEmbed(); } } void RenderWidgetHostViewAndroid::HideInternal() { DCHECK(!is_showing_ || !is_window_activity_started_ || !is_window_visible_) << "Hide called when the widget should be shown."; // As we stop visual observations, we clear the current fullscreen state. Once // ShowInternal() is invoked the most up to date visual properties will be // used. fullscreen_rotation_ = false; // Only preserve the frontbuffer if the activity was stopped while the // window is still visible. This avoids visual artifacts when transitioning // between activities. bool hide_frontbuffer = is_window_activity_started_ || !is_window_visible_; // Only stop observing the root window if the widget has been explicitly // hidden and the frontbuffer is being cleared. This allows window visibility // notifications to eventually clear the frontbuffer. bool stop_observing_root_window = !is_showing_ && hide_frontbuffer; if (hide_frontbuffer) { view_.GetLayer()->SetHideLayerAndSubtree(true); if (delegated_frame_host_) delegated_frame_host_->WasHidden(); } if (stop_observing_root_window) { DCHECK(!is_showing_); StopObservingRootWindow(); } if (!host() || host()->is_hidden()) return; if (overscroll_controller_) overscroll_controller_->Disable(); // Inform the renderer that we are being hidden so it can reduce its resource // utilization. host()->WasHidden(); } void RenderWidgetHostViewAndroid::StartObservingRootWindow() { DCHECK(view_.parent()); DCHECK(view_.GetWindowAndroid()); DCHECK(is_showing_); if (observing_root_window_) return; observing_root_window_ = true; view_.GetWindowAndroid()->AddObserver(this); ui::WindowAndroidCompositor* compositor = view_.GetWindowAndroid()->GetCompositor(); if (compositor) { delegated_frame_host_->AttachToCompositor(compositor); } OnUpdateScopedSelectionHandles(); } void RenderWidgetHostViewAndroid::StopObservingRootWindow() { if (!(view_.GetWindowAndroid())) { DCHECK(!observing_root_window_); return; } if (!observing_root_window_) return; // Reset window state variables to their defaults. is_window_activity_started_ = true; is_window_visible_ = true; observing_root_window_ = false; OnUpdateScopedSelectionHandles(); view_.GetWindowAndroid()->RemoveObserver(this); // If the DFH has already been destroyed, it will have cleaned itself up. // This happens in some WebView cases. if (delegated_frame_host_) delegated_frame_host_->DetachFromCompositor(); } bool RenderWidgetHostViewAndroid::Animate(base::TimeTicks frame_time) { bool needs_animate = false; if (overscroll_controller_) { needs_animate |= overscroll_controller_->Animate(frame_time, view_.parent()->GetLayer()); } // TODO(wjmaclean): Investigate how animation here does or doesn't affect // an OOPIF client. if (touch_selection_controller_) needs_animate |= touch_selection_controller_->Animate(frame_time); return needs_animate; } void RenderWidgetHostViewAndroid::RequestDisallowInterceptTouchEvent() { if (view_.parent()) view_.RequestDisallowInterceptTouchEvent(); } void RenderWidgetHostViewAndroid::TransformPointToRootSurface( gfx::PointF* point) { if (!host()->delegate()) return; RenderViewHostDelegateView* rvh_delegate_view = host()->delegate()->GetDelegateView(); if (rvh_delegate_view->DoBrowserControlsShrinkRendererSize()) *point += gfx::Vector2d(0, rvh_delegate_view->GetTopControlsHeight()); } // TODO(jrg): Find out the implications and answer correctly here, // as we are returning the WebView and not root window bounds. gfx::Rect RenderWidgetHostViewAndroid::GetBoundsInRootWindow() { return GetViewBounds(); } void RenderWidgetHostViewAndroid::ProcessAckedTouchEvent( const TouchEventWithLatencyInfo& touch, blink::mojom::InputEventResultState ack_result) { const bool event_consumed = ack_result == blink::mojom::InputEventResultState::kConsumed; gesture_provider_.OnTouchEventAck( touch.event.unique_touch_event_id, event_consumed, InputEventResultStateIsSetNonBlocking(ack_result)); if (touch.event.touch_start_or_first_touch_move && event_consumed && host()->delegate() && host()->delegate()->GetInputEventRouter()) { host() ->delegate() ->GetInputEventRouter() ->OnHandledTouchStartOrFirstTouchMove( touch.event.unique_touch_event_id); } } void RenderWidgetHostViewAndroid::GestureEventAck( const blink::WebGestureEvent& event, blink::mojom::InputEventResultState ack_result) { if (overscroll_controller_) overscroll_controller_->OnGestureEventAck(event, ack_result); mouse_wheel_phase_handler_.GestureEventAck(event, ack_result); ForwardTouchpadZoomEventIfNecessary(event, ack_result); // Stop flinging if a GSU event with momentum phase is sent to the renderer // but not consumed. StopFlingingIfNecessary(event, ack_result); if (gesture_listener_manager_) gesture_listener_manager_->GestureEventAck(event, ack_result); HandleSwipeToMoveCursorGestureAck(event); } void RenderWidgetHostViewAndroid::ChildDidAckGestureEvent( const blink::WebGestureEvent& event, blink::mojom::InputEventResultState ack_result) { if (gesture_listener_manager_) gesture_listener_manager_->GestureEventAck(event, ack_result); } blink::mojom::InputEventResultState RenderWidgetHostViewAndroid::FilterInputEvent( const blink::WebInputEvent& input_event) { if (overscroll_controller_ && blink::WebInputEvent::IsGestureEventType(input_event.GetType())) { blink::WebGestureEvent gesture_event = static_cast<const blink::WebGestureEvent&>(input_event); if (overscroll_controller_->WillHandleGestureEvent(gesture_event)) { // Terminate an active fling when a GSU generated from the fling progress // (GSU with inertial state) is consumed by the overscroll_controller_ and // overscrolling mode is not |OVERSCROLL_NONE|. The early fling // termination generates a GSE which completes the overscroll action. if (gesture_event.GetType() == blink::WebInputEvent::Type::kGestureScrollUpdate && gesture_event.data.scroll_update.inertial_phase == blink::WebGestureEvent::InertialPhaseState::kMomentum) { host_->StopFling(); } return blink::mojom::InputEventResultState::kConsumed; } } if (gesture_listener_manager_ && gesture_listener_manager_->FilterInputEvent(input_event)) { return blink::mojom::InputEventResultState::kConsumed; } if (!host()) return blink::mojom::InputEventResultState::kNotConsumed; if (input_event.GetType() == blink::WebInputEvent::Type::kGestureTapDown || input_event.GetType() == blink::WebInputEvent::Type::kTouchStart) { GpuProcessHost::CallOnIO(GPU_PROCESS_KIND_SANDBOXED, false /* force_create */, base::BindOnce(&WakeUpGpu)); } return blink::mojom::InputEventResultState::kNotConsumed; } blink::mojom::PointerLockResult RenderWidgetHostViewAndroid::LockMouse( bool request_unadjusted_movement) { NOTIMPLEMENTED(); return blink::mojom::PointerLockResult::kUnsupportedOptions; } blink::mojom::PointerLockResult RenderWidgetHostViewAndroid::ChangeMouseLock( bool request_unadjusted_movement) { NOTIMPLEMENTED(); return blink::mojom::PointerLockResult::kUnsupportedOptions; } void RenderWidgetHostViewAndroid::UnlockMouse() { NOTIMPLEMENTED(); } // Methods called from the host to the render void RenderWidgetHostViewAndroid::SendKeyEvent( const NativeWebKeyboardEvent& event) { if (!host()) return; RenderWidgetHostImpl* target_host = host(); // If there are multiple widgets on the page (such as when there are // out-of-process iframes), pick the one that should process this event. if (host()->delegate()) target_host = host()->delegate()->GetFocusedRenderWidgetHost(host()); if (!target_host) return; // Receiving a key event before the double-tap timeout expires cancels opening // the spellcheck menu. If the suggestion menu is open, we close the menu. if (text_suggestion_host_) text_suggestion_host_->OnKeyEvent(); ui::LatencyInfo latency_info; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kChar) { latency_info.set_source_event_type(ui::SourceEventType::KEY_PRESS); } latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_UI_COMPONENT); target_host->ForwardKeyboardEventWithLatencyInfo(event, latency_info); } void RenderWidgetHostViewAndroid::SendMouseEvent( const ui::MotionEventAndroid& motion_event, int action_button) { blink::WebInputEvent::Type webMouseEventType = ui::ToWebMouseEventType(motion_event.GetAction()); if (webMouseEventType == blink::WebInputEvent::Type::kUndefined) return; if (webMouseEventType == blink::WebInputEvent::Type::kMouseDown) UpdateMouseState(action_button, motion_event.GetX(0), motion_event.GetY(0)); int click_count = 0; if (webMouseEventType == blink::WebInputEvent::Type::kMouseDown || webMouseEventType == blink::WebInputEvent::Type::kMouseUp) click_count = (action_button == ui::MotionEventAndroid::BUTTON_PRIMARY) ? left_click_count_ : 1; blink::WebMouseEvent mouse_event = WebMouseEventBuilder::Build( motion_event, webMouseEventType, click_count, action_button); if (!host() || !host()->delegate()) return; if (ShouldRouteEvents()) { host()->delegate()->GetInputEventRouter()->RouteMouseEvent( this, &mouse_event, ui::LatencyInfo()); } else { host()->ForwardMouseEvent(mouse_event); } } void RenderWidgetHostViewAndroid::UpdateMouseState(int action_button, float mousedown_x, float mousedown_y) { if (action_button != ui::MotionEventAndroid::BUTTON_PRIMARY) { // Reset state if middle or right button was pressed. left_click_count_ = 0; prev_mousedown_timestamp_ = base::TimeTicks(); return; } const base::TimeTicks current_time = base::TimeTicks::Now(); const base::TimeDelta time_delay = current_time - prev_mousedown_timestamp_; const gfx::Point mousedown_point(mousedown_x, mousedown_y); const float distance_squared = (mousedown_point - prev_mousedown_point_).LengthSquared(); if (left_click_count_ > 2 || time_delay > kClickCountInterval || distance_squared > kClickCountRadiusSquaredDIP) { left_click_count_ = 0; } left_click_count_++; prev_mousedown_timestamp_ = current_time; prev_mousedown_point_ = mousedown_point; } void RenderWidgetHostViewAndroid::SendMouseWheelEvent( const blink::WebMouseWheelEvent& event) { if (!host() || !host()->delegate()) return; ui::LatencyInfo latency_info(ui::SourceEventType::WHEEL); latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_UI_COMPONENT); blink::WebMouseWheelEvent wheel_event(event); bool should_route_events = ShouldRouteEvents(); mouse_wheel_phase_handler_.AddPhaseIfNeededAndScheduleEndEvent( wheel_event, should_route_events); if (should_route_events) { host()->delegate()->GetInputEventRouter()->RouteMouseWheelEvent( this, &wheel_event, latency_info); } else { host()->ForwardWheelEventWithLatencyInfo(wheel_event, latency_info); } } void RenderWidgetHostViewAndroid::SendGestureEvent( const blink::WebGestureEvent& event) { // Sending a gesture that may trigger overscroll should resume the effect. if (overscroll_controller_) overscroll_controller_->Enable(); if (!host() || !host()->delegate() || event.GetType() == blink::WebInputEvent::Type::kUndefined) { return; } // We let the touch selection controller see gesture events here, since they // may be routed and not make it to FilterInputEvent(). if (touch_selection_controller_ && event.SourceDevice() == blink::WebGestureDevice::kTouchscreen) { switch (event.GetType()) { case blink::WebInputEvent::Type::kGestureLongPress: touch_selection_controller_->HandleLongPressEvent( event.TimeStamp(), event.PositionInWidget()); break; case blink::WebInputEvent::Type::kGestureTap: touch_selection_controller_->HandleTapEvent(event.PositionInWidget(), event.data.tap.tap_count); break; case blink::WebInputEvent::Type::kGestureScrollBegin: touch_selection_controller_->OnScrollBeginEvent(); break; default: break; } } ui::LatencyInfo latency_info = ui::WebInputEventTraits::CreateLatencyInfoForWebGestureEvent(event); if (event.SourceDevice() == blink::WebGestureDevice::kTouchscreen) { if (event.GetType() == blink::WebInputEvent::Type::kGestureScrollBegin) { // If there is a current scroll going on and a new scroll that isn't // wheel based, send a synthetic wheel event with kPhaseEnded to cancel // the current scroll. mouse_wheel_phase_handler_.DispatchPendingWheelEndEvent(); } else if (event.GetType() == blink::WebInputEvent::Type::kGestureScrollEnd) { // Make sure that the next wheel event will have phase = |kPhaseBegan|. // This is for maintaining the correct phase info when some of the wheel // events get ignored while a touchscreen scroll is going on. mouse_wheel_phase_handler_.IgnorePendingWheelEndEvent(); } } else if (event.GetType() == blink::WebInputEvent::Type::kGestureFlingStart && event.SourceDevice() == blink::WebGestureDevice::kTouchpad) { // Ignore the pending wheel end event to avoid sending a wheel event with // kPhaseEnded before a GFS. mouse_wheel_phase_handler_.IgnorePendingWheelEndEvent(); } if (ShouldRouteEvents()) { blink::WebGestureEvent gesture_event(event); host()->delegate()->GetInputEventRouter()->RouteGestureEvent( this, &gesture_event, latency_info); } else { host()->ForwardGestureEventWithLatencyInfo(event, latency_info); } } bool RenderWidgetHostViewAndroid::ShowSelectionMenu( RenderFrameHost* render_frame_host, const ContextMenuParams& params) { if (!selection_popup_controller_ || is_in_vr_) return false; return selection_popup_controller_->ShowSelectionMenu( render_frame_host, params, GetTouchHandleHeight()); } void RenderWidgetHostViewAndroid::MoveCaret(const gfx::Point& point) { if (host() && host()->delegate()) host()->delegate()->MoveCaret(point); } void RenderWidgetHostViewAndroid::DismissTextHandles() { if (touch_selection_controller_) touch_selection_controller_->HideAndDisallowShowingAutomatically(); } void RenderWidgetHostViewAndroid::SetTextHandlesTemporarilyHidden( bool hide_handles) { if (!touch_selection_controller_ || handles_hidden_by_selection_ui_ == hide_handles) return; handles_hidden_by_selection_ui_ = hide_handles; SetTextHandlesHiddenInternal(); } absl::optional<SkColor> RenderWidgetHostViewAndroid::GetCachedBackgroundColor() { return RenderWidgetHostViewBase::GetBackgroundColor(); } void RenderWidgetHostViewAndroid::SetIsInVR(bool is_in_vr) { if (is_in_vr_ == is_in_vr) return; is_in_vr_ = is_in_vr; // TODO(crbug.com/851054): support touch selection handles in VR. SetTextHandlesHiddenInternal(); gesture_provider_.UpdateConfig(ui::GetGestureProviderConfig( is_in_vr_ ? ui::GestureProviderConfigType::CURRENT_PLATFORM_VR : ui::GestureProviderConfigType::CURRENT_PLATFORM, content::GetUIThreadTaskRunner({BrowserTaskType::kUserInput}))); } bool RenderWidgetHostViewAndroid::IsInVR() const { return is_in_vr_; } void RenderWidgetHostViewAndroid::DidOverscroll( const ui::DidOverscrollParams& params) { if (sync_compositor_) sync_compositor_->DidOverscroll(params); if (!view_.parent() || !is_showing_) return; if (overscroll_controller_) overscroll_controller_->OnOverscrolled(params); } void RenderWidgetHostViewAndroid::DidStopFlinging() { if (!gesture_listener_manager_) return; gesture_listener_manager_->DidStopFlinging(); } const viz::FrameSinkId& RenderWidgetHostViewAndroid::GetFrameSinkId() const { if (!delegated_frame_host_) return viz::FrameSinkIdAllocator::InvalidFrameSinkId(); return delegated_frame_host_->GetFrameSinkId(); } void RenderWidgetHostViewAndroid::UpdateNativeViewTree( gfx::NativeView parent_native_view) { bool will_build_tree = parent_native_view != nullptr; bool has_view_tree = view_.parent() != nullptr; // Allows same parent view to be set again. DCHECK(!will_build_tree || !has_view_tree || parent_native_view == view_.parent()); StopObservingRootWindow(); bool resize = false; if (will_build_tree != has_view_tree) { touch_selection_controller_.reset(); if (has_view_tree) { view_.RemoveObserver(this); view_.RemoveFromParent(); view_.GetLayer()->RemoveFromParent(); } if (will_build_tree) { view_.AddObserver(this); parent_native_view->AddChild(&view_); parent_native_view->GetLayer()->AddChild(view_.GetLayer()); } // TODO(yusufo) : Get rid of the below conditions and have a better handling // for resizing after crbug.com/628302 is handled. bool is_size_initialized = !will_build_tree || view_.GetSize().width() != 0 || view_.GetSize().height() != 0; if (has_view_tree || is_size_initialized) resize = true; has_view_tree = will_build_tree; } if (!has_view_tree) { ResetSynchronousCompositor(); return; } // Parent native view can become null and then later non-null again, if // WebContents swaps away from this, and then later back to it. Need to // ensure SynchronousCompositor is recreated in this case. MaybeCreateSynchronousCompositor(); // Force an initial update of screen infos so the default RWHVBase value // is not used. // TODO(enne): figure out a more straightforward init path for screen infos. UpdateScreenInfo(); if (is_showing_ && view_.GetWindowAndroid()) StartObservingRootWindow(); if (resize) { SynchronizeVisualProperties( cc::DeadlinePolicy::UseSpecifiedDeadline( ui::DelegatedFrameHostAndroid::ResizeTimeoutFrames()), absl::nullopt); } if (!touch_selection_controller_) { ui::TouchSelectionControllerClient* client = touch_selection_controller_client_manager_.get(); if (touch_selection_controller_client_for_test_) client = touch_selection_controller_client_for_test_.get(); touch_selection_controller_ = CreateSelectionController(client, true); } CreateOverscrollControllerIfPossible(); } bool RenderWidgetHostViewAndroid::ShouldReportAllRootScrolls() { // In order to provide support for onScrollOffsetOrExtentChanged() // GestureListenerManager needs root-scroll-offsets. This is only necessary // if a GestureStateListenerWithScroll is added. return web_contents_accessibility_ != nullptr || (gesture_listener_manager_ && gesture_listener_manager_->has_listeners_attached()); } MouseWheelPhaseHandler* RenderWidgetHostViewAndroid::GetMouseWheelPhaseHandler() { return &mouse_wheel_phase_handler_; } TouchSelectionControllerClientManager* RenderWidgetHostViewAndroid::GetTouchSelectionControllerClientManager() { return touch_selection_controller_client_manager_.get(); } const viz::LocalSurfaceId& RenderWidgetHostViewAndroid::GetLocalSurfaceId() const { return local_surface_id_allocator_.GetCurrentLocalSurfaceId(); } void RenderWidgetHostViewAndroid::OnRendererWidgetCreated() { renderer_widget_created_ = true; if (sync_compositor_) sync_compositor_->InitMojo(); } bool RenderWidgetHostViewAndroid::OnMouseEvent( const ui::MotionEventAndroid& event) { // Ignore ACTION_HOVER_ENTER & ACTION_HOVER_EXIT because every mouse-down on // Android follows a hover-exit and is followed by a hover-enter. // https://crbug.com/715114 filed on distinguishing actual hover // enter/exit from these bogus ones. auto action = event.GetAction(); if (action == ui::MotionEventAndroid::Action::HOVER_ENTER || action == ui::MotionEventAndroid::Action::HOVER_EXIT) { return false; } RecordToolTypeForActionDown(event); SendMouseEvent(event, event.GetActionButton()); return true; } bool RenderWidgetHostViewAndroid::OnMouseWheelEvent( const ui::MotionEventAndroid& event) { SendMouseWheelEvent(WebMouseWheelEventBuilder::Build(event)); return true; } void RenderWidgetHostViewAndroid::OnGestureEvent( const ui::GestureEventData& gesture) { if ((gesture.type() == ui::ET_GESTURE_PINCH_BEGIN || gesture.type() == ui::ET_GESTURE_PINCH_UPDATE || gesture.type() == ui::ET_GESTURE_PINCH_END) && !IsPinchToZoomEnabled()) { return; } blink::WebGestureEvent web_gesture = ui::CreateWebGestureEventFromGestureEventData(gesture); // TODO(jdduke): Remove this workaround after Android fixes UiAutomator to // stop providing shift meta values to synthetic MotionEvents. This prevents // unintended shift+click interpretation of all accessibility clicks. // See crbug.com/443247. if (web_gesture.GetType() == blink::WebInputEvent::Type::kGestureTap && web_gesture.GetModifiers() == blink::WebInputEvent::kShiftKey) { web_gesture.SetModifiers(blink::WebInputEvent::kNoModifiers); } SendGestureEvent(web_gesture); } bool RenderWidgetHostViewAndroid::RequiresDoubleTapGestureEvents() const { return true; } void RenderWidgetHostViewAndroid::OnPhysicalBackingSizeChanged( absl::optional<base::TimeDelta> deadline_override) { // We may need to update the background color to match pre-surface-sync // behavior of EvictFrameIfNecessary. UpdateWebViewBackgroundColorIfNecessary(); int64_t deadline_in_frames = deadline_override ? ui::DelegatedFrameHostAndroid::TimeDeltaToFrames( deadline_override.value()) : ui::DelegatedFrameHostAndroid::ResizeTimeoutFrames(); // Cache the current rotation state so that we can start embedding with the // latest visual properties from SynchronizeVisualProperties(). bool in_rotation = in_rotation_; if (in_rotation) EndRotationBatching(); // When exiting fullscreen it is possible that // OnSynchronizedDisplayPropertiesChanged is either called out-of-order, or // not at all. If so we treat this as the start of the rotation. // // TODO(jonross): Build a unified screen state observer to replace all of the // individual signals used by RenderWidgetHostViewAndroid. if (fullscreen_rotation_ && !host()->delegate()->IsFullscreen()) BeginRotationBatching(); SynchronizeVisualProperties( cc::DeadlinePolicy::UseSpecifiedDeadline(deadline_in_frames), absl::nullopt); if (in_rotation) BeginRotationEmbed(); } void RenderWidgetHostViewAndroid::OnRootWindowVisibilityChanged(bool visible) { TRACE_EVENT1("browser", "RenderWidgetHostViewAndroid::OnRootWindowVisibilityChanged", "visible", visible); DCHECK(observing_root_window_); // Don't early out if visibility hasn't changed and visible. This is necessary // as OnDetachedFromWindow() sets |is_window_visible_| to true, so that this // may be called when ShowInternal() needs to be called. if (is_window_visible_ == visible && !visible) return; is_window_visible_ = visible; if (visible) ShowInternal(); else HideInternal(); } void RenderWidgetHostViewAndroid::OnAttachedToWindow() { if (!view_.parent()) return; if (is_showing_) StartObservingRootWindow(); DCHECK(view_.GetWindowAndroid()); if (view_.GetWindowAndroid()->GetCompositor()) OnAttachCompositor(); } void RenderWidgetHostViewAndroid::OnDetachedFromWindow() { StopObservingRootWindow(); OnDetachCompositor(); } void RenderWidgetHostViewAndroid::OnAttachCompositor() { DCHECK(view_.parent()); CreateOverscrollControllerIfPossible(); if (observing_root_window_ && using_browser_compositor_) { ui::WindowAndroidCompositor* compositor = view_.GetWindowAndroid()->GetCompositor(); delegated_frame_host_->AttachToCompositor(compositor); } } void RenderWidgetHostViewAndroid::OnDetachCompositor() { DCHECK(view_.parent()); overscroll_controller_.reset(); if (using_browser_compositor_) delegated_frame_host_->DetachFromCompositor(); } void RenderWidgetHostViewAndroid::OnAnimate(base::TimeTicks begin_frame_time) { if (Animate(begin_frame_time)) SetNeedsAnimate(); } void RenderWidgetHostViewAndroid::OnActivityStopped() { TRACE_EVENT0("browser", "RenderWidgetHostViewAndroid::OnActivityStopped"); DCHECK(observing_root_window_); is_window_activity_started_ = false; HideInternal(); } void RenderWidgetHostViewAndroid::OnActivityStarted() { TRACE_EVENT0("browser", "RenderWidgetHostViewAndroid::OnActivityStarted"); DCHECK(observing_root_window_); is_window_activity_started_ = true; ShowInternal(); } void RenderWidgetHostViewAndroid::SetTextHandlesHiddenForStylus( bool hide_handles) { if (!touch_selection_controller_ || handles_hidden_by_stylus_ == hide_handles) return; handles_hidden_by_stylus_ = hide_handles; SetTextHandlesHiddenInternal(); } void RenderWidgetHostViewAndroid::SetTextHandlesHiddenInternal() { if (!touch_selection_controller_) return; // TODO(crbug.com/851054): support touch selection handles in VR. touch_selection_controller_->SetTemporarilyHidden( is_in_vr_ || handles_hidden_by_stylus_ || handles_hidden_by_selection_ui_); } void RenderWidgetHostViewAndroid::OnStylusSelectBegin(float x0, float y0, float x1, float y1) { SetTextHandlesHiddenForStylus(true); // TODO(ajith.v) Refactor the event names as this is not really handle drag, // but currently we use same for long press drag selection as well. OnSelectionEvent(ui::SELECTION_HANDLE_DRAG_STARTED); SelectBetweenCoordinates(gfx::PointF(x0, y0), gfx::PointF(x1, y1)); } void RenderWidgetHostViewAndroid::OnStylusSelectUpdate(float x, float y) { MoveRangeSelectionExtent(gfx::PointF(x, y)); } void RenderWidgetHostViewAndroid::OnStylusSelectEnd(float x, float y) { SetTextHandlesHiddenForStylus(false); // TODO(ajith.v) Refactor the event names as this is not really handle drag, // but currently we use same for long press drag selection as well. OnSelectionEvent(ui::SELECTION_HANDLE_DRAG_STOPPED); } void RenderWidgetHostViewAndroid::OnStylusSelectTap(base::TimeTicks time, float x, float y) { // Treat the stylus tap as a long press, activating either a word selection or // context menu depending on the targetted content. blink::WebGestureEvent long_press = WebGestureEventBuilder::Build( blink::WebInputEvent::Type::kGestureLongPress, time, x, y); SendGestureEvent(long_press); } void RenderWidgetHostViewAndroid::ComputeEventLatencyOSTouchHistograms( const ui::MotionEvent& event) { base::TimeTicks event_time = event.GetEventTime(); base::TimeTicks current_time = base::TimeTicks::Now(); ui::EventType event_type; switch (event.GetAction()) { case ui::MotionEvent::Action::DOWN: case ui::MotionEvent::Action::POINTER_DOWN: event_type = ui::ET_TOUCH_PRESSED; break; case ui::MotionEvent::Action::MOVE: event_type = ui::ET_TOUCH_MOVED; break; case ui::MotionEvent::Action::UP: case ui::MotionEvent::Action::POINTER_UP: event_type = ui::ET_TOUCH_RELEASED; break; default: return; } ui::ComputeEventLatencyOS(event_type, event_time, current_time); } void RenderWidgetHostViewAndroid::CreateOverscrollControllerIfPossible() { // an OverscrollController is already set if (overscroll_controller_) return; RenderWidgetHostDelegate* delegate = host()->delegate(); if (!delegate) return; RenderViewHostDelegateView* delegate_view = delegate->GetDelegateView(); // render_widget_host_unittest.cc uses an object called // MockRenderWidgetHostDelegate that does not have a DelegateView if (!delegate_view) return; ui::OverscrollRefreshHandler* overscroll_refresh_handler = delegate_view->GetOverscrollRefreshHandler(); if (!overscroll_refresh_handler) return; if (!view_.parent()) return; // If window_android is null here, this is bad because we don't listen for it // being set, so we won't be able to construct the OverscrollController at the // proper time. ui::WindowAndroid* window_android = view_.GetWindowAndroid(); if (!window_android) return; ui::WindowAndroidCompositor* compositor = window_android->GetCompositor(); if (!compositor) return; overscroll_controller_ = std::make_unique<OverscrollControllerAndroid>( overscroll_refresh_handler, compositor, view_.GetDipScale()); } void RenderWidgetHostViewAndroid::SetOverscrollControllerForTesting( ui::OverscrollRefreshHandler* overscroll_refresh_handler) { overscroll_controller_ = std::make_unique<OverscrollControllerAndroid>( overscroll_refresh_handler, view_.GetWindowAndroid()->GetCompositor(), view_.GetDipScale()); } void RenderWidgetHostViewAndroid::TakeFallbackContentFrom( RenderWidgetHostView* view) { DCHECK(!static_cast<RenderWidgetHostViewBase*>(view) ->IsRenderWidgetHostViewChildFrame()); CopyBackgroundColorIfPresentFrom(*view); RenderWidgetHostViewAndroid* view_android = static_cast<RenderWidgetHostViewAndroid*>(view); if (!delegated_frame_host_ || !view_android->delegated_frame_host_) return; delegated_frame_host_->TakeFallbackContentFrom( view_android->delegated_frame_host_.get()); host()->GetContentRenderingTimeoutFrom(view_android->host()); } void RenderWidgetHostViewAndroid::OnSynchronizedDisplayPropertiesChanged( bool rotation) { if (rotation) { if (!in_rotation_) { // If this is a new rotation confirm the rotation state to prepare for // future exiting. As OnSynchronizedDisplayPropertiesChanged is not always // called when exiting. // TODO(jonross): Build a unified screen state observer to replace all of // the individual signals used by RenderWidgetHostViewAndroid. fullscreen_rotation_ = host()->delegate()->IsFullscreen() && is_showing_; BeginRotationBatching(); } else if (fullscreen_rotation_) { // If exiting fullscreen triggers a rotation, begin embedding now, as we // have previously had OnPhysicalBackingSizeChanged called. fullscreen_rotation_ = false; EndRotationBatching(); BeginRotationEmbed(); } } SynchronizeVisualProperties(cc::DeadlinePolicy::UseDefaultDeadline(), absl::nullopt); } absl::optional<SkColor> RenderWidgetHostViewAndroid::GetBackgroundColor() { return default_background_color_; } void RenderWidgetHostViewAndroid::DidNavigate() { if (!delegated_frame_host_) { RenderWidgetHostViewBase::DidNavigate(); return; } if (!is_showing_) { // Navigating while hidden should not allocate a new LocalSurfaceID. Once // sizes are ready, or we begin to Show, we can then allocate the new // LocalSurfaceId. local_surface_id_allocator_.Invalidate(); navigation_while_hidden_ = true; } else { // TODO(jonross): This was a legacy optimization to not perform too many // Surface Synchronization iterations for the first navigation. However we // currently are performing 5 full synchornizations before navigation // completes anyways. So we need to re-do RWHVA setup. // (https://crbug.com/1245652) // // In the interim we will not allocate a new Surface as long as the Renderer // has yet to produce any content. If we have existing content always // allocate a new surface, as the content will be from a pre-navigation // source. if (!pre_navigation_content_) { SynchronizeVisualProperties( cc::DeadlinePolicy::UseExistingDeadline(), local_surface_id_allocator_.GetCurrentLocalSurfaceId()); } else { SynchronizeVisualProperties(cc::DeadlinePolicy::UseExistingDeadline(), absl::nullopt); } // Only notify of navigation once a surface has been embedded. delegated_frame_host_->DidNavigate(); } pre_navigation_content_ = true; } WebContentsAccessibility* RenderWidgetHostViewAndroid::GetWebContentsAccessibility() { return web_contents_accessibility_; } viz::ScopedSurfaceIdAllocator RenderWidgetHostViewAndroid::DidUpdateVisualProperties( const cc::RenderFrameMetadata& metadata) { base::OnceCallback<void()> allocation_task = base::BindOnce( &RenderWidgetHostViewAndroid::OnDidUpdateVisualPropertiesComplete, weak_ptr_factory_.GetWeakPtr(), metadata); return viz::ScopedSurfaceIdAllocator(std::move(allocation_task)); } void RenderWidgetHostViewAndroid::GetScreenInfo( display::ScreenInfo* screen_info) { bool use_window_wide_color_gamut = GetContentClient()->browser()->GetWideColorGamutHeuristic() == ContentBrowserClient::WideColorGamutHeuristic::kUseWindow; auto* window = view_.GetWindowAndroid(); if (!window || !use_window_wide_color_gamut) { RenderWidgetHostViewBase::GetScreenInfo(screen_info); return; } display::DisplayUtil::DisplayToScreenInfo( screen_info, window->GetDisplayWithWindowColorSpace()); } std::vector<std::unique_ptr<ui::TouchEvent>> RenderWidgetHostViewAndroid::ExtractAndCancelActiveTouches() { ResetGestureDetection(); return {}; } void RenderWidgetHostViewAndroid::TransferTouches( const std::vector<std::unique_ptr<ui::TouchEvent>>& touches) { // Touch transfer for Android is not implemented in content/. } absl::optional<DisplayFeature> RenderWidgetHostViewAndroid::GetDisplayFeature() { gfx::Size view_size(view_.GetSize()); if (view_size.IsEmpty()) return absl::nullopt; // On Android, the display feature is exposed as a rectangle as a generic // concept. Here in the content layer, we translate that to a more // constrained concept, see content::DisplayFeature. absl::optional<gfx::Rect> display_feature_rect = view_.GetDisplayFeature(); if (!display_feature_rect) return absl::nullopt; // The display feature and view location are both provided in device pixels, // relative to the window. Convert this to DIP and view relative coordinates, // first by applying the scale, converting the display feature to view // relative coordinates, then intersect with the view bounds rect. // the convert to view-relative coordinates. float dip_scale = 1 / view_.GetDipScale(); gfx::Point view_location = view_.GetLocationOfContainerViewInWindow(); view_location = gfx::ScaleToRoundedPoint(view_location, dip_scale); gfx::Rect transformed_display_feature = gfx::ScaleToRoundedRect(*display_feature_rect, dip_scale); transformed_display_feature.Offset(-view_location.x(), -view_location.y()); transformed_display_feature.Intersect(gfx::Rect(view_size)); DisplayFeature display_feature; if (transformed_display_feature.x() == 0 && transformed_display_feature.width() == view_size.width()) { // A horizontal display feature covers the view's width and starts at // an x-offset of 0. display_feature = {DisplayFeature::Orientation::kHorizontal, transformed_display_feature.y(), transformed_display_feature.height()}; } else if (transformed_display_feature.y() == 0 && transformed_display_feature.height() == view_size.height()) { // A vertical display feature covers the view's height and starts at // a y-offset of 0. display_feature = {DisplayFeature::Orientation::kVertical, transformed_display_feature.x(), transformed_display_feature.width()}; } else { return absl::nullopt; } return display_feature; } void RenderWidgetHostViewAndroid::SetDisplayFeatureForTesting( const DisplayFeature* display_feature) { // RenderWidgetHostViewAndroid display feature mocking should be done via // TestViewAndroidDelegate instead - see MockDisplayFeature. NOTREACHED(); } void RenderWidgetHostViewAndroid::HandleSwipeToMoveCursorGestureAck( const blink::WebGestureEvent& event) { if (!touch_selection_controller_ || !selection_popup_controller_) { swipe_to_move_cursor_activated_ = false; return; } switch (event.GetType()) { case blink::WebInputEvent::Type::kGestureScrollBegin: { if (!event.data.scroll_begin.cursor_control) break; swipe_to_move_cursor_activated_ = true; touch_selection_controller_->OnSwipeToMoveCursorBegin(); OnSelectionEvent(ui::INSERTION_HANDLE_DRAG_STARTED); break; } case blink::WebInputEvent::Type::kGestureScrollUpdate: { if (!swipe_to_move_cursor_activated_) break; gfx::RectF rect = touch_selection_controller_->GetRectBetweenBounds(); // Suppress this when the input is not focused, in which case rect will be // 0x0. if (rect.width() != 0.f || rect.height() != 0.f) { selection_popup_controller_->OnDragUpdate( ui::TouchSelectionDraggable::Type::kNone, gfx::PointF(event.PositionInWidget().x(), rect.right_center().y())); } break; } case blink::WebInputEvent::Type::kGestureScrollEnd: { if (!swipe_to_move_cursor_activated_) break; swipe_to_move_cursor_activated_ = false; touch_selection_controller_->OnSwipeToMoveCursorEnd(); OnSelectionEvent(ui::INSERTION_HANDLE_DRAG_STOPPED); break; } default: break; } } void RenderWidgetHostViewAndroid::WasEvicted() { // Eviction can occur when the CompositorFrameSink has changed. This can // occur either from a lost connection, as well as from the initial conneciton // upon creating RenderWidgetHostViewAndroid. When this occurs while visible // a new LocalSurfaceId should be generated. If eviction occurs while not // visible, then the new LocalSurfaceId can be allocated upon the next Show. if (is_showing_) { local_surface_id_allocator_.GenerateId(); // Guarantee that the new LocalSurfaceId is propagated. Rather than relying // upon calls to Show() and OnDidUpdateVisualPropertiesComplete(). As there // is no guarantee that they will occur after the eviction. SynchronizeVisualProperties( cc::DeadlinePolicy::UseExistingDeadline(), local_surface_id_allocator_.GetCurrentLocalSurfaceId()); } else { local_surface_id_allocator_.Invalidate(); } } void RenderWidgetHostViewAndroid::OnUpdateScopedSelectionHandles() { if (!observing_root_window_ || !touch_selection_controller_client_manager_->has_active_selection()) { scoped_selection_handles_.reset(); return; } if (!scoped_selection_handles_) { scoped_selection_handles_ = std::make_unique<ui::WindowAndroid::ScopedSelectionHandles>( view_.GetWindowAndroid()); } } void RenderWidgetHostViewAndroid::SetWebContentsAccessibility( WebContentsAccessibilityAndroid* web_contents_accessibility) { web_contents_accessibility_ = web_contents_accessibility; UpdateReportAllRootScrolls(); } void RenderWidgetHostViewAndroid::SetNeedsBeginFrameForFlingProgress() { if (sync_compositor_) sync_compositor_->RequestOneBeginFrame(); } void RenderWidgetHostViewAndroid::BeginRotationBatching() { in_rotation_ = true; rotation_metrics_.emplace_back( std::make_pair(base::TimeTicks::Now(), viz::LocalSurfaceId())); // When a rotation begins, a series of calls update different aspects of // visual properties. Completing in EndRotationBatching, where the full new // set of properties is known. Trace the duration of that. const auto delta = rotation_metrics_.back().first - base::TimeTicks(); TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( "viz", "RenderWidgetHostViewAndroid::RotationBegin", TRACE_ID_LOCAL(delta.InNanoseconds()), "visible", is_showing_); } void RenderWidgetHostViewAndroid::EndRotationBatching() { in_rotation_ = false; DCHECK(!rotation_metrics_.empty()); const auto delta = rotation_metrics_.back().first - base::TimeTicks(); TRACE_EVENT_NESTABLE_ASYNC_END1( "viz", "RenderWidgetHostViewAndroid::RotationBegin", TRACE_ID_LOCAL(delta.InNanoseconds()), "local_surface_id", local_surface_id_allocator_.GetCurrentLocalSurfaceId().ToString()); } void RenderWidgetHostViewAndroid::BeginRotationEmbed() { DCHECK(!rotation_metrics_.empty()); rotation_metrics_.back().second = local_surface_id_allocator_.GetCurrentLocalSurfaceId(); // The full set of visual properties for a rotation is now known. This // tracks the time it takes until the Renderer successfully submits a frame // embedding the new viz::LocalSurfaceId. Tracking how long until a user // sees the complete rotation and layout of the page. This completes in // OnRenderFrameMetadataChangedAfterActivation. TRACE_EVENT_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP1( "viz", "RenderWidgetHostViewAndroid::RotationEmbed", TRACE_ID_LOCAL( local_surface_id_allocator_.GetCurrentLocalSurfaceId().hash()), base::TimeTicks::Now(), "LocalSurfaceId", local_surface_id_allocator_.GetCurrentLocalSurfaceId().ToString()); } } // namespace content
Jkoala/re
src/main/java/cn/ljtnono/re/service/impl/ReBlogTypeServiceImpl.java
package cn.ljtnono.re.service.impl; import cn.ljtnono.re.entity.ReBlog; import cn.ljtnono.re.entity.ReBlogType; import cn.ljtnono.re.enumeration.GlobalErrorEnum; import cn.ljtnono.re.enumeration.ReEntityRedisKeyEnum; import cn.ljtnono.re.exception.GlobalToJsonException; import cn.ljtnono.re.mapper.ReBlogTypeMapper; import cn.ljtnono.re.pojo.JsonResult; import cn.ljtnono.re.service.IReBlogService; import cn.ljtnono.re.service.IReBlogTypeService; import cn.ljtnono.re.util.RedisUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; /** * 博客类型服务实现类 * * @author ljt * @version 1.0.2 * @date 2019/12/23 */ @Service public class ReBlogTypeServiceImpl extends ServiceImpl<ReBlogTypeMapper, ReBlogType> implements IReBlogTypeService { private RedisUtil redisUtil; private IReBlogService iReBlogService; @Autowired public void setReBlogTypeServiceImpl(IReBlogService iReBlogService) { this.iReBlogService = iReBlogService; } @Autowired public void setRedisUtil(RedisUtil redisUtil) { this.redisUtil = redisUtil; } private static Logger logger = LoggerFactory.getLogger(ReBlogServiceImpl.class); @Override public JsonResult listBlogTypeAll() { // 首先从缓存中获取,如果缓存中没有的话从数据库获取 String redisKey = ReEntityRedisKeyEnum.RE_BLOG_TYPE_KEY.getKey() .replace(":id", ":*") .replace(":name", ":*"); List<ReBlogType> getByPattern = (List<ReBlogType>) redisUtil.getByPattern(redisKey); Optional<List<ReBlogType>> optionalGetByPattern = Optional.ofNullable(getByPattern); optionalGetByPattern.ifPresent(l -> logger.info("从缓存中获取所有博客类型列表,总条数:" + l.size())); List<ReBlogType> reBlogTypeList = optionalGetByPattern.orElseGet(() -> { List<ReBlogType> list = list(); list.forEach(reBlogType -> { redisUtil.set(ReEntityRedisKeyEnum.RE_BLOG_TYPE_KEY.getKey() .replace(":id", ":" + reBlogType.getId()) .replace(":name", ":" + reBlogType.getName()), reBlogType, RedisUtil.EXPIRE_TIME_DEFAULT); }); logger.info("从数据库中获取所有博客类型列表,总条数:" + list.size()); return list; }); return JsonResult.success(reBlogTypeList, reBlogTypeList.size()); } @Override public JsonResult listBlogTypePage(Integer page, Integer count) { Optional<Integer> optionalPage = Optional.ofNullable(page); Optional<Integer> optionalCount = Optional.ofNullable(count); optionalPage.orElseThrow(() -> new GlobalToJsonException(GlobalErrorEnum.PARAM_MISSING_ERROR)); optionalCount.orElseThrow(() -> new GlobalToJsonException(GlobalErrorEnum.PARAM_MISSING_ERROR)); optionalPage.filter(p -> p >= 0 && p <= 1000) .orElseThrow(() -> new GlobalToJsonException(GlobalErrorEnum.PARAM_INVALID_ERROR)); optionalCount.filter(c -> c >= 0 && c <= 60) .orElseThrow(() -> new GlobalToJsonException(GlobalErrorEnum.PARAM_INVALID_ERROR)); // 首先从缓存中获取,如果缓存中没有,那么从数据库中获取 String redisKey = ReEntityRedisKeyEnum.RE_BLOG_TYPE_PAGE_KEY.getKey() .replace(":page", ":" + page) .replace(":count", ":" + count); String totalRedisKey = ReEntityRedisKeyEnum.RE_BLOG_TYPE_PAGE_TOTAL_KEY.getKey() .replace(":page", ":" + page) .replace(":count", ":" + count); // 首先从缓存中拿 这里lGet如果查询不到,会自动返回空集合 List<?> objects = redisUtil.lGet(redisKey, 0, -1); if (!objects.isEmpty()) { logger.info("从缓存中获取" + page + "页ReBlogType数据,每页获取" + count + "条"); String getByPattern = (String) redisUtil.getByPattern(totalRedisKey); return JsonResult.success((Collection<?>) objects.get(0), ((Collection<?>) objects.get(0)).size()).addField("totalPages", getByPattern.split("_")[0]).addField("totalCount", getByPattern.split("_")[1]); } else { // 按照时间降序排列 IPage<ReBlogType> pageResult = page(new Page<>(page, count), new QueryWrapper<ReBlogType>().orderByDesc("modify_time")); logger.info("获取" + page + "页ReBlogType数据,每页获取" + count + "条"); redisUtil.lSet(redisKey, pageResult.getRecords(), RedisUtil.EXPIRE_TIME_PAGE_QUERY); redisUtil.set(totalRedisKey, pageResult.getPages() + "_" + pageResult.getTotal(), RedisUtil.EXPIRE_TIME_PAGE_QUERY); return JsonResult.success(pageResult.getRecords(), pageResult.getRecords().size()).addField("totalPages", pageResult.getPages()).addField("totalCount", pageResult.getTotal()); } } @Override public JsonResult saveEntity(ReBlogType entity) { Optional<ReBlogType> optionalReBlogType = Optional.ofNullable(entity); optionalReBlogType.orElseThrow(() -> new GlobalToJsonException(GlobalErrorEnum.PARAM_MISSING_ERROR)); boolean save = save(entity); String key = ReEntityRedisKeyEnum.RE_BLOG_TYPE_KEY.getKey() .replace(":id", ":" + entity.getId()) .replace(":name", ":" + entity.getName()); if (save) { // 将实体类存储到缓存中去 redisUtil.set(key, entity, RedisUtil.EXPIRE_TIME_DEFAULT); return JsonResult.successForMessage("操作成功!", 200); } else { throw new GlobalToJsonException(GlobalErrorEnum.SYSTEM_ERROR); } } @Override public JsonResult deleteEntityById(Serializable id) { Optional<Serializable> optionalId = Optional.ofNullable(id); optionalId.orElseThrow(() -> new GlobalToJsonException(GlobalErrorEnum.PARAM_MISSING_ERROR)); Integer blogTypeId = Integer.parseInt(id.toString()); if (blogTypeId >= 1) { // 在数据库中更新相关标签的状态 boolean updateResult = update(new UpdateWrapper<ReBlogType>().set("status", 0).eq("id", blogTypeId)); ReBlogType reBlogType = getById(blogTypeId); boolean update = iReBlogService.update(new UpdateWrapper<ReBlog>().set("status", 0).eq("type", reBlogType.getName())); if (updateResult && update) { // 删除所有相关缓存 redisUtil.deleteByPattern(ReEntityRedisKeyEnum.RE_BLOG_TYPE_KEY .getKey().replace(":id", ":*") .replace(":name", ":*")); redisUtil.deleteByPattern(ReEntityRedisKeyEnum.RE_BLOG_TYPE_PAGE_KEY .getKey().replace(":page", ":*") .replace(":count", ":*")); redisUtil.deleteByPattern(ReEntityRedisKeyEnum.RE_BLOG_TYPE_PAGE_TOTAL_KEY .getKey().replace(":page", ":*") .replace(":count", ":*")); return JsonResult.success(Collections.singletonList(reBlogType), 1); } else { throw new GlobalToJsonException(GlobalErrorEnum.SYSTEM_ERROR); } } else { throw new GlobalToJsonException(GlobalErrorEnum.PARAM_INVALID_ERROR); } } @Override public JsonResult updateEntityById(Serializable id, ReBlogType entity) { Optional<Serializable> optionalId = Optional.ofNullable(id); Optional<ReBlogType> optionalEntity = Optional.ofNullable(entity); optionalId.orElseThrow(() -> new GlobalToJsonException(GlobalErrorEnum.PARAM_MISSING_ERROR)); optionalEntity.orElseThrow(() -> new GlobalToJsonException(GlobalErrorEnum.PARAM_MISSING_ERROR)); Integer blogTypeId = Integer.parseInt(id.toString()); if (blogTypeId >= 1) { boolean updateResult = update(new UpdateWrapper<ReBlogType>().setEntity(entity).eq("id", blogTypeId)); if (updateResult) { // 更新操作 String key = ReEntityRedisKeyEnum.RE_BLOG_TYPE_KEY.getKey() .replace(":id", ":" + entity.getId()) .replace(":name", ":" + entity.getName()); boolean b = redisUtil.hasKey(key); if (b) { redisUtil.set(key, entity, RedisUtil.EXPIRE_TIME_DEFAULT); } return JsonResult.successForMessage("操作成功", 200); } else { throw new GlobalToJsonException(GlobalErrorEnum.SYSTEM_ERROR); } } else { throw new GlobalToJsonException(GlobalErrorEnum.PARAM_INVALID_ERROR); } } @Override public JsonResult getEntityById(Serializable id) { Optional<Serializable> optionalId = Optional.ofNullable(id); optionalId.orElseThrow(() -> new GlobalToJsonException(GlobalErrorEnum.PARAM_MISSING_ERROR)); Integer blogTypeId = Integer.parseInt(id.toString()); if (blogTypeId >= 1) { JsonResult jsonResult; // 如果缓存中存在,那么首先从缓存中获取 String key = ReEntityRedisKeyEnum.RE_BLOG_TYPE_KEY.getKey() .replace(":id", ":" + blogTypeId) .replace(":name", ":*"); boolean b = redisUtil.hasKeyByPattern(key); // 如果存在,那么直接获取 ReBlogType reBlogType; if (b) { reBlogType = (ReBlogType) redisUtil.getByPattern(key); if (reBlogType == null || reBlogType.getStatus() == 0) { throw new GlobalToJsonException(GlobalErrorEnum.NOT_EXIST_ERROR); } jsonResult = JsonResult.success(Collections.singletonList(reBlogType), 1); } else { reBlogType = getById(blogTypeId); // 如果不存在,那么返回 找不到资源错误 if (reBlogType == null || reBlogType.getStatus() == 0) { throw new GlobalToJsonException(GlobalErrorEnum.NOT_EXIST_ERROR); } redisUtil.set(ReEntityRedisKeyEnum.RE_BLOG_TYPE_KEY.getKey() .replace(":id", ":" + reBlogType.getId()) .replace(":name", ":" + reBlogType.getName()), reBlogType, RedisUtil.EXPIRE_TIME_DEFAULT); jsonResult = JsonResult.success(Collections.singletonList(reBlogType), 1); } jsonResult.setMessage("操作成功"); return jsonResult; } else { throw new GlobalToJsonException(GlobalErrorEnum.PARAM_INVALID_ERROR); } } @Override public JsonResult listEntityAll() { List<ReBlogType> reBlogTypeList = list(); Optional<List<ReBlogType>> optionalList = Optional.ofNullable(reBlogTypeList); optionalList.orElseThrow(() -> new GlobalToJsonException(GlobalErrorEnum.SYSTEM_ERROR)); optionalList.ifPresent((l) -> l.forEach(reBlogType -> { redisUtil.set(ReEntityRedisKeyEnum.RE_BLOG_TYPE_KEY.getKey() .replace(":id", ":" + reBlogType.getId()) .replace(":name", ":" + reBlogType.getName()), reBlogType, RedisUtil.EXPIRE_TIME_DEFAULT); })); optionalList.ifPresent(l -> logger.info("从数据库中获取所有博客类型列表,总条数:" + l.size())); JsonResult success = JsonResult.success(reBlogTypeList, reBlogTypeList.size()); success.setMessage("操作成功"); return success; } }
ralfhergert/mtg-deck-runner
src/main/java/de/ralfhergert/mtg/model/Step.java
package de.ralfhergert.mtg.model; public enum Step { UNTAP(Phase.BEGINNING), UPKEEP(Phase.BEGINNING), DRAW(Phase.BEGINNING), BEGINNING_OF_COMBAT(Phase.COMBAT), DECLARE_ATTACKERS(Phase.COMBAT), DECLARE_BLOCKERS(Phase.COMBAT), COMBAT_DAMAGE(Phase.COMBAT), END_OF_COMBAT(Phase.COMBAT), END(Phase.ENDING), CLEANUP(Phase.ENDING); private final Phase phase; Step(Phase phase) { this.phase = phase; } }
BehrRiley/Denizen-1
v1_13/src/main/java/com/denizenscript/denizen/nms/v1_13/impl/ImprovedOfflinePlayerImpl.java
<reponame>BehrRiley/Denizen-1 package com.denizenscript.denizen.nms.v1_13.impl; import com.denizenscript.denizen.nms.abstracts.ImprovedOfflinePlayer; import com.denizenscript.denizen.nms.v1_13.impl.jnbt.CompoundTagImpl; import com.denizenscript.denizencore.utilities.debugging.Debug; import net.minecraft.server.v1_13_R2.*; import org.bukkit.Bukkit; import org.bukkit.craftbukkit.v1_13_R2.inventory.CraftInventory; import org.bukkit.craftbukkit.v1_13_R2.inventory.CraftInventoryPlayer; import org.bukkit.inventory.Inventory; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.UUID; public class ImprovedOfflinePlayerImpl extends ImprovedOfflinePlayer { public ImprovedOfflinePlayerImpl(UUID playeruuid) { super(playeruuid); } @Override public org.bukkit.inventory.PlayerInventory getInventory() { if (offlineInventories.containsKey(getUniqueId())) { return offlineInventories.get(getUniqueId()); } PlayerInventory inventory = new PlayerInventory(null); inventory.b(((CompoundTagImpl) this.compound).toNMSTag().getList("Inventory", 10)); org.bukkit.inventory.PlayerInventory inv = new CraftInventoryPlayer(inventory); offlineInventories.put(getUniqueId(), inv); return inv; } @Override public void setInventory(org.bukkit.inventory.PlayerInventory inventory) { CraftInventoryPlayer inv = (CraftInventoryPlayer) inventory; NBTTagCompound nbtTagCompound = ((CompoundTagImpl) compound).toNMSTag(); nbtTagCompound.set("Inventory", inv.getInventory().a(new NBTTagList())); this.compound = CompoundTagImpl.fromNMSTag(nbtTagCompound); if (this.autosave) { savePlayerData(); } } @Override public Inventory getEnderChest() { if (offlineEnderChests.containsKey(getUniqueId())) { return offlineEnderChests.get(getUniqueId()); } InventoryEnderChest endchest = new InventoryEnderChest(null); endchest.a(((CompoundTagImpl) this.compound).toNMSTag().getList("EnderItems", 10)); org.bukkit.inventory.Inventory inv = new CraftInventory(endchest); offlineEnderChests.put(getUniqueId(), inv); return inv; } @Override public void setEnderChest(Inventory inventory) { NBTTagCompound nbtTagCompound = ((CompoundTagImpl) compound).toNMSTag(); nbtTagCompound.set("EnderItems", ((InventoryEnderChest) ((CraftInventory) inventory).getInventory()).i()); this.compound = CompoundTagImpl.fromNMSTag(nbtTagCompound); if (this.autosave) { savePlayerData(); } } @Override public double getMaxHealth() { AttributeInstance maxHealth = getAttributes().a(GenericAttributes.maxHealth); return maxHealth == null ? GenericAttributes.maxHealth.getDefault() : maxHealth.getValue(); } @Override public void setMaxHealth(double input) { AttributeMapBase attributes = getAttributes(); AttributeInstance maxHealth = attributes.a(GenericAttributes.maxHealth); if (maxHealth == null) { maxHealth = attributes.b(GenericAttributes.maxHealth); } maxHealth.setValue(input); setAttributes(attributes); } private AttributeMapBase getAttributes() { AttributeMapBase amb = new AttributeMapServer(); initAttributes(amb); GenericAttributes.a(amb, ((CompoundTagImpl) this.compound).toNMSTag().getList("Attributes", 10)); return amb; } private void initAttributes(AttributeMapBase amb) { // --v from EntityHuman superclass (EntityLiving) v-- amb.b(GenericAttributes.maxHealth); amb.b(GenericAttributes.c); //this.getAttributeMap().b(GenericAttributes.MOVEMENT_SPEED); -- merged below to simplify code amb.b(GenericAttributes.h); amb.b(GenericAttributes.i); // --v from EntityHuman v-- amb.b(GenericAttributes.ATTACK_DAMAGE).setValue(1.0D); //this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.10000000149011612D); -- merged below amb.b(GenericAttributes.MOVEMENT_SPEED).setValue(0.10000000149011612D); amb.b(GenericAttributes.g); amb.b(GenericAttributes.j); } public void setAttributes(AttributeMapBase attributes) { NBTTagCompound nbtTagCompound = ((CompoundTagImpl) compound).toNMSTag(); nbtTagCompound.set("Attributes", GenericAttributes.a(attributes)); this.compound = CompoundTagImpl.fromNMSTag(nbtTagCompound); if (this.autosave) { savePlayerData(); } } @Override protected boolean loadPlayerData(UUID uuid) { try { this.player = uuid; for (org.bukkit.World w : Bukkit.getWorlds()) { this.file = new File(w.getWorldFolder(), "playerdata" + File.separator + this.player + ".dat"); if (this.file.exists()) { this.compound = CompoundTagImpl.fromNMSTag(NBTCompressedStreamTools.a(new FileInputStream(this.file))); return true; } } } catch (Exception e) { Debug.echoError(e); } return false; } @Override public void savePlayerData() { if (this.exists) { try { NBTCompressedStreamTools.a(((CompoundTagImpl) this.compound).toNMSTag(), new FileOutputStream(this.file)); } catch (Exception e) { Debug.echoError(e); } } } }
intel/stacks-api
src/onecontainer_api/routers/tests/test_ai.py
# SPDX-License-Identifier: BSD-3-Clause # Copyright (c) 2020 Intel Corporation import os from fastapi.testclient import TestClient from onecontainer_api import models, schemas, config, startup_svc from onecontainer_api.frontend import app class TestAI(): def setup_method(self): models.Base.metadata.create_all(bind=models.engine) def teardown_method(self): os.remove(config.DATABASE_URL.split("///")[1]) def test_usage(self): with TestClient(app) as client: response = client.get("/service") data = list(filter(lambda x: x['app'] == 'dlrs-pytorch-torchub', response.json()))[0] svc_id = data.pop("id") response = client.get(f"/ai/{svc_id}/usage") assert response.status_code == 200, response.text def test_serve_missing_body(self): with TestClient(app) as client: response = client.get("/service") data = list(filter(lambda x: x['app'] == 'dlrs-pytorch-torchub', response.json()))[0] svc_id = data.pop("id") response = client.post(f"/ai/{svc_id}/serve") assert response.status_code == 400, response.text assert response.json() == {"endpoint": f"/ai/{svc_id}/serve", "status": "Bad Request"}
Maxython/pacman-for-termux
pacman-termux/test/pacman/tests/ignore008.py
<gh_stars>10-100 self.description = "Sync with relevant ignored fnmatched packages" package1 = pmpkg("foopkg", "1.0-1") self.addpkg2db("local", package1) package2 = pmpkg("barpkg", "2.0-1") self.addpkg2db("local", package2) package3 = pmpkg("bazpkg", "3.0-1") self.addpkg2db("local", package3) package1up = pmpkg("foopkg", "2.0-1") self.addpkg2db("sync", package1up) package2up = pmpkg("barpkg", "3.0-1") self.addpkg2db("sync", package2up) package3up = pmpkg("bazpkg", "4.0-1") self.addpkg2db("sync", package3up) self.option["IgnorePkg"] = ["foo*", "ba?pkg"] self.args = "-Su" self.addrule("PACMAN_RETCODE=0") self.addrule("PKG_VERSION=foopkg|1.0-1") self.addrule("PKG_VERSION=barpkg|2.0-1") self.addrule("PKG_VERSION=bazpkg|3.0-1")