content
stringlengths
10
4.9M
// New returns a new request id middleware. // It optionally accepts an ID Generator. // The Generator can stop the handlers chain with an error or // return a valid ID (string). // If it's nil then the `DefaultGenerator` will be used instead. func New(generator ...Generator) context.Handler { gen := DefaultGenerator if len(generator) > 0 { gen = generator[0] } return func(ctx context.Context) { if Get(ctx) != "" { ctx.Next() return } id := gen(ctx) if ctx.IsStopped() { return } ctx.SetID(id) ctx.Next() } }
<reponame>seniortesting/sparrow-jvfast<filename>jvfast/jvfast-api/jvfast-service/src/main/java/com/jvfast/module/monitor/model/param/ScheduleJobParam.java package com.jvfast.module.monitor.model.param; import lombok.Data; import javax.validation.constraints.NotEmpty; @Data public class ScheduleJobParam { @NotEmpty(message = "定时任务名称不能为空") private String jobName; @NotEmpty(message = "定时任务对应的任务类名不能为空") private String jobClassName; @NotEmpty(message = "定时任务的cron表达式不能为空") private String cronExpression = ""; private String jobData; private Boolean recovery; private Boolean isPause = false; private String description; }
Durability of antegrade synthetic aortomesenteric bypass for chronic mesenteric ischemia. OBJECTIVE The optimal treatment (endovascular/open repair, conduit, configuration) for chronic mesenteric ischemia (CMI) remains unresolved. This study was designed to review the outcome of patients with CMI treated with antegrade synthetic aortomesenteric bypass. METHODS The study was designed as a retrospective review in an academic tertiary care medical center. Patients with CMI who underwent antegrade synthetic aortomesenteric bypass were identified from a computerized vascular registry (from January 1987 to January 2001) with antegrade synthetic aortomesenteric bypass as intervention. Outcome measures were functional outcome (symptom relief, weight gain) and both graft patency (duplex ultrasound/angiography) and survival rates as determined with life-table analysis. RESULTS Forty-seven patients (female, 70%; age, 62 +/- 12 years) underwent aortomesenteric bypass (aortoceliac/aortosuperior mesenteric, n = 45; aortosuperior mesenteric, n = 2) for CMI (abdominal pain, 98%; weight loss, 83%). In-hospital mortality rate was 11% (four multiple organ dysfunction, one bowel infarction), mean length of stay was 32 +/- 30 days, three patients (6%) were discharged to a nursing home, and one (2%) was discharged home on parenteral nutrition (duration 4 months). At a mean follow-up period of 31 +/- 27 months, all patients had relief of abdominal pain and 86% had gained weight (at > or =1 year follow-up: mean ideal body weight 103 +/- 22%; versus before surgery: 87 +/- 17%; P <.001). Fourteen patients (34%) had diarrhea at discharge that persisted more than 6 months in 10. One patient had acute mesenteric ischemia develop from a failed graft (at 20 months), two patients had recurrent CMI develop from failing grafts (at 46 months and 49 months), and one asymptomatic patient was found to have a failing graft with duplex ultrasound scan (at 17 months); all grafts were revised. Primary, primary assisted, and secondary 5-year graft patency rates with life-table analysis were 69% (standard error , 17%), 94% (SE, 7%), and 100%, respectively, and the 5-year survival rate was 74% (SE, 12%). CONCLUSION Antegrade synthetic aortomesenteric bypass for CMI is associated with good functional outcome and long-term graft patency.
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // package api import ( "github.com/mattermost/mattermost-cloud/k8s" "github.com/mattermost/mattermost-cloud/model" "github.com/sirupsen/logrus" ) // Supervisor describes the interface to notify the background jobs of an actionable change. type Supervisor interface { Do() error } // Store describes the interface required to persist changes made via API requests. type Store interface { CreateCluster(cluster *model.Cluster, annotations []*model.Annotation) error GetCluster(clusterID string) (*model.Cluster, error) GetClusterDTO(clusterID string) (*model.ClusterDTO, error) GetClusters(filter *model.ClusterFilter) ([]*model.Cluster, error) GetClusterDTOs(filter *model.ClusterFilter) ([]*model.ClusterDTO, error) UpdateCluster(cluster *model.Cluster) error LockCluster(clusterID, lockerID string) (bool, error) UnlockCluster(clusterID, lockerID string, force bool) (bool, error) LockClusterAPI(clusterID string) error UnlockClusterAPI(clusterID string) error DeleteCluster(clusterID string) error CreateInstallation(installation *model.Installation, annotations []*model.Annotation) error GetInstallation(installationID string, includeGroupConfig, includeGroupConfigOverrides bool) (*model.Installation, error) GetInstallationDTO(installationID string, includeGroupConfig, includeGroupConfigOverrides bool) (*model.InstallationDTO, error) GetInstallations(filter *model.InstallationFilter, includeGroupConfig, includeGroupConfigOverrides bool) ([]*model.Installation, error) GetInstallationDTOs(filter *model.InstallationFilter, includeGroupConfig, includeGroupConfigOverrides bool) ([]*model.InstallationDTO, error) GetInstallationsCount(includeDeleted bool) (int64, error) GetInstallationsStatus() (*model.InstallationsStatus, error) UpdateInstallation(installation *model.Installation) error LockInstallation(installationID, lockerID string) (bool, error) UnlockInstallation(installationID, lockerID string, force bool) (bool, error) LockInstallationAPI(installationID string) error UnlockInstallationAPI(installationID string) error DeleteInstallation(installationID string) error GetClusterInstallation(clusterInstallationID string) (*model.ClusterInstallation, error) GetClusterInstallations(filter *model.ClusterInstallationFilter) ([]*model.ClusterInstallation, error) LockClusterInstallationAPI(clusterInstallationID string) error UnlockClusterInstallationAPI(clusterInstallationID string) error CreateGroup(group *model.Group) error GetGroup(groupID string) (*model.Group, error) GetGroups(filter *model.GroupFilter) ([]*model.Group, error) UpdateGroup(group *model.Group, forceSequenceUpdate bool) error LockGroup(groupID, lockerID string) (bool, error) UnlockGroup(groupID, lockerID string, force bool) (bool, error) LockGroupAPI(groupID string) error UnlockGroupAPI(groupID string) error DeleteGroup(groupID string) error GetGroupStatus(groupID string) (*model.GroupStatus, error) CreateWebhook(webhook *model.Webhook) error GetWebhook(webhookID string) (*model.Webhook, error) GetWebhooks(filter *model.WebhookFilter) ([]*model.Webhook, error) DeleteWebhook(webhookID string) error GetMultitenantDatabases(filter *model.MultitenantDatabaseFilter) ([]*model.MultitenantDatabase, error) GetOrCreateAnnotations(annotations []*model.Annotation) ([]*model.Annotation, error) CreateClusterAnnotations(clusterID string, annotations []*model.Annotation) ([]*model.Annotation, error) DeleteClusterAnnotation(clusterID string, annotationName string) error CreateInstallationAnnotations(installationID string, annotations []*model.Annotation) ([]*model.Annotation, error) DeleteInstallationAnnotation(installationID string, annotationName string) error IsInstallationBackupRunning(installationID string) (bool, error) CreateInstallationBackup(backupMeta *model.InstallationBackup) error UpdateInstallationBackupState(backupMeta *model.InstallationBackup) error GetInstallationBackup(id string) (*model.InstallationBackup, error) GetInstallationBackups(filter *model.InstallationBackupFilter) ([]*model.InstallationBackup, error) LockInstallationBackup(backupMetadataID, lockerID string) (bool, error) UnlockInstallationBackup(backupMetadataID, lockerID string, force bool) (bool, error) LockInstallationBackupAPI(backupID string) error UnlockInstallationBackupAPI(backupID string) error } // Provisioner describes the interface required to communicate with the Kubernetes cluster. type Provisioner interface { ExecClusterInstallationCLI(cluster *model.Cluster, clusterInstallation *model.ClusterInstallation, args ...string) ([]byte, error) ExecMattermostCLI(cluster *model.Cluster, clusterInstallation *model.ClusterInstallation, args ...string) ([]byte, error) GetClusterResources(*model.Cluster, bool) (*k8s.ClusterResources, error) } // Context provides the API with all necessary data and interfaces for responding to requests. // // It is cloned before each request, allowing per-request changes such as logger annotations. type Context struct { Store Store Supervisor Supervisor Provisioner Provisioner RequestID string Environment string Logger logrus.FieldLogger } // Clone creates a shallow copy of context, allowing clones to apply per-request changes. func (c *Context) Clone() *Context { return &Context{ Store: c.Store, Supervisor: c.Supervisor, Provisioner: c.Provisioner, Logger: c.Logger, } }
/** * Add a new edge to the graph. If one or both of the vertices are not in the graph * this will throw an exception * @param v1 vertex on one side of the edge * @param v2 vertex on other side of the edge * @return the graph */ public Graph<K, V> addEdge(Vertex<K, V> v1, Vertex<K, V> v2) { checkIfKeysAreInGraph(v1.getId(), v2.getId()); vertices.get(v2.getId()).addEdge(v1); vertices.get(v1.getId()).addEdge(v2); edges.add(Pair.of(v1, v2)); return this; }
def generate_datum(self, key, timestamp): uid = super().generate_datum(key, timestamp) i = next(self._point_counter) self._datum_kwargs_map[uid] = {'point_number': i} return uid
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE TemplateHaskell #-} module Main where -- Where a declaration starts with "prop_smoketest_" and has no type sig, it is -- a Bool that needs to be checked; otherwise we just care that things in here -- typecheck. -- -- TODO make some proper quickcheck tests, especially using the polymorphic TH -- test generator stuff. -- -- Contributers: Any changes that simplify or improve the structure of the -- Compose module are very welcome, as long as they don't break this test -- module. import Data.Shapely import Data.Shapely.Normal as Sh import Data.Shapely.Normal.TypeIndexed import Data.Shapely.Spine import Data.Proxy import Control.Monad(forM) import Data.Foldable(toList) import Data.Tree import Test.QuickCheck.All main = do passed <- $quickCheckAll if passed then putStrLn "Ok" else error "Some tests failed" -- --------------------------- s :: (Int,()) :+: (Char,()) :+: (Bool :*! String) -- Either (Int,()) (Either (Char,()) (Bool,(String,()))) s = Right (Right (True,("true",()))) p :: (Int,(Char,(Bool,()))) p = 1 *: 'a' *! True -- (1,('a',(True,()))) prop_smoketest_constructorsOfNormal_prod = constructorsOfNormal ('a',('b',())) 'x' 'y' == ('x',('y',())) {- -- CONCATABLE concated_p :: (Int,(Char,(Bool,(Int,(Char,(Bool,())))))) concated_p = Sh.concat (p, (p, ())) prop_smoketest_concated_s = ( Sh.concat $ (Right s :: Either (Either (Int,()) (Either (Char,()) (Bool,()))) (Either (Int,()) (Either (Char,()) (Bool,(String,())))) ) ) == Right (Right (Right (Right (Right (True,("true",())))))) -} prop_smoketest_distributeTerm = let s' = Right (Right (1,(True,("true",(9,()))))) in s' == 1 *< s >* 9 multiply1 :: Either (Int, (Int, ())) (Either (Int, (Char, ())) (Either (Int, (Bool, (String, ()))) (Either (Char, (Int, ())) (Either (Char, (Char, ())) (Either (Char, (Bool, (String, ()))) (Either (Bool, ([Char], (Int, ()))) (Either (Bool, ([Char], (Char, ()))) (Bool, ([Char], (Bool, (String, ()))))))))))) multiply1 = s >*< s prop_smoketest_multiply2 = p >*< () >*< p == 1 *: 'a' *: True *: 1 *: 'a' *! True prop_smoketest_multiply_monoid = and $ [ () >*< p == p , p >*< () == p , () >*< s == s , s >*< () == s , (p >*< p) >*< p == p >*< (p >*< p) , (s >*< p) >*< p == s >*< (p >*< p) , (p >*< s) >*< p == p >*< (s >*< p) , (p >*< p) >*< s == p >*< (p >*< s) , (s >*< s) >*< p == s >*< (s >*< p) , (p >*< s) >*< s == p >*< (s >*< s) , (s >*< s) >*< s == s >*< (s >*< s) ] -- REVERSABLE s_rev :: Either (Bool,(String,())) (Either (Char,()) (Int,())) s_rev = Sh.reverse s p_rev :: (Bool,(Char,(Int,()))) p_rev = Sh.reverse p p_empty_rev :: () p_empty_rev = Sh.reverse () -- SHIFTING: sr :: Either (Bool,(String,())) (Either (Int,()) (Char,())) sr = shiftr s sl :: Either (Char,()) (Either (Bool,(String,())) (Int,())) sl = shiftl s pr :: (Bool,(Int,(Char,()))) pr = shiftr p pl :: (Char,(Bool,(Int,()))) pl = shiftl p -- FANIN prop_smoketest_fanin_prod = Sh.fanin (\i c b-> if b then (i,c) else (9,'z')) p == (1,'a') prop_smoketest_unfanin_prod = Sh.fanin (Sh.unfanin(\(i,(c,(b,())))-> if b then (i,c) else (9,'z'))) p == (1,'a') prop_smoketest_fanin_sum = -- the sum arg must be unambiguous, but hopefully in practice a -- type signature won't be necessary (when e.g. the sum is a -- TH-generated instance): let s' = Right $ Right (1,([2..5],())) :: Either (Int,()) ( Either () (Int,([Int],())) ) in fanin ((+1), (3, (foldr (+), ()))) s' == 15 prop_smoketest_unfanin_sum = let f (Left (_,())) = "a" f (Right (Left (_,()))) = "b" f (Right (Right (_,(s,())))) = s in fanin (unfanin f) s == "true" -- NOTE: 'ary' is required for inference here prop_smoketest_ary_with_unfanin = (unfanin (_4 `ary` (shiftl . Sh.reverse)) 1 2 3 4) == (3,(2,(1,(4,())))) -- APPEND {- appended :: (Int,(Char,(Bool,(Int,(Char,(Bool,())))))) appended = p .++. p appended_s :: Either (Char, ()) (Either (Int, ()) (Either (Int, ()) (Either (Char, ()) (Bool, (String,()))))) appended_s = let s_ss = (Right s) :: Either ( Either (Char,()) (Int,()) ) ( Either (Int,()) (Either (Char,()) (Bool,(String,()))) ) in append s_ss -- == Right (Right (Right (Right (True,())))) -} -- Homogeneous prop_smoketest_toList = ( toList $ toFList (1,(2,(3,()))) ) == [1,2,3] prop_smoketest_toList2 = null $ toList $ toFList () prop_smoketest_homogenous_inferrence = (\(a,as) -> a == 1) $ fromFList $ toFList (1,(2,(3,()))) -- CARTESIAN-ESQUE -- NOTE: ambiguous without `==` prop_smoketest_fanout_prod = fanout (head,(tail,(Prelude.length,()))) [1..3] == (1,([2,3],(3,()))) -- test of inferrence convenience: prop_smoketest_repeat = (3 ==) $ (\(x,(y,(z,())))-> x+y+z) $ Sh.repeat 1 -- THIS DOESN'T WORK, HOWEVER. any way to restructure fanin to make inferrence possible? -- repeat_test2 = (3 ==) $ Sh.uncurry (\x y z-> x+y+z) $ Sh.repeat 1 prop_smoketest_repeat2 = (3 ==) $ Sh.fanin (\x y z-> x+y+z) (Sh.repeat 1 :: (Int,(Int,(Int,())))) prop_smoketest_replicate = (\(_,(a,_)) -> a == 2) $ Sh.replicate (Proxy :: Proxy (Either () (Either () ()))) 2 prop_smoketest_extract = let s' :: Either (Int,()) (Either (Int,()) (Int,())) s' = Right (Right (1,())) in extract s' == (1,()) prop_smoketest_factorPrefix = ('a',(True,())) == (fst $ factorPrefix (Left ('a',(True,('b',()))) :: Either (Char,(Bool,(Char,()))) (Char,(Bool,())) )) -------- MASSAGEABLE mb = ('a',("hi",())) mb_0 :: Either () (String,(Char,())) mb_0 = massageNormal () mb_1 :: Either (String,(Char,())) () mb_1 = massageNormal () mb_2 :: Either (Int,(Char,())) (String,(Char,())) mb_2 = massageNormal mb mb_3 :: Either (Char,(Int,())) (String,(Char,())) mb_3 = massageNormal mb mb_4 :: Either (Char,(String,(Int,()))) (Either () (String,(Char,()))) mb_4 = massageNormal mb mb_5 :: Either (String,()) (String,(Char,())) mb_5 = massageNormal mb mc = Left mb :: Either (Char,(String,())) () mc_0 :: Either (Int,()) (Either (String,(Char,())) ()) mc_0 = massageNormal mc -- Testing ordered tuples: md = (Left ('a',('b',(3,())))) :: Either (Char,(Char,(Int,()))) () md_0 :: Either (Char,(Char,(Bool,()))) (Either () (Char,(Char,(Int,())))) md_0 = massageNormal md prop_smoketest_md_1 = ( massageNormal md :: Either (Char,(Int,(Char,()))) (Either () (Char,(Char,(Int,())))) ) == (Right $ Right ('a',('b',(3,())))) prop_smoketest_md_2 = ( massageNormal ('a',('b',(True,()))) :: Either (Bool,()) (Char,(Char,(Bool,()))) ) == (Right ('a',('b',(True,())))) prop_smoketest_md_3 = ( massageNormal ('a',('b',())) :: Either (Char,(Char,())) (Either () (Int,())) ) == (Left ('a',('b',()))) {- -- must not typecheck massageNormal mb :: Either (String,(Char,())) (Char,(String,())) massageNormal () :: Either () () massageNormal mc :: Either (Int,()) (Either (String,(Char,())) (String,())) -- ordered product style massageNormal md :: Either (Char,(Char,(Int,()))) (Either () (Char,(Char,(Int,())))) massageNormal md :: Either (Char,(Char,(Bool,()))) (Either (Int,()) (Char,(Char,(Int,())))) -} -- Testing recursion: prop_smoketest_mr_id = massage "foo" == "foo" data OrderedRec = OCons Int Int OrderedRec | ONull deriving Eq deriveShapely ''OrderedRec prop_smoketest_orderedr_id = massage (OCons 1 1 (OCons 2 2 ONull)) == (OCons 1 1 (OCons 2 2 ONull)) -- OrderedRec but reordered constructors, plus an extra constructor to -- demonstrate non-bijective mapping, where the cons is non-ambiguous because -- it uses ordering-significant matching (because all terms not unique types) data OrderedRec3 = ONull3 | OCons3 Int Int OrderedRec3 | ONewCons3 OrderedRec3 Int Int deriving Eq deriveShapely ''OrderedRec3 prop_smoketest_rec_ordered_expand = massage (OCons 1 1 (OCons 2 2 ONull)) == (OCons3 1 1 (OCons3 2 2 ONull3)) -- [a] with both order of products and sums reversed: data Tsil a = Snoc (Tsil a) a | Lin deriving Eq deriveShapely ''Tsil prop_smoketest_m_unorderedr = massage "123" == Snoc (Snoc (Snoc Lin '3') '2') '1' -------- TYPE-INDEXED prop_smoketest_viewFirstTypeOf_prod = (('a',(False,(True,("potato",())))) `viewFirstTypeOf` True) == (False,('a',(True,("potato",())))) prop_smoketest_viewTypeOf_prod = (('a',(False,(True,("potato",())))) `viewFirstTypeOf` "tuber") == ("potato",('a',(False,(True,())))) viewTypeOf_sum1 :: Either (Int, ()) (Either (Char, ()) (Bool :*! String)) viewTypeOf_sum1 = s `viewTypeOf` ((1,()) :: (Int,())) viewTypeOf_sum2 :: Either (Char, ()) (Either (Int, ()) (Bool :*! String)) viewTypeOf_sum2 = s `viewTypeOf` ('a',()) viewTypeOf_sum3 :: Either (Bool :*! String) (Either (Int, ()) (Char, ())) viewTypeOf_sum3 = s `viewTypeOf` (True,("string",())) prop_smoketest_viewFirstTypeOf_sum1 = (Left () :: Either () ()) `viewFirstTypeOf` () == Left () prop_smoketest_viewFirstTypeOf_sum2 = (Right $ Left () :: Either (Int,()) (Either () ())) `viewFirstTypeOf` () == Left () {- MUST NOT TYPECHECK: ('a',(False,(True,("potato",())))) `viewTypeOf` True (Right $ Left () :: Either (Int,()) (Either () ())) `viewTypeOf` () (Left () :: Either () ()) `viewTypeOf` () -} nub_prod :: (Int, (Char, (Bool, ()))) nub_prod = nubType (undefined :: (Int,(Char,(Int,(Int,(Bool,(Bool,()))))))) -------- TH DERIVING: -- NON-RECURSIVE: data A = A deriving (Eq,Show) -- () data B = B Int deriving (Eq,Show) data C a b = C a b deriving (Eq,Show) -- (,) data D a b = D0 a | D1 b deriving (Eq,Show) -- Either data E a = E0 | E1 a deriving (Eq,Show) -- Maybe data F a b c = F0 a b c | F1 a b | F2 a deriving (Eq,Show) deriveShapely ''A deriveShapely ''B deriveShapely ''C deriveShapely ''D deriveShapely ''E deriveShapely ''F -- RECURSIVE: ------- data Li = Em | Co Char Li deriving Eq deriveShapely ''Li prop_smoketest_th_rec = let a = "works" b = Co 'w' $ Co 'o' $ Co 'r' $ Co 'k' $ Co 's' $ Em in coerce a == b && coerce b == a data SimpleTree a = SBr (SimpleTree a) a (SimpleTree a) | SEm deriving (Eq,Show) deriveShapely ''SimpleTree data LRTree a = LRTop (LTree a) a (RTree a) | LRTopEm data LTree a = LBr (LTree a) a (RTree a) | LEm data RTree a = RBr (LTree a) a (RTree a) | REm fmap Prelude.concat $ forM [''LRTree , ''LTree , ''RTree ] deriveShapely -- test deeper recursive structure: prop_smoketest_th_rec_multi = let lrTree = LRTop (LBr LEm 'b' REm) 'a' (RBr LEm 'b' REm) --st0 = (Proxy :: Proxy (LRTree Char), (Proxy :: Proxy (LTree Char), (Proxy :: Proxy (RTree Char), ()))) st0 = spine :: LRTree Char :-: LTree Char :-! RTree Char st1 = spine :: LRTree :-: LTree :-! RTree in coerceWith st0 lrTree == SBr (SBr SEm 'b' SEm) 'a' (SBr SEm 'b' SEm) && coerceWith st1 lrTree == SBr (SBr SEm 'b' SEm) 'a' (SBr SEm 'b' SEm) -- These demonstrate the need for parameter-agnostic spine elements: our type -- is recursive, with the paramters flip-flopping. Lots of other examples. data Simple2Tree a b = S2Br (Simple2Tree b a) a b (Simple2Tree b a) | S2Em deriving (Eq,Show) deriveShapely ''Simple2Tree data LR2Tree a b = LR2Top (L2Tree b a) a b (R2Tree b a) | LR2TopEm data L2Tree a b = L2Br (L2Tree b a) a b (R2Tree b a) | L2Em data R2Tree a b = R2Br (L2Tree b a) a b (R2Tree b a) | R2Em fmap Prelude.concat $ forM [''LR2Tree , ''L2Tree , ''R2Tree ] deriveShapely -- test deeper recursive structure: prop_smoketest_th_rec_multi_parameter_agnostic = let lrTree = LR2Top (L2Br (L2Br L2Em 'c' True R2Em) False 'b' R2Em) 'a' True (R2Br L2Em False 'b' R2Em) st = spine :: LR2Tree :-: L2Tree :-! R2Tree -- this avoids enumerating a/b, b/a variants for all types: -- st = spine :: LR2Tree Char Bool :-: L2Tree Char Bool :-: R2Tree Char Bool :-: -- LR2Tree Bool Char :-: L2Tree Bool Char :-! R2Tree Bool Char in coerceWith st lrTree == S2Br (S2Br (S2Br S2Em 'c' True S2Em) False 'b' S2Em) 'a' True (S2Br S2Em False 'b' S2Em) -- 'coerce' should handle regular recursion with parameter shuffling, because -- it uses Unapplied: data RegRecParams1 a b = RRPCons1 a b (RegRecParams1 b a) | RRPNil1 deriving (Eq,Show) data RegRecParams2 a b = RRPCons2 a b (RegRecParams2 b a) | RRPNil2 deriving (Eq,Show) fmap Prelude.concat $ forM [''RegRecParams1, ''RegRecParams2] deriveShapely prop_smoketest_th_rec_reg_param_swapping_coerce = (coerce $ RRPCons1 'a' True RRPNil1) == RRPCons2 'a' True RRPNil2 coerce_recursive_self :: [Char] coerce_recursive_self = coerce "where the instance shows source/target term equality, and equality in outer constructors" -- excercise coerce with recursive Functor type application data OurTree a = OurNode a (OurForest a) deriving (Eq, Functor, Show) data OurForest a = OurEmptyForest | OurForestCons (OurTree a) (OurForest a) deriving (Eq, Functor, Show) -- really a list fmap Prelude.concat $ forM [''Tree, ''OurTree, ''OurForest] deriveShapely ourTree = OurNode 'a' (OurForestCons (OurNode 'b' OurEmptyForest) (OurForestCons (OurNode 'c' OurEmptyForest) OurEmptyForest)) theirTree = Node 'a' ( [ Node 'b' [] , Node 'c' [] ]) prop_smoketest_coerceWith_type_application = coerceWith (spine :: OurTree :-! OurForest) ourTree == theirTree && coerceWith (spine :: [] :-! Tree) theirTree == ourTree {- TODO WE WOULD LIKE TO SUPPORT THIS: - where we need Shapely of OurForest to inline the newtype wrapper data OurTree a = OurNode a (OurForest a) deriving (Functor, Show) newtype OurForest a = OurForest [OurTree a] deriving ( Functor, Show) fmap Prelude.concat $ forM [''Tree, ''OurTree, ''OurForest] deriveShapely ourTree = OurNode 'a' (OurForest [OurNode 'b' (OurForest []) , OurNode 'c' (OurForest []) ]) theirTree = Node 'a' ( [ Node 'b' [] , Node 'c' [] ]) -} data WithFunctorTerm1 = WFT1 (Maybe WithFunctorTerm1) (Maybe [Int]) deriving Eq data WithFunctorTerm2 = WFT2 (Maybe WithFunctorTerm2) (Maybe [Int]) deriving Eq fmap Prelude.concat $ forM [''WithFunctorTerm1, ''WithFunctorTerm2] deriveShapely prop_smoketest_functor_term_sanity = coerce (WFT1 Nothing $ Just [1..3]) == (WFT2 Nothing $ Just [1..3]) -- TODO POLYMORPHISM/INFERRENCE-PRESERVING STUFF WE MIGHT LIKE TO SUPPORT SOMEHOW -- ------------------------------ {- prop_smoketest_th_rec_reg_param_swapping_coerce = (coerce RRPNil1) == (RRPNil2 :: RegRecParams2 Char Bool) prop_smoketest_th_rec_reg_poly_param_swapping_coerce = let (x,y) = (RRPNil1,coerce x) :: (RegRecParams1 a b, RegRecParams2 a b) in y == RRPNil2 -- But note: this is also (at the top level) ambiguous: -- foo = RRPNil2 == RRPNil2 th_rec_reg_poly_param_swapping_coerce :: (RegRecParams1 a b, RegRecParams2 a b) th_rec_reg_poly_param_swapping_coerce = let (x,y) = (RRPNil1, coerce x) in (x,y) -- if we can make FactorPrefix look like: -- class (Product ab)=> FactorPrefix ab abcs cs | ab abcs -> cs, ab cs -> abcs, abcs cs -> ab where -- we'd get better inferrence, supporting: prop_smoketest_factorPrefix2 = ( ('a',(True,())) , (Left ('b',())) :: Either (Char,()) () ) == (factorPrefix (Left ('a',(True,('b',()))) )) prop_smoketest_toList2 = ( toList $ toFList () ) == [] -- currently we need: _4th `asLength` as fanin (1,(2,(3,(4,())))) _4th -- we'd like this type to be inferable (AGAIN TECHNICALLY POSSIBLE WITH CLOSED TYPE FAMILIES) prop_smoketest_fanout_prod = fanout (head,(tail,(Prelude.length,()))) [1..3] == (1,([2,3],(3,()))) -} -- --------------------------------------------------------------------------- {- -- TO THINK ABOUT, when doing inlining, deeper structure on next version: -- these are old notes newtype Strange0 a = Strange0 (Either a (Strange0 a)) -- must pass `Strange0` as recursive target. newtype Strange1 = Strange1 [Strange1] -- e.g. (S1 []) : (S1 [ S1 [], S1 [] ]) : [] -- Either () (AlsoNormal Strange1, (AlsoNormal [Strange1], ())) -- we take normal form from argument [Strange1]: -- Either () (Strange1,([Strange1],())) -- ...but pass along *both* the newtype and inner wrapped type as recursion candidates data OddTree a rt = OddBranch (OddTree a rt) a rt | OddLeaf newtype Strange3 a = Strange3 (OddTree a (Strange3 a)) -- Either (AlsoNormal (OddTree a (Strange3 a)), (a, (AlsoNormal (Strange3 a), ()))) () -- (this is the same as Strange1) newtype Strange4 = Strange4 ([Either Strange4 Int]) -- a strange rose tree -- we have a mutually-recursive structure, but where recursive subterms are not at top-level, same as: data Strange4' = Cons4' (Either Strange4' Int) Strange4' | Empty4' -- Either (Either (AlsoNormal (Strange4')) (Int,()) , (AlsoNormal Strange4', ())) () -- \ ____________________________________ / -- Normal (Either Strange4' Int) -- -- We can't wrap in AlsoNormal, because an instance AlsoNormal (Either -- Strange4' Int) would overlap . But if that Either was a type we didn't have -- a Shapely instance for, we'd need to generate it. But we'd in turn need to -- generate the instance for the newtype-wrapped type, since we need its -- recursive Strange4' term bound. So... -- -- A different approach seems in order: -- - reify all *exposed* types on the RHS of type declaration -- - add AlsoNormal wrappers everywhere necessary to break cycles -- this might mean doing AlsoNormal [Foo] but keeping [Bar] -- -- Or maybe transform to a "flat" type first? by running an `mconcat`, e.g. -- Strange4' becomes: -- data Strange4' = Cons4'A Strange4' Strange4' -- | Cons4'B Int Strange4' -- | Empty4' -- And `data Bar a= Bar Int ((a,Char) , Int)` becomes: -- data Bar a = Bar Int a Char Int -- -- But then how de we differentiate between an Int term (which we shouldn't try -- to "unpack") and a Foo term? Just if it has arguments or not? -- -- Perhaps look at other generics libraries and see what they do. -}
/** * Created by Administrator on 2016/12/4. */ public class BaseApplication extends Application { private String navigation_state,navi_delete,navi_all; private static BaseApplication instance; @Override public void onCreate() { super.onCreate(); instance=this; } public String getNavi_all() { return navi_all; } public String getNavi_delete() { return navi_delete; } public String getNavigation_state() { return navigation_state; } public void setNavi_all(String navi_all) { this.navi_all = navi_all; } public void setNavi_delete(String navi_delete) { this.navi_delete = navi_delete; } public void setNavigation_state(String navigation_state) { this.navigation_state = navigation_state; } public static BaseApplication getInstance() { return instance; } }
/** * @param action * @param contentId * @param collectionId The Id of the collection. * @param userToken The token of the logged in user. * @param parameters * @param handler Response handler * @throws MalformedURLException */ public static void featureMessage(String action, String contentId, String collectionId, String userToken, HashMap<String, Object> parameters, JsonHttpResponseHandler handler) throws MalformedURLException { RequestParams bodyParams = new RequestParams(); bodyParams.put("lftoken", userToken); final Builder uriBuilder = new Uri.Builder().scheme(LivefyreConfig.scheme) .authority(LivefyreConfig.quillDomain + "." + LivefyreConfig.getConfiguredNetworkID()) .appendPath("api").appendPath("v3.0").appendPath("collection") .appendPath(collectionId).appendPath(action) .appendPath(contentId).appendPath("") .appendQueryParameter("lftoken", userToken) .appendQueryParameter("collection_id", collectionId); Log.d("SDK", "" + uriBuilder); HttpClient.client.post(uriBuilder.toString(), bodyParams, handler); }
Ouverture Since Week 2 of the Preseason, the 2016 Raiders defense has been struggling with giving up big plays. Over the first 4 weeks, the high-flying offense has been able to keep barely a step ahead and lead the team to 3 victories. In week 5, the Big Plays once again haunted the defense, prompting the clearly concerned Head Coach Jack Del Rio to say that the Raiders’ defense was “playing Santa Claus”. Christmas in October sounds great, but on the playing field, a Defense that is gifting big plays to opposing offenses is more a cause for increased work than a holiday. Overall, the Raiders defense is moving forward and there are definitely parts of the defense that have improved significantly since Week 1, but those are being overshadowed by these explosive plays. If the defense gives up a 50 yard TD bomb on 3rd down, who remembers the great defensive plays on 1st and 2nd down? In looking at the Christmas Defense, we can see that there’s no single problem; there are little things that are manifesting in different ways and in different places. Here’s a close look at some of these details and some insight into what is causing the explosive plays. * * * Coverage Scheme In the first four weeks, the defensive coverage was primarily Man-Free (man coverage with single free safety) and Cover 3 (3 deep zone coverage), similar to the Seattle Seahawks’ system. Unfortunatley, those coverages have been a problem since Week 1 when Drew Brees went for 423 yards and 4 TDs and a 131.3 passer rating. That game had Sean Smith’s head spinning for a week. It wasn’t much better against Matt Ryan (396 yards, 3 TDs, 131.5 rating), though Flacco was held relatively in check (298 yards, 1 TD, 83.7 rating) and Mariota without his #1 target Delanie Walker struggled (214 yards, 2 ints, 46.8 rating) In Week 5, Ken Norton changed it up; he installed Quarter Coverage. Quarters Coverage (also called Cover 4) is a hybrid scheme that initially sets up as a 4-deep/3-under Zone defense but it has substantial Man principles involved. As with most schemes, it requires good coordination and minor variances can create big holes. But when executed well, it can provide some nice advantages. It is particularly demanding on the safeties. It forces quick decisions and sets them up in potential 1-on-1 man coverage assignments against slot receivers. Here’s a look at how the Raiders ran Cover 4, how the safeties were playing it, and how Philip Rivers and the Chargers were attacking it. Play #1. Sean Smith on an Island 2-16-SD 18 (2:00) (Shotgun) P.Rivers pass incomplete deep left to T.Benjamin (S.Smith). Outside speed receiver Travis “Rabbit” Benjamin (5’10”, 172lbs, 4.36s 40 yard) run a deep post against RCB Sean Smith. Sean Smith keeps up with Benjamin and Rivers’ pass falls incomplete. The first reaction may be “Where’s the safety help?” When you look closely at the play, you’ll notice that if Benjamin does beat Smith and gets the completion, there is no one between him and the endzone. This looks like a “Zero Coverage” which is almost always a result of an All Out Blitz. The Raiders do blitz, but they have 6 in coverage, so what happened? 1. Routes Route Combination : TE #85 Antonio Gates lined up slot left runs an out route at about 8 yard depth. WR Travis Benjamin split wide left runs a deep post Remember this route combination; it is important and will show up again. With both Reggie Nelson and Sean Smith on the right side, we would expect that the deep post would have in/out bracket coverage taking away the deep throw. But Gates’ route will affect Nelson and create an empty deep field. 2. Routes and Coverage Bruce Irvin covers Gates on the intermediate out route. Sean Smith takes Benjamin on the deep route. Reggie Nelson has to make a decision. He must choose between Benjamin and Gates. For Quarters Coverage, his primary rule is : Pick up the inside receiver on a vertical route If inside receiver runs short, then double on the outside receiver It’s important for Nelson’s assessment to be in sync with both Sean Smith and Bruce Irvin. Each coverage defender has to know where Nelson is going to go, based on the routes. 3. On the Throw Benjamin is running the deep post route against Smith. Nelson is vacating his deep position to drop underneath. It appears that he has judged Gates to be running a deep corner route and is protecting against that. Notice that Bruce Irvin has great coverage on Gates. Rivers has just released the ball. The route combination is designed to draw Nelson; Rivers has read the coverage, is anticipating the deep 1-on-1, and is throwing it for the big play. 4. Ball Nelson gets stuck in No Man’s Land which leaves the defensive backfield empty. Benjamin gets a step on Smith and has the entire middle of the field to run into, but the throw by Rivers is to the outside. The throw allows Smith to get back into the play and to use his long arms to disrupt the pass. Sean Smith understood (or saw) that he did not have deep help from Nelson. Understanding that he was on an island meant that he had to defend the route more aggressively. It’s a great play by Smith, but it’s also a slight misfire by the Chargers. The play worked; it drew Nelson down underneath and the Chargers got the matchup they wanted. In the first few games, we’ve seen Smith get burned by a speed receiver. In this case, a better throw may have gone for a touchdown. A team may get away once with Zero coverage, but repeating it is asking for trouble. This play may have revealed a potential weakness in this coverage. Play #2. Deep Post TD Pass to Tyrell Williams 2-10-OAK 29 (13:13) P.Rivers pass deep middle to Ty.Williams for 29 yards, TOUCHDOWN. 2nd Year WR Tyrell Williams (6’3″, 4.45s 40 yard) runs a deep post and splits two Raiders’ defenders (Amerson and Nelson). Rivers delivers the ball perfectly into the endzone for the easy 29 yard touchdown. 1. Routes Route Combination : TE #85 Antonio Gates lined up as the TE runs an out route at about 10 yard depth. WR Tyrell Williams split wide right runs a deep post 2. Routes and Coverage LB Perry Riley drops in an underneath zone coverage with Gates. LCB David Amerson drops against Williams and protects against the outside deep route, playing as if assuming he has inside help. Reggie Nelson has to decide between the two routes. His rule is to pick up the TE if it is a vertical route, otherwise he doubles the WR. 3. The Break Gates’ route looks vertical until he breaks to the outside. Reggie Nelson has already come up to cover Gates and he is now is a difficult position to cover Williams. He must flip his hips and reverse direction against a younger, faster player. It’s not close. Notice Amerson. He’s turned his hips to the outside, allowing him to run with Williams on a Go route, but making it very difficult to cover on an inside breaking route. He’s depending on Nelson on the inside. Unfortunately, Williams just runs away from Nelson and makes the easy TD catch. Here’s a close up of the moment of truth for Reggie Nelson : Again, the Chargers used the same route combination against the Raiders’ Quarters Coverage. Again, they baited Reggie Nelson out of the deep field and got an open receiver. This time they converted for a touchdown. For a second time, the Raiders’ have shown a weakness in their coverage. Play #3. Sean Smith on an Island II 1-10-SD 20 (3:55) P.Rivers pass deep middle intended for T.Benjamin INTERCEPTED by S.Smith at OAK 41. S.Smith ran ob at SD 32 for 27 yards (T.Benjamin). Travis Benjamin again gets 1-on-1 v Sean Smith on the deep post. This time when Rivers makes the throw, Smith makes the interception. 1. Routes Route Combination : TE #86 Hunter Henry lined up as the TE runs an out route at about 12 yard depth. WR Travis Benjamin split wide left runs a deep post 2. Routes and Coverage Benjamin runs the deep post on Sean Smith. Nelson has man coverage on Hunter Henry because it is vertical. 10+ yards is enough to clear the underneath LB coverage and be deemed a vertical route. 3. The Throw Rivers is throwing to the deep post as Nelson breaks to cover Henry, leaving Smith isolated. The deep middle is open and Sean Smith has to try to make up ground on Benjamin. Notice on the opposite side, Amerson and Karl Joseph have the WR doubled because there was no inside receiver. 4. The Ball Benjamin has a step or so on Smith. Once again the ball is slightly off, this time it is underthrown by about 5 yards, allowing Smith to undercut and make the interception. Another great play by Sean Smith, partly because he understood that the safety was vacating and leaving him with true 1-on-1. Again, we notice that the Post/Out route combination did as intended and exposed the deep middle of the Raiders’ secondary. The result was fantastic (interception and nice return by Smith), but it is increasingly concerning that the Chargers are so easily able to get the matchup they want. Opposing offenses will certainly take note and look to attack this coverage. Play #4. Karl Joseph 3-16-SD 18 (1:54) (Shotgun) P.Rivers pass deep middle intended for D.Inman INTERCEPTED by K.Joseph [B.Irvin] at OAK 35. K.Joseph to SD 44 for 21 yards (D.Inman). This time it’s Karl Joseph’s turn. Same out/post route combination. Rivers throws deep to Dontrelle Inman on the post, but Inman falls down and Joseph makes the interception. 1. Routes Route Combination : TE #85 Antonio Gates slot right runs an out route at about 11 yard depth. WR Dontrelle Inman split wide right runs a deep post 2. Routes and Coverage 2 things : Same route combination as before, but this time the defense is in Cover 3 and so Karl does not have responsibilities on the inside receiver. Instead, he has deep middle third field responsibility. Amerson plays an aggressive man-coverage with inside position on Inman 3. The Throw See that Gates’ out-cut has no effect on Karl Joseph, who is playing deep middle. Amerson is playing very aggressively on Inman as Rivers is making the deep throw. We don’t know for sure, but Rivers may be thinking / anticipating one of two things : Misread coverage and anticipated Quarters coverage and Joseph vacating the middle Read correct Cover 3 and was throwing Jump Ball to 6’3″ Inman on 5’10” Karl Joseph, similar to Amari Cooper’s big jump ball reception v Chargers in 2015. At first, it appears that this is an indication that Karl Joseph’s safety play was far better than Reggie Nelson’s. On this play, though, it’s more because of the coverage rather than the actual decision making of the safety. This does bring up a couple of important things. First, installing a new coverage (Quarters coverage/Cover 4 has not been part of the Raiders’ scheme so far this year) mid year is always challenging. It’s made especially so with 4 secondary players who are still unfamiliar with each other. It’s actually imrpessive that they played it as well as they did. Second, Quarters is an interesting coverage scheme and does have some advantages, but it may not be a very good fit for Reggie Nelson’s skillset. It’s clear that Nelson’s footspeed is not great. At 33 years old, we don’t expect it to be, but aging veteran safeties make up for it with great anticipation (eg., CWood). Having Nelson play in a foreign coverage scheme and one that is a tough fit, may end up causing more problems than it solves. Third, Quarters may end up being a nice match for Karl Joseph. Karl’s diverse skillset may be put to great use in a scheme like this. Part of the reason to implement it may have been to assess Karl’s play in it. Karl is the future and Ken Norton may have wanted to get a sense of how it fit him. Play #5. Deep post to Tyrell Williams 1-10-SD 25 (11:19) P.Rivers pass deep middle to Ty.Williams to OAK 25 for 50 yards (D.Amerson). Penalty on OAK-S.Smith, Defensive Holding, declined. The Chargers’ routes combination is conceptually similar to what they ran earlier but here, it is to expose Reggie Nelson in Man-Free coverage. 1. Routes Route Combination : Travis Benjamin runs intermediate crosser from his tight split on the left side Tyrelle Williams runs a deep post on the right side 2. Routes and Coverage Man Coverage has Amerson on Williams and Sean Smith on Benjamin. The Crossing route runs right at Reggie Nelson and forces him to quickly decide where to double. 3. Throw Nelson doesn’t explicitly bite on Travis Benjamin’s route, but he does slow his feet. 4. The Ball That was enough to let Williams get on top of him and then run right by. Nelson went from 3 yard cushion to 3 yards trail in a heartbeat and that resulted in the 50 yard gainer. This is an interesting play because this is an equivalent concept to the first plays, but in Cover 1 v Cover 4. And once again, we see Reggie Nelson’s lack of speed being exposed in the deep secondary. It’s still too early to give up on Reggie Nelson. On thing to keep in mind is that he’s coming from playing under Mike Zimmer’ schemes 6 years (4 years under Zimmer and then two more under Zimmer’s assistant Paul Guenther). Moving from the reads and reactions in Zimmer’s schemes to those in Ken Norton’s scheme may be taking longer than we may have hoped. It’s hard to say whether these deep field problems are occuring because of Nelson’s footspeed or because his reaction and anticipation is compromised. All defensive backs are going to lose a step or so in their mid-30s, but the good (and great) ones are able to offset that with improved anticipation and game prep. Eg., Charles Woodson. Right now, it seems that Reggie is struggling with his recognition. * * * Scheme Problems Revisited Plays #1-5 showed the Big Play potential that the defense was showing. Mike McCoy and Philip Rivers were attacking the Raiders’ coverage in some specific ways and were often getting Reggie Nelson to get well out of position. Perhaps more concerning, though, is that there were a number of plays that looked like they were lifted from previous weeks. The Chargers scouts did a great job of looking at past Raiders’ film and grabbing some specific plays that were successful and added those to their weekly gameplan. And then at key points, they unleashed and the defense had not adjusted since. This is like the “Horn of Plenty”, a gift that keeps on giving or a Zombie rising from the dead to attack once again. Some fans may have not noticed, so here’s a closer look at those plays. Play #6. Spread out against 14 Personnel 1-1-OAK 1 (10:14) (Shotgun) K.Wiggins reported in as eligible. P.Rivers pass short middle to H.Henry for 1 yard, TOUCHDOWN. Week 1 in New Orleans. Early in the game, Sean Payton decided to go for it on 4th-and-goal from the 1 yard line. The Saints lined up with 13 Personnel and the Raiders defensive confusion resulted in 10 men on the field and a relatively easy TD pass. This week, SD sets up with goalline package, 14 Personnel with an extra OT. This time the Raiders do have 11 men on the field with 1 Safety, 5 DL, 5 linebackers. 1. Run Formation The initial formation is a heavy, goalline run formation. 2. Pass Formation Then the Chargers take all the TEs and then line them up as WRs as if in 11 Personnel. This stretches the field horizontally and puts linebackers like Bruce Irvin and Darren Bates out in coverage. Here’s a GIF showing the motion : 3. Routes and Coverage In this formation, rookie LB #57 Cory James is playing the FS position. On the outside, the TEs McGrath and Henry run a basic Pick Play against Bruce and Reggie. 4. The Throw Perry Riley and Cory James are both in No Man’s Land, neither close enough to challenge Rivers nor with enough depth to close down passing windows. Reggie gets picked and is in trail position on Henry. There is no inside help and so it’s an easy read and throw. 5. The TD That’s just too easy. Nearly the exact same play came from New Orleans in Week 1 : 1-2-OAK 2 (6:07) (Shotgun) D.Brees pass short left to T.Cadet for 2 yards, TOUCHDOWN. New Orleans put this on tape and SD cashed in on it. Now it’s up to Ken Norton to get it fixed. Play #7. Screen TD to Melvin Gordon 2-7-OAK 18 (12:38) (Shotgun) P.Rivers pass short left to M.Gordon for 18 yards, TOUCHDOWN. The Chargers fake a WR screen to the right and then throw the screen to Melvin Gordon to the left. It leaves only Reggie Nelson and Cory James to make the play and two blockers out in front. Nice play design against a young defense that tends to jump on first action. 1. Routes and Coverage Chargers show a WR screen to the right that draws 4+ defenders to that side and holds the other defenders so that blockers can get leverage. Meanwhile, the RB Melvin Gordon slips out to the opposite side which is empty. 2. The Reception The DLine doesn’t recognize it at all and are drawn upfield. Reggie Nelson and Cory James are blocked and Melvin Gordon has an clear path to the endzone. The big key to this was the fake screen and how it sheared the defense. Nelson and James had to hold their ground and were slow to read the RB screen. It’s very similar to Week 1 v New Orleans : 2-6-OAK 33 (8:01) D.Brees pass short left to M.Ingram to OAK 13 for 20 yards (J.Ward; M.Smith). There’s some misdirection that gets the Raiders’ defense to flow one way and then the screen pass goes to the empty opposite side. One good block and the RB is on his way. Young defenses are generally aggressive and susceptible to jumping on first action. This is a perfect example of that. Play #8. Double team Neutralizes Khalil Mack‘s Force 1-10-OAK 25 (10:53) M.Gordon right end pushed ob at OAK 1 for 24 yards (S.Smith). The TE and RT combine to neutralize Khalil Mack’s force and then Melvin Gordon gets to the outside. This was Melvin Gordon’s biggest run of the day. Aside from this play, the Raiders’ run defense did a pretty solid job on Gordon. 1. TE Pre Snap Motion TE #86 Hunter Henry motions from left to right. He sets up right in front of Khalil Mack. 2. Combo-Block coming Henry and the RT Chris Hairston double Mack. 3. Double With Mack sealed inside, the FB leads the play, and Melvin Gordon has a clear path to the outside. Notice #54 Perry Riley is in chase. Hunter Henry comes off his combo block and then seals Riley to the inside to spring this for the big yards. Here’s a look at the pre-snap motion : And this is a close up of the double team on Mack : This is basically the same play design that Tennessee used repeatedly to gain the edge on Khalil Mack. Here’s an example from the Tennessee game : 2-7-TEN 42 (13:48) D.Murray left end to OAK 41 for 17 yards (R.Nelson). In fact, there’s an entire post dedicated to on this blog : here This was definitely a scheme problem in Week 3 and here in Week 5, we are still seeing it gets exploited. Ken Norton and his staff definitely need to figure out how they want to address this. 9. Flea Flicking variant of the QB Boot 1-10-OAK 40 (9:03) Lateral from #17 P.Rivers to #28 M.Gordon. Lateral from #28 M.Gordon back to #17 P.Rivers. (Shotgun) P.Rivers pass short left to T.Benjamin to OAK 17 for 23 yards (R.Nelson). The QB Bootleg has been a problem since the preseason game against Green Bay and SD used a clever variant of it by making it a Flea Flicker. Basically the same principles and it gave the Raiders’ defense the same problems. 1. Routes and Coverage Clear out route by the backside WR. Rivers hands off to Gordon and then bootlegs away. When the defense flows, Gordon throws back to Rivers. Travis Benjamin runs the over route and is wide open. 2. Throw Karl recognizes and reads the play, but he can’t cover Travis Benjamin 1-on-1 in open space. On the play, Karl reacts to play the deep post as Benjamin runs the crosser. Perry Riley reacts late and tries to help underneath, but Benjamin v Riley is a total mismatch. The QB Boot is continuing to haunt this Raiders defense. Going Forward Ken Norton Jr is still trying to find the right match of scheme and personnel to counter the opposing offenses. The primary coverages of Man-Free (Cover 1) and Cover 3 were having some problems so, he experimented with Quarters (Cover 4). As you may expected, installing a new coverage in-season was and up-and-down exercise. At times, it seemed that San Diego felt more comfortable attacking the coverage than the Raiders did in playing it, though some of the disguising may have led to a misread by Rivers that led to Karl Joseph’s interception. Keep an eye on this in the weeks to come. We’ll find out more about Norton’s vision of the coverage scheme in weeks to come. Reggie Nelson has struggled in adjusting to this defense. Most of the problem is recognition which is putting him in poor position and he doesn’t have the footspeed to make up for it. How much of this is the transition from the Bengals’ defense and how much is it just Father Time taking its toll on Nelson’s skills? That’s yet to be answered, but we still have not seen the best of Reggie Nelson. We still have not seen him really play and react naturally and full speed. In a sense, it’s like seeing a rookie trying to get up to speed, which is surprising for a 10-year veteran. It’s too early to give up on Reggie, but how long it will take Reggie to fully make the transition to Ken Norton’s defense is an important question. The answer to this may determine how far the Raiders are able to go this year. Keep an eye on Karl’s role. He’s a tremendous talent and his field awareness is very good. In college, he was mostly playing near the line of scrimmage where he could affect the game more, so he may need some time to be able to play more often in deep safety coverages, but we may start seeing the Coaching staff trust in Karl more and more. The Gifts that keep on giving : There are now 5 weeks of tape on the Raiders’ defense and there are some scheme problems that are clear as day. We had a great glimpse of an opposing offense scouting the Raiders and adding plays to their playbook that have worked so far this year. As long as the Raiders continue to have problems with these plays, opposing teams are going to run those plays at them. QB Boots, LBs split wide and defending Pick Plays, TE motion and double to seal Mack, Misdirection, RB screens etc. You cannot fix everything at once. There’s just too much and this is just too young a squad with very little history to fall back on. It’s like having a carpet that is just slightly larger than the floor; push down on one side and the other side lifts up. Push down on both and the middle bubbles up. It takes time to trim the edges and get the right fit. That’s of little solace to impatient fans, but what we can feel optimistic about is that there is visible evidence that overall the defense is improving. The defense did some very nice things this past week and there has been clear growth by some players (eg., Stacy McGee, Jihad Ward, Karl Joseph) and some scheme problems have been cleaned up. Notice that the run defense was actually very good and that the interior defensive line has not been blown off the line of scrimmage as it had been earlier this year. And while they gifted San Diego several big plays, they also made some big plays of their own : 2 sacks, 2 tackles for loss, 4 turnovers + 1 other fumble nearly recovered. It’s dangerous to build a defense dependent on just big plays and turnovers, but it is also exciting to have players that are capable of doing so. Sean Smith just tied his career high for interceptions in a season, Amerson has been very good defending, and Karl Joseph looks like a star in the making. The Linebackers are growing and so far have had a knack for punching the ball out. And the the Pass Rush is still finding its way. It’s coming along. slowly Finale The Raiders’ Christmas Defense really came down to two things, Safety Play in the Coverage Scheme and Recurring Problem Plays. Most fans knew that the defensive backfield would take some time to gel and that the two new safeties would have to grow into the roles, but most thought that veteran Reggie Nelson would be close to “Plug and Play” while rookie Karl Joseph would be the one to be slowly weaned into the system. Right now, Ken Norton may be ready to increase Karl’s role and see how he fares. It’s bad enough to see the defense beaten for a big play; it’s much more frustrating to see that it was the same play that gouged the defense from a previous opponent. Recall last season around this time, the defense’s biggest problem was finding and stopping passes to the Tight Ends and Running Backs. The rest of the year, the defense did much better. Similarly, expect Ken Norton to address these problem areas and start moving the defense forward. After running the gauntlet of talented and savvy veteran QBs like Drew Brees, Matt Ryan, Joe Flacco, and Philip Rivers, the next four games provide potentially more favorable matchups : Alex Smith, KC Blake Bortles, JAX Jameis Winston, TB Trevor Siemian/Paxton Lynch, DEN Each of these QBs (and their respective offenses) is certainly talented and capable of having a big game, but they are less likely to dissect the defense the way the previous QBs have. The defense will continue to come together and will have a chance to show their improvement in these games. Look for this unit to turn the corner at some point and to start to give us a look at what we have long term with the Raiders. Share this: Twitter Facebook
def redraw_cross_section_regions(self): figcanvas = self.cross_section figcanvas.l_lbkg.set_xdata(self._low_bkg) figcanvas.l_hbkg.set_xdata(self._high_bkg) figcanvas.l_bc.set_xdata(self._true_centre) figcanvas.l_lfore.set_xdata(self._low_px) figcanvas.l_hfore.set_xdata(self._high_px) figcanvas.draw() figcanvas = self.detector_image figcanvas.l_lbkg.set_ydata(self._low_bkg - 0.5) figcanvas.l_hbkg.set_ydata(self._high_bkg + 0.5) figcanvas.l_bc.set_ydata(self._true_centre) figcanvas.l_lfore.set_ydata(self._low_px - 0.5) figcanvas.l_hfore.set_ydata(self._high_px + 0.5) figcanvas.draw()
<filename>src/status/interfaces/types/statusCheck.type.ts export type TStatusCheck = { currentStatus: string; newStatus: string; };
import Routes from 'src/constants/api/routes'; export const loginApiCaller = async (credentials: {[key: string]: string}): Promise<Response> => { /** ************ Request configuration ************ */ const reqUrl = Routes.login.url; const body = { ...credentials, }; const reqSettings = { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(body), }; return fetch(reqUrl, reqSettings).catch((e) => { throw e; }); }; export default loginApiCaller;
Republican leaders are adding a $75 billion magic asterisk to their Obamacare repeal plan It will help older people in some totally unspecified way. Allegedly. In an effort to blunt the American Health Care Act’s disastrous effect on older Americans, House Republican leaders are adding a provision that would set aside $75 billion to do ... something unspecified. Really. According to Politico, the new version of the bill will not say at all what to do with the $75 billion. Instead it will just “instruct the Senate” to come up with a plan to use the money to help people between the ages of 50 and 64. This is a very unusual way to legislate and reflects House Republicans’ desperation to push through basically anything as soon as possible and pass the buck to the Senate. The underlying issue is that the Affordable Care Act provides people earning less than 400 percent of the poverty line with sliding-scale subsidies to purchase health insurance. The less you earn, the more help you get. The ACA also limits insurance companies’ ability to charge older customers higher premiums than they charge to younger ones. AHCA changes the subsidies around, ensuring that everyone who makes less than $75,000 a year gets a subsidy that’s based on age. The older you are, the more help you get. This leaves the neediest families out of luck — the subsidy isn’t enough to buy an insurance plan if you’re just barely above the poverty line regardless of your age, so they would end up going uninsured and get nothing from the government at all. But even though older people get more generous subsidies, they are worse off than before too. That’s because AHCA allows insurers to charge older people as much as five times what they charge younger ones, so older people’s premiums will skyrocket far beyond anything the subsidy can deliver. The result is a health insurance system that really only works for relatively young, relatively affluent people. Older people are the Republican base, however, so a bill that badly damages their financial interests is a political problem for many House Republicans. Coming up with an actual fix to this problem is not conceptually impossible. But it would require a pretty substantial rethink of the underlying architecture of the AHCA, which is designed, on a deep level, to better serve the interests of people who don’t need much help while doing less to serve the interests of those who do. But Paul Ryan is determined to have the House vote on this bill on Thursday, which means they don’t have time for any big rethink or prolonged negotiation. So what they’ve come up with instead is, apparently, this $75 billion magic asterisk. The House will pass a bill with what amounts to a blank spot, and then members can say they repealed Obamacare and toss the hot potato of working out the details to their colleagues in the Senate.
#include <iostream> #include <cstdio> #include <cstdlib> #include <climits> #include <set> #include <map> #include <vector> #include <string> #include <cmath> #include <cstring> #include <queue> #include <stack> #include <algorithm> #include <sstream> #include <numeric> #include <unordered_map> using namespace std; #define ft first #define sc second #define re return #define pb push_back #define For(i,j,k) for (int i=(int)(j);i<=(k);i++) #define Rep(i,j,k) for (int i=(int)(j);i>=(k);i--) #define For2(i,j,k) for (int i=(int)(j);i<(k);i++) #define Rep2(i,j,k) for (int i=(int)(j);i>(k);i--) #define mp make_pair #define sz(a) int((a).size()) #define all(c) (c).begin(),(c).end() #define forit(it,S) for(__typeof(S.begin()) it = S.begin(); it != S.end(); ++it) #define vi vector<int> #define DEBUG false typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; const long long MOD = 1e9 + 7; template <class T> struct BIT { int n; vector<T> tree; BIT( int n ) :n( n + 1 ), tree( n + 1 ) {} void add( int x, T a ) { for ( ; x < n; x += x & -x ) tree[ x ] += a; } T sum( int x ) { T ret = 0; for ( ; x; x ^= x & -x ) ret += tree[ x ]; return ret; } T rangeSum( int l, int r ) { return( sum( r ) - sum( l - 1 ) ); } }; #define SEGMENT_TREE false #if (SEGMENT_TREE) namespace segtree { namespace lazy { //출처: https://bowbowbow.tistory.com/4 [멍멍멍] const int MAX_N = 1000010; ll arr[ MAX_N ]; typedef struct Tree { ll value, lazy; } Tree; Tree tree[ 3 * MAX_N ]; ll init( int node, int start, int end ) { if ( start == end ) return tree[ node ].value = arr[ start ]; else return tree[ node ].value = init( node * 2, start, ( start + end ) / 2 ) + init( node * 2 + 1, ( start + end ) / 2 + 1, end ); } void update( int node, int start, int end, int i, int j, ll diff ) { if ( tree[ node ].lazy != 0 ) { tree[ node ].value += ( (ll)(end)-(ll)(start)+1 ) * tree[ node ].lazy; if ( start != end ) { tree[ node * 2 ].lazy += tree[ node ].lazy; tree[ node * 2 + 1 ].lazy += tree[ node ].lazy; } tree[ node ].lazy = 0; } if ( j < start || i > end ) return; if ( i <= start && end <= j ) { tree[ node ].value += ( (ll)(end)-(ll)(start)+1 ) * diff; if ( start != end ) { tree[ node * 2 ].lazy += diff; tree[ node * 2 + 1 ].lazy += diff; } return; } update( node * 2, start, ( start + end ) / 2, i, j, diff ); update( node * 2 + 1, ( start + end ) / 2 + 1, end, i, j, diff ); tree[ node ].value = tree[ node * 2 ].value + tree[ node * 2 + 1 ].value; } ll getsum( int node, int start, int end, int i, int j ) { if ( tree[ node ].lazy != 0 ) { tree[ node ].value += ( (ll)(end)-(ll)(start)+1 ) * tree[ node ].lazy; if ( start != end ) { tree[ node * 2 ].lazy += tree[ node ].lazy; tree[ node * 2 + 1 ].lazy += tree[ node ].lazy; } tree[ node ].lazy = 0; } if ( i > end || j < start ) return 0; if ( i <= start && end <= j ) return tree[ node ].value; return tree[ node ].value = getsum( node * 2, start, ( start + end ) / 2, i, j ) + getsum( node * 2 + 1, ( start + end ) / 2 + 1, end, i, j ); } ll getmax( int node, int start, int end, int i, int j ) { if ( tree[ node ].lazy != 0 ) { tree[ node ].value += ( (ll)(end)-(ll)(start)+1 ) * tree[ node ].lazy; if ( start != end ) { tree[ node * 2 ].lazy += tree[ node ].lazy; tree[ node * 2 + 1 ].lazy += tree[ node ].lazy; } tree[ node ].lazy = 0; } if ( i > end || j < start ) return 0; if ( i <= start && end <= j ) return tree[ node ].value; return tree[ node ].value = max( getmax( node * 2, start, ( start + end ) / 2, i, j ), getmax( node * 2 + 1, ( start + end ) / 2 + 1, end, i, j ) ); } } namespace standard { // https://stonejjun.tistory.com/66 const int MAX_N = 1000010; ll arr[ MAX_N ]; ll tree[ 3 * MAX_N ]; void update( int node, int start, int en, int index, long long int diff ) { if ( index<start || index>en ) return; tree[ node ] = tree[ node ] + diff; if ( start != en ) { update( node * 2, start, ( start + en ) / 2, index, diff ); update( node * 2 + 1, ( start + en ) / 2 + 1, en, index, diff ); } } long long getsum( int node, int start, int en, int left, int right ) { if ( left > en || right < start ) return 0; if ( left <= start && en <= right ) return tree[ node ]; return getsum( node * 2, start, ( start + en ) / 2, left, right ) + getsum( node * 2 + 1, ( start + en ) / 2 + 1, en, left, right ); } } } #endif /* ----------------------------------------------------- */ long long fact[ 4000000 ] = { 0, }; long long getPow( long long base, int exponent ) { if ( exponent == 0 ) return 1; if ( exponent == 1 ) return base; long long pow = getPow( base, exponent / 2 ); if ( exponent % 2 == 1 ) { return ( ( ( base * pow ) % MOD ) * pow ) % MOD; } return ( pow * pow ) % MOD; } inline void pre() { /* fact[ 0 ] = 1; fact[ 1 ] = 1; for ( int i = 2; i <= 1020; i++ ) { fact[ i ] = ( fact[ i - 1 ] * i ) % MOD; } */ } const ll MYMOD = 1e9 + 7; const int MAX_N = 1e2 + 7; const bool TEST_CASES = true; int n; ll k; ll p[ MAX_N ]; ll sum[ MAX_N ]; inline void read() { cin >> n >> k; For( i, 0, n - 1 ) cin >> p[ i ]; } inline void solve() { // sum = 20100 // sum = 20 sum[ 0 ] = p[ 0 ]; For( i, 1, n - 1 ) { sum[ i ] = p[ i ] + sum[ i - 1 ]; } ll ret = 0; For( i, 1, n - 1 ) { ll here = p[ i ]; ll cnt = 0; if ( here * 100 > ( sum[ i - 1 ] + cnt ) * k ) { cnt = ( here * 100 ) / k - sum[ i - 1 ]; while ( here * 100 > ( sum[ i - 1 ] + cnt ) * k ) cnt++; } ret += cnt; sum[ i ] = p[i] + sum[i - 1] + cnt; } cout << ret << '\n'; } int main() { ios::sync_with_stdio( false ); cin.tie( 0 ); cout.tie( 0 ); cout.precision( 2 ); cout << fixed; pre(); int t = 1; if ( TEST_CASES ) cin >> t; while ( t-- ) { read(); solve(); } return 0; }
/** * Move this ScriptFamily component to end of body and returns <code>true</code> if done so. This method * needs to be called from {@link #processEvent(ComponentSystemEvent)} during {@link PostAddToViewEvent} or * {@link PostRestoreStateEvent}. This has basically the same effect as setting <code>target="body"</code> on a * component resource. * @param event The involved event, which can be either {@link PostAddToViewEvent} or {@link PostRestoreStateEvent}. * @return <code>true</code> if the move has taken place. */ protected boolean moveToBody(ComponentSystemEvent event) { if (!(event instanceof PostAddToViewEvent || event instanceof PostRestoreStateEvent)) { return false; } FacesContext context = event.getFacesContext(); UIViewRoot view = context.getViewRoot(); if (context.isPostback() ? !view.getComponentResources(context, "body").contains(this) : event instanceof PostAddToViewEvent) { view.addComponentResource(context, this, "body"); return true; } else { return false; } }
/** * Chat session * * @author jexa7410 */ public abstract class ChatSession extends ImsServiceSession implements MsrpEventListener { /** * Subject */ private String subject = null; /** * First message */ private InstantMessage firstMessage = null; /** * List of participants */ private ListOfParticipant participants = new ListOfParticipant(); /** * MSRP manager */ private MsrpManager msrpMgr = null; /** * Is composing manager */ private IsComposingManager isComposingMgr = new IsComposingManager(this); /** * Chat activity manager */ private ChatActivityManager activityMgr = new ChatActivityManager(this); /** * Max number of participants in the session */ private int maxParticipants = RcsSettings.getInstance().getMaxChatParticipants(); /** * Contribution ID */ private String contributionId = null; /** * The logger */ private Logger logger = Logger.getLogger(this.getClass().getName()); /** * Constructor * * @param parent IMS service * @param contact Remote contact */ public ChatSession(ImsService parent, String contact) { super(parent, contact); // Create the MSRP manager int localMsrpPort = NetworkRessourceManager.generateLocalMsrpPort(); String localIpAddress = getImsService().getImsModule().getCurrentNetworkInterface().getNetworkAccess().getIpAddress(); msrpMgr = new MsrpManager(localIpAddress, localMsrpPort); } /** * Constructor * * @param parent IMS service * @param contact Remote contact * @param participants List of participants */ public ChatSession(ImsService parent, String contact, ListOfParticipant participants) { this(parent, contact); // Set the session participants setParticipants(participants); } /** * Return the first message of the session * * @return Instant message */ public InstantMessage getFirstMessage() { return firstMessage; } /** * Set first message * * @param firstMessage First message */ protected void setFirstMesssage(InstantMessage firstMessage) { this.firstMessage = firstMessage; } /** * Returns the subject of the session * * @return String */ public String getSubject() { return subject; } /** * Set the subject of the session * * @param subject Subject */ public void setSubject(String subject) { this.subject = subject; } /** * Returns the IMDN manager * * @return IMDN manager */ public ImdnManager getImdnManager() { return ((InstantMessagingService)getImsService()).getImdnManager(); } /** * Returns the session activity manager * * @return Activity manager */ public ChatActivityManager getActivityManager() { return activityMgr; } /** * Return the contribution ID * * @return Contribution ID */ public String getContributionID() { return contributionId; } /** * Set the contribution ID * * @param id Contribution ID */ public void setContributionID(String id) { this.contributionId = id; } /** * Returns the list of participants * * @return List of participants */ public ListOfParticipant getParticipants() { return participants; } /** * Set the list of participants * * @param participants List of participants */ public void setParticipants(ListOfParticipant participants) { this.participants = participants; } /** * Returns the list of participants currently connected to the session * * @return List of participants */ public abstract ListOfParticipant getConnectedParticipants(); /** * Returns the IM session identity * * @return Identity (e.g. SIP-URI) */ public String getImSessionIdentity() { if (getDialogPath() != null) { return getDialogPath().getTarget(); } else { return null; } } /** * Returns the MSRP manager * * @return MSRP manager */ public MsrpManager getMsrpMgr() { return msrpMgr; } /** * Close the MSRP session */ public void closeMsrpSession() { if (getMsrpMgr() != null) { getMsrpMgr().closeSession(); if (logger.isActivated()) { logger.debug("MSRP session has been closed"); } } } /** * Handle error * * @param error Error */ public void handleError(ChatError error) { // Error if (logger.isActivated()) { logger.info("Session error: " + error.getErrorCode() + ", reason=" + error.getMessage()); } // Close media session closeMediaSession(); // Remove the current session getImsService().removeSession(this); // Notify listeners if (!isInterrupted()) { for(int i=0; i < getListeners().size(); i++) { ((ChatSessionListener)getListeners().get(i)).handleImError(error); } } } /** * Data has been transfered * * @param msgId Message ID */ public void msrpDataTransfered(String msgId) { if (logger.isActivated()) { logger.info("Data transfered"); } // Update the activity manager activityMgr.updateActivity(); } /** * Data transfer has been received * * @param msgId Message ID * @param data Received data * @param mimeType Data mime-type */ public void msrpDataReceived(String msgId, byte[] data, String mimeType) { if (logger.isActivated()) { logger.info("Data received (type " + mimeType + ")"); } // Update the activity manager activityMgr.updateActivity(); if ((data == null) || (data.length == 0)) { // By-pass empty data if (logger.isActivated()) { logger.debug("By-pass received empty data"); } return; } if (ChatUtils.isApplicationIsComposingType(mimeType)) { // Is composing event receiveIsComposing(getRemoteContact(), data); } else if (ChatUtils.isTextPlainType(mimeType)) { // Text message receiveText(getRemoteContact(), StringUtils.decodeUTF8(data), null, false, new Date()); } else if (ChatUtils.isMessageCpimType(mimeType)) { // Receive a CPIM message try { CpimParser cpimParser = new CpimParser(data); CpimMessage cpimMsg = cpimParser.getCpimMessage(); if (cpimMsg != null) { /** M: ALPS00504086 Get local time for the received message to order the list @{ */ //Date date = cpimMsg.getMessageDate(); Date date = new Date(); /** @} */ /** M: add server date for delivery status @{ */ long dateTime = 0L; if (date != null) { dateTime = date.getTime(); } /** @} */ String cpimMsgId = cpimMsg.getHeader(ImdnUtils.HEADER_IMDN_MSG_ID); if (cpimMsgId == null) { cpimMsgId = msgId; } String contentType = cpimMsg.getContentType(); String from = cpimMsg.getHeader(CpimMessage.HEADER_FROM); if (from.indexOf("[email protected]") != -1) { from = getRemoteContact(); } if (ChatUtils.isTextPlainType(contentType)) { // Text message // Check if the message needs a delivery report boolean imdnDisplayedRequested = false; String dispositionNotification = cpimMsg.getHeader(ImdnUtils.HEADER_IMDN_DISPO_NOTIF); if (dispositionNotification != null) { if (dispositionNotification.contains(ImdnDocument.POSITIVE_DELIVERY)) { // Positive delivery requested, send MSRP message with status "delivered" sendMsrpMessageDeliveryStatus(from, cpimMsgId, ImdnDocument.DELIVERY_STATUS_DELIVERED); } if (dispositionNotification.contains(ImdnDocument.DISPLAY)) { imdnDisplayedRequested = true; } } // Get received text message receiveText(from, StringUtils.decodeUTF8(cpimMsg.getMessageContent()), cpimMsgId, imdnDisplayedRequested, date); // Mark the message as waiting a displayed report if needed if (imdnDisplayedRequested) { RichMessaging.getInstance().setChatMessageDeliveryRequested(cpimMsgId); } } else if (ChatUtils.isApplicationIsComposingType(contentType)) { // Is composing event receiveIsComposing(from, cpimMsg.getMessageContent().getBytes()); } else if (ChatUtils.isMessageImdnType(contentType)) { // Receive a delivery report /** M: add server date for delivery status @{ */ receiveMessageDeliveryStatus(cpimMsg.getMessageContent(), dateTime); /** @} */ } } } catch(Exception e) { if (logger.isActivated()) { logger.error("Can't parse the CPIM message", e); } } } else { // Not supported content if (logger.isActivated()) { logger.debug("Not supported content " + mimeType + " in chat session"); } } } /** * Data transfer in progress * * @param currentSize Current transfered size in bytes * @param totalSize Total size in bytes */ public void msrpTransferProgress(long currentSize, long totalSize) { // Not used by chat } /** * Data transfer has been aborted */ public void msrpTransferAborted() { // Not used by chat } /** * Data transfer error * * @param error Error */ public void msrpTransferError(String error) { if (logger.isActivated()) { logger.info("Data transfer error: " + error); } // Notify listeners for(int i=0; i < getListeners().size(); i++) { ((ChatSessionListener)getListeners().get(i)).handleImError(new ChatError(ChatError.MEDIA_SESSION_FAILED)); } } /** * Receive text message * * @param contact Contact * @param txt Text message * @param msgId Message Id * @param flag indicating that an IMDN "displayed" is requested for this message * @param date Date of the message */ private void receiveText(String contact, String txt, String msgId, boolean imdnDisplayedRequested, Date date) { // Is composing event is reset isComposingMgr.receiveIsComposingEvent(contact, false); // Notify listeners for(int i=0; i < getListeners().size(); i++) { ((ChatSessionListener)getListeners().get(i)).handleReceiveMessage(new InstantMessage(msgId, contact, txt, imdnDisplayedRequested, date)); } } /** * Receive is composing event * * @param contact Contact * @param event Event */ private void receiveIsComposing(String contact, byte[] event) { isComposingMgr.receiveIsComposingEvent(contact, event); } /** * Send an empty data chunk */ public void sendEmptyDataChunk() { try { msrpMgr.sendEmptyChunk(); } catch(Exception e) { if (logger.isActivated()) { logger.error("Problem while sending empty data chunk", e); } } } /** * Send data chunk with a specified MIME type * * @param msgId Message ID * @param data Data * @param mime MIME type * @return Boolean result */ public boolean sendDataChunks(String msgId, String data, String mime) { try { ByteArrayInputStream stream = new ByteArrayInputStream(data.getBytes()); msrpMgr.sendChunks(stream, msgId, mime, data.getBytes().length); return true; } catch(Exception e) { // Error if (logger.isActivated()) { logger.error("Problem while sending data chunks", e); } return false; } } /** * Is group chat * * @return Boolean */ public abstract boolean isGroupChat(); /** * Is Store & Forward * * @return Boolean */ public boolean isStoreAndForward() { if (this instanceof TerminatingStoreAndForwardMsgSession) { return true; } else { return false; } } /** * Send a text message * * @param msgId Message-ID * @param txt Text message * @return Boolean result */ public abstract void sendTextMessage(String msgId, String txt); /** * Send message delivery status via MSRP * * @param contact Contact that requested the delivery status * @param msgId Message ID * @param status Status */ public abstract void sendMsrpMessageDeliveryStatus(String contact, String msgId, String status); /** * Send is composing status * * @param status Status */ public abstract void sendIsComposingStatus(boolean status); /** * Add a participant to the session * * @param participant Participant */ public abstract void addParticipant(String participant); /** * Add a list of participants to the session * * @param participants List of participants */ public abstract void addParticipants(List<String> participants); /** M: add server date for delivery status @{ */ /** * Receive a message delivery status from a SIP message * * @param msgId Message ID * @param status Delivery status */ public void receiveMessageDeliveryStatus(String msgId, String status, long date) { // Notify listeners for (int i = 0; i < getListeners().size(); i++) { ((ChatSessionListener) getListeners().get(i)).handleMessageDeliveryStatus(msgId, status, date); } } /** * Receive a message delivery status from an XML document * * @param xml XML document */ public void receiveMessageDeliveryStatus(String xml, long date) { try { ImdnDocument imdn = ChatUtils.parseDeliveryReport(xml); if (imdn != null) { // Notify listeners String status = imdn.getStatus(); for (int i = 0; i < getListeners().size(); i++) { ((ChatSessionListener) getListeners().get(i)).handleMessageDeliveryStatus( imdn.getMsgId(), status, date); } } } catch (Exception e) { if (logger.isActivated()) { logger.error("Can't parse IMDN document", e); } } } /** @} */ /** * Get max number of participants in the session including the initiator * * @return Integer */ public int getMaxParticipants() { return maxParticipants; } /** * Set max number of participants in the session including the initiator * * @param maxParticipants Max number */ public void setMaxParticipants(int maxParticipants) { this.maxParticipants = maxParticipants; } /** * Reject the session invitation */ public abstract void rejectSession(); }
class WorkerSettings: """ WorkerSettings class is used to configure worker. If you are using yatq-worker command line utility, you should implement custom config by inheriting this class and implementing `redis_client` method, along with setting `factory_kwargs` and/or custom `factory_cls`. """ factory_cls: Type[BaseJobFactory] = SimpleJobFactory factory_kwargs: Optional[Dict] = None queue_namespace: Optional[str] = None @staticmethod async def on_startup() -> None: # pragma: no cover ... @staticmethod async def on_shutdown() -> None: # pragma: no cover ... @staticmethod async def redis_client() -> aioredis.Redis: # pragma: no cover ... @staticmethod async def on_task_process_exception( job: BaseJob, exc_info: T_ExcInfo, ) -> None: # pragma: no cover ...
/** * Apply the default csv schema to the provided builder. * * @param builder the builder to use for schema configuration * @return the configured csv schema */ public CsvSchema defaultSchemaForBuilder(CsvSchema.Builder builder) { return builder. build(). withAllowComments(true). withArrayElementSeparator(MZTabConstants.BAR_S). withNullValue(MZTabConstants.NULL). withUseHeader(true). withoutQuoteChar(). withoutEscapeChar(). withLineSeparator(MZTabConstants.NEW_LINE). withColumnSeparator(MZTabConstants.TAB); }
As expected the IEEE has ratified a new Ethernet specification -- IEEE P802.3bz – that defines 2.5GBASE-T and 5GBASE-T, boosting the current top speed of traditional Ethernet five-times without requiring the tearing out of current cabling. The Ethernet Alliance wrote that the IEEE 802.3bz Standard for Ethernet Amendment sets Media Access Control Parameters, Physical Layers and Management Parameters for 2.5G and 5Gbps Operation lets access layer bandwidth evolve incrementally beyond 1Gbps, it will help address emerging needs in a variety of settings and applications, including enterprise, wireless networks. +More on Network World: Ethernet: Are there worlds left to conquer?+ Indeed, the wireless component may be the most significant implication of the standard as 2.5G and 5G Ethernet will allow connectivity to 802.11ac Wave 2 Access Points, considered by many to be the real driving force behind bringing up the speed of traditional NBase-T products. “As new 802.11ac Wave 2 wireless technology is being deployed the need to offload more and more data at higher and higher speeds from the wireless to the wired network has never been so critical,” wrote Sachin Gupta, vice president of product management in a blog celebrating the ratification. “Going beyond 1 Gb/s with existing Cat5e and Cat6 cables was little more than a talking point two years ago. But now with NBASE-T, we have the ability to extend the life of an enormous asset —your wired network.” Gupta added: “For some, a re-cabling isn’t even possible. For others, unfeasible. For the rest, re-cabling is just costly and disruptive. It is easy to imagine the value of delivering multi-gigabit speeds to the more than 1.3 billion Cat 5e/6 outlets worldwide if it doesn’t require the huge head-ache and expense of a major cable replacement. The promise of NBASE-T has to have nearly every CFO, CTO, building manager and IT group breathing a huge sigh of relief.” “The applications for NBASE-T solutions are vast and growing. Enterprise, small medium business, industrial and home networks can take advantage of this technology to enable higher capacity wireless access points and faster downloads to client systems such as medical imaging systems that work with large data files, upgraded industrial and home networks,” the NBASE-T Alliance wrote of the ratification. "Last quarter, NBASE-T switch and access point ports surged significantly as enterprises began to upgrade their campus networks to speeds beyond 1G," said Alan Weckel, vice president of Ethernet switch market research at Dell'Oro Group in a statement. "There will be a sizable upgrade cycle around NBASE-T technology with robust growth expected over the next several years. As a result, we expect 2017 NBASE-T port shipments to exceed three million ports." +More on Network World: Low-speed Ethernet champions set plugfest ahead of new net standard Hand-in-hand with adoption of a low-speed Ethernet standard by the IEEE, proponents of the technology will hold an interoperability plugfest in October to tout the readiness of 2.5GBASE-T and 5GBASE-T products. For the plugfest, which will be held the week of Oct. 10 at the University of New Hampshire InterOperability Laboratory in Durham, N.H., the two groups behind the new Ethernet speeds the Ethernet Alliance and the NBASE-T Alliance will work together and share post-event results of the interoperability testing performed. Related Video:
// GetWord translation from url. func GetWord(word string) (*Result, error) { w := strings.Replace(word, " ", "+", -1) url := strings.Replace(UrlRequestTemplate, ":w", w, -1) res := &Result{List: make([]Res, 0), Url: url, Word: word} doc, err := goquery.NewDocument(url) if err != nil { return nil, nil } sub, skip := "", false doc.Find(".subj,.trans").Each(func(i int, selection *goquery.Selection) { if selection.Get(0).Attr[0].Val == "subj" { sub = strings.Trim(selection.Text(), " , - >") if strings.Contains(sub, ` `) { skip = true } } else if selection.Get(0).Attr[0].Val == "trans" { if skip || res.HasSub(sub) { skip = false return } c := (i + 1) / 2 if len(res.List) > c { log.Error().Msgf("search idx %d, trans. count %d", i, c) return } res.List = append(res.List, Res{Sub: sub, Trans: selection.Text()}) } }) return res, nil }
def _GetFullTableSQL(table, name, delete_where): if delete_where: yield 'DELETE FROM %s WHERE %s;' % (name, delete_where) for sql in table.GetInsertSQLList(name, max_size=2**20, on_duplicate_key_update=True): yield sql
#include "clar_libgit2.h" void test_repo_getters__is_empty_correctly_deals_with_pristine_looking_repos(void) { git_repository *repo; repo = cl_git_sandbox_init("empty_bare.git"); cl_git_remove_placeholders(git_repository_path(repo), "dummy-marker.txt"); cl_assert_equal_i(true, git_repository_is_empty(repo)); cl_git_sandbox_cleanup(); } void test_repo_getters__is_empty_can_detect_used_repositories(void) { git_repository *repo; cl_git_pass(git_repository_open(&repo, cl_fixture("testrepo.git"))); cl_assert_equal_i(false, git_repository_is_empty(repo)); git_repository_free(repo); } void test_repo_getters__retrieving_the_odb_honors_the_refcount(void) { git_odb *odb; git_repository *repo; cl_git_pass(git_repository_open(&repo, cl_fixture("testrepo.git"))); cl_git_pass(git_repository_odb(&odb, repo)); cl_assert(((git_refcount *)odb)->refcount.val == 2); git_repository_free(repo); cl_assert(((git_refcount *)odb)->refcount.val == 1); git_odb_free(odb); }
<filename>pkg/tensorflow/contrib/boosted_trees/proto/learner.pb.go // Code generated by protoc-gen-go. DO NOT EDIT. // source: tensorflow/contrib/boosted_trees/proto/learner.proto /* Package proto is a generated protocol buffer package. It is generated from these files: tensorflow/contrib/boosted_trees/proto/learner.proto tensorflow/contrib/boosted_trees/proto/quantiles.proto tensorflow/contrib/boosted_trees/proto/tree_config.proto It has these top-level messages: TreeRegularizationConfig TreeConstraintsConfig LearningRateConfig LearningRateFixedConfig LearningRateLineSearchConfig AveragingConfig LearningRateDropoutDrivenConfig LearnerConfig QuantileConfig QuantileEntry QuantileSummaryState QuantileStreamState TreeNode TreeNodeMetadata Leaf Vector SparseVector DenseFloatBinarySplit SparseFloatBinarySplitDefaultLeft SparseFloatBinarySplitDefaultRight CategoricalIdBinarySplit CategoricalIdSetMembershipBinarySplit DecisionTreeConfig DecisionTreeMetadata GrowingMetadata DecisionTreeEnsembleConfig */ package proto import proto1 "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto1.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto1.ProtoPackageIsVersion2 // please upgrade the proto package type LearnerConfig_PruningMode int32 const ( LearnerConfig_PRE_PRUNE LearnerConfig_PruningMode = 0 LearnerConfig_POST_PRUNE LearnerConfig_PruningMode = 1 ) var LearnerConfig_PruningMode_name = map[int32]string{ 0: "PRE_PRUNE", 1: "POST_PRUNE", } var LearnerConfig_PruningMode_value = map[string]int32{ "PRE_PRUNE": 0, "POST_PRUNE": 1, } func (x LearnerConfig_PruningMode) String() string { return proto1.EnumName(LearnerConfig_PruningMode_name, int32(x)) } func (LearnerConfig_PruningMode) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{7, 0} } type LearnerConfig_GrowingMode int32 const ( LearnerConfig_WHOLE_TREE LearnerConfig_GrowingMode = 0 // Layer by layer is only supported by the batch learner. LearnerConfig_LAYER_BY_LAYER LearnerConfig_GrowingMode = 1 ) var LearnerConfig_GrowingMode_name = map[int32]string{ 0: "WHOLE_TREE", 1: "LAYER_BY_LAYER", } var LearnerConfig_GrowingMode_value = map[string]int32{ "WHOLE_TREE": 0, "LAYER_BY_LAYER": 1, } func (x LearnerConfig_GrowingMode) String() string { return proto1.EnumName(LearnerConfig_GrowingMode_name, int32(x)) } func (LearnerConfig_GrowingMode) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{7, 1} } type LearnerConfig_MultiClassStrategy int32 const ( LearnerConfig_TREE_PER_CLASS LearnerConfig_MultiClassStrategy = 0 LearnerConfig_FULL_HESSIAN LearnerConfig_MultiClassStrategy = 1 LearnerConfig_DIAGONAL_HESSIAN LearnerConfig_MultiClassStrategy = 2 ) var LearnerConfig_MultiClassStrategy_name = map[int32]string{ 0: "TREE_PER_CLASS", 1: "FULL_HESSIAN", 2: "DIAGONAL_HESSIAN", } var LearnerConfig_MultiClassStrategy_value = map[string]int32{ "TREE_PER_CLASS": 0, "FULL_HESSIAN": 1, "DIAGONAL_HESSIAN": 2, } func (x LearnerConfig_MultiClassStrategy) String() string { return proto1.EnumName(LearnerConfig_MultiClassStrategy_name, int32(x)) } func (LearnerConfig_MultiClassStrategy) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{7, 2} } // Tree regularization config. type TreeRegularizationConfig struct { // Classic L1/L2. L1 float32 `protobuf:"fixed32,1,opt,name=l1" json:"l1,omitempty"` L2 float32 `protobuf:"fixed32,2,opt,name=l2" json:"l2,omitempty"` // Tree complexity penalizes overall model complexity effectively // limiting how deep the tree can grow in regions with small gain. TreeComplexity float32 `protobuf:"fixed32,3,opt,name=tree_complexity,json=treeComplexity" json:"tree_complexity,omitempty"` } func (m *TreeRegularizationConfig) Reset() { *m = TreeRegularizationConfig{} } func (m *TreeRegularizationConfig) String() string { return proto1.CompactTextString(m) } func (*TreeRegularizationConfig) ProtoMessage() {} func (*TreeRegularizationConfig) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *TreeRegularizationConfig) GetL1() float32 { if m != nil { return m.L1 } return 0 } func (m *TreeRegularizationConfig) GetL2() float32 { if m != nil { return m.L2 } return 0 } func (m *TreeRegularizationConfig) GetTreeComplexity() float32 { if m != nil { return m.TreeComplexity } return 0 } // Tree constraints config. type TreeConstraintsConfig struct { // Maximum depth of the trees. MaxTreeDepth uint32 `protobuf:"varint,1,opt,name=max_tree_depth,json=maxTreeDepth" json:"max_tree_depth,omitempty"` // Min hessian weight per node. MinNodeWeight float32 `protobuf:"fixed32,2,opt,name=min_node_weight,json=minNodeWeight" json:"min_node_weight,omitempty"` } func (m *TreeConstraintsConfig) Reset() { *m = TreeConstraintsConfig{} } func (m *TreeConstraintsConfig) String() string { return proto1.CompactTextString(m) } func (*TreeConstraintsConfig) ProtoMessage() {} func (*TreeConstraintsConfig) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *TreeConstraintsConfig) GetMaxTreeDepth() uint32 { if m != nil { return m.MaxTreeDepth } return 0 } func (m *TreeConstraintsConfig) GetMinNodeWeight() float32 { if m != nil { return m.MinNodeWeight } return 0 } // LearningRateConfig describes all supported learning rate tuners. type LearningRateConfig struct { // Types that are valid to be assigned to Tuner: // *LearningRateConfig_Fixed // *LearningRateConfig_Dropout // *LearningRateConfig_LineSearch Tuner isLearningRateConfig_Tuner `protobuf_oneof:"tuner"` } func (m *LearningRateConfig) Reset() { *m = LearningRateConfig{} } func (m *LearningRateConfig) String() string { return proto1.CompactTextString(m) } func (*LearningRateConfig) ProtoMessage() {} func (*LearningRateConfig) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } type isLearningRateConfig_Tuner interface { isLearningRateConfig_Tuner() } type LearningRateConfig_Fixed struct { Fixed *LearningRateFixedConfig `protobuf:"bytes,1,opt,name=fixed,oneof"` } type LearningRateConfig_Dropout struct { Dropout *LearningRateDropoutDrivenConfig `protobuf:"bytes,2,opt,name=dropout,oneof"` } type LearningRateConfig_LineSearch struct { LineSearch *LearningRateLineSearchConfig `protobuf:"bytes,3,opt,name=line_search,json=lineSearch,oneof"` } func (*LearningRateConfig_Fixed) isLearningRateConfig_Tuner() {} func (*LearningRateConfig_Dropout) isLearningRateConfig_Tuner() {} func (*LearningRateConfig_LineSearch) isLearningRateConfig_Tuner() {} func (m *LearningRateConfig) GetTuner() isLearningRateConfig_Tuner { if m != nil { return m.Tuner } return nil } func (m *LearningRateConfig) GetFixed() *LearningRateFixedConfig { if x, ok := m.GetTuner().(*LearningRateConfig_Fixed); ok { return x.Fixed } return nil } func (m *LearningRateConfig) GetDropout() *LearningRateDropoutDrivenConfig { if x, ok := m.GetTuner().(*LearningRateConfig_Dropout); ok { return x.Dropout } return nil } func (m *LearningRateConfig) GetLineSearch() *LearningRateLineSearchConfig { if x, ok := m.GetTuner().(*LearningRateConfig_LineSearch); ok { return x.LineSearch } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*LearningRateConfig) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) { return _LearningRateConfig_OneofMarshaler, _LearningRateConfig_OneofUnmarshaler, _LearningRateConfig_OneofSizer, []interface{}{ (*LearningRateConfig_Fixed)(nil), (*LearningRateConfig_Dropout)(nil), (*LearningRateConfig_LineSearch)(nil), } } func _LearningRateConfig_OneofMarshaler(msg proto1.Message, b *proto1.Buffer) error { m := msg.(*LearningRateConfig) // tuner switch x := m.Tuner.(type) { case *LearningRateConfig_Fixed: b.EncodeVarint(1<<3 | proto1.WireBytes) if err := b.EncodeMessage(x.Fixed); err != nil { return err } case *LearningRateConfig_Dropout: b.EncodeVarint(2<<3 | proto1.WireBytes) if err := b.EncodeMessage(x.Dropout); err != nil { return err } case *LearningRateConfig_LineSearch: b.EncodeVarint(3<<3 | proto1.WireBytes) if err := b.EncodeMessage(x.LineSearch); err != nil { return err } case nil: default: return fmt.Errorf("LearningRateConfig.Tuner has unexpected type %T", x) } return nil } func _LearningRateConfig_OneofUnmarshaler(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error) { m := msg.(*LearningRateConfig) switch tag { case 1: // tuner.fixed if wire != proto1.WireBytes { return true, proto1.ErrInternalBadWireType } msg := new(LearningRateFixedConfig) err := b.DecodeMessage(msg) m.Tuner = &LearningRateConfig_Fixed{msg} return true, err case 2: // tuner.dropout if wire != proto1.WireBytes { return true, proto1.ErrInternalBadWireType } msg := new(LearningRateDropoutDrivenConfig) err := b.DecodeMessage(msg) m.Tuner = &LearningRateConfig_Dropout{msg} return true, err case 3: // tuner.line_search if wire != proto1.WireBytes { return true, proto1.ErrInternalBadWireType } msg := new(LearningRateLineSearchConfig) err := b.DecodeMessage(msg) m.Tuner = &LearningRateConfig_LineSearch{msg} return true, err default: return false, nil } } func _LearningRateConfig_OneofSizer(msg proto1.Message) (n int) { m := msg.(*LearningRateConfig) // tuner switch x := m.Tuner.(type) { case *LearningRateConfig_Fixed: s := proto1.Size(x.Fixed) n += proto1.SizeVarint(1<<3 | proto1.WireBytes) n += proto1.SizeVarint(uint64(s)) n += s case *LearningRateConfig_Dropout: s := proto1.Size(x.Dropout) n += proto1.SizeVarint(2<<3 | proto1.WireBytes) n += proto1.SizeVarint(uint64(s)) n += s case *LearningRateConfig_LineSearch: s := proto1.Size(x.LineSearch) n += proto1.SizeVarint(3<<3 | proto1.WireBytes) n += proto1.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } // Config for a fixed learning rate. type LearningRateFixedConfig struct { LearningRate float32 `protobuf:"fixed32,1,opt,name=learning_rate,json=learningRate" json:"learning_rate,omitempty"` } func (m *LearningRateFixedConfig) Reset() { *m = LearningRateFixedConfig{} } func (m *LearningRateFixedConfig) String() string { return proto1.CompactTextString(m) } func (*LearningRateFixedConfig) ProtoMessage() {} func (*LearningRateFixedConfig) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (m *LearningRateFixedConfig) GetLearningRate() float32 { if m != nil { return m.LearningRate } return 0 } // Config for a tuned learning rate. type LearningRateLineSearchConfig struct { // Max learning rate. Must be strictly positive. MaxLearningRate float32 `protobuf:"fixed32,1,opt,name=max_learning_rate,json=maxLearningRate" json:"max_learning_rate,omitempty"` // Number of learning rate values to consider between [0, max_learning_rate). NumSteps int32 `protobuf:"varint,2,opt,name=num_steps,json=numSteps" json:"num_steps,omitempty"` } func (m *LearningRateLineSearchConfig) Reset() { *m = LearningRateLineSearchConfig{} } func (m *LearningRateLineSearchConfig) String() string { return proto1.CompactTextString(m) } func (*LearningRateLineSearchConfig) ProtoMessage() {} func (*LearningRateLineSearchConfig) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } func (m *LearningRateLineSearchConfig) GetMaxLearningRate() float32 { if m != nil { return m.MaxLearningRate } return 0 } func (m *LearningRateLineSearchConfig) GetNumSteps() int32 { if m != nil { return m.NumSteps } return 0 } // When we have a sequence of trees 1, 2, 3 ... n, these essentially represent // weights updates in functional space, and thus we can use averaging of weight // updates to achieve better performance. For example, we can say that our final // ensemble will be an average of ensembles of tree 1, and ensemble of tree 1 // and tree 2 etc .. ensemble of all trees. // Note that this averaging will apply ONLY DURING PREDICTION. The training // stays the same. type AveragingConfig struct { // Types that are valid to be assigned to Config: // *AveragingConfig_AverageLastNTrees // *AveragingConfig_AverageLastPercentTrees Config isAveragingConfig_Config `protobuf_oneof:"config"` } func (m *AveragingConfig) Reset() { *m = AveragingConfig{} } func (m *AveragingConfig) String() string { return proto1.CompactTextString(m) } func (*AveragingConfig) ProtoMessage() {} func (*AveragingConfig) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } type isAveragingConfig_Config interface { isAveragingConfig_Config() } type AveragingConfig_AverageLastNTrees struct { AverageLastNTrees float32 `protobuf:"fixed32,1,opt,name=average_last_n_trees,json=averageLastNTrees,oneof"` } type AveragingConfig_AverageLastPercentTrees struct { AverageLastPercentTrees float32 `protobuf:"fixed32,2,opt,name=average_last_percent_trees,json=averageLastPercentTrees,oneof"` } func (*AveragingConfig_AverageLastNTrees) isAveragingConfig_Config() {} func (*AveragingConfig_AverageLastPercentTrees) isAveragingConfig_Config() {} func (m *AveragingConfig) GetConfig() isAveragingConfig_Config { if m != nil { return m.Config } return nil } func (m *AveragingConfig) GetAverageLastNTrees() float32 { if x, ok := m.GetConfig().(*AveragingConfig_AverageLastNTrees); ok { return x.AverageLastNTrees } return 0 } func (m *AveragingConfig) GetAverageLastPercentTrees() float32 { if x, ok := m.GetConfig().(*AveragingConfig_AverageLastPercentTrees); ok { return x.AverageLastPercentTrees } return 0 } // XXX_OneofFuncs is for the internal use of the proto package. func (*AveragingConfig) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) { return _AveragingConfig_OneofMarshaler, _AveragingConfig_OneofUnmarshaler, _AveragingConfig_OneofSizer, []interface{}{ (*AveragingConfig_AverageLastNTrees)(nil), (*AveragingConfig_AverageLastPercentTrees)(nil), } } func _AveragingConfig_OneofMarshaler(msg proto1.Message, b *proto1.Buffer) error { m := msg.(*AveragingConfig) // config switch x := m.Config.(type) { case *AveragingConfig_AverageLastNTrees: b.EncodeVarint(1<<3 | proto1.WireFixed32) b.EncodeFixed32(uint64(math.Float32bits(x.AverageLastNTrees))) case *AveragingConfig_AverageLastPercentTrees: b.EncodeVarint(2<<3 | proto1.WireFixed32) b.EncodeFixed32(uint64(math.Float32bits(x.AverageLastPercentTrees))) case nil: default: return fmt.Errorf("AveragingConfig.Config has unexpected type %T", x) } return nil } func _AveragingConfig_OneofUnmarshaler(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error) { m := msg.(*AveragingConfig) switch tag { case 1: // config.average_last_n_trees if wire != proto1.WireFixed32 { return true, proto1.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.Config = &AveragingConfig_AverageLastNTrees{math.Float32frombits(uint32(x))} return true, err case 2: // config.average_last_percent_trees if wire != proto1.WireFixed32 { return true, proto1.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.Config = &AveragingConfig_AverageLastPercentTrees{math.Float32frombits(uint32(x))} return true, err default: return false, nil } } func _AveragingConfig_OneofSizer(msg proto1.Message) (n int) { m := msg.(*AveragingConfig) // config switch x := m.Config.(type) { case *AveragingConfig_AverageLastNTrees: n += proto1.SizeVarint(1<<3 | proto1.WireFixed32) n += 4 case *AveragingConfig_AverageLastPercentTrees: n += proto1.SizeVarint(2<<3 | proto1.WireFixed32) n += 4 case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type LearningRateDropoutDrivenConfig struct { // Probability of dropping each tree in an existing so far ensemble. DropoutProbability float32 `protobuf:"fixed32,1,opt,name=dropout_probability,json=dropoutProbability" json:"dropout_probability,omitempty"` // When trees are built after dropout happen, they don't "advance" to the // optimal solution, they just rearrange the path. However you can still // choose to skip dropout periodically, to allow a new tree that "advances" // to be added. // For example, if running for 200 steps with probability of dropout 1/100, // you would expect the dropout to start happening for sure for all iterations // after 100. However you can add probability_of_skipping_dropout of 0.1, this // way iterations 100-200 will include approx 90 iterations of dropout and 10 // iterations of normal steps.Set it to 0 if you want just keep building // the refinement trees after dropout kicks in. ProbabilityOfSkippingDropout float32 `protobuf:"fixed32,2,opt,name=probability_of_skipping_dropout,json=probabilityOfSkippingDropout" json:"probability_of_skipping_dropout,omitempty"` // Between 0 and 1. LearningRate float32 `protobuf:"fixed32,3,opt,name=learning_rate,json=learningRate" json:"learning_rate,omitempty"` } func (m *LearningRateDropoutDrivenConfig) Reset() { *m = LearningRateDropoutDrivenConfig{} } func (m *LearningRateDropoutDrivenConfig) String() string { return proto1.CompactTextString(m) } func (*LearningRateDropoutDrivenConfig) ProtoMessage() {} func (*LearningRateDropoutDrivenConfig) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } func (m *LearningRateDropoutDrivenConfig) GetDropoutProbability() float32 { if m != nil { return m.DropoutProbability } return 0 } func (m *LearningRateDropoutDrivenConfig) GetProbabilityOfSkippingDropout() float32 { if m != nil { return m.ProbabilityOfSkippingDropout } return 0 } func (m *LearningRateDropoutDrivenConfig) GetLearningRate() float32 { if m != nil { return m.LearningRate } return 0 } type LearnerConfig struct { // Number of classes. NumClasses uint32 `protobuf:"varint,1,opt,name=num_classes,json=numClasses" json:"num_classes,omitempty"` // Fraction of features to consider in each tree sampled randomly // from all available features. // // Types that are valid to be assigned to FeatureFraction: // *LearnerConfig_FeatureFractionPerTree // *LearnerConfig_FeatureFractionPerLevel FeatureFraction isLearnerConfig_FeatureFraction `protobuf_oneof:"feature_fraction"` // Regularization. Regularization *TreeRegularizationConfig `protobuf:"bytes,4,opt,name=regularization" json:"regularization,omitempty"` // Constraints. Constraints *TreeConstraintsConfig `protobuf:"bytes,5,opt,name=constraints" json:"constraints,omitempty"` // Pruning. PruningMode LearnerConfig_PruningMode `protobuf:"varint,8,opt,name=pruning_mode,json=pruningMode,enum=tensorflow.boosted_trees.learner.LearnerConfig_PruningMode" json:"pruning_mode,omitempty"` // Growing Mode. GrowingMode LearnerConfig_GrowingMode `protobuf:"varint,9,opt,name=growing_mode,json=growingMode,enum=tensorflow.boosted_trees.learner.LearnerConfig_GrowingMode" json:"growing_mode,omitempty"` // Learning rate. LearningRateTuner *LearningRateConfig `protobuf:"bytes,6,opt,name=learning_rate_tuner,json=learningRateTuner" json:"learning_rate_tuner,omitempty"` // Multi-class strategy. MultiClassStrategy LearnerConfig_MultiClassStrategy `protobuf:"varint,10,opt,name=multi_class_strategy,json=multiClassStrategy,enum=tensorflow.boosted_trees.learner.LearnerConfig_MultiClassStrategy" json:"multi_class_strategy,omitempty"` // If you want to average the ensembles (for regularization), provide the // config below. AveragingConfig *AveragingConfig `protobuf:"bytes,11,opt,name=averaging_config,json=averagingConfig" json:"averaging_config,omitempty"` } func (m *LearnerConfig) Reset() { *m = LearnerConfig{} } func (m *LearnerConfig) String() string { return proto1.CompactTextString(m) } func (*LearnerConfig) ProtoMessage() {} func (*LearnerConfig) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } type isLearnerConfig_FeatureFraction interface { isLearnerConfig_FeatureFraction() } type LearnerConfig_FeatureFractionPerTree struct { FeatureFractionPerTree float32 `protobuf:"fixed32,2,opt,name=feature_fraction_per_tree,json=featureFractionPerTree,oneof"` } type LearnerConfig_FeatureFractionPerLevel struct { FeatureFractionPerLevel float32 `protobuf:"fixed32,3,opt,name=feature_fraction_per_level,json=featureFractionPerLevel,oneof"` } func (*LearnerConfig_FeatureFractionPerTree) isLearnerConfig_FeatureFraction() {} func (*LearnerConfig_FeatureFractionPerLevel) isLearnerConfig_FeatureFraction() {} func (m *LearnerConfig) GetFeatureFraction() isLearnerConfig_FeatureFraction { if m != nil { return m.FeatureFraction } return nil } func (m *LearnerConfig) GetNumClasses() uint32 { if m != nil { return m.NumClasses } return 0 } func (m *LearnerConfig) GetFeatureFractionPerTree() float32 { if x, ok := m.GetFeatureFraction().(*LearnerConfig_FeatureFractionPerTree); ok { return x.FeatureFractionPerTree } return 0 } func (m *LearnerConfig) GetFeatureFractionPerLevel() float32 { if x, ok := m.GetFeatureFraction().(*LearnerConfig_FeatureFractionPerLevel); ok { return x.FeatureFractionPerLevel } return 0 } func (m *LearnerConfig) GetRegularization() *TreeRegularizationConfig { if m != nil { return m.Regularization } return nil } func (m *LearnerConfig) GetConstraints() *TreeConstraintsConfig { if m != nil { return m.Constraints } return nil } func (m *LearnerConfig) GetPruningMode() LearnerConfig_PruningMode { if m != nil { return m.PruningMode } return LearnerConfig_PRE_PRUNE } func (m *LearnerConfig) GetGrowingMode() LearnerConfig_GrowingMode { if m != nil { return m.GrowingMode } return LearnerConfig_WHOLE_TREE } func (m *LearnerConfig) GetLearningRateTuner() *LearningRateConfig { if m != nil { return m.LearningRateTuner } return nil } func (m *LearnerConfig) GetMultiClassStrategy() LearnerConfig_MultiClassStrategy { if m != nil { return m.MultiClassStrategy } return LearnerConfig_TREE_PER_CLASS } func (m *LearnerConfig) GetAveragingConfig() *AveragingConfig { if m != nil { return m.AveragingConfig } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*LearnerConfig) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) { return _LearnerConfig_OneofMarshaler, _LearnerConfig_OneofUnmarshaler, _LearnerConfig_OneofSizer, []interface{}{ (*LearnerConfig_FeatureFractionPerTree)(nil), (*LearnerConfig_FeatureFractionPerLevel)(nil), } } func _LearnerConfig_OneofMarshaler(msg proto1.Message, b *proto1.Buffer) error { m := msg.(*LearnerConfig) // feature_fraction switch x := m.FeatureFraction.(type) { case *LearnerConfig_FeatureFractionPerTree: b.EncodeVarint(2<<3 | proto1.WireFixed32) b.EncodeFixed32(uint64(math.Float32bits(x.FeatureFractionPerTree))) case *LearnerConfig_FeatureFractionPerLevel: b.EncodeVarint(3<<3 | proto1.WireFixed32) b.EncodeFixed32(uint64(math.Float32bits(x.FeatureFractionPerLevel))) case nil: default: return fmt.Errorf("LearnerConfig.FeatureFraction has unexpected type %T", x) } return nil } func _LearnerConfig_OneofUnmarshaler(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error) { m := msg.(*LearnerConfig) switch tag { case 2: // feature_fraction.feature_fraction_per_tree if wire != proto1.WireFixed32 { return true, proto1.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.FeatureFraction = &LearnerConfig_FeatureFractionPerTree{math.Float32frombits(uint32(x))} return true, err case 3: // feature_fraction.feature_fraction_per_level if wire != proto1.WireFixed32 { return true, proto1.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.FeatureFraction = &LearnerConfig_FeatureFractionPerLevel{math.Float32frombits(uint32(x))} return true, err default: return false, nil } } func _LearnerConfig_OneofSizer(msg proto1.Message) (n int) { m := msg.(*LearnerConfig) // feature_fraction switch x := m.FeatureFraction.(type) { case *LearnerConfig_FeatureFractionPerTree: n += proto1.SizeVarint(2<<3 | proto1.WireFixed32) n += 4 case *LearnerConfig_FeatureFractionPerLevel: n += proto1.SizeVarint(3<<3 | proto1.WireFixed32) n += 4 case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } func init() { proto1.RegisterType((*TreeRegularizationConfig)(nil), "tensorflow.boosted_trees.learner.TreeRegularizationConfig") proto1.RegisterType((*TreeConstraintsConfig)(nil), "tensorflow.boosted_trees.learner.TreeConstraintsConfig") proto1.RegisterType((*LearningRateConfig)(nil), "tensorflow.boosted_trees.learner.LearningRateConfig") proto1.RegisterType((*LearningRateFixedConfig)(nil), "tensorflow.boosted_trees.learner.LearningRateFixedConfig") proto1.RegisterType((*LearningRateLineSearchConfig)(nil), "tensorflow.boosted_trees.learner.LearningRateLineSearchConfig") proto1.RegisterType((*AveragingConfig)(nil), "tensorflow.boosted_trees.learner.AveragingConfig") proto1.RegisterType((*LearningRateDropoutDrivenConfig)(nil), "tensorflow.boosted_trees.learner.LearningRateDropoutDrivenConfig") proto1.RegisterType((*LearnerConfig)(nil), "tensorflow.boosted_trees.learner.LearnerConfig") proto1.RegisterEnum("tensorflow.boosted_trees.learner.LearnerConfig_PruningMode", LearnerConfig_PruningMode_name, LearnerConfig_PruningMode_value) proto1.RegisterEnum("tensorflow.boosted_trees.learner.LearnerConfig_GrowingMode", LearnerConfig_GrowingMode_name, LearnerConfig_GrowingMode_value) proto1.RegisterEnum("tensorflow.boosted_trees.learner.LearnerConfig_MultiClassStrategy", LearnerConfig_MultiClassStrategy_name, LearnerConfig_MultiClassStrategy_value) } func init() { proto1.RegisterFile("tensorflow/contrib/boosted_trees/proto/learner.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 946 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x56, 0x6f, 0x6f, 0xdb, 0xb6, 0x13, 0x8e, 0xdc, 0x5f, 0xd2, 0xe4, 0x14, 0x3b, 0x0e, 0x9b, 0xdf, 0xaa, 0x6d, 0x05, 0x12, 0x78, 0xc3, 0x56, 0x0c, 0xab, 0x8d, 0x78, 0x05, 0x86, 0xad, 0x58, 0x01, 0x3b, 0x71, 0x9a, 0x02, 0x6a, 0xe2, 0xca, 0xe9, 0x8a, 0x0c, 0xdb, 0x08, 0x5a, 0xa2, 0x15, 0x22, 0x12, 0x29, 0x50, 0x54, 0xfe, 0xec, 0x3b, 0xec, 0x9b, 0xec, 0xd5, 0x3e, 0xc0, 0x3e, 0xd7, 0x5e, 0x0e, 0xa4, 0x18, 0x5b, 0xf9, 0xd3, 0x25, 0xd9, 0x3b, 0xdd, 0xf1, 0x9e, 0xe7, 0x78, 0xcf, 0x1d, 0x0f, 0x82, 0xe7, 0x8a, 0xf2, 0x5c, 0xc8, 0x49, 0x22, 0x4e, 0x3b, 0xa1, 0xe0, 0x4a, 0xb2, 0x71, 0x67, 0x2c, 0x44, 0xae, 0x68, 0x84, 0x95, 0xa4, 0x34, 0xef, 0x64, 0x52, 0x28, 0xd1, 0x49, 0x28, 0x91, 0x9c, 0xca, 0xb6, 0xb1, 0xd0, 0xc6, 0x0c, 0xd5, 0xbe, 0x14, 0xdd, 0xb6, 0x71, 0xad, 0x10, 0xbc, 0x03, 0x49, 0x69, 0x40, 0xe3, 0x22, 0x21, 0x92, 0xfd, 0x46, 0x14, 0x13, 0x7c, 0x4b, 0xf0, 0x09, 0x8b, 0x51, 0x03, 0x6a, 0xc9, 0xa6, 0xe7, 0x6c, 0x38, 0x4f, 0x6b, 0x41, 0x2d, 0xd9, 0x34, 0x76, 0xd7, 0xab, 0x59, 0xbb, 0x8b, 0xbe, 0x84, 0x15, 0x4d, 0x86, 0x43, 0x91, 0x66, 0x09, 0x3d, 0x63, 0xea, 0xdc, 0x7b, 0x60, 0x0e, 0x1b, 0xda, 0xbd, 0x35, 0xf5, 0xb6, 0x28, 0xfc, 0xff, 0xc0, 0x78, 0x78, 0xae, 0x24, 0x61, 0x5c, 0xe5, 0x36, 0xc3, 0xe7, 0xd0, 0x48, 0xc9, 0x99, 0xb9, 0x12, 0x8e, 0x68, 0xa6, 0x8e, 0x4c, 0xb6, 0x7a, 0xb0, 0x9c, 0x92, 0x33, 0x8d, 0xd8, 0xd6, 0x3e, 0xf4, 0x05, 0xac, 0xa4, 0x8c, 0x63, 0x2e, 0x22, 0x8a, 0x4f, 0x29, 0x8b, 0x8f, 0x94, 0xbd, 0x44, 0x3d, 0x65, 0x7c, 0x4f, 0x44, 0xf4, 0xbd, 0x71, 0xb6, 0xfe, 0xac, 0x01, 0xf2, 0x75, 0x5d, 0x8c, 0xc7, 0x01, 0x51, 0xd4, 0x26, 0x79, 0x0b, 0xf3, 0x13, 0x76, 0x46, 0x23, 0xc3, 0xed, 0x76, 0xbf, 0x6b, 0xdf, 0x26, 0x4a, 0xbb, 0x4a, 0xb2, 0xa3, 0xa1, 0x25, 0xd3, 0xee, 0x5c, 0x50, 0x32, 0xa1, 0x5f, 0xe0, 0x61, 0x24, 0x45, 0x26, 0x8a, 0xf2, 0x26, 0x6e, 0xb7, 0x77, 0x3f, 0xd2, 0xed, 0x12, 0xbc, 0x2d, 0xd9, 0x09, 0xe5, 0x53, 0xf2, 0x0b, 0x4e, 0x44, 0xc0, 0x4d, 0x18, 0xa7, 0x38, 0xa7, 0x44, 0x86, 0x47, 0x46, 0x54, 0xb7, 0xfb, 0xf2, 0x7e, 0x29, 0x7c, 0xc6, 0xe9, 0xc8, 0xe0, 0xa7, 0xfc, 0x90, 0x4c, 0x7d, 0xfd, 0x87, 0x30, 0xaf, 0x0a, 0x3d, 0x00, 0x2f, 0xe1, 0xf1, 0x07, 0xca, 0x45, 0x9f, 0x41, 0x3d, 0xb1, 0x47, 0x58, 0x12, 0x45, 0xed, 0x28, 0x2c, 0x27, 0x95, 0xf8, 0x56, 0x0c, 0x4f, 0xfe, 0x2d, 0x2d, 0xfa, 0x0a, 0x56, 0x75, 0x8b, 0x6f, 0x22, 0x5a, 0x49, 0xc9, 0x59, 0x15, 0x8b, 0x3e, 0x85, 0x25, 0x5e, 0xa4, 0x38, 0x57, 0x34, 0xcb, 0x8d, 0xb0, 0xf3, 0xc1, 0x22, 0x2f, 0xd2, 0x91, 0xb6, 0x5b, 0xbf, 0x3b, 0xb0, 0xd2, 0x3b, 0xa1, 0x92, 0xc4, 0x8c, 0xc7, 0x96, 0x7c, 0x13, 0xd6, 0x88, 0x71, 0x51, 0x9c, 0x90, 0x5c, 0x61, 0x5e, 0x0a, 0x52, 0xf2, 0xef, 0xce, 0x05, 0xab, 0xf6, 0xd4, 0x27, 0xb9, 0xda, 0xd3, 0x03, 0x95, 0xa3, 0x1f, 0xe0, 0x93, 0x4b, 0x90, 0x8c, 0xca, 0x90, 0x72, 0x65, 0x81, 0x35, 0x0b, 0x7c, 0x5c, 0x01, 0x0e, 0xcb, 0x08, 0x03, 0xef, 0x2f, 0xc2, 0x42, 0x68, 0x72, 0xb7, 0xfe, 0x72, 0x60, 0xfd, 0x96, 0x9e, 0xa2, 0x0e, 0x3c, 0xb2, 0x3d, 0xc5, 0x99, 0x14, 0x63, 0x32, 0x66, 0x89, 0x7e, 0x25, 0x65, 0xf9, 0xc8, 0x1e, 0x0d, 0x67, 0x27, 0x68, 0x00, 0xeb, 0x95, 0x40, 0x2c, 0x26, 0x38, 0x3f, 0x66, 0x59, 0xa6, 0x85, 0xab, 0x0e, 0x5c, 0x2d, 0x78, 0x52, 0x09, 0xdb, 0x9f, 0x8c, 0x6c, 0x90, 0xbd, 0xc3, 0xf5, 0xce, 0x3d, 0xb8, 0xa1, 0x73, 0x7f, 0x2c, 0x42, 0xdd, 0x2f, 0x27, 0xc7, 0x5e, 0x77, 0x1d, 0x5c, 0xad, 0x7f, 0x98, 0x90, 0x3c, 0xb7, 0x2a, 0xd6, 0x03, 0xe0, 0x45, 0xba, 0x55, 0x7a, 0xd0, 0x0b, 0xf8, 0x78, 0x42, 0x89, 0x2a, 0x24, 0xc5, 0x13, 0x49, 0x42, 0xbd, 0x2b, 0xb4, 0x80, 0x46, 0xbc, 0xa9, 0x76, 0x1f, 0xd9, 0x90, 0x1d, 0x1b, 0x31, 0xa4, 0x52, 0x6b, 0xa7, 0x95, 0xbf, 0x11, 0x9c, 0xd0, 0x13, 0x9a, 0x94, 0x37, 0xd4, 0xca, 0x5f, 0x47, 0xfb, 0x3a, 0x00, 0x8d, 0xa1, 0x21, 0x2f, 0x6d, 0x29, 0xef, 0x7f, 0xe6, 0x5d, 0x7c, 0x7f, 0xfb, 0xbb, 0xf8, 0xd0, 0x86, 0x0b, 0xae, 0x30, 0xa2, 0x43, 0x70, 0xc3, 0xd9, 0x92, 0xf2, 0xe6, 0x4d, 0x82, 0x6f, 0xef, 0x96, 0xe0, 0xda, 0x76, 0x0b, 0xaa, 0x5c, 0xe8, 0x57, 0x58, 0xce, 0x64, 0x61, 0x3a, 0x92, 0x8a, 0x88, 0x7a, 0x8b, 0x1b, 0xce, 0xd3, 0x46, 0xf7, 0xc5, 0x1d, 0x1f, 0xf5, 0x45, 0x8b, 0xda, 0xc3, 0x92, 0xe3, 0x8d, 0x88, 0x68, 0xe0, 0x66, 0x33, 0x43, 0xf3, 0xc7, 0x52, 0x9c, 0x4e, 0xf9, 0x97, 0xfe, 0x1b, 0xff, 0xab, 0x92, 0xa3, 0xe4, 0x8f, 0x67, 0x06, 0x8a, 0xe0, 0xd1, 0xa5, 0x91, 0xc2, 0x66, 0x7d, 0x78, 0x0b, 0x46, 0xa2, 0xe7, 0xf7, 0xdb, 0x4d, 0x56, 0x9f, 0xd5, 0xea, 0x38, 0x1e, 0x68, 0x3a, 0xa4, 0x60, 0x2d, 0x2d, 0x12, 0xc5, 0xca, 0x19, 0xc4, 0x5a, 0x3d, 0x45, 0xe3, 0x73, 0x0f, 0x4c, 0x35, 0xfd, 0xfb, 0x56, 0xf3, 0x46, 0x73, 0x99, 0xe1, 0x1d, 0x59, 0xa6, 0x00, 0xa5, 0xd7, 0x7c, 0xe8, 0x67, 0x68, 0x92, 0x8b, 0xcd, 0x82, 0xcb, 0xe7, 0xed, 0xb9, 0xa6, 0xb0, 0xcd, 0xdb, 0x33, 0x5e, 0xd9, 0x49, 0xc1, 0x0a, 0xb9, 0xec, 0x68, 0x7d, 0x0d, 0x6e, 0xa5, 0x6b, 0xa8, 0x0e, 0x4b, 0xc3, 0x60, 0x80, 0x87, 0xc1, 0xbb, 0xbd, 0x41, 0x73, 0x0e, 0x35, 0x00, 0x86, 0xfb, 0xa3, 0x03, 0x6b, 0x3b, 0xad, 0x4d, 0x70, 0x2b, 0x3d, 0xd0, 0xc7, 0xef, 0x77, 0xf7, 0xfd, 0x01, 0x3e, 0x08, 0x06, 0x3a, 0x1c, 0x41, 0xc3, 0xef, 0x1d, 0x0e, 0x02, 0xdc, 0x3f, 0xc4, 0xe6, 0xa3, 0xe9, 0xb4, 0x86, 0x80, 0xae, 0x17, 0xaa, 0x23, 0x35, 0x06, 0x0f, 0x07, 0x01, 0xde, 0xf2, 0x7b, 0xa3, 0x51, 0x73, 0x0e, 0x35, 0x61, 0x79, 0xe7, 0x9d, 0xef, 0xe3, 0xdd, 0xc1, 0x68, 0xf4, 0xba, 0xb7, 0xd7, 0x74, 0xd0, 0x1a, 0x34, 0xb7, 0x5f, 0xf7, 0x5e, 0xed, 0xef, 0xf5, 0x66, 0xde, 0x5a, 0x1f, 0x41, 0xf3, 0xea, 0x53, 0xed, 0xff, 0xf8, 0xd3, 0xdb, 0x98, 0xa9, 0xa3, 0x62, 0xdc, 0x0e, 0x45, 0xda, 0x89, 0x24, 0x3d, 0x3f, 0xee, 0xcc, 0xc4, 0x79, 0x96, 0x53, 0x79, 0xc2, 0x78, 0xfc, 0x2c, 0x16, 0x9d, 0xec, 0x38, 0xee, 0xdc, 0xed, 0x77, 0xe5, 0x6f, 0xc7, 0x19, 0x2f, 0x98, 0xaf, 0x6f, 0xfe, 0x09, 0x00, 0x00, 0xff, 0xff, 0x61, 0x5c, 0xc6, 0xf7, 0xe2, 0x08, 0x00, 0x00, }
def process_color(self, color): self.controller.game.receive_color(color) self.parent.parent.update_stat_frame() self.parent.parent.update_table_frame() self.parent.parent.end_turn()
import { CreatePurchaseDto } from '../../dto/create-purchase.dto'; export class PurchaseCommand { constructor(public readonly createPurchaseDTO: CreatePurchaseDto) {} }
import pickle import pandas as pd from instances.config import MODEL_PATH class PredictionTools(): def __init__(self): self.categorization_model = pickle.load(open(MODEL_PATH, 'rb')) def categorize_product(self, product): predicted_category = self.categorization_model.predict(pd.Series(product)) return predicted_category[0]
import * as mongoose from 'mongoose'; const Schema = mongoose.Schema; export const LocalizationSchema = new Schema({ _id: Schema.Types.ObjectId, city: String, type: { type: String, enum: ['Point'], required: true }, geometry: { coordinates: {type: [Number], index: '2dsphere'} }, user: {type: Schema.Types.ObjectId, ref: 'User'}, createdAt: { type: Date, default: Date.now }, updatedAt: {type: Date, default: Date.now} });
<gh_stars>1-10 import { BaseSeeder, Seeder } from '../../../../src'; import { SecondSeederCircularMock } from './SecondSeederCircularMock'; @Seeder({ runsBefore: [SecondSeederCircularMock] }) export class FirstSeederCircularMock implements BaseSeeder { public seed(): void { // pass } }
IN-VITRO ANTIOXIDANT, LIPID PEROXIDATION INHIBITION AND LIPID PROFILE MODULATORY ACTIVITIES OF HB CLEANSER®BITTERS IN WISTAR RATS Background: HB cleanser® bitters is a polyherbal formulation with six medicinal plants as phytoconstituents which is being sold to the public for the treatment of various diseases. Hence, it becomes pertinent to evaluate the likelihood of health issues that may be associated with its consumption to provide information to the public on the biological activity and safety. Objectives: This study was conducted to investigate the in vitro antioxidant, lipid peroxidation inhibition and lipid profile effects of HB cleanser® bitters in Wistar rats. Methods: In vitro antioxidant activity was carried using 2,2-diphenyl-1-picryl-hydrazyl (DPPH) assay, nitric oxide scavenging activity, ferric reducing antioxidant power assay. Inhibitory activity on lipid peroxidation was also measured. Phytochemical evaluation was done. Twenty-eight male rats were allotted into four groups of seven animals each. Group A received 5 ml/kg normal saline while groups B, C and D were administered with 1 ml/kg, 1.03 ml/kg and 1.29 ml/kg of the bitters based on the manufacturer’s recommendation through the oral route for 28days consecutively. Lipid parameters assayed were total cholesterol, total triglyceride, high density lipoprotein-cholesterol (HDL-C), and low-density lipoprotein-cholesterol (LDL-C). Results: Phytochemical screening indicated the presence of flavonoids and saponins. The antioxidant activity of HB cleanser® bitters was dose dependent as it significantly (p<0.05) increased with increase in concentration when compared with ascorbic acid. HB bitters®at 1000 µg/ml significantly (p<0.05)   inhibited lipid peroxidation (78.21±0.53 %) compared to ascorbic acid (94.43±0.53 %) in-vitro. The bitters at 1.29 ml/kg exhibited a non-statistically significant (P>0.05) decrease of total cholesterol and total triglyceride (2.32±0.15 mmol/L, 0.92±0.13 mmol /L) with a marked increase in low density lipoprotein-cholesterol (1.32±0.20 mmol/L) compared to control. Conclusion: The findings of this study have revealed that HB cleanser®bitters possesses good antioxidant activity and may increase low- density lipoprotein-cholesterol, therefore it should be used with caution.                     Peer Review History: Received: 2 September 2022; Revised: 11 October; Accepted: 7 November, Available online: 15 November 2022 Academic Editor: Dr. Gehan Fawzy Abdel Raoof Kandeel, Pharmacognosy Department, National Research Centre, Dokki, 12622,  Giza, Egypt, [email protected]  Received file:                             Reviewer's Comments: Average Peer review marks at initial stage: 5.5/10 Average Peer review marks at publication stage: 7.0/10 Reviewers: Dr. Rima Benatoui,Laboratory of Applied Neuroendocrinology, Department of Biology, Faculty of Science, Badji Mokhtar University Annaba, Algeria.  [email protected] Dr. DANIYAN Oluwatoyin Michael, Obafemi Awolowo University, ILE-IFE, Nigeria, [email protected] Similar Articles:   NUTRITIONAL COMPOSITION, CONSTITUENTS, AND ANTIOXIDANT ACTIVITY OF POWDER FRACTIONS OF FICUS DICRANOSTYLA MILDBREAD LEAVES STORAGE EFFECT ON THE GC-MS PROFILING AND ANTIOXIDANT ACTIVITIES OF ESSENTIAL OILS FROM LEAVES OF ANNONA SQUAMOSA L. ANTIHYPERGLYCEMIC AND ANTI-OXIDANT POTENTIAL OF ETHANOL EXTRACT OF VITEX THYRSIFLORA LEAVES ON DIABETIC RATS
<gh_stars>1-10 use cdbc::io::Encode; #[derive(Debug)] pub struct Sync; impl Encode<'_> for Sync { fn encode_with(&self, buf: &mut Vec<u8>, _: ()) { buf.push(b'S'); buf.extend(&4_i32.to_be_bytes()); } }
Steamforged Games launched its Resident Evil 2: The Board Game Kickstarter on September 26, 2017. Within one hour, the project was funded and had even manged to crash Kickstarter. Thankfully, the crowdfunding platform is fully functional again and the project page is still live. Founded in 2014, Steamforged Games is a UK based tabletop games company, focused on modern tabletop gaming. Steamforged has previously released board games based on Dark Souls and Dark Souls II. Resident Evil 2: The Board Game is a co-op survival horror game for 1-4 players. Set during the events of Resident Evil 2, players will need to explore and survive Raccoon City in order to escape. The game itself is a combination of resource management and Steamforged’s ‘Tension Deck’ mechanic. Players will need to find clues, equipment and weapons to stay alive. The Tension Deck forces players to consider every move they make and what the best course of action may be. As a co-op game, everyone must survive in order to win. If a single player dies, it’s game over. Each character has special rules and abilities which will need to be used to succeed. Steamforged broadcast a live playthrough of the demo version of the game to give players an idea of what to expect. The Kickstarter is a simple one, with only one pledge level of £70 (roughly $120 AUD) which grants access to the board game, B-Files Expansion, Kickstarter exclusive Leon costume and all future stretch goals. At the time of writing, the following stretch goals have been unlocked; Four Male Zombies; Flamethrower; Zombie Dog; Custom Handgun; Two RPD Zombies; Custom Magnum; Licker; Sherry Birkin, Two Flaming RPD Zombies; and A second Zombie Dog The next stretch goal to be unlocked it Plant 43, which will be available with £340,000 pledged. The current total stands at £330,117 with 4, 473 backers and 26 days remaining. There are also optional purchases available to backers simply by upping your pledge and selecting the rewards at the conclusion of the Kickstarter. Add-ons include; Malformations of G; Retro Pack Extra Survivor Pledge The Resident Evil 2: The Board Game Kickstarter ends on October 26, 2017. It has been funded so will be successful. Now’s your chance to get in on the ground floor.
<gh_stars>0 #include "Memory.h" /* Constructor e*/ Memory::Memory(int size) : size(size) { memory = new int[size]; programSize = 0; for(int i = 0; i < size; i++) { memory[i] = 0; } } /* Destructor */ Memory::~Memory() { delete memory; } /* Loads a program into memory */ void Memory::loadProgram (std::istream &in) { for (int i = 0; !in.eof(); i++, programSize++) { memory[i] = (in.get() << 24) | (in.get() << 16) | (in.get() << 8) | (in.get()); } programSize--; // Remove EOF token in memory } /* [] Index operator */ int Memory::operator [] (int i) const { return memory[i]; } /* [] Assignemnt operator */ int & Memory::operator [] (int i) { return memory[i]; }
def linked_downstream_reports_by_domain(master_domain, report_id): from corehq.apps.linked_domain.dbaccessors import get_linked_domains linked_domains = {} for domain_link in get_linked_domains(master_domain): linked_domains[domain_link.linked_domain] = any( r for r in get_linked_report_configs(domain_link.linked_domain, report_id) ) return linked_domains
Vic Beasley Clemson, RLB/SLB Height: 6.3 Weight: 235 Age: 23 Check out all of The War Room content Athleticism: A Excellent athlete who has the potential to play with his hand in the ground, as a standup rusher, and as a strong side linebacker. Great first step off the line at the snap and accelerates into his rush immediately. Exceptionally agile for a pass rusher, as he has the body of an oversized safety. Showed the ability to drop back into coverage and has the tools to convert to linebacker full-time. Pass Rush: B+ Is a speed rusher by trade, but is not necessarily a one-trick pony, though he is somewhat limited by his size and strength. Consistently bends the edge and gets pressure on the quarterback from behind. Is capable of slipping through the B or C gap on stunts and delayed blitzes. Uses his hands well to shed laterally and uses a deadly spin move. Lacks much of a bull rush, rarely pushing the pocket. Might struggle to get pressure against more athletic tackles and to track down more athletic quarterbacks. Run Defense: D+ Simply lacks the bulk and strength to hold up versus the run as an edge rusher in the NFL, whether as a defensive end or a rush linebacker. Explosive when shooting gaps, but lacks the anchor to dig in his heels or to knock back opposing linemen. Needs to protect his legs better. Gave up the winning play against Florida State in 2014 by leaving outside contain. Technique: B+ Excellent use of hands to shed blocks and is very active with the mitts. Plays with good pad level for the most part and generally only loses leverage when he starts to tire. Tackling needs work as he too often will let running backs and quarterbacks slip through his arms. Intangibles: B Plays with very good effort for the most part, but will have stretches where he looks like he is tired or just conserving energy. Motor is hottest when asked to pin his ears back and get upfield. Gives strong effort in pursuit, but can be selective at times. Has good instincts off the snap and generally is assignment sound getting contain, setting the edge, and using moves. Red Flags: Size, Tweener Bottom Line: Vic Beasley might have been considered a first round lock last season, but more tape his senior season has confirmed he is a bit of a one-sided player who still needs to undergo a positon switch to make an impact in the NFL. Beasley could either play as an edge rusher in 3-4 defense, or as a Sam in a 4-3 defense, but either way his success is not assured at either positon. Beasley could easily become the next Robert Mathis or the next Larry English, but he will most likely be a very good pass rush specialist. Comparison: Bruce Irvin Grade: 9.0 (1st Round) Thank you for reading. Follow me on Twitter – @LWOS_Sibo. Support LWOS by following us on Twitter – @LastWordOnSport and @LWOSworld – and “liking” our Facebook page. Have you tuned into Last Word On Sports Radio? LWOS is pleased to bring you 24/7 sports radio to your PC, laptop, tablet or smartphone. What are you waiting for?
<reponame>U007D/k210_pac #[doc = "Reader of register status"] pub type R = crate::R<u32, super::STATUS>; #[doc = "Reader of field `activity`"] pub type ACTIVITY_R = crate::R<bool, bool>; #[doc = "Reader of field `tfnf`"] pub type TFNF_R = crate::R<bool, bool>; #[doc = "Reader of field `tfe`"] pub type TFE_R = crate::R<bool, bool>; #[doc = "Reader of field `rfne`"] pub type RFNE_R = crate::R<bool, bool>; #[doc = "Reader of field `rff`"] pub type RFF_R = crate::R<bool, bool>; #[doc = "Reader of field `mst_activity`"] pub type MST_ACTIVITY_R = crate::R<bool, bool>; #[doc = "Reader of field `slv_activity`"] pub type SLV_ACTIVITY_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - ACTIVITY"] #[inline(always)] pub fn activity(&self) -> ACTIVITY_R { ACTIVITY_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - TFNF"] #[inline(always)] pub fn tfnf(&self) -> TFNF_R { TFNF_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - TFE"] #[inline(always)] pub fn tfe(&self) -> TFE_R { TFE_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - RFNE"] #[inline(always)] pub fn rfne(&self) -> RFNE_R { RFNE_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - RFF"] #[inline(always)] pub fn rff(&self) -> RFF_R { RFF_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - MST_ACTIVITY"] #[inline(always)] pub fn mst_activity(&self) -> MST_ACTIVITY_R { MST_ACTIVITY_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - SLV_ACTIVITY"] #[inline(always)] pub fn slv_activity(&self) -> SLV_ACTIVITY_R { SLV_ACTIVITY_R::new(((self.bits >> 6) & 0x01) != 0) } }
<filename>cmd/smallpoint/api.go<gh_stars>1-10 package main import ( "encoding/json" "fmt" "github.com/Symantec/ldap-group-management/lib/userinfo" "log" "net/http" "sort" "strings" ) //All handlers and API endpoints starts from here. var permissionMapping = map[string]int{ "create": permCreate, "update": permUpdate, "delete": permDelete, } var resourceMapping = map[string]int{ "group": resourceGroup, "service_account": resourceSVC, } func (state *RuntimeState) getPreferredAcceptType(r *http.Request) string { preferredAcceptType := "application/json" acceptHeader, ok := r.Header["Accept"] if ok { for _, acceptValue := range acceptHeader { if strings.Contains(acceptValue, "text/html") { preferredAcceptType = "text/html" } } } return preferredAcceptType } func (state *RuntimeState) renderTemplateOrReturnJson(w http.ResponseWriter, r *http.Request, templateName string, pageData interface{}) error { preferredAcceptType := state.getPreferredAcceptType(r) switch preferredAcceptType { case "text/html": setSecurityHeaders(w) cacheControlValue := "private, max-age=60" if templateName != "simpleMessagePage" { cacheControlValue = "private, max-age=5" } w.Header().Set("Cache-Control", cacheControlValue) err := state.htmlTemplate.ExecuteTemplate(w, templateName, pageData) if err != nil { log.Printf("Failed to execute %v", err) http.Error(w, "error", http.StatusInternalServerError) return err } default: b, err := json.Marshal(pageData) if err != nil { log.Printf("Failed marshal %v", err) http.Error(w, "error", http.StatusInternalServerError) return err } _, err = w.Write(b) if err != nil { log.Printf("Incomplete write %v", err) return err } } return nil } // Create a group handler --required func (state *RuntimeState) createGrouphandler(w http.ResponseWriter, r *http.Request) { if r.Method != postMethod { state.writeFailureResponse(w, r, "POST Method is required", http.StatusMethodNotAllowed) return } username, err := state.GetRemoteUserName(w, r) if err != nil { return } err = r.ParseForm() if err != nil { log.Println(err) if err.Error() == "missing form body" { http.Error(w, fmt.Sprint(err), http.StatusBadRequest) } else { state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) } return } var groupinfo userinfo.GroupInfo groupinfo.Groupname = r.PostFormValue("groupname") groupinfo.Description = r.PostFormValue("description") members := r.PostFormValue("members") //check whether the user has the ability to create group allow, err := state.canPerformAction(username, groupinfo.Groupname, resourceGroup, permCreate) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } if !allow { state.writeFailureResponse(w, r, fmt.Sprintf("You don't have permission to create group %s", groupinfo.Groupname), http.StatusForbidden) return } //check if the group name already exists or not. groupExistsorNot, _, err := state.Userinfo.GroupnameExistsornot(groupinfo.Groupname) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } if groupExistsorNot { http.Error(w, fmt.Sprint("Groupname already exists! Choose a different one!"), http.StatusInternalServerError) return } //if the group managed attribute (description) isn't self-managed and thus another groupname. check if that group exists or not if groupinfo.Description != descriptionAttribute { descriptiongroupExistsorNot, _, err := state.Userinfo.GroupnameExistsornot(groupinfo.Description) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } if !descriptiongroupExistsorNot { http.Error(w, fmt.Sprintf("Managed by group doesn't exists! managerGroup='%s'", groupinfo.Description), http.StatusInternalServerError) return } } //check if all the users to be added exists or not. for _, member := range strings.Split(members, ",") { if len(member) < 1 { continue } userExistsorNot, err := state.Userinfo.UsernameExistsornot(member) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } if !userExistsorNot { http.Error(w, fmt.Sprintf("User %s doesn't exist!", member), http.StatusInternalServerError) return } groupinfo.MemberUid = append(groupinfo.MemberUid, member) } err = state.Userinfo.CreateGroup(groupinfo) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("error occurred! May be group name exists or may be members are not available!"), http.StatusInternalServerError) return } if state.sysLog != nil { state.sysLog.Write([]byte(fmt.Sprintf("Group "+"%s"+" was created by "+"%s", groupinfo.Groupname, username))) for _, member := range strings.Split(members, ",") { state.sysLog.Write([]byte(fmt.Sprintf("%s"+" was added to Group "+"%s"+" by "+"%s", member, groupinfo.Groupname, username))) } } isAdmin := state.Userinfo.UserisadminOrNot(username) pageData := simpleMessagePageData{ UserName: username, IsAdmin: isAdmin, Title: "Group Creation Success", SuccessMessage: "Group has been successfully Created", } state.renderTemplateOrReturnJson(w, r, "simpleMessagePage", pageData) } //Delete groups handler --required func (state *RuntimeState) deleteGrouphandler(w http.ResponseWriter, r *http.Request) { if r.Method != postMethod { state.writeFailureResponse(w, r, "POST Method is required", http.StatusMethodNotAllowed) return } username, err := state.GetRemoteUserName(w, r) if err != nil { return } err = r.ParseForm() if err != nil { log.Println(err) if err.Error() == "missing form body" { http.Error(w, fmt.Sprint(err), http.StatusBadRequest) } else { state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) } return } var groupnames []string groups := r.PostFormValue("groupnames") //check if groupnames are valid or not. for _, eachGroup := range strings.Split(groups, ",") { allow, err := state.canPerformAction(username, eachGroup, resourceGroup, permDelete) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } if !allow { state.writeFailureResponse(w, r, fmt.Sprintf("You don't have permission to delete group %s", eachGroup), http.StatusForbidden) return } groupnameExistsorNot, _, err := state.Userinfo.GroupnameExistsornot(eachGroup) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } if !groupnameExistsorNot { state.writeFailureResponse(w, r, fmt.Sprintf("Group %s doesn't exist!", eachGroup), http.StatusBadRequest) return } for _, groupname := range state.Config.Base.AutoGroups { if eachGroup == groupname { state.writeFailureResponse(w, r, groupname+" is part of auto-added group, you cannot delete it!", http.StatusBadRequest) return } } groupnames = append(groupnames, eachGroup) } err = state.Userinfo.DeleteGroup(groupnames) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("error occurred! May be there is no such group!"), http.StatusInternalServerError) return } if state.sysLog != nil { for _, eachGroup := range groupnames { state.sysLog.Write([]byte(fmt.Sprintf("Group "+"%s"+" was deleted by "+"%s", eachGroup, username))) } } err = deleteEntryofGroupsInDB(groupnames, state) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } isAdmin := state.Userinfo.UserisadminOrNot(username) pageData := simpleMessagePageData{ UserName: username, IsAdmin: isAdmin, Title: "Group Deletion Suucess", SuccessMessage: "Group has been successfully Deleted", } state.renderTemplateOrReturnJson(w, r, "simpleMessagePage", pageData) } func (state *RuntimeState) createServiceAccounthandler(w http.ResponseWriter, r *http.Request) { if r.Method != postMethod { state.writeFailureResponse(w, r, "POST Method is required", http.StatusMethodNotAllowed) return } username, err := state.GetRemoteUserName(w, r) if err != nil { return } err = r.ParseForm() if err != nil { log.Println(err) if err.Error() == "missing form body" { http.Error(w, fmt.Sprint(err), http.StatusBadRequest) } else { state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) } return } var groupinfo userinfo.GroupInfo groupinfo.Groupname = r.PostFormValue("AccountName") groupinfo.Mail = r.PostFormValue("mail") groupinfo.LoginShell = r.PostFormValue("loginShell") allow, err := state.canPerformAction(username, groupinfo.Groupname, resourceSVC, permCreate) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } if !allow { state.writeFailureResponse(w, r, fmt.Sprintf("You don't have permission to create service account %s", groupinfo.Groupname), http.StatusForbidden) return } if !(groupinfo.LoginShell == "/bin/false") && !(groupinfo.LoginShell == "/bin/bash") { log.Println("Bad request! Not an valid LoginShell value") http.Error(w, fmt.Sprint("Bad request! Not an valid LoginShell value"), http.StatusBadRequest) return } GroupExistsornot, _, err := state.Userinfo.GroupnameExistsornot(groupinfo.Groupname) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } if GroupExistsornot { log.Println("Bad request! A group already exists with that name!") http.Error(w, fmt.Sprint("Bad request! A group already exists with that name!"), http.StatusBadRequest) return } serviceAccountExists, _, err := state.Userinfo.ServiceAccountExistsornot(groupinfo.Groupname) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } if serviceAccountExists { log.Println("Service Account already exists!") http.Error(w, fmt.Sprint("Service Account already exists!"), http.StatusBadRequest) return } err = state.Userinfo.CreateServiceAccount(groupinfo) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("error occurred! May be group name exists or may be members are not available!"), http.StatusInternalServerError) return } if state.sysLog != nil { state.sysLog.Write([]byte(fmt.Sprintf("Service account "+"%s"+" was created by "+"%s", groupinfo.Groupname, username))) } isAdmin := state.Userinfo.UserisadminOrNot(username) pageData := simpleMessagePageData{ UserName: username, IsAdmin: isAdmin, Title: "Service Account Creation Success", SuccessMessage: "Service Account successfully created", } state.renderTemplateOrReturnJson(w, r, "simpleMessagePage", pageData) } func (state *RuntimeState) changeownership(w http.ResponseWriter, r *http.Request) { if r.Method != postMethod { state.writeFailureResponse(w, r, "POST Method is required", http.StatusMethodNotAllowed) return } username, err := state.GetRemoteUserName(w, r) if err != nil { return } err = r.ParseForm() if err != nil { log.Println(err) if err.Error() == "missing form body" { http.Error(w, fmt.Sprint(err), http.StatusBadRequest) } else { state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) } return } groupList := strings.Split(r.PostFormValue("groupnames"), ",") managegroup := r.PostFormValue("managegroup") if len(groupList) < 1 { state.writeFailureResponse(w, r, "groupnamesParameter is missing", http.StatusBadRequest) return } donecount := 0 //check if given member exists or not and see if he is already a groupmember if yes continue. for _, group := range groupList { // Our UI likes to put commas as the end of the group, so we get usually "foo,bar,"... resulting in a list // with an empty value. if len(group) < 1 { continue } groupinfo := userinfo.GroupInfo{} groupinfo.Groupname = group allow, err := state.canPerformAction(username, group, resourceGroup, permUpdate) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } if !allow { state.writeFailureResponse(w, r, fmt.Sprintf("You don't have permission to update manager group for group %s", group), http.StatusForbidden) return } err = state.groupExistsorNot(w, groupinfo.Groupname) if err != nil { return } err = state.Userinfo.ChangeDescription(group, managegroup) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } if state.sysLog != nil { state.sysLog.Write([]byte(fmt.Sprintf("Group %s is managed by %s now, this change was made by %s.", group, managegroup, username))) } donecount += 1 } if donecount == 0 { state.writeFailureResponse(w, r, "Invalid groupnames parameter", http.StatusBadRequest) return } isAdmin := state.Userinfo.UserisadminOrNot(username) pageData := simpleMessagePageData{ UserName: username, IsAdmin: isAdmin, Title: "Change Ownership success", SuccessMessage: "Group(s) have successfuly changed ownership", } state.renderTemplateOrReturnJson(w, r, "simpleMessagePage", pageData) } // TODO: figure out how to do this with templates or even better migrate to AJAX to get data const getGroupsJSRequestAccessText = ` document.addEventListener('DOMContentLoaded', function () { var groupnames = %s; var final_groupnames=array(groupnames); RequestAccess(final_groupnames); datalist(groupnames[0]); }); ` const getGroupsJSPendingActionsText = ` document.addEventListener('DOMContentLoaded', function () { var ajaxRequest = new XMLHttpRequest(); ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ if(ajaxRequest.status == 200){ var jsonObj = JSON.parse(ajaxRequest.responseText); var groups = jsonObj.Groups; console.log("groups :" + groups); //list_members(users); var pending_actions=arrayPendingActions(groups); pendingActionsTable(pending_actions); } else { console.log("Status error: " + ajaxRequest.status); } } } ajaxRequest.open('GET', '/getGroups.js?type=pendingActions&encoding=json'); ajaxRequest.send(); pendingActions = %s; }); ` type groupsJSONData struct { Groups [][]string } func (state *RuntimeState) getGroupsJSHandler(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { state.writeFailureResponse(w, r, "GET Method is required", http.StatusMethodNotAllowed) return } username, err := state.GetRemoteUserName(w, r) if err != nil { return } outputText := getGroupsJSRequestAccessText var groupsToSend [][]string switch r.FormValue("type") { case "all": groupsToSend, err = state.Userinfo.GetAllGroupsManagedBy() if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } case "pendingRequests": groupsToSend, err = state.getPendingRequestGroupsofUser(username) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } case "allNoManager": allgroups, err := state.Userinfo.GetallGroups() if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } sort.Strings(allgroups) groupsToSend = [][]string{allgroups} case "pendingActions": outputText = getGroupsJSPendingActionsText if r.FormValue("encoding") == "json" { groupsToSend, err = state.getUserPendingActions(username) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } } case "managedByMe": allGroups, err := state.Userinfo.GetAllGroupsManagedBy() if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } userGroups, err := state.Userinfo.GetgroupsofUser(username) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } userGroupMap := make(map[string]interface{}) for _, groupName := range userGroups { userGroupMap[groupName] = nil } for _, groupTuple := range allGroups { managingGroup := groupTuple[1] _, ok := userGroupMap[managingGroup] if ok { groupsToSend = append(groupsToSend, groupTuple) } } default: groupsToSend, err = state.Userinfo.GetGroupsInfoOfUser(state.Config.TargetLDAP.GroupSearchBaseDNs, username) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } } switch r.FormValue("encoding") { case "json": w.Header().Set("Cache-Control", "private, max-age=15") w.Header().Set("Content-Type", "application/json") groupsJSON := groupsJSONData{Groups: groupsToSend} err = json.NewEncoder(w).Encode(groupsJSON) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } default: encodedGroups, err := json.Marshal(groupsToSend) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } w.Header().Set("Cache-Control", "private, max-age=15") w.Header().Set("Content-Type", "application/javascript") fmt.Fprintf(w, outputText, encodedGroups) return } return } const getUsersJSText = ` document.addEventListener('DOMContentLoaded', function () { var ajaxRequest = new XMLHttpRequest(); ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ if(ajaxRequest.status == 200){ var jsonObj = JSON.parse(ajaxRequest.responseText); var users = jsonObj.Users; //console.log("users :" + users); list_members(users); } else { console.log("Status error: " + ajaxRequest.status); } } } ajaxRequest.open('GET', '/getUsers.js?type=all&encoding=json'); ajaxRequest.send(); //var Allusers = %s; //list_members(Allusers); }); ` const getUsersGroupJSText = ` document.addEventListener('DOMContentLoaded', function () { var groupUsers = %s; var usernames=arrayUsers(groupUsers); Group_Info(usernames); }); ` type usersJSONData struct { Users []string } func (state *RuntimeState) getUsersJSHandler(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { state.writeFailureResponse(w, r, "GET Method is required", http.StatusMethodNotAllowed) return } _, err := state.GetRemoteUserName(w, r) if err != nil { log.Println(err) return } outputText := getUsersJSText var usersToSend []string switch r.FormValue("type") { case "group": groupName := r.FormValue("groupName") if groupName == "" { log.Printf("No groupName found") http.Error(w, fmt.Sprint(err), http.StatusBadRequest) return } usersToSend, _, err = state.Userinfo.GetusersofaGroup(groupName) if err != nil { log.Println(err) if err == userinfo.GroupDoesNotExist { http.Error(w, fmt.Sprint("Group doesn't exist!"), http.StatusBadRequest) return } state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } outputText = getUsersGroupJSText default: if r.FormValue("encoding") == "json" { usersToSend, err = state.Userinfo.GetallUsers() if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } } else { go state.Userinfo.GetallUsers() } } sort.Strings(usersToSend) switch r.FormValue("encoding") { case "json": w.Header().Set("Cache-Control", "private, max-age=15") w.Header().Set("Content-Type", "application/json") usersJSON := usersJSONData{Users: usersToSend} err = json.NewEncoder(w).Encode(usersJSON) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } default: encodedUsers, err := json.Marshal(usersToSend) if err != nil { log.Println(err) state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) return } w.Header().Set("Cache-Control", "private, max-age=15") w.Header().Set("Content-Type", "application/javascript") fmt.Fprintf(w, outputText, encodedUsers) return } return } func (state *RuntimeState) permissionManageHandler(w http.ResponseWriter, r *http.Request) { if r.Method != postMethod { state.writeFailureResponse(w, r, "POST Method is required", http.StatusMethodNotAllowed) return } username, err := state.GetRemoteUserName(w, r) if err != nil { log.Println(err) return } if !state.Userinfo.UserisadminOrNot(username) { http.Error(w, "you are not authorized", http.StatusForbidden) return } err = r.ParseForm() if err != nil { log.Println(err) if err.Error() == "missing form body" { http.Error(w, fmt.Sprint(err), http.StatusBadRequest) } else { state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) } return } groupname := r.PostFormValue("groupname") resourceType := r.PostFormValue("resourceType") resourceName := r.PostFormValue("resourceName") log.Println(r.PostFormValue("permissions")) permissionList := strings.Split(r.PostFormValue("permissions"), ",") if len(permissionList) < 1 { state.writeFailureResponse(w, r, "permissionsParameter is missing", http.StatusBadRequest) return } err = state.groupExistsorNot(w, groupname) if err != nil { log.Println(err) return } var resourceVal int var ok bool if resourceVal, ok = resourceMapping[resourceType]; !ok { state.writeFailureResponse(w, r, fmt.Sprintf("%s resource type does not exist", resourceType), http.StatusBadRequest) return } var permissions, permVal int for _, permission := range permissionList { if permVal, ok = permissionMapping[permission]; !ok { state.writeFailureResponse(w, r, fmt.Sprintf("%s permission does not exist", permission), http.StatusBadRequest) return } permissions += permVal } err = insertPermissionEntry(groupname, resourceName, resourceVal, permissions, state) if err != nil { state.writeFailureResponse(w, r, fmt.Sprintf("Something wrong with internal server."), http.StatusInternalServerError) log.Println(err) return } if state.sysLog != nil { state.sysLog.Write([]byte(fmt.Sprintf("Permission %d to group %s was created by "+"%s", permissions, groupname, username))) } pageData := simpleMessagePageData{ UserName: username, IsAdmin: true, Title: "Permission Creation Success", SuccessMessage: "permissions successfully created", } state.renderTemplateOrReturnJson(w, r, "simpleMessagePage", pageData) }
<reponame>rgupta3349/FHIR /* * (C) Copyright IBM Corp. 2020 * * SPDX-License-Identifier: Apache-2.0 */ package com.ibm.fhir.bulkimport; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.batch.api.partition.PartitionAnalyzer; import javax.batch.runtime.BatchStatus; import javax.batch.runtime.context.JobContext; import javax.inject.Inject; public class ImportPartitionAnalyzer implements PartitionAnalyzer { @Inject JobContext jobContext; private List<ImportCheckPointData> partitionSummaries = new ArrayList<>(); public ImportPartitionAnalyzer() { } @Override public void analyzeStatus(BatchStatus batchStatus, String exitStatus) { } @Override public void analyzeCollectorData(Serializable data) { if (data == null) { return; } partitionSummaries.add((ImportCheckPointData) data); jobContext.setTransientUserData(partitionSummaries); } }
Story highlights FBI Director James Comey says there are more terrorist organizations desiring to attack U.S. than there were at 9/11 Terrorists' ability to have a safe haven increases their ability to mount a sophisticated attack against the U.S., he added Washington (CNN) FBI Director James Comey said Wednesday that the U.S. is at its greatest threat level from terrorist groups since 9/11. Comey shared the information at a Senate FBI oversight hearing after Sen. Lindsey Graham questioned him on his agency's knowledge of terrorism. "Do you agree with the following statement: There are more terrorist organizations with men, equipment and safe havens, along with desire to attack the American homeland, anytime since 9/11 ?" the South Carolina Republican asked. "I agree," Comey said. Comey said budget cuts imposed by Congress in recent years have reduced the FBI's ability to protect America from terrorism. Read More
Police in Boston are searching for a suspect in a shooting that witnesses said occurred due to a parking space saver. Witnesses told necn the incident occurred when a man moved a space saver and parked his car. When the man who originally parked in the spot returned, he opened fire, they said. The victim, a 34-year-old man, is suffering from non-life threatening injuries, according to police. The shooting happened just after 2:30 p.m. at 69 Nightingale St. in the Dorchester section of the city. The police say the suspect is a 27-year-old man from the Dorcester neighborhood. Although they do not have him in custody, the police believe they know who the man is. Saving parking spaces is a highly controversial act that is frowned upon in some cities, like Chicago and Philadelphia, where police started a "no savesies" campaign online before this weekend's major winter storm. While the tradition is long-standing in Boston, last year, groups in Fenway and North End urged Mayor Martin J. Walsh to implement a clear ban on space saving. People are, informally, allowed to claim a space for the first 48 hours after they shovel it out. At the time, Walsh said of the tradition: "If it works, it works."
import { promisify } from "util"; import low from "lowdb"; import FileSync from "lowdb/adapters/FileSync"; import { chain, template } from "lodash"; import { join } from "path"; import differenceInWeeks from "date-fns/difference_in_weeks"; import format from "date-fns/format"; import { writeFile, readFile, createWriteStream } from "fs"; import repng from "repng"; import { Gauge, GaugeProps } from "../components/Gauge"; import { MetricBar, MetricBarProps } from "../components/MetricBar"; import S3 from "aws-sdk/clients/s3"; import uploadStream from "s3-stream-upload"; import { getSiteMetrics } from "../metrics"; /** * The number of weeks that the email covers */ const WEEKS_TO_MEASURE = 4; let outputDir = "dist"; let BUCKET_FOLDER = ""; let BUCKET = "artsy-performance-dashboard"; const read = promisify(readFile); const write = promisify(writeFile); const s3 = new S3(); const adapter = new FileSync(join(process.cwd(), "data", "snapshot-db.json")); const db = low(adapter); db.defaults({ snapshots: [] }).write(); if (!(process.env.PATH || "").includes("./node_modules/.bin")) { process.env.PATH = `${process.env.PATH}:./node_modules/.bin`; } enum METRIC { FCP = "first-contentful-paint", FMP = "first-meaningful-paint", SI = "speed_index" } // Metrics grabbed from https://docs.google.com/spreadsheets/d/1d0n8ZHX_M0neBMIq6SIhMMITYF_mQE8I6jHhzu9hdr0/edit?usp=sharing const METRICS = [ { name: METRIC.FCP, top: 0, mid: 2336, low: 4000, goal: 2000 }, { name: METRIC.FMP, top: 0, mid: 2336, low: 4000, goal: 2500 }, { name: METRIC.SI, top: 0, mid: 3387, low: 5800, goal: 3000 } ]; const getDateRange = (weeks: number = WEEKS_TO_MEASURE) => { const d = (dt: string) => format(dt, "MMM D, YYYY"); const [firstDate, ...otherDates] = db .get("snapshots") .sortBy(s => s.iid) .map(s => s.createdAt) .filter(date => differenceInWeeks(new Date(), date) < weeks) .value(); const lastDate = otherDates.pop(); return { firstDate, lastDate, dateRange: `${d(firstDate)}—${d(lastDate)}` }; }; const renderGauge = async (score: number, delta: string, filename: string) => { const outFile = createWriteStream(join("dist", filename)); const size = 200; await repng<GaugeProps>(Gauge, { cssLibrary: "styled-components", props: { score, size, delta }, width: size, height: size }).then((img: any) => img .pipe( BUCKET ? uploadStream(s3, { Bucket: BUCKET, Key: BUCKET_FOLDER + filename, ACL: "public-read" }) : outFile ) .on("error", (err: Error) => { console.error(`Failed to upload ${filename} to S3.`, err); }) ); }; // @ts-ignore // const debug = o => console.log(o) || o; const debug = i => i; const renderMetricBar = (metric: any, deltaOverride?: string) => { const filename = `${metric.page}-${metric.name}.png`; const outFile = createWriteStream(join("dist", filename)); repng<MetricBarProps>( MetricBar, debug({ cssLibrary: "styled-components", props: { value: metric.average, range: { top: metric.top, mid: metric.mid, low: metric.low }, goal: metric.goal, delta: deltaOverride || metric.delta, width: 600 }, width: 600, height: 60 }) ).then((img: any) => img .pipe( BUCKET ? uploadStream(s3, { Bucket: BUCKET, Key: BUCKET_FOLDER + filename, ACL: "public-read" }) : outFile ) .on("error", (err: Error) => { console.error(`Failed to upload ${filename} to S3.`, err); }) ); return filename; }; // Work closure (async () => { const { dateRange, firstDate, lastDate } = getDateRange(); const f = (date: any) => format(date, "DD-MM-YYYY"); BUCKET_FOLDER = `${f(firstDate)}_${f(lastDate)}/`; const mjmlTemplate = template( await read(join(__dirname, "email-template.mjml"), "utf-8") ); const artistPage = getSiteMetrics("artist/", "mobile"); const artworkPage = getSiteMetrics("artwork/", "mobile"); const articlePage = getSiteMetrics("article/", "mobile"); renderGauge( artistPage["lighthouse-performance-score"].average, artistPage["lighthouse-performance-score"].delta, "artist-gauge.png" ); renderGauge( artworkPage["lighthouse-performance-score"].average, artworkPage["lighthouse-performance-score"].delta, "artwork-gauge.png" ); renderGauge( articlePage["lighthouse-performance-score"].average, articlePage["lighthouse-performance-score"].delta, "article-gauge.png" ); const formatMetrics = ( page: string, pageMetrics: Array<{ name: string }>, deltaOverrides?: { [metric in METRIC]?: string } ) => chain(Object.values(pageMetrics)) .filter(metric => metric.name !== "lighthouse-performance-score") .sortBy(["name"]) .map((metric: any) => ({ ...metric, ...METRICS.find(({ name }) => name === metric.name), page })) .map((metric: any) => ({ ...metric, img: renderMetricBar( metric, deltaOverrides ? deltaOverrides[metric.name as METRIC] : undefined ) })) .value(); const finalTemplate = mjmlTemplate({ url: BUCKET ? `https://s3.amazonaws.com/${BUCKET}/${BUCKET_FOLDER}` : "", logo: `https://s3.amazonaws.com/${BUCKET}/Artsy_Logo_Full_Black_Jpeg_Small.jpg`, legend: `https://s3.amazonaws.com/${BUCKET}/bar-description-2.jpg`, dateRange, intro: ` Welcome to Artsy's web performance report. The purpose of this communication is to provide transparency around the state of performance at Artsy. This report has been extended to coincide with the start of Q1. <br/><br/> All the data in this report is from a mid-tier mobile device on a 3G network. We're using this as a baseline to match Google's current performance recommendations. Performance on 4G networks with upper tier devices and desktop significantly outperform the below results. <br/><br/> The deltas listed in this report (green or red numbers) cover a month long period and aren't expected to align with numbers from the last report. If you have questions about these metrics or about performance in general please join us in the <b>#performance</b> slack channel. `, pageSummary: ` The metrics below are Google's <a href="https://developers.google.com/web/tools/lighthouse/v3/scoring#perf">Lighthouse performance score</a> for each of the associated page types. This score goes from 0 (being the worst) to 100 (being the best). It's an aggregate of multiple weighted metrics that gives a rough indication of the overall performance health of a webpage. `, pages: [ { name: "Artist", img: "artist-gauge.png", metrics: formatMetrics("artist", artistPage), description: ` Artist page has remained relatively stable over the last month. We're still underperforming relative to our goals. The deltas from this report is based on the last month of data, not just the period covered by the last report. ` }, { name: "Artwork", img: "artwork-gauge.png", metrics: formatMetrics("artwork", artworkPage), description: ` We've seen a performance degradation in the last month relating to the release of the responsive (and completely rebuilt) artwork page. Mobile 4G and desktop haven't seen the same level of performance degradations. These numbers may be slightly skewed due to ongoing intermittent elasticsearch issues. We'll continue to investigate and optimize artwork page performance. ` }, { name: "Article", img: "article-gauge.png", metrics: formatMetrics("article", articlePage), description: ` Article page performance remained relatively stable over the last two months. More analysis is required for the increase ` } ] }); write("dist/performance-email.mjml", finalTemplate); })(); // console.log(renderToString(<Gauge score={50} delta="-7%" />));
/*! * \file alphabets.hpp * \brief Exports utilities for creating alphabets as std::arrays from * ranges of ASCII values. **/ #ifndef INCG_ITSP3_ALPHABETS_HPP #define INCG_ITSP3_ALPHABETS_HPP #include <array> // std::array #include <pl/cont/make_array.hpp> // pl::cont::makeArray #include <type_traits> // std::index_sequence, std::make_index_sequence namespace itsp3 { namespace detail { /*! * \brief Implementation function of makeAlphabet. * \note Not to be used directly. **/ template<int From, int To, std::size_t... Indices> constexpr std::array<char, To - From> makeAlphabetImpl( std::index_sequence<Indices...>) { /* If 'From' is 0x41 (The ASCII value for 'A') * and 'To' is 0x43 (The ASCII value for 'C') * then sizeof...(Indices) will be 2. * So there will be 2 std::size_ts in the non-type * template parameter pack, since 0x43 - 0x41 = 2. * Then the statement below will 'expand' to: * { { 0x41 + 0, 0x41 + 1 } } * resulting in: * { { 0x41, 0x42 } } * which creates a * std::array<char, 2>{ 'A', 'B' } * at compile time. */ return {{(From + static_cast<int>(Indices))...}}; } } // namespace detail /*! * \brief Compile time function to create an alphabet. * \return The alphabet created. * \warning Assumes that the underlying C++ implementation implements * the char type using ASCII encoding, which is very likely in *practice, albeit specifically not required by the C++ standard. * * Creates an alphabet as std::array at compile time. * 'From' indicates the ASCII value at which the alphabet shall begin. * 'To' indicates the ASCII value at which the alphabet shall end. * Note that the character with the ASCII value of 'To' will not be included * in the resulting std::array, as the range denoted by ['From' .. 'To') is * half open, much like C++ style iterators. **/ template<int From, int To> constexpr std::array<char, To - From> makeAlphabet() { static_assert(To >= From, "To was less than From!"); // The index_sequence is effectively a compile time (type based) list // of compile time std::size_t objects. // An index_sequence<5> would 'hold' the values 0U, 1U, 2U, 3U, 4U // in its type. // The index_sequence object created (at compile time) is merely used // so that the implementation function can deduce the std::size_ts // as a template non-type parameter pack, which can then be used // in a template parameter pack expansion context. return detail::makeAlphabetImpl<From, To>( std::make_index_sequence<To - From>{}); } namespace { /*! * The ASCII alphabet. * Contains the characters of the range [0x00 .. 0x80), which is equivalent to * [0x00 .. 0x7F]. * See an ASCII chart here: http://en.cppreference.com/w/cpp/language/ascii **/ constexpr std::array<char, 0x80 - 0x00> asciiAlphabet = makeAlphabet<0x00, 0x80>(); } // anonymous namespace } // namespace itsp3 #endif // INCG_ITSP3_ALPHABETS_HPP
Britain's Prince Harry (C) attends Armistice Day commemorations at the National Memorial Arboretum in Alrewas, Britain, November 11, 2016. REUTERS/Darren Staples LONDON (Reuters) - French President Francois Hollande and Britain’s Prince Harry led commemorations as the two nations marked Armistice Day on Friday to remember those killed in war. At 11 a.m, millions across Britain observed two minutes’ silence, marking the time fighting ended on the Western front of World War One on Nov. 11, 1918. Hollande laid a wreath under the Arc de Triomphe during particularly solemn tributes in Paris which came roughly a year after 130 people were killed when gunmen and suicide bombers attacked the city’s Stade de France sports stadium, cafes and the Bataclan concert venue. “November 11 marks the memory of the First World War and of a rising wave of nationalism that could not be contained. We must continue to remember it,” Hollande said. In Britain, offices, schools and city centers fell silent while in Trafalgar Square in central London, traffic came to a halt, with crowds invited to put poppy petals in the square’s famous fountains. Prince Harry, Queen Elizabeth’s grandson who himself served with the British military on two tours of duty in Afghanistan, led commemorations at a service at the Armed Forces Memorial at the National Memorial Arboretum in central England. The Royal British Legion charity, which since 1921 has sold red poppy symbols to raise money for veterans of the armed forces, said this year it wanted people to “rethink Remembrance” to embrace veterans from recent conflicts as well as those who died in the two World Wars. England and Scotland soccer players are planning to wear poppies during their World Cup qualifier on Friday which could see them in breach of FIFA rules which forbid wearing anything that could be perceived as a political statement. Armistice Day is followed by Remembrance Sunday on Nov. 13 when Britain’s royal family and senior politicians pay their respects at the Cenotaph memorial in central London.
<reponame>bato1015/CIT_brains_2021_linetrace<gh_stars>0 #include <stdio.h> #include <pigpio.h> #define MOTOR_R1 13 //GPIO13 PIN33 #define MOTOR_R2 19 //GPIO19 PIN35 #define MOTOR_L1 12 //GPIO12 PIN32 #define MOTOR_L2 18 //GPIO18 PIN12 #define SENSOR_R 9 //GPIO9 PIN21 #define SENSOR_L 11 //GPIO11 PIN23 void move_motor(int pin_num1, int pin_num2, int speed) { //speed : -255~255 gpioSetMode(pin_num1, PI_OUTPUT); gpioSetMode(pin_num2, PI_OUTPUT); gpioPWM(pin_num1, speed); gpioPWM(pin_num2, speed); } int main() { if (gpioInitialise() < 0) printf("pigpio initialisation failed."); else printf("pigpio initialised okay."); sleep(10); while (1) { if (gpioRead(SENSOR_R) && gpioRead(SENSOR_L) == 1) { move_motor(MOTOR_R1, MOTOR_R2, 200); // //speed (ここでいうi)は-255~255の範囲 gpioSleep(PI_TIME_RELATIVE, 0, 1000000 * 1); move_motor(MOTOR_L1, MOTOR_L2, -200); // //speed (ここでいうi)は-255~255の範囲 gpioSleep(PI_TIME_RELATIVE, 0, 1000000 * 1); sleep(2); } if (gpioRead(SENSOR_R) == 0 && gpioRead(SENSOR_L) == 1) { move_motor(MOTOR_R1, MOTOR_R2, 100); // //speed (ここでいうi)は-255~255の範囲 gpioSleep(PI_TIME_RELATIVE, 0, 1000000 * 1); move_motor(MOTOR_L1, MOTOR_L2, -200); // //speed (ここでいうi)は-255~255の範囲 gpioSleep(PI_TIME_RELATIVE, 0, 1000000 * 1); sleep(2); } if (gpioRead(SENSOR_R) == 1 && gpioRead(SENSOR_L) == 0) { move_motor(MOTOR_R1, MOTOR_R2, 200); // //speed (ここでいうi)は-255~255の範囲 gpioSleep(PI_TIME_RELATIVE, 0, 1000000 * 1); move_motor(MOTOR_L1, MOTOR_L2, -100); // //speed (ここでいうi)は-255~255の範囲 gpioSleep(PI_TIME_RELATIVE, 0, 1000000 * 1); sleep(2); } if (gpioRead(SENSOR_R) && gpioRead(SENSOR_L) == 0) { move_motor(MOTOR_R1, MOTOR_R2, 0); // //speed (ここでいうi)は-255~255の範囲 gpioSleep(PI_TIME_RELATIVE, 0, 1000000 * 1); move_motor(MOTOR_L1, MOTOR_L2, 0); // //speed (ここでいうi)は-255~255の範囲 gpioSleep(PI_TIME_RELATIVE, 0, 1000000 * 1); sleep(2); } } return 0; }
#include<stdio.h> int wb[110],n,i,shoot; int main() { scanf("%d",&n); for(i=1; i<=n; i++) scanf("%d",&wb[i]); scanf("%d",&shoot); int th,num; while(shoot--) { scanf("%d%d",&th,&num); if(th-1>=1) wb[th-1]+=num-1; if(th+1<=n) wb[th+1]+=wb[th]-num; wb[th]=0; } for(i=1; i<=n; i++) printf("%d\n",wb[i]); return 0; }
/** * Release the lock for the path after writing. * * Note: the caller should resolve the path to make sure we are locking the correct absolute * path. */ private static void releasePathLock(Path resolvedPath) { final Object lock = pathLock.remove(resolvedPath); synchronized(lock) { lock.notifyAll(); } }
n=int(input()) s=input() freq=[0]*26 for i in s: freq[ord(i)-ord('a')]+=1 change=0 for i in range(26): if freq[i]: change+=freq[i]-1 distinct=0 for i in range(26): if freq[i]: distinct+=1 if distinct+change>26: print(-1) else: print(change)
import { ButtonState } from "../helpers/types"; import { isDomElement } from "../helpers/utils"; import { buttonStyles } from "../styles/styles"; import { loader, logo } from "../styles/templates"; import { orbaOneLoaderId } from "../helpers/defaultConfig"; function getButtonTemplate() { return ` <div style="display:flex; align-items: center;height: 100%;" > <div style="display: flex;width: 20%;flex-direction: column; align-items: center; padding: 0.5rem 1rem 0 1rem;"> ${logo} <p style="font-size:8px; color: #718096; white-space: nowrap;">By Orba One</p> </div> <div id="${orbaOneLoaderId}" style="border-left: 1px solid #edf2f7; margin-top: 10px; margin-bottom: 10px; width:80%; display: flex; align-items:center; justify-items: center;padding: 0.5rem 1rem 0.5rem 1rem;"> ${setButtonText("Verify Me")} </div> </div> `; } export function setButtonText(text: string) { return ` <div style="width: 100%; text-align:center;"> <p style="font-weight: 600; margin:0 auto; color: #4a5568;">${text}</p> </div> `; } export function createButtonState(orbaOneloader: HTMLElement) { if (!orbaOneloader) { throw new Error("No loader found!"); } return { loading() { orbaOneloader.innerHTML = loader; }, idle() { orbaOneloader.innerHTML = setButtonText("Verify Me"); }, success() { orbaOneloader.innerHTML = setButtonText("Complete"); }, error() { orbaOneloader.innerHTML = setButtonText("Could Not Start Verification"); }, }; } export function applyDefaultButtonStyle(buttonElement: HTMLElement) { buttonElement.setAttribute("style", buttonStyles); buttonElement.classList.add("orba-verify-button"); buttonElement.innerHTML = getButtonTemplate(); return buttonElement; } export function createButton( target: string | HTMLElement | Element, disableStyle = false, onChange?: (status: ButtonState) => void, ) { const buttonElement = isDomElement(target) ? (target as HTMLElement) : (document.querySelector(target) as HTMLElement); if (!buttonElement) { throw `Target Element ${buttonElement} not found`; } const button = disableStyle ? buttonElement : applyDefaultButtonStyle(buttonElement); const buttonState = disableStyle ? {} : createButtonState(button.querySelector(`#${orbaOneLoaderId}`) as HTMLElement); return { el: button, setState: (state: ButtonState) => { if (!disableStyle) { if (buttonState[state]) { buttonState[state](); if (onChange) { onChange(state); } } } }, }; }
The Tiny Desk Contest Is Back! YouTube Sometimes small ideas can have a big impact, and our Tiny Desk Contest has had a major impact on unknown artists. The first year we ran the contest, we thought we'd watch a few fun videos of bands playing original songs and call it a day. That small idea turned into thousands of videos from musicians in every state in the country, a national tour, two winning artists and two years of pure music-discovery joy. I'm asking you to join me once again. Let's have another Tiny Desk Contest to find that one magic musical act to play its very own Tiny Desk concert — and, in the process, to discover a host of talent around this wonderful country. Here's how you enter: Make a video of yourself performing an original song behind a desk of your choosing. Gather your friends and grab a smartphone (if you think like last year's winner, Gaelynn Lea) or an iPad (if you're like our inaugural winner, the now-Grammy-nominated Fantastic Negrito) or a full-on camera rig (if you're, oh, say, Cactus Tractor). Shoot it however you like. What matters is the music, and that you have as much fun as possible bringing this together. We'll take submissions between Jan. 13 and Jan. 29, 2017, at 11:59 p.m. ET! We're giving you a whole month to get started on your entry video. You can use the time however you like — make an elaborate set for your video, write a new song, start a new band, learn a new instrument or learn how to play several instruments all at once. The winner of the contest will come play a Tiny Desk concert behind my desk here at NPR (watch Gaelynn Lea's and Fantastic Negrito's if you want proof), and then go on a fully funded tour of the United States with NPR Music and our sponsor, Lagunitas Brewing Co. We have a wonderful lineup of judges this year. Pop singer BANKS, R&B and gospel singer Anthony Hamilton, R&B crooner Miguel, jam-band legend Trey Anastasio of Phish and guitar-shredder (and glitter-wearer) Ben Hopkins of glam-punk band PWR BTTM have all played their own Tiny Desk concerts, so they're ready to watch your videos to find that winner. We're rounding out the judging panel with Talia Schlanger of WXPN's World Café; Rita Houston of WFUV; Stas THEE Boss of KEXP; Robin Hilton, my co-host on All Songs Considered; and me, Bob Boilen. As we watch the videos (and believe me, our team watches every single one), they'll appear on our website for fans to see. There's only one winner of the contest, but we've discovered that so much happens to the artists making these videos. We post the thrilling ones and the interesting ones on our Tumblr; we call them out in our weekly newsletter; we feature some of them on All Songs Considered; we have them play at local shows on our tour. Several Tiny Desk Contest entrants have even played their own Tiny Desk concerts even though they didn't win (looking at you, River Whyless, Valley Queen and Deqn Sue). This is a chance for the national music community to come together and lift one another up. So, here we are again. Let's make music together.
def fingerprint(self) -> Text: return rasa.shared.utils.io.deep_container_fingerprint( [self.data, self.features] )
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func inorderTraversal(root *TreeNode) []int { ret := make([]int, 0) if root == nil { return ret } stack := make([]*TreeNode, 0) for p := root; p != nil; p = p.Left { stack = append(stack, p) } for len(stack) > 0 { p := stack[len(stack)-1] ret = append(ret, p.Val) stack = stack[:len(stack)-1] if p.Right != nil { for p = p.Right; p != nil; p = p.Left { stack = append(stack, p) } } } return ret }
def load(): ddir = utils.datadir() files = glob(ddir+'parsec_*fits.gz') nfiles = len(files) if nfiles==0: raise Exception("No default isochrone files found in "+ddir) iso = [] for f in files: iso.append(Table.read(f)) if len(iso)==1: iso=iso[0] iso['AGE'] = 10**iso['LOGAGE'].copy() iso['METAL'] = iso['MH'] grid = IsoGrid(iso) return grid
/** * Helper method for generating the minimal catalog object. toMinimalTCatalogObject() * may be overrided by subclasses so we put the general implementation here. */ private TCatalogObject toMinimalTCatalogObjectHelper() { TCatalogObject catalogObject = new TCatalogObject(getCatalogObjectType(), getCatalogVersion()); catalogObject.setTable(new TTable(getDb().getName(), getName())); return catalogObject; }
shoulder-to-shoulder support for clinical staff members during the golive phase of electronic health record implementation N ursing informatics is an exciting nursing specialtydit affects learning environments, meaningful use, interprofessional collaboration, patient care settings, strategic planning, patient satisfaction, and, ultimately, patient outcomes. Simply put, nursing informatics is the practice of using nursing science and technology to enhance the pathway that data take to become knowledge to improve patient care. Furthermore, nursing informatics “is the synthesis of nursing science, information science, computer science, and cognitive science for the purpose of managing and enhancing health care data, information, knowledge, and wisdom to improve patient care and the nursing profession.” According to Hebda and Czar, it is “broadly defined as the use of information and computer technology to support all aspects of nursing practice, including direct delivery of care, administration, education, and research. The definition of nursing informatics is evolving as advances occur in nursing practice and technology.” Nursing informatics is important to all nursing specialty areas. It is important for nurses to understand the relevance of nursing informatics to their practice. In clinical practice, for example, nursing informatics can be used to track patient outcomes, find data trends, and assess workload and interventions. It also can help develop technologies, such as apps, to help health care workers virtually monitor and stay in touch with patients, improve workflows, and help patients deal with their diseases. The use of nursing informatics in nursing education supports virtual teaching and learning, assessment, analytics associated with educational outcomes, and the paradigm shift of bringing the library to the student virtually. Nurse executives use nursing informatics to help them with cost containment, improved workflows, decision support, budgeting tools, and trending costs and savings. Nursing informatics also can facilitate and support nursing research by evaluating patient outcomes, evidence-based practice, standardized terminologies, and virtual knowledge bases. As nurses learn nursing informatics, they must learn to use all information technologies effectively, recognize the benefits and limitations of this technology, and integrate them into how they implement these technologies. In this era of large amounts of data, nursing informatics competencies are key to safe, efficient, and quality practice, and good use of nursing informatics can result in enhanced patient care outcomes.
Having earlier given Brew an autograph, Clarke was unimpressed when, after refusing to lend his bat for a photo shoot, the teenager quipped: ''Why not? You never use it in the middle.'' Yesterday's incident was the latest in a summer to forget for Clarke. While captaining his country in a Test for the first time was a highlight, it came amid a lean run with the bat which yielded just 193 runs at 21.44 during the Ashes. Last Sunday he suffered the ignominy of being jeered on home soil just days after receiving a stinging public rebuke from Cricket Australia chief James Sutherland for showing a ''supreme lack of judgment'' by attending a charity function on the morning of the Boxing Day Test. Clarke said he would happily cop more flak from impatient fans not happy with his scoring rate if it meant he was doing the job for his team. ''What's important for me as the captain of this team right now is to do whatever it takes to help Australia win every game of cricket we play,'' he said. ''When I first walked out to bat, the ball was reverse-swinging a little bit. It wasn't the easiest of conditions to walk out and just smack it. ''Watto [Shane Watson] was playing an amazing knock and my role was to get up the other end and try not to lose wickets, try to build a partnership. ''If people want to see fours, sixes and wickets taken every ball, that's not international cricket. My role will be the same it has been over the 180 one-dayers I've played, to play the best type of cricket I can for the team, try to help win the game. ''If it means I need to go steady, I go steady. If it means I come in early and need to maximise the power play, well then I maximise the power play.'' Clarke denied Watson's match-winning 161 last Sunday ''papered over the cracks'' of an Australian team which leaked runs with the ball and in the field. ''I certainly don't think it hid any cracks, it was exactly what we're after,'' Clarke said. ''We've said openly that we play our best one-day cricket when someone in the top four makes a big score. Our bowling and our fielding for the first 30 overs of the game was as bad as I've seen and played in. The whole team is aware of that, but as a batting unit I thought we went about it the right way.'' Australia have another six one-dayers against England, starting with today's game in Hobart, and two practice matches on the subcontinent to rectify matters before they start their defence of the World Cup on February 21. Loading ''Our main focus is to win this game,'' Clarke said. ''That's got to be our focus - to try and win this series, and try and get that winning feeling back into the group like we did the other night and then we build momentum towards that World Cup. ''I think the guys that aren't playing will be working overtime in the nets … I think the guys that are playing will be 100 per cent focused on what's in front of us and then if we have an extra training day or have time in our training to be able to prepare for the subcontinent.''
<gh_stars>0 package Exercicios_java; import java.util.Scanner; public class CalcDespesas { public CalcDespesas() { double qtd,valor,media=0; String despesa; System.out.println("Bem Vindo a calculadora de gastos"); System.out.println("Quantas despesas mensais deseja inserir: "); qtd = new Scanner(System.in).nextInt(); for(int i=0;i<qtd;i++){ System.out.println("Introduza o nome da despesa: "); despesa = new Scanner(System.in).nextLine(); System.out.println("Introduza o valor da despesa: "); valor = new Scanner(System.in).nextInt(); media = media + valor; } System.out.println("Tera que fazer um investimento anual de " + media*12 +"€" +"\nO que equivale a " + media + "€ por mes"); } }
<reponame>StrahinjaJacimovic/mikrosdk_click_v2 /* * MikroSDK - MikroE Software Development Kit * Copyright© 2020 MikroElektronika d.o.o. * * 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. */ /*! * \file * */ #include "eeram2.h" // ------------------------------------------------------------- PRIVATE MACROS #define EERAM2_DUMMY 0 // ------------------------------------------------------------------ VARIABLES static const uint16_t crc16_ccitt_table[ 256 ] = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0 }; // ---------------------------------------------- PRIVATE FUNCTION DECLARATIONS static uint16_t dev_crc16_ccitt ( uint8_t *p_data ); // ------------------------------------------------ PUBLIC FUNCTION DEFINITIONS void eeram2_cfg_setup ( eeram2_cfg_t *cfg ) { // Communication gpio pins cfg->sck = HAL_PIN_NC; cfg->miso = HAL_PIN_NC; cfg->mosi = HAL_PIN_NC; cfg->cs = HAL_PIN_NC; // Additional gpio pins cfg->hld = HAL_PIN_NC; cfg->spi_mode = SPI_MASTER_MODE_0; cfg->cs_polarity = SPI_MASTER_CHIP_SELECT_POLARITY_ACTIVE_LOW; cfg->spi_speed = 100000; } EERAM2_RETVAL eeram2_init ( eeram2_t *ctx, eeram2_cfg_t *cfg ) { spi_master_config_t spi_cfg; spi_master_configure_default( &spi_cfg ); spi_cfg.speed = cfg->spi_speed; spi_cfg.mode = cfg->spi_mode; spi_cfg.sck = cfg->sck; spi_cfg.miso = cfg->miso; spi_cfg.mosi = cfg->mosi; spi_cfg.default_write_data = EERAM2_DUMMY; digital_out_init( &ctx->cs, cfg->cs ); ctx->chip_select = cfg->cs; if ( spi_master_open( &ctx->spi, &spi_cfg ) == SPI_MASTER_ERROR ) { return EERAM2_INIT_ERROR; } spi_master_set_default_write_data( &ctx->spi, EERAM2_DUMMY ); spi_master_set_mode( &ctx->spi, spi_cfg.mode ); spi_master_set_speed( &ctx->spi, spi_cfg.speed ); spi_master_set_chip_select_polarity( cfg->cs_polarity ); spi_master_deselect_device( ctx->chip_select ); // Output pins digital_out_init( &ctx->hld, cfg->hld ); return EERAM2_OK; } void eeram2_generic_transfer ( eeram2_t *ctx, uint8_t *wr_buf, uint16_t wr_len, uint8_t *rd_buf, uint16_t rd_len ) { spi_master_select_device( ctx->chip_select ); spi_master_write_then_read( &ctx->spi, wr_buf, wr_len, rd_buf, rd_len ); spi_master_deselect_device( ctx->chip_select ); } void eeram2_set_on_hold_status ( eeram2_t *ctx, uint8_t en_hold ) { if ( en_hold == EERAM2_HOLD_ENABLE ) { digital_out_low( &ctx->hld ); } else { digital_out_high( &ctx->hld ); } } void eeram2_set_command ( eeram2_t *ctx, uint8_t command ) { uint8_t tx_buf[ 1 ]; tx_buf[ 0 ] = command; spi_master_select_device( ctx->chip_select ); spi_master_write( &ctx->spi, tx_buf, 1 ); spi_master_deselect_device( ctx->chip_select ); } void eeram2_set_write_status ( eeram2_t *ctx, uint8_t en_write ) { if ( en_write == EERAM2_WRITE_ENABLE ) { eeram2_set_command( ctx, EERAM2_CMD_WREN ); } else { eeram2_set_command( ctx, EERAM2_CMD_WRDI ); } } void eeram2_set_status ( eeram2_t *ctx, uint8_t tx_data ) { uint8_t tx_buf[ 2 ]; tx_buf[ 0 ] = EERAM2_CMD_WRSR; tx_buf[ 1 ] = tx_data; spi_master_select_device( ctx->chip_select ); spi_master_write( &ctx->spi, tx_buf, 2 ); spi_master_deselect_device( ctx->chip_select ); } uint8_t eeram2_get_status ( eeram2_t *ctx ) { uint8_t tx_buf[ 1 ]; uint8_t rx_buf[ 1 ]; tx_buf[ 0 ] = EERAM2_CMD_RDSR; spi_master_select_device( ctx->chip_select ); spi_master_write( &ctx->spi, tx_buf, 1 ); spi_master_read( &ctx->spi, rx_buf, 1 ); spi_master_deselect_device( ctx->chip_select ); return rx_buf[ 0 ]; } uint8_t eeram2_write_byte ( eeram2_t *ctx, uint32_t reg, uint8_t tx_data ) { uint8_t tx_buf[ 5 ]; uint8_t status; status = EERAM2_SUCCESS; if ( reg > EERAM2_SRAM_ADDR_LAST ) { status = EERAM2_ERROR; } tx_buf[ 0 ] = EERAM2_CMD_WRITE; tx_buf[ 1 ] = ( uint8_t ) ( reg >> 16 ); tx_buf[ 2 ] = ( uint8_t ) ( reg >> 8 ); tx_buf[ 3 ] = ( uint8_t ) reg; tx_buf[ 4 ] = tx_data; spi_master_select_device( ctx->chip_select ); spi_master_write( &ctx->spi, tx_buf, 5 ); spi_master_deselect_device( ctx->chip_select ); return status; } uint8_t eeram2_read_byte ( eeram2_t *ctx, uint32_t reg ) { uint8_t tx_buf[ 4 ]; uint8_t rx_buf[ 1 ]; reg &= EERAM2_SRAM_ADDR_LAST; tx_buf[ 0 ] = EERAM2_CMD_READ; tx_buf[ 1 ] = ( uint8_t ) ( reg >> 16 ); tx_buf[ 2 ] = ( uint8_t ) ( reg >> 8 ); tx_buf[ 3 ] = ( uint8_t ) reg; spi_master_select_device( ctx->chip_select ); spi_master_write( &ctx->spi, tx_buf, 4 ); spi_master_read( &ctx->spi, rx_buf, 1 ); spi_master_deselect_device( ctx->chip_select ); return rx_buf[ 0 ]; } uint8_t eeram2_write_continuous ( eeram2_t *ctx, uint32_t reg, uint8_t *p_tx_data, uint8_t n_bytes ) { uint8_t tx_buf[ 256 ]; uint8_t n_cnt; uint8_t status; status = EERAM2_SUCCESS; if ( reg > EERAM2_SRAM_ADDR_LAST ) { status = EERAM2_ERROR; } tx_buf[ 0 ] = EERAM2_CMD_WRITE; tx_buf[ 1 ] = ( uint8_t ) ( reg >> 16 ); tx_buf[ 2 ] = ( uint8_t ) ( reg >> 8 ); tx_buf[ 3 ] = ( uint8_t ) reg; for ( n_cnt = 0; n_cnt < n_bytes; n_cnt++ ) { tx_buf[ n_cnt + 4 ] = p_tx_data[ n_cnt ]; } spi_master_select_device( ctx->chip_select ); spi_master_write( &ctx->spi, tx_buf, n_bytes ); spi_master_deselect_device( ctx->chip_select ); return status; } uint8_t eeram2_read_continuous ( eeram2_t *ctx, uint32_t reg, uint8_t *p_rx_data, uint8_t n_bytes ) { uint8_t tx_buf[ 4 ]; uint8_t n_cnt; reg &= EERAM2_SRAM_ADDR_LAST; tx_buf[ 0 ] = EERAM2_CMD_READ; tx_buf[ 1 ] = ( uint8_t ) ( reg >> 16 ); tx_buf[ 2 ] = ( uint8_t ) ( reg >> 8 ); tx_buf[ 3 ] = ( uint8_t ) reg; spi_master_select_device( ctx->chip_select ); spi_master_write( &ctx->spi, tx_buf, 4 ); spi_master_read( &ctx->spi, p_rx_data, n_bytes ); spi_master_deselect_device( ctx->chip_select ); return EERAM2_SUCCESS; } uint8_t eeram2_write_nonvolatile ( eeram2_t *ctx, uint8_t *p_tx_data ) { uint8_t tx_buf[ 17 ]; uint8_t n_cnt; tx_buf[ 0 ] = EERAM2_CMD_WRNUR; for ( n_cnt = 0; n_cnt < 16; n_cnt++ ) { tx_buf[ n_cnt + 1 ] = p_tx_data[ n_cnt ]; } spi_master_select_device( ctx->chip_select ); spi_master_write( &ctx->spi, tx_buf, 16 ); spi_master_deselect_device( ctx->chip_select ); return EERAM2_SUCCESS; } uint8_t eeram2_read_nonvolatile ( eeram2_t *ctx, uint8_t *p_rx_data ) { uint8_t tx_buf[ 1 ]; tx_buf[ 0 ] = EERAM2_CMD_RDNUR; spi_master_select_device( ctx->chip_select ); spi_master_write( &ctx->spi, tx_buf, 1 ); spi_master_read( &ctx->spi, p_rx_data, 16 ); spi_master_deselect_device( ctx->chip_select ); return EERAM2_SUCCESS; } uint8_t eeram2_secure_write ( eeram2_t *ctx, uint16_t reg, uint8_t *p_tx_data ) { uint8_t tx_buf[ 133 ]; uint8_t n_cnt; uint16_t crc; crc = dev_crc16_ccitt( &p_tx_data[ 0 ] ); tx_buf[ 0 ] = EERAM2_CMD_SECURE_WRITE; tx_buf[ 1 ] = ( uint8_t ) ( reg >> 8 ); tx_buf[ 2 ] = ( uint8_t ) reg; for ( n_cnt = 0; n_cnt < 128; n_cnt++ ) { tx_buf[ n_cnt + 3 ] = p_tx_data[ n_cnt ]; } tx_buf[ 131 ] = ( uint8_t ) ( crc >> 8 ); tx_buf[ 132 ] = ( uint8_t ) crc; spi_master_select_device( ctx->chip_select ); spi_master_write( &ctx->spi, tx_buf, 132 ); spi_master_deselect_device( ctx->chip_select ); return EERAM2_SUCCESS; } uint8_t eeram2_secure_read ( eeram2_t *ctx, uint16_t reg, uint8_t *p_rx_data ) { uint8_t tx_buf[ 3 ]; uint8_t rx_buf[ 2 ]; uint16_t crc; uint8_t n_cnt; reg &= EERAM2_SRAM_ADDR_LAST; tx_buf[ 0 ] = EERAM2_CMD_SECURE_READ; tx_buf[ 1 ] = ( uint8_t ) ( reg >> 8 ); tx_buf[ 2 ] = ( uint8_t ) reg; spi_master_select_device( ctx->chip_select ); spi_master_write( &ctx->spi, tx_buf, 3 ); spi_master_read( &ctx->spi, p_rx_data, 127 ); spi_master_read( &ctx->spi, rx_buf, 2 ); spi_master_deselect_device( ctx->chip_select ); crc = rx_buf[ 0 ]; crc <<= 8; crc |= rx_buf[ 1 ]; if ( crc == dev_crc16_ccitt( &p_rx_data[ 0 ] ) ) { return EERAM2_SUCCESS; } else { return EERAM2_ERROR; } } // ----------------------------------------------- PRIVATE FUNCTION DEFINITIONS static uint16_t dev_crc16_ccitt ( uint8_t *p_data ) { uint16_t crc; uint8_t len; uint8_t tmp; crc = 0x0000; for ( len = 0; len < 128; len++ ) { tmp = ( uint8_t ) ( crc >> 8 ); tmp ^= p_data[ len ]; crc <<= 8; crc ^= crc16_ccitt_table[ tmp ]; } return crc; } // ------------------------------------------------------------------------- END
<reponame>yeonjju21/HelloWorld package org.yjj.chapter.s099; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import org.yjj.chapter.s098.SovereignFlag; public class RequestFromWikipedai { ArrayList<String> htmls=new ArrayList<String>(); ArrayList<SovereignFlag> flags=new ArrayList<SovereignFlag>(); public ArrayList<SovereignFlag> getFlags() { return flags; } public RequestFromWikipedai() { htmls.clear(); flags.clear(); } boolean isConnection=false; public void getAllHtml(String newUrls){ htmls.clear(); InputStream inputStream; URL url=null; try { url= new URL(newUrls); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); inputStream = new BufferedInputStream(urlConnection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8); String line = null; while ((line = reader.readLine()) != null) { if(!line.trim().equals("")){ htmls.add(line.trim()); } } inputStream.close(); isConnection=true; } catch (Exception e) { isConnection = false; System.out.println(e); } } public String __toStr(String msg){ return msg.replaceAll("_", " "); } public String emptyto_(String msg){ return msg.replaceAll(" ", "_"); } public String replaceper(String msg){ String ss=msg; return ss.trim(); } public synchronized void getSevereign(String msg){ int count=0; flags.clear(); for (int i=0; i<htmls.size(); i++) { String ss=htmls.get(i); if(ss.contains(msg)){ if(ss.contains(".svg.png")){ String korname=ss.substring(0,ss.lastIndexOf("</a></td>"));// korname=korname.substring(korname.lastIndexOf(">")+1);// String flag=ss.substring(0,ss.lastIndexOf(".svg.png")+".svg.png".length());// flag="https:"+flag.substring(flag.lastIndexOf("//upload.wikimedia.org/wikipedia"));// String name=flag.substring(flag.lastIndexOf("/")+1); name=name.substring(0,name.lastIndexOf(".svg.png"));// if(name.contains("Flag_of_the_")){ name=name.substring(name.lastIndexOf("Flag_of_the_")+"Flag_of_the_".length());// }else if(name.contains("Flag_of_The_")){ name=name.substring(name.lastIndexOf("Flag_of_The_")+"Flag_of_The_".length());// }else if(name.contains("Flag_of_")){ name=name.substring(name.lastIndexOf("Flag_of_")+"Flag_of_".length());// } String code=htmls.get(i+1); code=code.substring(0,code.lastIndexOf("<")); code=code.substring(code.indexOf(">")+1); String shortname=htmls.get(i+3); shortname=shortname.substring(0,shortname.lastIndexOf("<")); shortname=shortname.substring(shortname.indexOf(">")+1); SovereignFlag sflag=new SovereignFlag(__toStr(name),shortname,code,flag,korname); flags.add(sflag); } } } } public void printHtml(){ for (String dto : htmls) { System.out.println(dto); } } public void printFlags(){ int count=1; for (SovereignFlag dto : flags) { System.out.println((count++)+"\t"+dto); } } public static void main(String[] args) { RequestFromWikipedai rfw=new RequestFromWikipedai(); String a="https://ko.wikipedia.org/wiki/ISO_3166-1"; String msg="srcset=\"//upload.wikimedia.org/wikipedia"; rfw.getAllHtml(a); rfw.getSevereign(msg); rfw.printFlags(); } }
-- Informatics 1 Functional Programming -- December 2012 -- SITTING 1 (09:30 - 11:30) import Test.QuickCheck( quickCheck, Arbitrary( arbitrary ), oneof, elements, sized ) import Control.Monad -- defines liftM, liftM2, used below -- Question 1 -- 1a f :: Int -> [Int] -> [Int] f = undefined -- 1b g :: Int -> [Int] -> [Int] g = undefined -- Question 2 -- 2a p :: [Int] -> Bool p = undefined -- 2b q :: [Int] -> Bool q = undefined -- 2c r :: [Int] -> Bool r = undefined -- Question 3 data Prop = X | F | T | Not Prop | Prop :|: Prop deriving (Eq, Ord) -- turns a Prop into a string approximating mathematical notation showProp :: Prop -> String showProp X = "X" showProp F = "F" showProp T = "T" showProp (Not p) = "(~" ++ showProp p ++ ")" showProp (p :|: q) = "(" ++ showProp p ++ "|" ++ showProp q ++ ")" -- For QuickCheck instance Show Prop where show = showProp instance Arbitrary Prop where arbitrary = sized prop where prop n | n <= 0 = atom | otherwise = oneof [ atom , liftM Not subform , liftM2 (:|:) subform subform ] where atom = oneof [elements [X,F,T]] subform = prop (n `div` 2) -- 3a eval :: Prop -> Bool -> Bool eval X b = b eval F _ = False eval T _ = True eval (Not x) b = not (eval x b) eval (x :|: y) b = (eval x b) || (eval y b) -- 3b simplify :: Prop -> Prop simplify = undefined
package main import ( "fmt" "log" "regexp" "strconv" "strings" "github.com/knq/snaker" ) // In case we need to do something version specific var dbVersion int // Field describes a single column of a table, and is also abused to store // query parameters type Field struct { Name string Position int Type string NotNull bool Array bool GoType string visible bool typeid uint32 HasDefault bool } // Unique describes a unique index type Unique struct { Name string PrimaryKey bool Columns []string } // ForeignKey describes a foreign key type ForeignKey struct { Name string Columns []string ForeignTable string ForeignColumns []string } // Query describes a SQL query type Query struct { Name string Query string OriginalQuery string Fields []Field Parameters []Field SingleRow bool } // Table describes a database table type Table struct { oid uint32 Name string Schema string Type string Fields []Field Indexes []Unique Primary Unique IDField Field Queries []Query ForeignKeys []ForeignKey } // Enum describes a database enum type type Enum struct { oid uint32 Name string Labels []string } // Result is all the information generated from database introspection type Result struct { Tables []Table Enums []Enum } // type mappings, pulled in from config var nullType = map[uint32]string{} var notNullType = map[uint32]string{} // enums we've seen in a query or table OID -> name var seenEnums = map[uint32]string{} // all enums, extracted from pg_type OID -> name var allEnums = map[uint32]string{} var result Result var queries = map[string]string{} // introspect does all the database work needed to create our Result // object func introspect() Result { // Get the version of the database we're talking to var versionString string err := db.QueryRow(`select current_setting('server_version_num')`).Scan(&versionString) if err != nil { log.Fatalf("Failed to read server version: %s", err) } dbVersion, err = strconv.Atoi(versionString) if err != nil { log.Fatalf("Bad version '%s': %s", versionString, err) } // Get a list of enums that are in the database err = listEnums() if err != nil { log.Fatalf("%s", err) } // Fetch the postgresql-to-Go type maps from the configuration file err = readTypes() if err != nil { log.Fatalf("%s", err) } // Get the structure of tables we're interested in err = readTables() if err != nil { log.Fatalf("%s", err) } // Load the labels of enums we've seen in use in a table err = loadEnums() if err != nil { log.Fatalf("%s", err) } // Read SQL queries from configuration file err = readQueries() if err != nil { log.Fatalf("%s", err) } // Find unique indexes for each table, synthesize queries err = readIndexes() if err != nil { log.Fatalf("%s", err) } // Find foreign keys for each table, synthesize queries err = readFKs() if err != nil { log.Fatalf("%s", err) } // Generate types for each SQL query err = generateQueries() if err != nil { log.Fatalf("%s", err) } // Remove columns that aren't visible, either ignored or deleted removeColumns() // Try and avoid name clashes between parameters and internal template variables fixQueryParameters() return result } var nameMapping = map[string]string{} var seenNameMapping = map[string]struct{}{} var nonLetterRe = regexp.MustCompile(`[^\pL_]`) // goname converts a snake_case name to a GoStyle name // It also maps invalid names to valid ones and avoids collisions func goname(s string) string { r, ok := nameMapping[s] if ok { return r } r = snaker.SnakeToCamel(nonLetterRe.ReplaceAllString(s, "_x")) _, ok = seenNameMapping[r] if ok { i := 2 for { u := fmt.Sprintf("%s%d", r, i) _, ok = seenNameMapping[u] if !ok { r = u break } i++ } } seenNameMapping[r] = struct{}{} nameMapping[s] = r return r } // makeRegexp converts a slice of glob patterns to a regexp func makeRegexp(parts []string) string { for k, v := range parts { parts[k] = strings.Replace(regexp.QuoteMeta(v), `\*`, `.*`, -1) } return "^(" + strings.Join(parts, "|") + ")$" } func removeColumns() { for ti, table := range result.Tables { newFields := []Field{} for _, f := range table.Fields { if f.visible { newFields = append(newFields, f) } } table.Fields = newFields result.Tables[ti] = table } } // readTypes takes the type mappings from the configuration file // sanity checks them and normalizes them func readTypes() error { for k, v := range c.NotNullTypes { var canonicalType uint32 if k == "*" { notNullType[0] = v continue } qerr := db.QueryRow(`select $1::regtype::oid`, k).Scan(&canonicalType) if qerr != nil { log.Printf("Failed to canonicalize type '%s': %s", k, qerr) continue } al, ok := notNullType[canonicalType] if ok { // We have an alias if al != v { return fmt.Errorf("Postgresql type '%s' is mapped two different ways, to '%s' and '%s'", k, v, al) } } else { notNullType[canonicalType] = v } } for k, v := range c.Types { var canonicalType uint32 if k == "*" { nullType[0] = v continue } qerr := db.QueryRow(`select $1::regtype::oid`, k).Scan(&canonicalType) if qerr != nil { log.Printf("Failed to canonicalize type '%s': %s", k, qerr) continue } al, ok := nullType[canonicalType] if ok { // We have an alias if al != v { return fmt.Errorf("Postgresql type '%s' is mapped two different ways, to '%s' and '%s'", k, v, al) } } else { nullType[canonicalType] = v } // A nullable type can be used for a not null field, so fill in gaps ... _, ok = notNullType[canonicalType] if !ok { notNullType[canonicalType] = v } } return nil } // readTables reads all the tables func readTables() error { include := c.IncludeTables if len(include) == 0 { include = []string{"public.*"} } for k, v := range include { if !strings.Contains(v, ".") { include[k] = "public." + v } } exclude := c.ExcludeTables for k, v := range exclude { if !strings.Contains(v, ".") { exclude[k] = "*." + v } } const tableSQL = `select c.oid, c.relkind::text, c.relname, n.nspname` + ` from pg_class c, pg_namespace n` + ` where c.relkind in ('r', 'v', 'm') and` + ` n.nspname || '.' || c.relname ~ $1 and` + ` n.nspname || '.' || c.relname !~ $2 and` + ` n.oid = c.relnamespace` q, err := db.Query(tableSQL, makeRegexp(include), makeRegexp(exclude)) if err != nil { return err } defer q.Close() for q.Next() { t := Table{} err = q.Scan(&t.oid, &t.Type, &t.Name, &t.Schema) if err != nil { return err } result.Tables = append(result.Tables, t) } q.Close() for k, t := range result.Tables { conf, ok := c.Table[t.Schema+"."+t.Name] if !ok { conf, ok = c.Table[t.Name] } if !ok { conf = c.Default } t.Fields, err = readColumns(t.oid, t.Name, conf) if err != nil { log.Fatalln(err) } result.Tables[k] = t } return nil } // goType returns the Go type that a postgresql type oid maps to func goType(oid uint32, notnull bool, typename string, tablename string) string { var ok bool var gt string if notnull { gt, ok = notNullType[oid] if ok { return gt } } gt, ok = nullType[oid] if ok { return gt } enumname, ok := seenEnums[oid] if ok { return goname(enumname) } // TODO: nullable enums enumname, ok = allEnums[oid] if ok { seenEnums[oid] = enumname return goname(enumname) } if notnull { gt, ok = notNullType[0] if ok { log.Printf("Using fallback type for type %s in %s\n", typename, tablename) return gt } } gt, ok = nullType[0] if ok { log.Printf("Using fallback type for type %s in %s\n", typename, tablename) return gt } log.Printf("Couldn't translate type %s in %s\n", typename, tablename) return "?unknown?" } // readColumns reads the columns for a single table func readColumns(oid uint32, tableName string, conf TableConfig) ([]Field, error) { ret := []Field{} // Explicitly pass NULL instead of atttypmod to format_type as we // don't _really_ care about max length, etc var attrSQL string if dbVersion >= 110000 { // Identity columns were added in 11.0, we treat them as // having a default attrSQL = `select a.attnum, a.attname, format_type(a.atttypid, NULL),` + ` a.attnotnull, a.attndims <> 0,` + ` a.attname ~* $2 and a.attname !~* $3 and not a.attisdropped,` + ` a.atttypid, a.atthasdef or a.attidentity <> ''` + ` from pg_attribute a` + ` where a.attrelid = $1` + ` order by a.attnum asc` } else { attrSQL = `select a.attnum, a.attname, format_type(a.atttypid, NULL),` + ` a.attnotnull, a.attndims <> 0,` + ` a.attname ~* $2 and a.attname !~* $3 and not a.attisdropped,` + ` a.atttypid, a.atthasdef` + ` from pg_attribute a` + ` where a.attrelid = $1` + ` order by a.attnum asc` } include := conf.IncludeColumns if len(include) == 0 { include = []string{"*"} } q, err := db.Query(attrSQL, oid, makeRegexp(include), makeRegexp(conf.ExcludeColumns)) if err != nil { return nil, err } defer q.Close() for q.Next() { f := Field{} err = q.Scan(&f.Position, &f.Name, &f.Type, &f.NotNull, &f.Array, &f.visible, &f.typeid, &f.HasDefault) if err != nil { return nil, err } if f.Position < 0 { // System field // TODO: check for explicit match in IncludeColumns continue } if f.visible { // Only look at the type of a field if we're not ignoring it colType := f.Type if f.Array { colType = colType + "[]" } // table specific override gotype, ok := conf.ColumnType[f.Name] if !ok { gotype = goType(f.typeid, f.NotNull, colType, tableName) } f.GoType = gotype } ret = append(ret, f) } return ret, nil } // listEnums loads a list of all enum types func listEnums() error { q, err := db.Query(`select oid, typname from pg_type where typtype = 'e'`) if err != nil { return err } defer q.Close() for q.Next() { var oid uint32 var name string err = q.Scan(&oid, &name) if err != nil { return err } allEnums[oid] = name } return nil } // loadEnums loads the enum types that we've seen in a table func loadEnums() error { for oid, name := range seenEnums { e := Enum{ Name: name, } q, err := db.Query(`select enumlabel from pg_enum`+ ` where enumtypid=$1`+ ` order by enumsortorder`, oid) if err != nil { return err } defer q.Close() values := []string{} for q.Next() { var label string err = q.Scan(&label) if err != nil { return err } values = append(values, label) } e.Labels = values q.Close() result.Enums = append(result.Enums, e) } return nil } // readIndexes finds all the unique indexes for all our tables func readIndexes() error { for k, v := range result.Tables { var err error v.Indexes, err = uniques(v) if err != nil { return err } for _, idx := range v.Indexes { if idx.PrimaryKey { v.Primary = idx // If there's a single column primary key we use that for update / upsert if len(idx.Columns) == 1 { for _, field := range v.Fields { if field.Name == idx.Columns[0] && field.HasDefault { v.IDField = field } } } } if c.GenerateUniqueQueries || (c.GeneratePKQueries && idx.PrimaryKey) { // Generate a query based on this index nameParts := []string{v.Name, "by"} paramParts := []string{} for pidx, pname := range idx.Columns { nameParts = append(nameParts, pname) paramParts = append(paramParts, fmt.Sprintf("%s = $%d", maybequote1(pname), pidx+1)) } addQuery(goname(strings.Join(nameParts, "_")), fmt.Sprintf("select * from %s where %s", maybequote1(v.Name), strings.Join(paramParts, " and "))) } } result.Tables[k] = v } return nil } func readFKs() error { for k, table := range result.Tables { q, err := db.Query(`select conname, confrelid, conkey, confkey from pg_constraint where conrelid=$1 and contype='f'`, table.oid) if err != nil { return err } for q.Next() { fk := ForeignKey{ Columns: []string{}, ForeignColumns: []string{}, } conkey := []int16{} confkey := []int16{} var confrelid uint32 err = q.Scan(&fk.Name, &confrelid, &conkey, &confkey) if err != nil { return err } if len(conkey) == 0 { // ?? continue } for _, col := range conkey { if col < 1 || int(col) > len(table.Fields) { return fmt.Errorf("Column %d of foreign key %s outside columns for %s", col, fk.Name, table.Name) } fk.Columns = append(fk.Columns, table.Fields[col-1].Name) } for _, foreignTable := range result.Tables { if foreignTable.oid == confrelid { fk.ForeignTable = foreignTable.Name for _, fcol := range confkey { if fcol < 1 || int(fcol) > len(foreignTable.Fields) { return fmt.Errorf("Column %d of foreign key %s outside columns of target table %s", fcol, fk.Name, fk.ForeignTable) } fk.ForeignColumns = append(fk.ForeignColumns, foreignTable.Fields[fcol-1].Name) } } } result.Tables[k].ForeignKeys = append(result.Tables[k].ForeignKeys, fk) if c.GenerateFKQueries { nameParts := []string{table.Name, "by"} paramParts := []string{} for pidx, pname := range fk.Columns { nameParts = append(nameParts, pname) paramParts = append(paramParts, fmt.Sprintf("%s = $%d", maybequote1(pname), pidx+1)) } addQuery(goname(strings.Join(nameParts, "_")), fmt.Sprintf("select * from %s where %s", maybequote1(table.Name), strings.Join(paramParts, " and "))) } } } return nil } // uniques finds all the unique indexes for a table func uniques(t Table) ([]Unique, error) { q, err := db.Query(`select i.indisprimary, i.indkey::int2[], c.relname`+ ` from pg_index i, pg_class c`+ ` where i.indrelid = $1`+ ` and i.indisunique`+ ` and i.indexrelid = c.oid`, t.oid) if err != nil { return nil, err } defer q.Close() uniques := []Unique{} OUTER: for q.Next() { u := Unique{} posns := []uint16{} err = q.Scan(&u.PrimaryKey, &posns, &u.Name) if err != nil { return nil, err } if len(posns) == 0 { continue } for _, pos := range posns { if pos == 0 { // Functional index continue OUTER } // Postgresql is 1-based, we're 0-based if !t.Fields[pos-1].visible { // Index on a column we're ignoring continue OUTER } u.Columns = append(u.Columns, t.Fields[pos-1].Name) } uniques = append(uniques, u) } return uniques, nil } // Read the user-provided SQL queries from the configuration file func readQueries() error { queries = c.Queries return nil } // add a generated query, renaming it if needed to avoid clashes func addQuery(name string, query string) { for { _, ok := queries[name] if !ok { break } name = name + "_" } queries[name] = query } func generateQueries() error { for name, query := range queries { err := readQuery(name, query, false) if err != nil { return err } } return nil } func readQuery(name string, query string, single bool) error { starre := regexp.MustCompile(`(?is)^\s*select\s+\*\s+(.*)`) realquery := query // Prepare the query, so we can get metadata about parameters and results prepared, err := db.Prepare(name, query) if err != nil { return fmt.Errorf("while preparing query %s: %s", name, err) } if len(prepared.FieldDescriptions) == 0 { return fmt.Errorf("query %s doesn't return anything", name) } tableoid := prepared.FieldDescriptions[0].Table tableidx := -1 for i, t := range result.Tables { if t.oid == uint32(tableoid) { tableidx = i } } if tableidx == -1 { // TODO: generic queries return fmt.Errorf("query %s uses a table that's not included - not supported", name) } table := result.Tables[tableidx] matches := starre.FindStringSubmatch(query) if matches != nil { // it's a select * from a single table - rewrite to use concrete columns cols := []string{} for _, f := range table.Fields { if !f.visible { continue } cols = append(cols, maybequote1(f.Name)) } realquery = `select ` + strings.Join(cols, ", ") + " " + matches[1] prepared, err = db.Prepare(name, query) if err != nil { return fmt.Errorf("while preparing query for *-expanded %s: %s", name, err) } } // Make sure the results will fit into the struct we already have created for table returnedFields := []Field{} for _, fd := range prepared.FieldDescriptions { if fd.Table != tableoid { // TODO: generic queries return fmt.Errorf("query %s returns from multiple tables - not supported", name) } f := table.Fields[fd.AttributeNumber-1] if f.Position != int(fd.AttributeNumber) { return fmt.Errorf("query %s - internal error finding columns", name) } returnedFields = append(returnedFields, f) } // Handle the $1, $2, $3 ... parameters parameterFields := []Field{} eqParameters := []string{} for i, paramoid := range prepared.ParameterOIDs { paramField := Field{} findNameRe := regexp.MustCompile(fmt.Sprintf(`\$%d\s*/\*\s*([^*]*[^ *])\s*\*/`, i+1)) // Look for annotations of the form /* name */ or /* name gotype */ matches := findNameRe.FindStringSubmatch(query) if matches != nil { parts := regexp.MustCompile(`\s+`).Split(matches[1], -1) if len(parts) > 2 { return fmt.Errorf("query %s - couldn't understand type annotation '%s'", name, matches[1]) } if len(parts) > 1 { paramField.GoType = parts[1] } if len(parts) > 0 { paramField.Name = parts[0] } } // Crude check for where constraints of the form <column_name>=$<digit> findEqualRe := regexp.MustCompile(fmt.Sprintf(`(\S+)\s*=\s*\$%d`, i+1)) matches = findEqualRe.FindStringSubmatch(query) if matches != nil { eqParameters = append(eqParameters, matches[1]) } if paramField.Name == "" { if matches != nil { if strings.Contains(matches[1], "_") { paramField.Name = goname(matches[1]) } else { paramField.Name = matches[1] } } else { paramField.Name = fmt.Sprintf("p%d", i+1) } } if paramField.GoType == "" { // OK, lets try and guess based on the paramoid paramField.GoType = goType(uint32(paramoid), true, fmt.Sprintf("$%d", i+1), name) } parameterFields = append(parameterFields, paramField) } // If query ends in "limit 1" or includes /* singlerow */ make it return a single row limitre := regexp.MustCompile(`(?i)limit\s+1\s*;?\s*$`) if limitre.MatchString(query) || strings.Contains(query, "/* singlerow */") { single = true } // Deep nesting, but the number of indexes and parameters will be small // https://accidentallyquadratic.tumblr.com if !single && len(eqParameters) > 0 { // There's at least one parameter of the form column = parameter for _, index := range table.Indexes { columnMatches := 0 for _, indexCol := range index.Columns { for _, paramCol := range eqParameters { if paramCol == indexCol { columnMatches++ } } } if columnMatches == len(index.Columns) { // our parameters are a superset of the columns of a unique index, so we'll return one row single = true break } } } // Provide an escape hatch for when we want multiple rows if strings.Contains(query, "/* multirow */") { single = false } table.Queries = append(table.Queries, Query{ Name: name, Query: realquery, OriginalQuery: query, Fields: returnedFields, Parameters: parameterFields, SingleRow: single, }) result.Tables[tableidx] = table return nil } // fixQueryParameters renames parameters so as not to clash with // variables used in the generated code. func fixQueryParameters() { rn := c.ReservedNames if len(rn) == 0 { rn = []string{"q", "row", "result", "db", "err"} } exclude := map[string]struct{}{} for _, name := range rn { exclude[name] = struct{}{} } for tableidx, table := range result.Tables { for queryidx, query := range table.Queries { for paramidx, param := range query.Parameters { _, ok := exclude[param.Name] if ok { // Clashes param.Name = param.Name + "_" query.Parameters[paramidx] = param } } table.Queries[queryidx] = query } result.Tables[tableidx] = table } }
import java.util.Scanner; public class even_odds318A { public static long n , k , odd , even , lastOddPosition; public static void main(String[] args) { Scanner scan = new Scanner(System.in); n = scan.nextLong(); k= scan.nextLong(); // odd = Math.round(n/2); odd = n/2; even = n/2; if(n%2!=0) { odd++; } lastOddPosition = odd; if(k<=lastOddPosition) { findOdd(); } else { findEven(); } //printNum(); } private static void findEven() { System.out.println((k-odd)*2); } private static void findOdd() { System.out.println(k+(k-1)); } private static void printNum() { System.out.println("odd is = " + odd); System.out.println("even is = " + even); System.out.println("lastOdd is = " + lastOddPosition); } }
By Daniel Cabrera, M.D. Author: David Nestler, MD (@DrDavidNestler) Heard about the “MACRA” bill in the news lately? Here’s why, and some brief updates about it. In April 2015 Congress passed HR-2, aka “MACRA” (the Medicare Access and CHIP Reauthorization Act). On 4/27/16, CMS released a Notice of Proposed Rulemaking as part of the implementation plan, causing a flurry of media discussion. Most simply, MACRA replaces the long-standing sustainable growth rate (SGR) formula, which was used to calculate Medicare payments to providers. This SGR required a yearly “fix”, and was constantly in the news. MACRA also rolls in several existing Medicare programs used to measure quality, including Accountable Care Organizations (ACOs), the Physician Quality Reporting System (PQRS), the Value-based Modifier (VBM) Program, and the EHR Incentive Program (aka Meaningful Use, or MU). These programs are not dead. Rather, they are rolled into MACRA, with an opportunity to update their design. Some key points: MACRA starts affecting payments in 2019, but 2017 performance measures will be used to calculate the 2019 payment. MACRA is led by CMS. It is NOT part of the Affordable Care Act, and MACRA has strong bipartisan agreement. The goal of MACRA is to create a new framework to reward hospitals based on performance and health outcomes, rather than volume. MACRA has two tracks: the Merit-based Incentive Payment System (MIPS); and Alternative Payment Models (APM). Provider groups will be assigned to one of these two tracks. Since several details regarding how groups will quality for APMs are not released yet, more discussion has focused on MIPS. MIPS: Is one program with four categories: quality, resource use, clinical practice improvement and meaningful use of EHRs. Can be considered a combination of MU, PQRS, and VBM Will generate a single composite score once performance in each of the four categories are compiled This score will be used to affect Medicare reimbursement. Composite scores above or below the mean will translate into positive or negative payment adjustments to the base rate of Medicare Part B payments accordingly The potential maximum adjustment increases each year from 2019 to 2022, when the maximum adjustment is a gain or loss of 9% To keep the MACRA budget neutral, it will allow the positive adjustment to be scaled up to three times greater (presumably if there are more losers than winners) Therefore, the true swing will be from a 9% loss to a 27% gain APM: Only available to groups that CMS categorize as either an “APM” or “advanced APM”; details about how a group qualifies for APM status have not been released For groups that quality under the Comprehensive Primary Care Plus (CPC+) model, the Next Generation ACO model, and others Rewards a lump sum payment, but involves more risk for the group So, for now, keep doing what you’re doing with quality reporting. But be on the lookout for more MACRA information! Tags: Uncategorized
<reponame>k4leung4/fulcio // // Copyright 2022 The Sigstore Authors. // // 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. // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.1 // protoc v3.12.4 // source: fulcio.proto package protobuf import ( _ "google.golang.org/genproto/googleapis/api/annotations" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type PublicKeyAlgorithm int32 const ( PublicKeyAlgorithm_PUBLIC_KEY_ALGORITHM_UNSPECIFIED PublicKeyAlgorithm = 0 PublicKeyAlgorithm_RSA_PSS PublicKeyAlgorithm = 1 PublicKeyAlgorithm_ECDSA PublicKeyAlgorithm = 2 PublicKeyAlgorithm_ED25519 PublicKeyAlgorithm = 3 ) // Enum value maps for PublicKeyAlgorithm. var ( PublicKeyAlgorithm_name = map[int32]string{ 0: "PUBLIC_KEY_ALGORITHM_UNSPECIFIED", 1: "RSA_PSS", 2: "ECDSA", 3: "ED25519", } PublicKeyAlgorithm_value = map[string]int32{ "PUBLIC_KEY_ALGORITHM_UNSPECIFIED": 0, "RSA_PSS": 1, "ECDSA": 2, "ED25519": 3, } ) func (x PublicKeyAlgorithm) Enum() *PublicKeyAlgorithm { p := new(PublicKeyAlgorithm) *p = x return p } func (x PublicKeyAlgorithm) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (PublicKeyAlgorithm) Descriptor() protoreflect.EnumDescriptor { return file_fulcio_proto_enumTypes[0].Descriptor() } func (PublicKeyAlgorithm) Type() protoreflect.EnumType { return &file_fulcio_proto_enumTypes[0] } func (x PublicKeyAlgorithm) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use PublicKeyAlgorithm.Descriptor instead. func (PublicKeyAlgorithm) EnumDescriptor() ([]byte, []int) { return file_fulcio_proto_rawDescGZIP(), []int{0} } type CreateSigningCertificateRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // // Identity information about who possesses the private / public key pair presented Credentials *Credentials `protobuf:"bytes,1,opt,name=credentials,proto3" json:"credentials,omitempty"` // // The public key to be stored in the requested certificate PublicKey *PublicKey `protobuf:"bytes,2,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` // // Proof that the client possesses the private key; must be verifiable by provided public key // // This is a currently a signature over the `sub` claim from the OIDC identity token ProofOfPossession []byte `protobuf:"bytes,3,opt,name=proof_of_possession,json=proofOfPossession,proto3" json:"proof_of_possession,omitempty"` } func (x *CreateSigningCertificateRequest) Reset() { *x = CreateSigningCertificateRequest{} if protoimpl.UnsafeEnabled { mi := &file_fulcio_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *CreateSigningCertificateRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*CreateSigningCertificateRequest) ProtoMessage() {} func (x *CreateSigningCertificateRequest) ProtoReflect() protoreflect.Message { mi := &file_fulcio_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CreateSigningCertificateRequest.ProtoReflect.Descriptor instead. func (*CreateSigningCertificateRequest) Descriptor() ([]byte, []int) { return file_fulcio_proto_rawDescGZIP(), []int{0} } func (x *CreateSigningCertificateRequest) GetCredentials() *Credentials { if x != nil { return x.Credentials } return nil } func (x *CreateSigningCertificateRequest) GetPublicKey() *PublicKey { if x != nil { return x.PublicKey } return nil } func (x *CreateSigningCertificateRequest) GetProofOfPossession() []byte { if x != nil { return x.ProofOfPossession } return nil } type Credentials struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Types that are assignable to Credentials: // *Credentials_OidcIdentityToken Credentials isCredentials_Credentials `protobuf_oneof:"credentials"` } func (x *Credentials) Reset() { *x = Credentials{} if protoimpl.UnsafeEnabled { mi := &file_fulcio_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Credentials) String() string { return protoimpl.X.MessageStringOf(x) } func (*Credentials) ProtoMessage() {} func (x *Credentials) ProtoReflect() protoreflect.Message { mi := &file_fulcio_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Credentials.ProtoReflect.Descriptor instead. func (*Credentials) Descriptor() ([]byte, []int) { return file_fulcio_proto_rawDescGZIP(), []int{1} } func (m *Credentials) GetCredentials() isCredentials_Credentials { if m != nil { return m.Credentials } return nil } func (x *Credentials) GetOidcIdentityToken() string { if x, ok := x.GetCredentials().(*Credentials_OidcIdentityToken); ok { return x.OidcIdentityToken } return "" } type isCredentials_Credentials interface { isCredentials_Credentials() } type Credentials_OidcIdentityToken struct { // // The OIDC token that identifies the caller OidcIdentityToken string `protobuf:"bytes,1,opt,name=oidc_identity_token,json=oidcIdentityToken,proto3,oneof"` } func (*Credentials_OidcIdentityToken) isCredentials_Credentials() {} type PublicKey struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // // The cryptographic algorithm to use with the key material Algorithm PublicKeyAlgorithm `protobuf:"varint,1,opt,name=algorithm,proto3,enum=dev.sigstore.fulcio.v2.PublicKeyAlgorithm" json:"algorithm,omitempty"` // // PEM encoded public key Content string `protobuf:"bytes,2,opt,name=content,proto3" json:"content,omitempty"` } func (x *PublicKey) Reset() { *x = PublicKey{} if protoimpl.UnsafeEnabled { mi := &file_fulcio_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PublicKey) String() string { return protoimpl.X.MessageStringOf(x) } func (*PublicKey) ProtoMessage() {} func (x *PublicKey) ProtoReflect() protoreflect.Message { mi := &file_fulcio_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PublicKey.ProtoReflect.Descriptor instead. func (*PublicKey) Descriptor() ([]byte, []int) { return file_fulcio_proto_rawDescGZIP(), []int{2} } func (x *PublicKey) GetAlgorithm() PublicKeyAlgorithm { if x != nil { return x.Algorithm } return PublicKeyAlgorithm_PUBLIC_KEY_ALGORITHM_UNSPECIFIED } func (x *PublicKey) GetContent() string { if x != nil { return x.Content } return "" } type SigningCertificate struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Types that are assignable to Certificate: // *SigningCertificate_SignedCertificateDetachedSct // *SigningCertificate_SignedCertificateEmbeddedSct Certificate isSigningCertificate_Certificate `protobuf_oneof:"certificate"` } func (x *SigningCertificate) Reset() { *x = SigningCertificate{} if protoimpl.UnsafeEnabled { mi := &file_fulcio_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SigningCertificate) String() string { return protoimpl.X.MessageStringOf(x) } func (*SigningCertificate) ProtoMessage() {} func (x *SigningCertificate) ProtoReflect() protoreflect.Message { mi := &file_fulcio_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SigningCertificate.ProtoReflect.Descriptor instead. func (*SigningCertificate) Descriptor() ([]byte, []int) { return file_fulcio_proto_rawDescGZIP(), []int{3} } func (m *SigningCertificate) GetCertificate() isSigningCertificate_Certificate { if m != nil { return m.Certificate } return nil } func (x *SigningCertificate) GetSignedCertificateDetachedSct() *SigningCertificateDetachedSCT { if x, ok := x.GetCertificate().(*SigningCertificate_SignedCertificateDetachedSct); ok { return x.SignedCertificateDetachedSct } return nil } func (x *SigningCertificate) GetSignedCertificateEmbeddedSct() *SigningCertificateEmbeddedSCT { if x, ok := x.GetCertificate().(*SigningCertificate_SignedCertificateEmbeddedSct); ok { return x.SignedCertificateEmbeddedSct } return nil } type isSigningCertificate_Certificate interface { isSigningCertificate_Certificate() } type SigningCertificate_SignedCertificateDetachedSct struct { SignedCertificateDetachedSct *SigningCertificateDetachedSCT `protobuf:"bytes,1,opt,name=signed_certificate_detached_sct,json=signedCertificateDetachedSct,proto3,oneof"` } type SigningCertificate_SignedCertificateEmbeddedSct struct { SignedCertificateEmbeddedSct *SigningCertificateEmbeddedSCT `protobuf:"bytes,2,opt,name=signed_certificate_embedded_sct,json=signedCertificateEmbeddedSct,proto3,oneof"` } func (*SigningCertificate_SignedCertificateDetachedSct) isSigningCertificate_Certificate() {} func (*SigningCertificate_SignedCertificateEmbeddedSct) isSigningCertificate_Certificate() {} // (-- api-linter: core::0142::time-field-type=disabled // aip.dev/not-precedent: SCT is defined in RFC6962 and we keep the name consistent for easier understanding. --) type SigningCertificateDetachedSCT struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // // The certificate chain serialized with the leaf certificate first, followed // by all intermediate certificates (if present), finishing with the root certificate. // // All values are PEM-encoded certificates. Chain *CertificateChain `protobuf:"bytes,1,opt,name=chain,proto3" json:"chain,omitempty"` // // The signed certificate timestamp is a promise for including the certificate in // a certificate transparency log. It can be "stapled" to verify the inclusion of // a certificate in the log in an offline fashion. SignedCertificateTimestamp []byte `protobuf:"bytes,2,opt,name=signed_certificate_timestamp,json=signedCertificateTimestamp,proto3" json:"signed_certificate_timestamp,omitempty"` } func (x *SigningCertificateDetachedSCT) Reset() { *x = SigningCertificateDetachedSCT{} if protoimpl.UnsafeEnabled { mi := &file_fulcio_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SigningCertificateDetachedSCT) String() string { return protoimpl.X.MessageStringOf(x) } func (*SigningCertificateDetachedSCT) ProtoMessage() {} func (x *SigningCertificateDetachedSCT) ProtoReflect() protoreflect.Message { mi := &file_fulcio_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SigningCertificateDetachedSCT.ProtoReflect.Descriptor instead. func (*SigningCertificateDetachedSCT) Descriptor() ([]byte, []int) { return file_fulcio_proto_rawDescGZIP(), []int{4} } func (x *SigningCertificateDetachedSCT) GetChain() *CertificateChain { if x != nil { return x.Chain } return nil } func (x *SigningCertificateDetachedSCT) GetSignedCertificateTimestamp() []byte { if x != nil { return x.SignedCertificateTimestamp } return nil } type SigningCertificateEmbeddedSCT struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // // The certificate chain serialized with the leaf certificate first, followed // by all intermediate certificates (if present), finishing with the root certificate. // // All values are PEM-encoded certificates. Chain *CertificateChain `protobuf:"bytes,1,opt,name=chain,proto3" json:"chain,omitempty"` } func (x *SigningCertificateEmbeddedSCT) Reset() { *x = SigningCertificateEmbeddedSCT{} if protoimpl.UnsafeEnabled { mi := &file_fulcio_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SigningCertificateEmbeddedSCT) String() string { return protoimpl.X.MessageStringOf(x) } func (*SigningCertificateEmbeddedSCT) ProtoMessage() {} func (x *SigningCertificateEmbeddedSCT) ProtoReflect() protoreflect.Message { mi := &file_fulcio_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SigningCertificateEmbeddedSCT.ProtoReflect.Descriptor instead. func (*SigningCertificateEmbeddedSCT) Descriptor() ([]byte, []int) { return file_fulcio_proto_rawDescGZIP(), []int{5} } func (x *SigningCertificateEmbeddedSCT) GetChain() *CertificateChain { if x != nil { return x.Chain } return nil } // This is created for forward compatibility in case we want to add fields to the TrustBundle service in the future type GetTrustBundleRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *GetTrustBundleRequest) Reset() { *x = GetTrustBundleRequest{} if protoimpl.UnsafeEnabled { mi := &file_fulcio_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GetTrustBundleRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetTrustBundleRequest) ProtoMessage() {} func (x *GetTrustBundleRequest) ProtoReflect() protoreflect.Message { mi := &file_fulcio_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetTrustBundleRequest.ProtoReflect.Descriptor instead. func (*GetTrustBundleRequest) Descriptor() ([]byte, []int) { return file_fulcio_proto_rawDescGZIP(), []int{6} } type TrustBundle struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // // The set of PEM-encoded certificate chains for this Fulcio instance; each chain will start with any // intermediate certificates (if present), finishing with the root certificate. Chains []*CertificateChain `protobuf:"bytes,1,rep,name=chains,proto3" json:"chains,omitempty"` } func (x *TrustBundle) Reset() { *x = TrustBundle{} if protoimpl.UnsafeEnabled { mi := &file_fulcio_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TrustBundle) String() string { return protoimpl.X.MessageStringOf(x) } func (*TrustBundle) ProtoMessage() {} func (x *TrustBundle) ProtoReflect() protoreflect.Message { mi := &file_fulcio_proto_msgTypes[7] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TrustBundle.ProtoReflect.Descriptor instead. func (*TrustBundle) Descriptor() ([]byte, []int) { return file_fulcio_proto_rawDescGZIP(), []int{7} } func (x *TrustBundle) GetChains() []*CertificateChain { if x != nil { return x.Chains } return nil } type CertificateChain struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // // The PEM-encoded certificate chain, ordered from leaf to intermediate to root as applicable. Certificates []string `protobuf:"bytes,1,rep,name=certificates,proto3" json:"certificates,omitempty"` } func (x *CertificateChain) Reset() { *x = CertificateChain{} if protoimpl.UnsafeEnabled { mi := &file_fulcio_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *CertificateChain) String() string { return protoimpl.X.MessageStringOf(x) } func (*CertificateChain) ProtoMessage() {} func (x *CertificateChain) ProtoReflect() protoreflect.Message { mi := &file_fulcio_proto_msgTypes[8] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CertificateChain.ProtoReflect.Descriptor instead. func (*CertificateChain) Descriptor() ([]byte, []int) { return file_fulcio_proto_rawDescGZIP(), []int{8} } func (x *CertificateChain) GetCertificates() []string { if x != nil { return x.Certificates } return nil } var File_fulcio_proto protoreflect.FileDescriptor var file_fulcio_proto_rawDesc = []byte{ 0x0a, 0x0c, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x16, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2e, 0x76, 0x32, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x5f, 0x62, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xe9, 0x01, 0x0a, 0x1f, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x53, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x4a, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x23, 0x2e, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x43, 0x72, 0x65, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x73, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x0b, 0x63, 0x72, 0x65, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x73, 0x12, 0x45, 0x0a, 0x0a, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65, 0x79, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x09, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65, 0x79, 0x12, 0x33, 0x0a, 0x13, 0x70, 0x72, 0x6f, 0x6f, 0x66, 0x5f, 0x6f, 0x66, 0x5f, 0x70, 0x6f, 0x73, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x11, 0x70, 0x72, 0x6f, 0x6f, 0x66, 0x4f, 0x66, 0x50, 0x6f, 0x73, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x4e, 0x0a, 0x0b, 0x43, 0x72, 0x65, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x73, 0x12, 0x30, 0x0a, 0x13, 0x6f, 0x69, 0x64, 0x63, 0x5f, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x11, 0x6f, 0x69, 0x64, 0x63, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x42, 0x0d, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x73, 0x22, 0x74, 0x0a, 0x09, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65, 0x79, 0x12, 0x48, 0x0a, 0x09, 0x61, 0x6c, 0x67, 0x6f, 0x72, 0x69, 0x74, 0x68, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2a, 0x2e, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65, 0x79, 0x41, 0x6c, 0x67, 0x6f, 0x72, 0x69, 0x74, 0x68, 0x6d, 0x52, 0x09, 0x61, 0x6c, 0x67, 0x6f, 0x72, 0x69, 0x74, 0x68, 0x6d, 0x12, 0x1d, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x22, 0xa3, 0x02, 0x0a, 0x12, 0x53, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x12, 0x7e, 0x0a, 0x1f, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x64, 0x5f, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x5f, 0x64, 0x65, 0x74, 0x61, 0x63, 0x68, 0x65, 0x64, 0x5f, 0x73, 0x63, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x35, 0x2e, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x53, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x44, 0x65, 0x74, 0x61, 0x63, 0x68, 0x65, 0x64, 0x53, 0x43, 0x54, 0x48, 0x00, 0x52, 0x1c, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x64, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x44, 0x65, 0x74, 0x61, 0x63, 0x68, 0x65, 0x64, 0x53, 0x63, 0x74, 0x12, 0x7e, 0x0a, 0x1f, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x64, 0x5f, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x5f, 0x65, 0x6d, 0x62, 0x65, 0x64, 0x64, 0x65, 0x64, 0x5f, 0x73, 0x63, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x35, 0x2e, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x53, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x45, 0x6d, 0x62, 0x65, 0x64, 0x64, 0x65, 0x64, 0x53, 0x43, 0x54, 0x48, 0x00, 0x52, 0x1c, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x64, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x45, 0x6d, 0x62, 0x65, 0x64, 0x64, 0x65, 0x64, 0x53, 0x63, 0x74, 0x42, 0x0d, 0x0a, 0x0b, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x22, 0xa1, 0x01, 0x0a, 0x1d, 0x53, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x44, 0x65, 0x74, 0x61, 0x63, 0x68, 0x65, 0x64, 0x53, 0x43, 0x54, 0x12, 0x3e, 0x0a, 0x05, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x52, 0x05, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x12, 0x40, 0x0a, 0x1c, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x64, 0x5f, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x1a, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x64, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x22, 0x5f, 0x0a, 0x1d, 0x53, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x45, 0x6d, 0x62, 0x65, 0x64, 0x64, 0x65, 0x64, 0x53, 0x43, 0x54, 0x12, 0x3e, 0x0a, 0x05, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x52, 0x05, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x22, 0x17, 0x0a, 0x15, 0x47, 0x65, 0x74, 0x54, 0x72, 0x75, 0x73, 0x74, 0x42, 0x75, 0x6e, 0x64, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x4f, 0x0a, 0x0b, 0x54, 0x72, 0x75, 0x73, 0x74, 0x42, 0x75, 0x6e, 0x64, 0x6c, 0x65, 0x12, 0x40, 0x0a, 0x06, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x52, 0x06, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x73, 0x22, 0x36, 0x0a, 0x10, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x12, 0x22, 0x0a, 0x0c, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0c, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x73, 0x2a, 0x5f, 0x0a, 0x12, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65, 0x79, 0x41, 0x6c, 0x67, 0x6f, 0x72, 0x69, 0x74, 0x68, 0x6d, 0x12, 0x24, 0x0a, 0x20, 0x50, 0x55, 0x42, 0x4c, 0x49, 0x43, 0x5f, 0x4b, 0x45, 0x59, 0x5f, 0x41, 0x4c, 0x47, 0x4f, 0x52, 0x49, 0x54, 0x48, 0x4d, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0b, 0x0a, 0x07, 0x52, 0x53, 0x41, 0x5f, 0x50, 0x53, 0x53, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x45, 0x43, 0x44, 0x53, 0x41, 0x10, 0x02, 0x12, 0x0b, 0x0a, 0x07, 0x45, 0x44, 0x32, 0x35, 0x35, 0x31, 0x39, 0x10, 0x03, 0x32, 0xaa, 0x02, 0x0a, 0x02, 0x43, 0x41, 0x12, 0x9f, 0x01, 0x0a, 0x18, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x53, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x12, 0x37, 0x2e, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x53, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2a, 0x2e, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x53, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x22, 0x1e, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x18, 0x22, 0x13, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x76, 0x32, 0x2f, 0x73, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x43, 0x65, 0x72, 0x74, 0x3a, 0x01, 0x2a, 0x12, 0x81, 0x01, 0x0a, 0x0e, 0x47, 0x65, 0x74, 0x54, 0x72, 0x75, 0x73, 0x74, 0x42, 0x75, 0x6e, 0x64, 0x6c, 0x65, 0x12, 0x2d, 0x2e, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x47, 0x65, 0x74, 0x54, 0x72, 0x75, 0x73, 0x74, 0x42, 0x75, 0x6e, 0x64, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2e, 0x76, 0x32, 0x2e, 0x54, 0x72, 0x75, 0x73, 0x74, 0x42, 0x75, 0x6e, 0x64, 0x6c, 0x65, 0x22, 0x1b, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x15, 0x12, 0x13, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x76, 0x32, 0x2f, 0x74, 0x72, 0x75, 0x73, 0x74, 0x42, 0x75, 0x6e, 0x64, 0x6c, 0x65, 0x42, 0x5a, 0x0a, 0x16, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2e, 0x76, 0x32, 0x42, 0x0b, 0x46, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x31, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2f, 0x66, 0x75, 0x6c, 0x63, 0x69, 0x6f, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x64, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_fulcio_proto_rawDescOnce sync.Once file_fulcio_proto_rawDescData = file_fulcio_proto_rawDesc ) func file_fulcio_proto_rawDescGZIP() []byte { file_fulcio_proto_rawDescOnce.Do(func() { file_fulcio_proto_rawDescData = protoimpl.X.CompressGZIP(file_fulcio_proto_rawDescData) }) return file_fulcio_proto_rawDescData } var file_fulcio_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_fulcio_proto_msgTypes = make([]protoimpl.MessageInfo, 9) var file_fulcio_proto_goTypes = []interface{}{ (PublicKeyAlgorithm)(0), // 0: dev.sigstore.fulcio.v2.PublicKeyAlgorithm (*CreateSigningCertificateRequest)(nil), // 1: dev.sigstore.fulcio.v2.CreateSigningCertificateRequest (*Credentials)(nil), // 2: dev.sigstore.fulcio.v2.Credentials (*PublicKey)(nil), // 3: dev.sigstore.fulcio.v2.PublicKey (*SigningCertificate)(nil), // 4: dev.sigstore.fulcio.v2.SigningCertificate (*SigningCertificateDetachedSCT)(nil), // 5: dev.sigstore.fulcio.v2.SigningCertificateDetachedSCT (*SigningCertificateEmbeddedSCT)(nil), // 6: dev.sigstore.fulcio.v2.SigningCertificateEmbeddedSCT (*GetTrustBundleRequest)(nil), // 7: dev.sigstore.fulcio.v2.GetTrustBundleRequest (*TrustBundle)(nil), // 8: dev.sigstore.fulcio.v2.TrustBundle (*CertificateChain)(nil), // 9: dev.sigstore.fulcio.v2.CertificateChain } var file_fulcio_proto_depIdxs = []int32{ 2, // 0: dev.sigstore.fulcio.v2.CreateSigningCertificateRequest.credentials:type_name -> dev.sigstore.fulcio.v2.Credentials 3, // 1: dev.sigstore.fulcio.v2.CreateSigningCertificateRequest.public_key:type_name -> dev.sigstore.fulcio.v2.PublicKey 0, // 2: dev.sigstore.fulcio.v2.PublicKey.algorithm:type_name -> dev.sigstore.fulcio.v2.PublicKeyAlgorithm 5, // 3: dev.sigstore.fulcio.v2.SigningCertificate.signed_certificate_detached_sct:type_name -> dev.sigstore.fulcio.v2.SigningCertificateDetachedSCT 6, // 4: dev.sigstore.fulcio.v2.SigningCertificate.signed_certificate_embedded_sct:type_name -> dev.sigstore.fulcio.v2.SigningCertificateEmbeddedSCT 9, // 5: dev.sigstore.fulcio.v2.SigningCertificateDetachedSCT.chain:type_name -> dev.sigstore.fulcio.v2.CertificateChain 9, // 6: dev.sigstore.fulcio.v2.SigningCertificateEmbeddedSCT.chain:type_name -> dev.sigstore.fulcio.v2.CertificateChain 9, // 7: dev.sigstore.fulcio.v2.TrustBundle.chains:type_name -> dev.sigstore.fulcio.v2.CertificateChain 1, // 8: dev.sigstore.fulcio.v2.CA.CreateSigningCertificate:input_type -> dev.sigstore.fulcio.v2.CreateSigningCertificateRequest 7, // 9: dev.sigstore.fulcio.v2.CA.GetTrustBundle:input_type -> dev.sigstore.fulcio.v2.GetTrustBundleRequest 4, // 10: dev.sigstore.fulcio.v2.CA.CreateSigningCertificate:output_type -> dev.sigstore.fulcio.v2.SigningCertificate 8, // 11: dev.sigstore.fulcio.v2.CA.GetTrustBundle:output_type -> dev.sigstore.fulcio.v2.TrustBundle 10, // [10:12] is the sub-list for method output_type 8, // [8:10] is the sub-list for method input_type 8, // [8:8] is the sub-list for extension type_name 8, // [8:8] is the sub-list for extension extendee 0, // [0:8] is the sub-list for field type_name } func init() { file_fulcio_proto_init() } func file_fulcio_proto_init() { if File_fulcio_proto != nil { return } if !protoimpl.UnsafeEnabled { file_fulcio_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*CreateSigningCertificateRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_fulcio_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Credentials); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_fulcio_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PublicKey); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_fulcio_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SigningCertificate); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_fulcio_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SigningCertificateDetachedSCT); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_fulcio_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SigningCertificateEmbeddedSCT); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_fulcio_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetTrustBundleRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_fulcio_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TrustBundle); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_fulcio_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*CertificateChain); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } file_fulcio_proto_msgTypes[1].OneofWrappers = []interface{}{ (*Credentials_OidcIdentityToken)(nil), } file_fulcio_proto_msgTypes[3].OneofWrappers = []interface{}{ (*SigningCertificate_SignedCertificateDetachedSct)(nil), (*SigningCertificate_SignedCertificateEmbeddedSct)(nil), } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_fulcio_proto_rawDesc, NumEnums: 1, NumMessages: 9, NumExtensions: 0, NumServices: 1, }, GoTypes: file_fulcio_proto_goTypes, DependencyIndexes: file_fulcio_proto_depIdxs, EnumInfos: file_fulcio_proto_enumTypes, MessageInfos: file_fulcio_proto_msgTypes, }.Build() File_fulcio_proto = out.File file_fulcio_proto_rawDesc = nil file_fulcio_proto_goTypes = nil file_fulcio_proto_depIdxs = nil }
/** * Copyright (c) 2015-2016 YCSB contributors. All rights reserved. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. See accompanying * LICENSE file. */ package com.yahoo.ycsb.db; import com.yahoo.ycsb.*; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Vector; /** * This is a client implementation for Infinispan 5.x in client-server mode. */ public class InfinispanRemoteClient extends DB { private static final Log LOGGER = LogFactory.getLog(InfinispanRemoteClient.class); private RemoteCacheManager remoteIspnManager; private String cacheName = null; @Override public void init() throws DBException { remoteIspnManager = RemoteCacheManagerHolder.getInstance(getProperties()); cacheName = getProperties().getProperty("cache"); } @Override public void cleanup() { remoteIspnManager.stop(); remoteIspnManager = null; } @Override public Status insert(String table, String recordKey, HashMap<String, ByteIterator> values) { String compositKey = createKey(table, recordKey); Map<String, String> stringValues = new HashMap<>(); StringByteIterator.putAllAsStrings(stringValues, values); try { cache().put(compositKey, stringValues); return Status.OK; } catch (Exception e) { LOGGER.error(e); return Status.ERROR; } } @Override public Status read(String table, String recordKey, Set<String> fields, HashMap<String, ByteIterator> result) { String compositKey = createKey(table, recordKey); try { Map<String, String> values = cache().get(compositKey); if (values == null || values.isEmpty()) { return Status.NOT_FOUND; } if (fields == null) { //get all field/value pairs StringByteIterator.putAllAsByteIterators(result, values); } else { for (String field : fields) { String value = values.get(field); if (value != null) { result.put(field, new StringByteIterator(value)); } } } return Status.OK; } catch (Exception e) { LOGGER.error(e); return Status.ERROR; } } @Override public Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { LOGGER.warn("Infinispan does not support scan semantics"); return Status.NOT_IMPLEMENTED; } @Override public Status update(String table, String recordKey, HashMap<String, ByteIterator> values) { String compositKey = createKey(table, recordKey); try { Map<String, String> stringValues = new HashMap<>(); StringByteIterator.putAllAsStrings(stringValues, values); cache().put(compositKey, stringValues); return Status.OK; } catch (Exception e) { LOGGER.error(e); return Status.ERROR; } } @Override public Status delete(String table, String recordKey) { String compositKey = createKey(table, recordKey); try { cache().remove(compositKey); return Status.OK; } catch (Exception e) { LOGGER.error(e); return Status.ERROR; } } private RemoteCache<String, Map<String, String>> cache() { if (this.cacheName != null) { return remoteIspnManager.getCache(cacheName); } else { return remoteIspnManager.getCache(); } } private String createKey(String table, String recordKey) { return table + "-" + recordKey; } }
<gh_stars>10-100 package com.opencredo.concursus.domain.events.indexing; import com.opencredo.concursus.domain.common.AggregateId; import java.util.Set; /** * Finds aggregate ids by parameter name/value pairs. */ @FunctionalInterface public interface EventIndex { /** * Find all the aggregates for which the most recently-observed event parameter of the given name had the given value. * @param parameterName The parameter name to search for. * @param parameterValue The parameter value to search for. * @return All matching aggregate ids. */ Set<AggregateId> findAggregates(String parameterName, Object parameterValue); }
#ifndef OPENPOSE_WRAPPER_WRAPPER_STRUCT_HAND_HPP #define OPENPOSE_WRAPPER_WRAPPER_STRUCT_HAND_HPP #include <openpose/core/common.hpp> #include <openpose/core/enumClasses.hpp> #include <openpose/hand/handParameters.hpp> #include <openpose/wrapper/enumClasses.hpp> namespace op { /** * WrapperStructHand: Hand estimation and rendering configuration struct. * WrapperStructHand allows the user to set up the hand estimation and rendering parameters that will be used for * the OpenPose WrapperT template and Wrapper class. */ struct OP_API WrapperStructHand { /** * Whether to extract hand. */ bool enable; /** * Kind of hand rectangle detector. Recommended Detector::Body (fastest one if body is enabled and most * accurate one), which is based on the OpenPose body keypoint detector. * For hand, there is the alternative of Detector::BodyWithTracking. If selected, it will add tracking * between frames. Adding hand tracking might improve hand keypoints detection for webcam (if the frame * rate is high enough, i.e., >7 FPS per GPU) and video. This is not person ID tracking, it simply looks * for hands in positions at which hands were located in previous frames, but it does not guarantee the * same person id among frames. */ Detector detector; /** * CCN (Conv Net) input size. * The greater, the slower and more memory it will be needed, but it will potentially increase accuracy. * Both width and height must be divisible by 16. */ Point<int> netInputSize; /** * Number of scales to process. * The greater, the slower and more memory it will be needed, but it will potentially increase accuracy. * This parameter is related with scaleRange, such as the final pose estimation will be an average of the * predicted results for each scale. */ int scalesNumber; /** * Total range between smallest and biggest scale. The scales will be centered in ratio 1. E.g., if * scaleRange = 0.4 and scalesNumber = 2, then there will be 2 scales, 0.8 and 1.2. */ float scaleRange; /** * Whether to render the output (pose locations, body, background or PAF heat maps) with CPU or GPU. * Select `None` for no rendering, `Cpu` or `Gpu` por CPU and GPU rendering respectively. */ RenderMode renderMode; /** * Rendering blending alpha value of the pose point locations with respect to the background image. * Value in the range [0, 1]. 0 will only render the background, 1 will fully render the pose. */ float alphaKeypoint; /** * Rendering blending alpha value of the heat maps (hand part, background or PAF) with respect to the * background image. * Value in the range [0, 1]. 0 will only render the background, 1 will only render the heat map. */ float alphaHeatMap; /** * Rendering threshold. Only estimated keypoints whose score confidences are higher than this value will be * rendered. Note: Rendered refers only to visual display in the OpenPose basic GUI, not in the saved results. * Generally, a high threshold (> 0.5) will only render very clear body parts; while small thresholds * (~0.1) will also output guessed and occluded keypoints, but also more false positives (i.e., wrong * detections). */ float renderThreshold; /** * Constructor of the struct. * It has the recommended and default values we recommend for each element of the struct. * Since all the elements of the struct are public, they can also be manually filled. */ WrapperStructHand( const bool enable = false, const Detector detector = Detector::Body, const Point<int>& netInputSize = Point<int>{368, 368}, const int scalesNumber = 1, const float scaleRange = 0.4f, const RenderMode renderMode = RenderMode::Auto, const float alphaKeypoint = HAND_DEFAULT_ALPHA_KEYPOINT, const float alphaHeatMap = HAND_DEFAULT_ALPHA_HEAT_MAP, const float renderThreshold = 0.2f); }; } #endif // OPENPOSE_WRAPPER_WRAPPER_STRUCT_HAND_HPP
/** * A class field. */ public class JvmField extends Field { private String type; private boolean isStatic; private String declaringClassId; /** No-arg constructor, use setters or fromMap() to populate the object. */ public JvmField() {} /** * Single-arg constructor, use setters or fromMap() to populate the object. * Used during deserialization. * @param id a unique deserialization id */ public JvmField(String id) { this.id = id; } /** * Normal object constructor. * @param position the source position * @param sourceFileName the source file * @param source true if the field appears in source code * @param name the name of the field * @param symbolId the unique symbol id * @param type the type of the field * @param declaringClassId the symbol id of the enclosing type * @param isStatic true if this is a static field */ public JvmField(Position position, String sourceFileName, boolean source, String name, String symbolId, String type, String declaringClassId, boolean isStatic) { super(position, sourceFileName, source, name, symbolId); this.type = type; this.declaringClassId = declaringClassId; this.isStatic = isStatic; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isStatic() { return isStatic; } public void setStatic(boolean aStatic) { isStatic = aStatic; } public String getDeclaringClassId() { return declaringClassId; } public void setDeclaringClassId(String declaringClassId) { this.declaringClassId = declaringClassId; } @Override protected void saveTo(Map<String, Object> map) { super.saveTo(map); map.put("type", getType()); map.put("isStatic", isStatic()); map.put("declaringClassId", getDeclaringClassId()); } @Override public void fromMap(Map<String, Object> map){ super.fromMap(map); setType((String) map.get("type")); setStatic((Boolean) map.get("isStatic")); setDeclaringClassId((String) map.get("declaringClassId")); } @Override public boolean equals(Object that) { if (this == that) return true; if (!(that instanceof JvmField)) return false; JvmField field = (JvmField) that; return super.equals(field) && Objects.equals(type, field.type) && Objects.equals(isStatic, field.isStatic) && Objects.equals(declaringClassId, field.declaringClassId); } @Override public int hashCode() { return Objects.hash(super.hashCode(), type, isStatic, declaringClassId); } }
Ad blockers are often painted as the enemy of online publishers, but sometimes things are more complicated. AdBlock Plus, for example, just announced that they’re working with startup Flattr on a new product that allows readers to pay the publishers who produce the content they read, listen to and watch. As a result of the partnership, AdBlock Plus said it has also made a small investment of undisclosed size in Flattr . Together, the two companies have created a new product called Flattr Plus. Like Flattr itself, it allows users to allocate a monthly budget that they want to pay publishers. Unlike Flattr, users don’t have to click a button to “Flattr” a website — instead, it will automatically track their browsing activity and distribute the money based on their engagement. It sounds somewhat similar to the way a company like Spotify distributes subscription fees to musicians — except it’s not just for artists on a single website or app. Plus, the question of exactly how to calculate engagement is a tricky one. You probably don’t want to reward a worthless article with a dumb-but-effective clickbait headline. You might also leave an article open for hours without actually reading it. Ben Williams, who leads communication and operations at AdBlock Plus, told me that the product is still in beta testing (the plan is to do a full launch later this year) partly so the team can experiment with ways to measure engagement — it will involve some combination of factors like time spent and scroll activity. Publishers will have to sign up with Flattr Plus if they want to get paid, b ut Williams said that if they’re don’t, the money they’re due will be held for them until they join the program . (Update: Williams said that actually, AdBlock Plus won’t hold the money — it’ll just tell them how much money they could have earned.) The goal, he added, is to earn half a billion dollars in revenue for publishers next year. He doesn’t necessarily expect every AdBlock Plus user to volunteer to pay, but he predicted that many will — and when you’ve got 500 million downloads, just a small percentage of users paying a few dollars a month can add up. In fact, he said the AdBlock Plus users who opt out of seeing any advertising whatever (even if it’s part of the company’s acceptable ads program), are the ones who “have been the most vocal in asking for solutions like this.” Basically, these users have told the company they don’t like any ads, period, but they still want to support publishers and creators. Now we’ll get a chance to see if they meant it. Oh, and if you want to hear more about Flattr Plus and AdBlock Plus’ broader vision, I’ll be interviewing CEO Till Faida next week at Disrupt NY.
/** * Provides actions needed by the 'Script -> Run...' menu item. It uses a * file open dialog to request a script from the user and then executes the * script. */ private void loadAndRunScript() { FileDialog fd = new FileDialog(shell, SWT.OPEN); fd.setText("Select script to run"); fd.setFilterExtensions(IScriptEditor.SCRIPT_EXTNS); fd.setFilterNames(IScriptEditor.SCRIPT_NAMES); String result = fd.open(); if (null == result) { return; } executeTextScript(result); }
// TableStatsFromJSON loads statistic from JSONTable and return the Block of statistic. func TableStatsFromJSON(blockInfo *perceptron.TableInfo, physicalID int64, jsonTbl *JSONTable) (*statistics.Block, error) { newHistDefCausl := statistics.HistDefCausl{ PhysicalID: physicalID, HavePhysicalID: true, Count: jsonTbl.Count, ModifyCount: jsonTbl.ModifyCount, DeferredCausets: make(map[int64]*statistics.DeferredCauset, len(jsonTbl.DeferredCausets)), Indices: make(map[int64]*statistics.Index, len(jsonTbl.Indices)), } tbl := &statistics.Block{ HistDefCausl: newHistDefCausl, } for id, jsonIdx := range jsonTbl.Indices { for _, idxInfo := range blockInfo.Indices { if idxInfo.Name.L != id { continue } hist := statistics.HistogramFromProto(jsonIdx.Histogram) hist.ID, hist.NullCount, hist.LastUFIDelateVersion, hist.Correlation = idxInfo.ID, jsonIdx.NullCount, jsonIdx.LastUFIDelateVersion, jsonIdx.Correlation idx := &statistics.Index{ Histogram: *hist, CMSketch: statistics.CMSketchFromProto(jsonIdx.CMSketch), Info: idxInfo, } tbl.Indices[idx.ID] = idx } } for id, jsonDefCaus := range jsonTbl.DeferredCausets { for _, colInfo := range blockInfo.DeferredCausets { if colInfo.Name.L != id { continue } hist := statistics.HistogramFromProto(jsonDefCaus.Histogram) count := int64(hist.TotalRowCount()) sc := &stmtctx.StatementContext{TimeZone: time.UTC} hist, err := hist.ConvertTo(sc, &colInfo.FieldType) if err != nil { return nil, errors.Trace(err) } hist.ID, hist.NullCount, hist.LastUFIDelateVersion, hist.TotDefCausSize, hist.Correlation = colInfo.ID, jsonDefCaus.NullCount, jsonDefCaus.LastUFIDelateVersion, jsonDefCaus.TotDefCausSize, jsonDefCaus.Correlation col := &statistics.DeferredCauset{ PhysicalID: physicalID, Histogram: *hist, CMSketch: statistics.CMSketchFromProto(jsonDefCaus.CMSketch), Info: colInfo, Count: count, IsHandle: blockInfo.PKIsHandle && allegrosql.HasPriKeyFlag(colInfo.Flag), } tbl.DeferredCausets[col.ID] = col } } return tbl, nil }
<commit_msg>Move data directory in package <commit_before>import os.path as osp def get_data_dir(): this_dir = osp.dirname(osp.abspath(__file__)) return osp.realpath(osp.join(this_dir, '../data')) def get_logs_dir(): this_dir = osp.dirname(osp.abspath(__file__)) return osp.realpath(osp.join(this_dir, '../logs')) <commit_after>import os.path as osp def get_data_dir(): this_dir = osp.dirname(osp.abspath(__file__)) return osp.realpath(osp.join(this_dir, '_data'))
#include "Question198C.h" #include "../../Utility/AtCoderInOut.h" #include "../../Utility/Utility.h" #include <math.h> namespace Question198C { namespace { const char* INPUT_CASE[] = { R"(100000 100000 100000)", R"(5 11 0)", R"(3 4 4)", }; const char* OUTPUT_CASE[] = { R"(2)", R"(3)", R"(2)", }; static_assert(SIZEOF(OUTPUT_CASE) == SIZEOF(INPUT_CASE), "num of OUTPUT_CASE is invalid."); } // end of anonymous namespace. const char* AtCoderQuestion::GetInputCase(uint8_t index) const { if (index < SIZEOF(INPUT_CASE)) { return INPUT_CASE[index]; } return ""; } const char* AtCoderQuestion::GetOutputCase(uint8_t index) const { if (index < SIZEOF(OUTPUT_CASE)) { return OUTPUT_CASE[index]; } return ""; } AtCoderQuestion::AtCoderQuestion() : AtCoderQuestionBase<InputStruct, OutputStruct>() { m_numTestCase = SIZEOF(INPUT_CASE); } InputStruct AtCoderQuestion::Input() { InputStruct input; InputFormat("%d %d %d", &input.range, &input.x, &input.y); return input; } void AtCoderQuestion::Output(const OutputStruct& output, std::string* outStr) { OutputFormat(outStr, "%d", output.step); } OutputStruct AtCoderQuestion::Solver(const InputStruct& input) { long long power = (long long)input.x * (long long)input.x + (long long)input.y * (long long)input.y; double distance = sqrt(power); OutputStruct result; if (distance < input.range) { result.step = 2; } else { result.step = ceil(distance / input.range); } return result; } }
/* records transmitted from extern CDU to MX 4200 */ #define PMVXG_S_INITMODEA 0 /* initialization/mode part A */ #define PMVXG_S_INITMODEB 1 /* initialization/mode part B*/ #define PMVXG_S_SATHEALTH 2 /* satellite health control */ #define PMVXG_S_DIFFNAV 3 /* differential navigation control */ #define PMVXG_S_PORTCONF 7 /* control port configuration */ #define PMVXG_S_GETSELFTEST 13 /* self test (request results) */ #define PMVXG_S_RTCMCONF 16 /* RTCM port configuration */ #define PMVXG_S_PASSTHRU 17 /* equipment port pass-thru config */ #define PMVXG_S_RESTART 18 /* restart control */ #define PMVXG_S_OSCPARAM 19 /* oscillator parameter */ #define PMVXG_S_DOSELFTEST 20 /* self test (activate a test) */ #define PMVXG_S_TRECOVCONF 23 /* time recovery configuration */ #define PMVXG_S_RAWDATASEL 24 /* raw data port data selection */ #define PMVXG_S_EQUIPCONF 26 /* equipment port configuration */ #define PMVXG_S_RAWDATACONF 27 /* raw data port configuration */ /* records transmitted from MX 4200 to external CDU */ #define PMVXG_D_STATUS 0 /* status */ #define PMVXG_D_POSITION 1 /* position */ #define PMVXG_D_OPDOPS 3 /* (optimum) DOPs */ #define PMVXG_D_MODEDATA 4 /* mode data */ #define PMVXG_D_SATPRED 5 /* satellite predictions */ #define PMVXG_D_SATHEALTH 6 /* satellite health status */ #define PMVXG_D_UNRECOG 7 /* unrecognized request response */ #define PMVXG_D_SIGSTRLOC 8 /* sig strength & location (sats 1-4) */ #define PMVXG_D_SPEEDHEAD 11 /* speed/heading data */ #define PMVXG_D_OSELFTEST 12 /* (old) self-test results */ #define PMVXG_D_SIGSTRLOC2 18 /* sig strength & location (sats 5-8) */ #define PMVXG_D_OSCPARAM 19 /* oscillator parameter */ #define PMVXG_D_SELFTEST 20 /* self test results */ #define PMVXG_D_PHV 21 /* position, height & velocity */ #define PMVXG_D_DOPS 22 /* DOPs */ #define PMVXG_D_SOFTCONF 30 /* software configuration */ #define PMVXG_D_DIFFGPSMODE 503 /* differential gps moding */ #define PMVXG_D_TRECOVUSEAGE 523 /* time recovery usage */ #define PMVXG_D_RAWDATAOUT 524 /* raw data port data output */ #define PMVXG_D_TRECOVRESULT 828 /* time recovery results */ #define PMVXG_D_TRECOVOUT 830 /* time recovery output message */
/** * Created by thy humble Lovnag on 26.04.2017. * ( Just a small vector lib) */ public class Vector3 { private double x; private double y; private double z; public Vector3(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public double getX() { return x; } public double getY() { return y; } public double getZ() { return z; } public double theDotProduct(final Vector3 vect) { return x * vect.getX() + y * vect.getY() + z * vect.getZ(); } public double length() { return Math.sqrt(x * x + y * y + z * z); } public Vector3 theVectorProduct(final Vector3 vect) { return new Vector3(y * vect.getZ() - z * vect.getY(), z * vect.getX() - x * vect.getZ(), x * vect.getY() - y * vect.getX()); } public Vector3 theAddition(final Vector3 vect) { return new Vector3(x + vect.getX(), y + vect.getY(), z + vect.getZ()); } public Vector3 theSubstraction(final Vector3 vect) { return new Vector3(x - vect.getX(), y - vect.getY(), z - vect.getZ()); } public Vector3 theMultiplication(final double a) { return new Vector3(a * x, a * y, a * z); } }
# -*- coding: utf-8 -*- """CICID1.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1q-T0VLplhSabpHZXApgXDZsoW7aG3Hnw """ import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import matplotlib.pyplot as plt import time from sklearn.metrics import accuracy_score # Input data files are available in the "../input/" directory. # For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory import os #for dirname, _, filenames in os.walk('/content/drive/My Drive/Colab Notebooks/kshield_project/dataset'): # for filename in filenames: # print(filename) #print(os.path.join(dirname, filename)) # Any results you write to the current directory are saved as output. #/content/drive/My Drive/Colab Notebooks/kshield_project/dataset/cicids2017/MachineLearningCSV/MachineLearningCVE/Friday-WorkingHours-Afternoon-DDos.pcap_ISCX.csv pd.set_option('display.float_format', '{:.5f}'.format) df1=pd.read_csv("/content/drive/My Drive/Colab Notebooks/kshield_project/dataset/cicids2017/MachineLearningCSV/MachineLearningCVE/Friday-WorkingHours-Afternoon-DDos.pcap_ISCX.csv") df2=pd.read_csv("/content/drive/My Drive/Colab Notebooks/kshield_project/dataset/cicids2017/MachineLearningCSV/MachineLearningCVE/Friday-WorkingHours-Afternoon-PortScan.pcap_ISCX.csv") df3=pd.read_csv("/content/drive/My Drive/Colab Notebooks/kshield_project/dataset/cicids2017/MachineLearningCSV/MachineLearningCVE/Friday-WorkingHours-Morning.pcap_ISCX.csv") df4=pd.read_csv("/content/drive/My Drive/Colab Notebooks/kshield_project/dataset/cicids2017/MachineLearningCSV/MachineLearningCVE/Monday-WorkingHours.pcap_ISCX.csv") df5=pd.read_csv("/content/drive/My Drive/Colab Notebooks/kshield_project/dataset/cicids2017/MachineLearningCSV/MachineLearningCVE/Thursday-WorkingHours-Afternoon-Infilteration.pcap_ISCX.csv") df6=pd.read_csv("/content/drive/My Drive/Colab Notebooks/kshield_project/dataset/cicids2017/MachineLearningCSV/MachineLearningCVE/Thursday-WorkingHours-Morning-WebAttacks.pcap_ISCX.csv") df7=pd.read_csv("/content/drive/My Drive/Colab Notebooks/kshield_project/dataset/cicids2017/MachineLearningCSV/MachineLearningCVE/Tuesday-WorkingHours.pcap_ISCX.csv") df8=pd.read_csv("/content/drive/My Drive/Colab Notebooks/kshield_project/dataset/cicids2017/MachineLearningCSV/MachineLearningCVE/Wednesday-workingHours.pcap_ISCX.csv") df1.head() #import xgboost as xgb df=pd.concat([df1,df2,df3,df4,df5,df6,df7,df8]) del df1,df2,df3,df4,df5,df6,df7,df8 #df2=df[df.columns[6:-1]] #df=df2 #df2=[] #del df2 print(df) df=df.dropna( axis=0, how='any') df.info() label_list = list(df[df.columns[-1]]) label_type = list(set(label_list)) total=0 for i in label_type: num = label_list.count(i) print("%27s\t%d" % (i, num)) total += num print("total:",total) #df=df.replace(',,', np.nan, inplace=False) df=df.drop(columns=[' Fwd Header Length.1'], axis=1, inplace=False) df.replace("Infinity", 0, inplace=True) df['Flow Bytes/s'].replace("Infinity", 0,inplace=True) df[" Flow Packets/s"].replace("Infinity", 0, inplace=True) df[" Flow Packets/s"].replace(np.nan, 0, inplace=True) df['Flow Bytes/s'].replace(np.nan, 0,inplace=True) df["Bwd Avg Bulk Rate"].replace("Infinity", 0, inplace=True) df["Bwd Avg Bulk Rate"].replace(",,", 0, inplace=True) df["Bwd Avg Bulk Rate"].replace(np.nan, 0, inplace=True) df[" Bwd Avg Packets/Bulk"].replace("Infinity", 0, inplace=True) df[" Bwd Avg Packets/Bulk"].replace(",,", 0, inplace=True) df[" Bwd Avg Packets/Bulk"].replace(np.nan, 0, inplace=True) df[" Bwd Avg Bytes/Bulk"].replace("Infinity", 0, inplace=True) df[" Bwd Avg Bytes/Bulk"].replace(",,", 0, inplace=True) df[" Bwd Avg Bytes/Bulk"].replace(np.nan, 0, inplace=True) df[" Fwd Avg Bulk Rate"].replace("Infinity", 0, inplace=True) df[" Fwd Avg Bulk Rate"].replace(",,", 0, inplace=True) df[" Fwd Avg Bulk Rate"].replace(np.nan, 0, inplace=True) df[" Fwd Avg Packets/Bulk"].replace("Infinity", 0, inplace=True) df[" Fwd Avg Packets/Bulk"].replace(",,", 0, inplace=True) df[" Fwd Avg Packets/Bulk"].replace(np.nan, 0, inplace=True) df["Fwd Avg Bytes/Bulk"].replace("Infinity", 0, inplace=True) df["Fwd Avg Bytes/Bulk"].replace(",,", 0, inplace=True) df["Fwd Avg Bytes/Bulk"].replace(np.nan, 0, inplace=True) df[" CWE Flag Count"].replace("Infinity", 0, inplace=True) df[" CWE Flag Count"].replace(",,", 0, inplace=True) df[" CWE Flag Count"].replace(np.nan, 0, inplace=True) df[" Bwd URG Flags"].replace("Infinity", 0, inplace=True) df[" Bwd URG Flags"].replace(",,", 0, inplace=True) df[" Bwd URG Flags"].replace(np.nan, 0, inplace=True) df[" Bwd PSH Flags"].replace("Infinity", 0, inplace=True) df[" Bwd PSH Flags"].replace(",,", 0, inplace=True) df[" Bwd PSH Flags"].replace(np.nan, 0, inplace=True) df[" Fwd URG Flags"].replace("Infinity", 0, inplace=True) df[" Fwd URG Flags"].replace(",,", 0, inplace=True) df[" Fwd URG Flags"].replace(np.nan, 0, inplace=True) df["Flow Bytes/s"]=df["Flow Bytes/s"].astype("float64") df[' Flow Packets/s']=df[" Flow Packets/s"].astype("float64") df['Bwd Avg Bulk Rate']=df["Bwd Avg Bulk Rate"].astype("float64") df[' Bwd Avg Packets/Bulk']=df[" Bwd Avg Packets/Bulk"].astype("float64") df[' Bwd Avg Bytes/Bulk']=df[" Bwd Avg Bytes/Bulk"].astype("float64") df[' Fwd Avg Bulk Rate']=df[" Fwd Avg Bulk Rate"].astype("float64") df[' Fwd Avg Packets/Bulk']=df[" Fwd Avg Packets/Bulk"].astype("float64") df['Fwd Avg Bytes/Bulk']=df["Fwd Avg Bytes/Bulk"].astype("float64") df[' CWE Flag Count']=df[" CWE Flag Count"].astype("float64") df[' Bwd URG Flags']=df[" Bwd URG Flags"].astype("float64") df[' Bwd PSH Flags']=df[" Bwd PSH Flags"].astype("float64") df[' Fwd URG Flags']=df[" Fwd URG Flags"].astype("float64") df.replace('Infinity', 0.0, inplace=True) df.replace('NaN', 0.0, inplace=True) df.head() X=df[df.columns[0:-1]] y=df[df.columns[-1]] del df from scipy import stats cols = list(X.columns) for col in cols: X[col] = stats.zscore(X[col]) features=X.columns #features=[" Fwd Packet Length Max"," Flow IAT Std"," Fwd Packet Length Std" ,"Fwd IAT Total",' Flow Packets/s', " Fwd Packet Length Mean", "Flow Bytes/s", " Flow IAT Mean", " Bwd Packet Length Mean", " Flow IAT Max", " Bwd Packet Length Std", ] X=X[features].copy() X.dropna(axis=1, inplace=True) X.head() from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test=train_test_split(X,y,test_size=0.2, random_state=10) y_test_arr=y_test.to_numpy() #as_matrix() def calculate_metrics(true,false,not_detected): true_positive=0 true_negative=0 false_positive=0 false_negative=0 if 'BENIGN' in true: true_positive=sum(true.values())-true['BENIGN'] true_negative=true['BENIGN'] if 'BENIGN' in false: false_negative=false['BENIGN'] if 'BENIGN' in not_detected: false_positive=not_detected['BENIGN'] if true_positive+false_positive==0: precision="undefined" else: precision=(true_positive/(true_positive+false_positive))*100 if true_positive+false_negative ==0: recall="undefined" else: recall=(true_positive/(true_positive+false_negative))*100 accuracy=((true_positive+true_negative)/(true_positive+true_negative+false_positive+false_negative))*100 print("========================================") print(" True positives :: ", true_positive) print(" True negatives :: ", true_negative) print(" False positive :: ", false_positive) print(" False negative :: ", false_negative) print(" Accuracy :: ", accuracy) print(" Recall :: ", recall) print( " Precision :: ", precision) print("========================================") def calculate_confusion_matrix(y_test_arr,yhat): true={} false={} not_detected={} for x in range(len(y_test_arr)): if y_test_arr[x]==yhat[x]: if y_test_arr[x] in true: true[y_test_arr[x]]=true[y_test_arr[x]]+1 else: true[y_test_arr[x]]=1 elif y_test_arr[x]!=yhat[x]: if yhat[x] in false: false[yhat[x]]=false[yhat[x]]+1 if y_test_arr[x] in not_detected: not_detected[y_test_arr[x]]=not_detected[y_test_arr[x]]+1 else: not_detected[y_test_arr[x]]=1 else: false[yhat[x]]=1 if y_test_arr[x] in not_detected: not_detected[y_test_arr[x]]=not_detected[y_test_arr[x]]+1 else: not_detected[y_test_arr[x]]=1 calculate_metrics(true,false,not_detected) from sklearn.neighbors import KNeighborsClassifier from sklearn.feature_selection import SelectFromModel t1=time.time() knnselector = SelectFromModel(estimator=KNeighborsClassifier()).fit(X, y) columns = X.columns knn_selected = columns[knnselector.get_support()] print(knn_selected) knn=KNeighborsClassifier() model_knn=knn.fit(X_train,y_train) yhat=model_knn.predict(X_test) print("knn accuracy is : ", accuracy_score(y_test, yhat)) calculate_confusion_matrix(y_test_arr,yhat) t2=time.time() print(" time for knn :: ", (t2-t1)/60 , " minutes") #knn ''' t1=time.time() knn=KNeighborsClassifier() model_knn=knn.fit(X_train,y_train) yhat=model_knn.predict(X_test) print("knn accuracy is : ", accuracy_score(y_test, yhat)) calculate_confusion_matrix(y_test_arr,yhat) t2=time.time() print(" time for knn :: ", (t2-t1)/60 , " minutes") ''' #xgboost ''' from xgboost import XGBClassifier t1=time.time() xgb=XGBClassifier() model_xgb=xgb.fit(X_train, y_train) yhat=model_xgb.predict(X_test) print("xgb accuracy is : ", accuracy_score(y_test, yhat)) calculate_confusion_matrix(y_test_arr,yhat) t2=time.time() print(" time for xgb :: ", (t2-t1)/60 , " minutes") ''' #randomforest ''' from sklearn.ensemble import RandomForestClassifier t1=time.time() randromforest=RandomForestClassifier() model_randromforest=randromforest.fit(X_train, y_train) yhat=model_randromforest.predict(X_test) print("randromforest accuracy is : ", accuracy_score(y_test, yhat)) calculate_confusion_matrix(y_test_arr,yhat) t2=time.time() print(" time for randromforest :: ", (t2-t1)/60 , " minutes") ''' #for i in count: #for i in range(1,len(X_train.columns)+1): #knn=KNeighborsClassifier(n_neighbors=i) #model_knn=knn.fit(X_train,y_train) #yhat=model_knn.predict(X_test) #print("for " , i, " as K, accuracy is : ", accuracy_score(y_test, yhat)) #t2=time.time() #print(" time for ", i ," k's :: ", (t2-t1)/60 , " minutes") #calculate_confusion_matrix(y_test_arr,yhat)
<filename>packages/ipfs-w3auth/auth-handler/src/index.ts import {Request} from 'express'; import {AuthError} from './types'; import authRegistry from './authRegistry'; const _ = require('lodash'); const chainTypeDelimiter = '-'; const pkSigDelimiter = ':'; async function auth(req: Request, res: any, next: any) { // 1. Parse basic auth header 'Authorization: Basic [AuthToken]' if ( !_.includes(req.headers.authorization, 'Basic ') && !_.includes(req.headers.authorization, 'Bearer ') ) { res.writeHead(401, {'Content-Type': 'application/json'}); res.end( JSON.stringify({ Error: 'Empty Signature', }) ); return; } try { // 2. Decode AuthToken const base64Credentials = _.split( _.trim(req.headers.authorization), ' ' )[1]; const credentials = Buffer.from(base64Credentials, 'base64').toString( 'ascii' ); // 3. Parse AuthToken as `ChainType[substrate/eth/solana].PubKey:SignedMsg` const [passedAddress, sig] = _.split(credentials, pkSigDelimiter); console.log(`Got public address '${passedAddress}' and sigature '${sig}'`); // 4. Extract chain type, default: 'sub' if not specified const gaugedAddress = _.includes(passedAddress, chainTypeDelimiter) ? passedAddress : `sub${chainTypeDelimiter}${passedAddress}`; const [chainType, address, txMsg] = _.split( gaugedAddress, chainTypeDelimiter ); const result = await authRegistry.auth(chainType, { address, txMsg, signature: sig, }); if (result === true) { console.log( `Validate chainType: ${chainType} address: ${address} success` ); res.chainType = chainType; res.chainAddress = address; next(); } else { console.error('Validation failed'); res.writeHead(401, {'Content-Type': 'application/json'}); res.end( JSON.stringify({ Error: 'Invalid Signature', }) ); } } catch (error: any) { console.error(error.message); res.writeHead(401, {'Content-Type': 'application/json'}); res.end( JSON.stringify({ Error: error instanceof AuthError ? error.message : 'Invalid Signature', }) ); return; } } module.exports = auth;
This was the second(?) pic I've done where I've experimented with painting clouds and a background. I think they turned out well! And of course Derpy is happy as always :3 This was actually done before the Fluttershy portrait, so I was still figuring things out. Hope you like itIf anyone remembers my old sketch of Derpy that I intended to finish, but never did, think of this drawing as its successor. I may go back and redo the older one if any of you are interested, or if i have nothing else to draw.Also, Would you prefer I just set the display options for the uploads here at full original resolution, or leave it at 1600px wide, and the download at full res? Idk which looks better so I'd like to know what works best for you all! For comparison, The previous drawings of Fluttershy and Luna are set to 1600px display, while this is set at original resolution (when you click it to zoom in, you can zoom in a lot more.As you may notice now, downloading the full resolution file is now available. Its something I now am doing with all my art moving forward. You can alternatively get the full resolution image from my Patreon page free of charge.If you like my art, consider supporting me on Patreon: www.patreon.com/Xeirla My Little Pony © HasbroArt © 2016 Xeirla
def add_tags(self): c, setting = self.c, self.tags_setting aList = c.config.getData(setting) or [] aList = [z.lower() for z in aList] return aList
/** Class for TypeInstance for all nodes of type TRY_WITH_RESOURCE_TYPE. */ private static class TryWithResourceTypeInstance extends TypeInstance { private final Node<?, ? extends AutoCloseable> resourceNode; private TryWithResourceTypeInstance(Node<?, ? extends AutoCloseable> resourceNode) { this.resourceNode = resourceNode; } public Node<?, ? extends AutoCloseable> getResourceNode() { return resourceNode; } }
Not to be confused with "Give Hope Now" campaign by the American Red Cross The Hope Now Alliance is a cooperative effort between the US government, counselors, investors, and lenders to help homeowners who may not be able to pay their mortgages. Created in 2007[1] in response to the subprime mortgage crisis, the alliance claims to have helped over 1 million homeowners avoid foreclosure through January 2008. Critics of the alliance contend that the assistance provided does not go far enough,[2] and that not enough homeowners are being helped.[3] Creation [ edit ] On August 31, 2007 President George W. Bush asked Housing and Urban Development Secretary Alphonso Jackson and Treasury Secretary Henry Paulson to work with mortgage lenders, foreclosure counsellors, the Federal Housing Administration, Fannie Mae and Freddie Mac to launch a new "foreclosure avoidance initiative".[4] These discussions led to the creation of the Hope Now alliance, which was announced by Secretary Paulson on October 10, 2007.[5] At its inception the Alliance was composed of lenders representing 60% of all outstanding mortgages in the United States, counseling services, trade organizations and a group representing investors in mortgage backed securities.[5] Additional organizations joined over the following months.[6][7] Strategy [ edit ] The group promotes a national 24-hour toll-free telephone number (known as the Homeowner's HOPE Hotline), through which the Homeownership Preservation Foundation (a member) offers free counseling to homeowners concerned about foreclosure[8] It also encourages homeowners in difficulty to contact their lender directly, and provides on its website a list of contact for member organizations[9] Beginning in October 2007 mortgage lenders & servicing companies within the group reached out to homeowners with past due accounts via mail, giving information to them of the group and the assistance available. Over 200,000 letters were sent in the first batch, with additional mailings occurring in November, January & February 2008. In total one million letters have been sent.[10] Relief options [ edit ] Hope Now describes the assistance that it provides to homeowners as loan workouts, a form of loss mitigation. These workouts can either result in establishing a modified repayment plan with the homeowner to bring them up to date, or a loan modification where the terms of the mortgage are modified in order to make the loan serviceable for the homeowner. Results [ edit ] Since first being mentioned in December 2007, the Homeowner's HOPE Hotline received more than 140,000 calls in 2007 (including over 45,000 in the first three days), and an average of 3,200 calls per day in January 2008[11][12] There are claims that the group has not been effective at addressing the increasing problem of foreclosures in the United States, with recent figures indicating that the rate of foreclosures rising faster than the increase in homeowners helped.[3][13][14] It has also been noted that the majority of assistance provided by the group has been to establish repayment plans, rather than actually modifying the terms of the mortgage.[15] Concerns about the limitations of data collected by groups such as Hope Now led the Office of the Comptroller of the Currency to undertake its own investigation into foreclosures.[15] Membership [ edit ] A current list of Hope Now members is available here See also [ edit ]
/* After having computed ideal weights for the case where a weight exists for every texel, we want to compute the ideal weights for the case where weights exist only for some texels. We do this with a steepest-descent grid solver; this works as follows: * First, for each actual weight, perform a weighted averaging based on the texels affected by the weight. * Then, set step size to <some initial value> * Then, repeat: 1: First, compute for each weight how much the error will change if we change the weight by an infinitesimal amount. 2: This produces a vector that points the direction we should step in. Normalize this vector. 3: Perform a step 4: Check if the step actually improved the error. If it did, perform another step in the same direction; repeat until error no longer improves. If the *first* step did not improve error, then we halve the step size. 5: If the step size dropped down below <some threshold value>, then we quit, else we go back to #1. Subroutines: one routine to apply a step and compute the step's effect on the error one routine to compute the error change of an infinitesimal weight change Data structures needed: For every decimation pattern, we need: * For each weight, a list of <texel, weight> tuples that tell which texels the weight influences. * For each texel, a list of <texel, weight> tuples that tell which weights go into a given texel. */ float compute_error_of_weight_set( const endpoints_and_weights* eai, const decimation_table* it, const float* weights ) { vfloat verror_summa(0.0f); float error_summa = 0.0f; int texel_count = it->texel_count; int i = 0; #if ASTCENC_SIMD_WIDTH > 1 int clipped_texel_count = round_down_to_simd_multiple_vla(texel_count); for (; i < clipped_texel_count; i += ASTCENC_SIMD_WIDTH) { vint weight_idx0 = vint(&(it->texel_weights_4t[0][i])); vint weight_idx1 = vint(&(it->texel_weights_4t[1][i])); vint weight_idx2 = vint(&(it->texel_weights_4t[2][i])); vint weight_idx3 = vint(&(it->texel_weights_4t[3][i])); vfloat weight_val0 = gatherf(weights, weight_idx0); vfloat weight_val1 = gatherf(weights, weight_idx1); vfloat weight_val2 = gatherf(weights, weight_idx2); vfloat weight_val3 = gatherf(weights, weight_idx3); vfloat tex_weight_float0 = loada(&(it->texel_weights_float_4t[0][i])); vfloat tex_weight_float1 = loada(&(it->texel_weights_float_4t[1][i])); vfloat tex_weight_float2 = loada(&(it->texel_weights_float_4t[2][i])); vfloat tex_weight_float3 = loada(&(it->texel_weights_float_4t[3][i])); vfloat current_values = (weight_val0 * tex_weight_float0 + weight_val1 * tex_weight_float1) + (weight_val2 * tex_weight_float2 + weight_val3 * tex_weight_float3); vfloat actual_values = loada(&(eai->weights[i])); vfloat diff = current_values - actual_values; vfloat significance = loada(&(eai->weight_error_scale[i])); vfloat error = diff * diff * significance; verror_summa = verror_summa + error; } error_summa += hadd_s(verror_summa); #endif for (; i < texel_count; i++) { float current_value = (weights[it->texel_weights_4t[0][i]] * it->texel_weights_float_4t[0][i] + weights[it->texel_weights_4t[1][i]] * it->texel_weights_float_4t[1][i]) + (weights[it->texel_weights_4t[2][i]] * it->texel_weights_float_4t[2][i] + weights[it->texel_weights_4t[3][i]] * it->texel_weights_float_4t[3][i]); float valuedif = current_value - eai->weights[i]; float error = valuedif * valuedif * eai->weight_error_scale[i]; error_summa += error; } return error_summa; }
/** * Responsible for verifying the signature, returns true if the verification passed, false * otherwise. * * * @param key The public key used to verify the signature * @param signable Contains the data (seed) and signature * @return True if signature valid, false otherwise * @throws AnnotatorException */ private Boolean verifySignature(KeyInfo key, Signable signable) throws AnnotatorException { final SignProviderFactory signFactory = new SignProviderFactory(); final SignProvider signProvider; try { signProvider = signFactory.getProvider(key.getType()); } catch(SignException e) { throw new AnnotatorException("Could not instantiate signing provider", e); } try { final String publicKeyPath = key.getPath(); final String publicKey = Files.readString( Paths.get(publicKeyPath), StandardCharsets.US_ASCII); signProvider.verify( Encoder.hexToBytes(publicKey), signable.getSeed().getBytes(), Encoder.hexToBytes(signable.getSignature())); return true; } catch(SignException e) { return false; } catch(IOException e) { throw new AnnotatorException("Failed to load public key", e); } }
Call me a tightwad, but when I heard that Montreal had rental bikes you can pick up and drop off all over town for a mere $5 Canadian a day (about $4.85 U.S.), it was like angels singing. See the city, sample the local cuisine and work it off without paying usurious day rates at the gym. This I had to try. The bike system, called Bixi (think "bike" plus "taxi"), started last year in Montreal and proved so successful among both commuters and tourists that the technology has been exported to Minneapolis, London and Melbourne, Australia; Paris already has something similar. Boston and Washington, D.C., are to adopt Bixi systems this year. Bixi bikes are heavy and sturdy, with just three gears and a narrow turning radius, so they're not for racing or riding up, say, Mount Royal, the mountain park in the city center. For everything else, they're pretty darn great. With some 5,000 bikes at 400 solar-powered, wirelessly linked stations throughout the city, a Bixi is rarely more than a few blocks away (at least in busier neighborhoods). They're even a bit design-y: boomerang-shaped frame, wheel-powered generator for front and rear lights, front rack big enough for a small backpack, a tiny bell and an enclosure for the chain to prevent greasy pant legs. Montreal has about 280 miles of bike paths on streets, through parks and along waterways, including a part of La Route Verte, the Green Route through Quebec province. Bixi does have its limits. It operates in only three seasons, avoiding the bitter cold and snow; this year, it's scheduled to wrap up in November. Helmets aren't provided, and because bike paths don't go everywhere, the only option sometimes is to bike in traffic. Then there's the timing. Bixis must be returned within 30 minutes to avoid extra charges; timing is computer-monitored. The daily charge is $5.. For longer rides, it's much like changing buses. You get off one bike and check out another. You must wait five minutes between Bixis.
def display(): for good in goods: print(good.get("number"), good.get("stock"))
Inverse initial problem for fractional reaction-diffusion equation with nonlinearities The initial inverse problem of finding solutions and their initial values ($t = 0$) appearing in a general class of fractional reaction-diffusion equations from the knowledge of solutions at the final time ($t = T$). Our work focuses on the existence and regularity of mild solutions in two cases: \begin{itemize} \item The first case: The nonlinearity is globally Lipschitz and uniformly bounded which plays important roles in PDE theories, and especially in numerical analysis. \item The second case: The nonlinearity is locally critical which widely arises from the Navier-Stokes, Schr\"odinger, Burgers, Allen-Cahn, Ginzburg-Landau equations, etc. \end{itemize} Our solutions are local-in-time and are derived via fixed point arguments in suitable functional spaces. The key idea is to combine the theories of Mittag-Leffler functions and fractional Sobolev embeddings. To firm the effectiveness of our methods, we finally apply our main results to time fractional Navier-Stokes and Allen-Cahn equations. Introduction Let Ω be a C 2 bounded open set of R k , k ≥ 2, and let A be a symmetric and uniformly elliptic operator on Ω defined by where a ij ∈ C 1 Ω , b ∈ C Ω; , finance , hydrology . Note also that denoting by ∂ α * the Caputo fractional derivative operator of order α, the first equation of (1) with Riemann-Liouville derivative can be transformed into the following form where I 1−α t is the fractional integral of the order 1 − α defined by Let us observe that many mathematical studies have been devoted to the analysis of linear PDEs with time-fractional derivative. Without being exhaustive, we can mention the works of dealing with fractional diffusion equations with time-fractional derivatives, in the Caputo sense, in different contexts. We mention also the works of devoted to the regularity of solutions of such equations. Note that the presence of a nonlinear term increases considerably the difficulty of these problems, and so studying the regularity of solutions of nonlinear fractional PDEs is a challenge. In , the authors considered the existence, uniqueness, and regularity of a solution to the nonlinear time-fractional FokkerPlanck equations. Y. Kian and M. Yamamoto gave the existence of a local solution to a semilinear fractional wave equation. M. Warma et al investigated the existence and regularity of a global solution of a nonlinear time-fractional wave equation. B. Ahmad et al studied the existence and regularity of a solution to the time-fractional diffusion equations in Banach space. F. Camilli et al investigated the existence, uniqueness and regularity properties of a classical solution to the time-fractional Hamilton-Jacobi equation arising in Mean Field Games theory. Y. Giga et al established the existence, stability and some regularity results of a viscosity solution of the Hamilton-Jacobi equation with Caputos time-fractional derivative. Very recently, Y. Giga et al introduce a discrete scheme for second-order fully nonlinear parabolic PDEs with Caputo's time-fractional derivatives. Note that the initial value problem for (1) has a long history and has attracted much attention among the mathematical community. Both linear and nonlinear equations have been considered. In the linear case, corresponding to G = G(x, t), the work is one of the first works devoted to the fractional diffusion equations similar to Problem (1). The study of such equations received much attention such as . Note also that models with a singular kernel at the origin are well-known and arise in the heat conduction and viscoelasticity as well as other models (see ). We also mention some works that devoted to the study of (1) can be found in as well as in , where the regularity of solutions of a time-fractional diffusion equation similar to (1) has been considered. Numerical solutions of the alternative representation of Problem (1) have been studied in . In contrast to the linear case, nonlinear equations of the form Problem (1) with G = G(x, t, u) have received less attention. We can mention results like , where the authors studied the local well-posedness for the Cauchy problem of a semilinear fractional diffusion equation. Very recently, the work considered a family of nonlinear Volterra equations which is a generalization of model (1). The existence of a local mild solution to the problem and the continuous dependence concerning initial data have been discussed. Despite the numerous papers devoted to the study of the direct problem as mentioned above, as far as we know, the inverse initial problems (called terminal value problem, or backward problem) for fractional diffusion-wave equations have not been investigated widely. However, backward problems for fractional diffusion equations have an important role in some practical areas, where the recovery of the previous distribution of physical diffusion processes plays an important role in several areas. For instance, some engineering problems consist in determining the previous data of the physical field from its present state. Backward problems for time-fractional diffusions with Caputo derivative can be found in some recent works like . This paper aims to study the inverse initial value problem (1)- (2) for nonlinear fractional reactiondiffusion with respect to 0 < α < 1. We are particularly interested in the theory of existence, uniqueness, and regularity of solutions. Our analysis is motivated by the necessity for a rigorous study of a numerical scheme to approximate solutions in several applications. In our knowledge, regularity results on inverse initial value problems (final value problems) for fractional diffusion equations are still limited. We also emphasize that, to the best of our knowledge, there are no results devoted to the analysis of Problem (1)- (2). In what follows, we briefly present some difficulties that appear in the study of Problem (1)-(2): • A substitution cannot transfer the problem into the respective initial value problem since the Riemann-Liouville fractional derivative is locally defined. Indeed, for 0 < α < 1, • It is well-known that the Grönwall's inequality is a powerful tool to prove the well-posedness of initial value problems. Unfortunately, applying the Grönwall's inequality is not fitting to deal with inverse initial value problems containing non-locally fractional derivatives (see (8) and (12)). Besides, one cannot convert Problem (1)-(2) into a same form as (3). , t ≥ 0, which appear in the precise representation (see (12)) of solutions is weaker than E α,1 (−t α A) in the following senses and for fixed 0 ≤ s < 1, In addition, the representation (12) of solutions of Problem (1)-(2) is more complex than the respectively initial problem (8). This paper is organized as follows. In Section 2, we present some basic definitions and the setting for our work. Moreover, we obtain a precise representation of solutions by using Mittag-Leffler operators. In Section 3, we investigate the well-posedness, and regularity for Problem (1)-(2) under globally Lipschitz assumptions imposed on the source term. Furthermore, we also discuss regularity results for the mild solution. This section contains two main results. The first one is obtained by using the Banach fixed point theorem in the strongly final data case φ ∈ D(A), where A = A acts on L 2 (Ω) with domain D(A) = H 1 0 (Ω) ∩ H 2 (Ω). The regularity results for the solution and its derivative of the first order are studied by basing on some Sobolev embeddings. The second result concerns the problem in the weakly final data case φ ∈ D(A ζ ) with some 0 < ζ < 1. An important ingredient in the proof of this result arises from an applying of Picard iterations. The difficulty here comes from finding where solutions belong. In Section 4, we investigate the existence of a mild solution under a class of critical nonlinearities. As we know, nonlinear PDEs with critical nonlinearities are an interesting topic. We can mention this in Y. Giga and A. N. Carvalho et al ; W l1,q (Ω)). The main difficulty comes from the choice of involved parameters, especially, the choice of l 1 , l 2 , q. Finally, to firm the effectiveness of our methods, we give some applications to fractional Navier-Stokes and Allen-Cahn equations. Notations For a given Banach space X, we define by L ∞ (0, T ; X) the space of all essentially bounded measurable functions f on endowed with the norm f L ∞ (0,T ;X) := ess sup 0≤t≤T f (t) X . For 0 < σ < 1, we denote by C σ ( ; X) the subspace of C( ; X) satisfying For X 1 , X 2 two Banach spaces, we denote by L (X 1 , X 2 ) the space of all linear bounded operators S from X 1 to X 2 endowed with the norm To study Problem (1), we consider the operator A = A acting on L 2 (Ω) with domain D(A) = H 1 0 (Ω) ∩ H 2 (Ω). There exist the sequences λ n n≥1 and φ n n≥1 ⊂ D(A) which are the eigenvalues and eigenvectors of A respectively. As we known that λ n n≥1 is positive, non-decreasing and lim n→∞ λ n = ∞. In what follows, we would find a representation of solutions of Problem (1)-(2) basing on some special operators. For this purpose, we first consider the initial value problem There are some methods which help to find a representation for solutions of Problem (7), see e.g. and therein. More specificly, the Laplace transform method can be refered in . We refer to the method in where solutions of Problem (7) represented by Then, it is obvious to see that the operators E α,1 (−t α A) and E −1 α,1 (−t α A) are the inverse operators of each other. Hence, we obtain a representation of solutions of Problem (1)-(2) as Now, we give a definition of mild solutions of Problem (1)-(2). Well-posedness with globally Lipschitz nonlinearities In this section, we present the existence, uniqueness and regularity of a mild solution of Problem (1)-(2) which are based on a Lipschitz assumption on the source function G. (G1) G(0) = 0, and there exists a constant K > 0 such that, for all 0 ≤ t ≤ T and v 1 , v 2 ∈ L 2 (Ω), (G2) G(0) = 0, and there exists a constant K > 0 such that, for all 0 ≤ t 1 , without considering the initial time. Indeed, Equation (12) is not defined for t = 0, namely, we cannot substitute t = 0 into (12) to obtain u(., 0). The inverse problem (1)-(2) did not give u(., 0). Hence, it is necessary to recover the initial value u(., 0) in . It is useful to note that the Sobolev embedding The following lemma will be useful for the recovery u(., 0) by considering the limit lim h→0 + u(., h). This combined with (16) allow the estimate Hence, letting β 1 = 0 in Part c of Lemma 4.7 gives This implies lim Moreover, by using the inequality (39), noting G(., µ, u(., µ)) ≤ KC 1 ϕ D(A) as Theorem 3.1, and letting β 1 = 0 in Part a of Lemma 4.7, we derive the following estimate This implies lim h→0 + Z α,2 (u)(., h) = 0 in the sense of the space D A − 1 q . Let us show the last limit. By using the inequality (40), one can see that The integrand of the above integral can be estimated by using Part c, and Part b of Lemma 4.7 as Hence, by denoting Therefore, the last limit is obtained by letting h tends to 0. Due to the above lemma, it is relevant to define the initial value by u(., 0) = lim t→0 + u(., t), namely in D(A − 1 q ). Next, we will establish the continuity of the mild solution u on the whole interval . Moreover, there exists a positive constant Proof. We note that, (p; ρ; r) ∈ V 3 α as (p; q; ρ; r) ∈ V 4 α . Hence, the assumptions of this theorem also fulfills Theorem 3.1. Therefore, it is sufficient to prove that Here, we also use the notations Z α,j , 1 ≤ j ≤ 3, in the proof of Theorem 3.1. Note that (p; q; ρ; r) ∈ V 4 α includes q > 1. Hence, by using the inequality (39), and Lemma 4.7, we derive where have used that G(., µ, u(., µ)) ≤ KC 1 ϕ D(A) . Moreover, the following estimate holds This estimate implies Therefore, there exists a constant ω 7 > 0 such that, for all t ∈ ; W l1,q (Ω)), which is also formulated in (33). Then, we prove the existence of a mild solution to Problem (1)-(2) by employing the Banach contraction principle. In what follows, we denote by and divide the proof into the following parts. 4.2. Applications to time fractional Navier-Stokes equations. In this subsection, we discuss about an applications of our methods given in Subsection 4.1 to a motion of viscous fluid substances in physics. Let us consider the final value problem of finding the flow velocity u = k×1 of a fluid for the following time fractional Navier-Stokes equations where 0 < α ≤ 1, Ω is a C 2 bounded open set of R k (k ≥ 2), div u = k j=1 ∇ j u j is the divergence of u, the notation u · div u is defined by and p is the pressure, ∇p = k×1 . Note that the order of operations in (85) is very important. More specifically, the operation in the brackets must be done first. In the case α = 1, the first equation of (84) becomes the classical Navier-Stokes equation which has been studied by many authors such as Y. Giga , H. Iwashita , E.S. Titi et al . In order to study Problem (84), we now recall some analysis on the Stokes operator. For each 1 < r < ∞, let us set X r = Closure of υ ∈ C ∞ 0 (Ω) : div υ = 0 in L r (Ω) k , G r = ∇p : p ∈ W 1,r (Ω) . Then, according to the Helmholtz decomposition, we have the direct sum L r (Ω) k = X r ⊕G r . Therefore, we can consider the continuous projection P r (called the Helmholtz projection) from L r (Ω) k to X r . Now, we let −∆ be the negative Laplace operator on the domain D(−∆) = υ ∈ W 2,r (Ω) k : υ ∂Ω = 0 , then P r (−∆) : X r ∩ D(−∆) −→ X r is called the Stokes operator, e.g. see p.201 or . Furthermore, applying the Stokes operator on both sides of (84) deduces the following equations with eliminating the pressure term By getting rid of the vector fields, a simple comparison between Problem (1)-(2) and Problem (86) yields that the second one is a special case of the first one with respect to the operator A = P r (−∆) and the nonlinearity G = −P r (u, ∇)u . We also note that denoting by ∂ α * the Caputo fractional derivative operator of order α can transforms Problem (86) into the form where F (u; ∇u) := −b(t)P r (u, ∇)u , and I 1−α t is the fractional integral of the order 1 − α. To apply our method in Subsection 4.1, we recall the following properties of the spectrum of the Stokes operator in the case r = 2, that is, A is an unbounded, self-adjoint, and positive operator in X 2 and has a compact inverse, e.g. see Section 6 in ; k ) such that Proof. To establish the ensuing estimates of the nonlinearity, we will present some interpretations of the given numbers. Firstly, we note that if k = 5 then q belongs to the interval (15/8, 5/2), and so that |q − 2|k/4q is bounded by 1/4. Therefore, the condition |q − 2|k/4q < 1 holds true. Secondly, we will prove that 1/2 + k/(2q) < l † * . Since k/(k − 3) is always less than k if (k, q) ∈ Θ k,q , we claim that q is always less than k for all (k, q) ∈ Θ k,q . This ensures that 1/2 + k/(2q) < k/q. Hence, in order to show 1/2 + k/(2q) < l † * , we will show that 1/2 + k/(2q) < l † . Indeed, if (k, q) ∈ Θ (1) k,q , then k,q , then employing the above techniques shows that Thus, we conclude that 1/2 + k/(2q) < l † * . The above analysis consequently indicates that the interval
<filename>src/Parser.hs module Parser (tokenize, parse) where import Parser.Tokens import Parser.Grammer
<filename>src/rxjsNoStaticObservableMethodsRule.ts import * as Lint from 'tslint'; import * as tsutils from 'tsutils'; import * as ts from 'typescript'; import { subtractSets, concatSets, isObservable, returnsObservable, computeInsertionIndexForImports } from './utils'; /** * A typed TSLint rule that inspects observable * static methods and turns them into function calls. */ export class Rule extends Lint.Rules.TypedRule { static metadata: Lint.IRuleMetadata = { ruleName: 'rxjs-no-static-observable-methods', description: 'Updates the static methods of the Observable class.', optionsDescription: '', options: null, typescriptOnly: true, type: 'functionality' }; static IMPORT_FAILURE_STRING = 'prefer operator imports with no side-effects'; static OBSERVABLE_FAILURE_STRING = 'prefer function calls'; applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] { const failure = this.applyWithFunction(sourceFile, ctx => this.walk(ctx, program)); return failure; } private walk(ctx: Lint.WalkContext<void>, program: ts.Program) { this.removePatchedOperatorImports(ctx); const sourceFile = ctx.sourceFile; const typeChecker = program.getTypeChecker(); const insertionStart = computeInsertionIndexForImports(sourceFile); let rxjsOperatorImports = new Set<OperatorWithAlias>( Array.from(findImportedRxjsOperators(sourceFile)).map(o => OPERATOR_WITH_ALIAS_MAP[o]) ); function checkPatchableOperatorUsage(node: ts.Node) { if (!isRxjsStaticOperatorCallExpression(node, typeChecker)) { return ts.forEachChild(node, checkPatchableOperatorUsage); } const callExpr = node as ts.CallExpression; if (!tsutils.isPropertyAccessExpression(callExpr.expression)) { return ts.forEachChild(node, checkPatchableOperatorUsage); } const propAccess = callExpr.expression as ts.PropertyAccessExpression; const name = propAccess.name.getText(sourceFile); const operatorName = OPERATOR_RENAMES[name] || name; const start = propAccess.getStart(sourceFile); const end = propAccess.getEnd(); const operatorsToImport = new Set<OperatorWithAlias>([OPERATOR_WITH_ALIAS_MAP[operatorName]]); const operatorsToAdd = subtractSets(operatorsToImport, rxjsOperatorImports); const imports = createImportReplacements(operatorsToAdd, insertionStart); rxjsOperatorImports = concatSets(rxjsOperatorImports, operatorsToAdd); ctx.addFailure( start, end, Rule.OBSERVABLE_FAILURE_STRING, [Lint.Replacement.replaceFromTo(start, end, operatorAlias(operatorName))].concat(imports) ); return ts.forEachChild(node, checkPatchableOperatorUsage); } return ts.forEachChild(ctx.sourceFile, checkPatchableOperatorUsage); } private removePatchedOperatorImports(ctx: Lint.WalkContext<void>): void { const sourceFile = ctx.sourceFile; for (const importStatement of sourceFile.statements.filter(tsutils.isImportDeclaration)) { const moduleSpecifier = importStatement.moduleSpecifier.getText(); if (!moduleSpecifier.startsWith(`'rxjs/add/observable/`)) { continue; } const importStatementStart = importStatement.getStart(sourceFile); const importStatementEnd = importStatement.getEnd(); ctx.addFailure( importStatementStart, importStatementEnd, Rule.IMPORT_FAILURE_STRING, Lint.Replacement.deleteFromTo(importStatementStart, importStatementEnd) ); } } } function isRxjsStaticOperator(node: ts.PropertyAccessExpression) { return 'Observable' === node.expression.getText() && RXJS_OPERATORS.has(node.name.getText()); } function isRxjsStaticOperatorCallExpression(node: ts.Node, typeChecker: ts.TypeChecker) { // Expression is of the form fn() if (!tsutils.isCallExpression(node)) { return false; } // Expression is of the form foo.fn if (!tsutils.isPropertyAccessExpression(node.expression)) { return false; } // fn is one of RxJs instance operators if (!isRxjsStaticOperator(node.expression)) { return false; } // fn(): k. Checks if k is an observable. Required to distinguish between // array operators with same name as RxJs operators. if (!returnsObservable(node, typeChecker)) { return false; } return true; } function findImportedRxjsOperators(sourceFile: ts.SourceFile): Set<string> { return new Set<string>( sourceFile.statements.filter(tsutils.isImportDeclaration).reduce((current, decl) => { if (!decl.importClause) { return current; } if (!decl.moduleSpecifier.getText().startsWith(`'rxjs'`)) { return current; } if (!decl.importClause.namedBindings) { return current; } const bindings = decl.importClause.namedBindings; if (ts.isNamedImports(bindings)) { return [ ...current, ...(Array.from(bindings.elements) || []).map(element => { return element.name.getText(); }) ]; } return current; }, []) ); } function operatorAlias(operator: string) { return 'observable' + operator[0].toUpperCase() + operator.substring(1, operator.length); } function createImportReplacements(operatorsToAdd: Set<OperatorWithAlias>, startIndex: number): Lint.Replacement[] { return [...Array.from(operatorsToAdd.values())].map(tuple => Lint.Replacement.appendText(startIndex, `\nimport {${tuple.operator} as ${tuple.alias}} from 'rxjs';\n`) ); } /* * https://github.com/ReactiveX/rxjs/tree/master/compat/add/observable */ const RXJS_OPERATORS = new Set([ 'bindCallback', 'bindNodeCallback', 'combineLatest', 'concat', 'defer', 'empty', 'forkJoin', 'from', 'fromEvent', 'fromEventPattern', 'fromPromise', 'generate', 'if', 'interval', 'merge', 'never', 'of', 'onErrorResumeNext', 'pairs', 'rase', 'range', 'throw', 'timer', 'using', 'zip' ]); // Not handling NEVER and EMPTY const OPERATOR_RENAMES: { [key: string]: string } = { throw: 'throwError', if: 'iif', fromPromise: 'from' }; type OperatorWithAlias = { operator: string; alias: string }; type OperatorWithAliasMap = { [key: string]: OperatorWithAlias }; const OPERATOR_WITH_ALIAS_MAP: OperatorWithAliasMap = Array.from(RXJS_OPERATORS).reduce((a, o) => { const operatorName = OPERATOR_RENAMES[o] || o; a[operatorName] = { operator: operatorName, alias: operatorAlias(operatorName) }; return a; }, {});
<reponame>pbernasconi/kanel // @generated // Automatically generated. Don't change this file manually. // Name: category export type CategoryId = number & { " __flavor"?: 'category' }; export default interface Category { /** Primary key. Index: category_pkey */ category_id: CategoryId; name: string; last_update: Date; } export interface CategoryInitializer { /** * Default value: nextval('category_category_id_seq'::regclass) * Primary key. Index: category_pkey */ category_id?: CategoryId; name: string; /** Default value: now() */ last_update?: Date; }
/** * Execute the procedure up to "lastStep" and then the ProcedureExecutor * is restarted and an abort() is injected. * If the procedure implement abort() this should result in rollback being triggered. * Each rollback step is called twice, by restarting the executor after every step. * At the end of this call the procedure should be finished and rolledback. * This method assert on the procedure being terminated with an AbortException. */ public static void testRollbackAndDoubleExecution( final ProcedureExecutor<MasterProcedureEnv> procExec, final long procId, final int lastStep) throws Exception { testRollbackAndDoubleExecution(procExec, procId, lastStep, false); }
/** * Controller for managing scheduled task history. * * @author Lateef Ojulari * @since 1.0 */ @Component("/system/scheduledtaskhist") @UplBinding("web/system/upl/managescheduledtaskhist.upl") public class ScheduledTaskHistController extends AbstractSystemFormController<ScheduledTaskHistPageBean, ScheduledTaskHist> { @Configurable private SystemService systemService; public ScheduledTaskHistController() { super(ScheduledTaskHistPageBean.class, ScheduledTaskHist.class, ManageRecordModifier.SECURE | ManageRecordModifier.VIEW | ManageRecordModifier.REPORTABLE); } @Override protected void onOpenPage() throws UnifyException { super.onOpenPage(); ScheduledTaskHistPageBean pageBean = getPageBean(); if (pageBean.getSearchExecutionDt() == null) { pageBean.setSearchExecutionDt(systemService.getToday()); } } @Override protected List<ScheduledTaskHist> find() throws UnifyException { ScheduledTaskHistPageBean pageBean = getPageBean(); ScheduledTaskHistQuery query = new ScheduledTaskHistQuery(); if (pageBean.getSearchExecutionDt() != null && QueryUtils.isValidLongCriteria(pageBean.getSearchScheduledTaskId())) { query.scheduledTaskId(pageBean.getSearchScheduledTaskId()); if (pageBean.getSearchStatus() != null) { query.taskStatus(pageBean.getSearchStatus()); } query.startedOn(pageBean.getSearchExecutionDt()); return systemService.findScheduledTaskHistory(query); } return Collections.emptyList(); } @Override protected ScheduledTaskHist find(Long id) throws UnifyException { return systemService.findScheduledTaskHist(id); } @Override protected Object create(ScheduledTaskHist scheduledTaskHist) throws UnifyException { return null; } @Override protected int update(ScheduledTaskHist scheduledTaskHist) throws UnifyException { return 0; } @Override protected int delete(ScheduledTaskHist scheduledTaskHist) throws UnifyException { return 0; } }
AMD Processors APU OR CPU: WHAT’S THE DIFFERENCE? AMD pioneered APUs (Advanced Processing Unit), which combines the Radeon graphics chips found in their discrete graphics cards, with the CPU processing technologies onto a single chip. While the the graphics technologies found within the APU isn’t as fast as a dedicated graphics card, they do yield the benefits of energy efficiency and low power requirements. These traits also apply to the CPU section of the APU, while still maintaining the multi-core technologies featured on standalone CPUs. With AMD CPUs (Central Processing Units), you have the flexibility to choose the best discrete graphics card solution for your budget. CPUs offer faster clock speeds, enhanced user control, reliable overclocking capabilities and multi-core variants that offer improved performance over APUs. These serve as the best choice for gamers and high-performance consumers. AMD PROCESSOR PRODUCT RANGE: Socket AM1 – Athlon/Sempron APUs. Socket AM3 & AM3+ – Piledriver FX-4 Quad Core, FX-6 Six Core, FX-8 Eight Core. Socket FM2 – AMD Trinity/Richland A4, A6, A8, A10 APUs. Socket FM2+ – Kaveri A6, A8 and A10 APUs. Athlon X4 CPUs. Socket AM4 – Ryzen 1800X, 1700X, 1700 CPUs. AMD CPU Delivering flexibility and choice within four different platforms, AMD processors are designed to meet every price point and every computing requirement. While the FM2 and AM1 platforms such as the A4 7300 are best suited for everyday computing, those such as FM2+, AM3+ and the latest AM4 are built to meet the needs of the high-end enthusiasts as well as power users. Along with four, six and eight-core variants processors such as the latest Ryzen 1800X feature 8 Cores with 16 threads, as well as an unlocked multiplier for clock speeds over 4GHz. Those looking to gain the most from these processors will find aftermarket coolers to be a necessary requirement should they wish to maintain consistent performance and low temperatures. ENTRY-LEVEL Buyers looking to build a machine for the purposes of general computing and everyday tasks will find valuable purchasing options with processors such as the Athlon X4 860K or the Athlon X4 845. These processors do well in delivering high clock speeds as well as multi-core variants, making them ideal for simultaneous multi-tasking such as browsing the internet or video playback while word processing. As these processors do not contain an on-board graphics chip, users of these CPUs will require the use of a dedicated graphics card solution, making them also ideal for casual gaming and light-media production work. Functional with FM2 and FM2+ socket motherboards, the selection for different form-factors does well in catering to the consumer – providing personal preference – all the while being valuable and compatible with the selected processor. HIGH-END Placed on the high-end of AMD's mainstream line-up, gamers and enthusiasts will find the most benefits from their computing requirements primarily within the AM3+ and AM4 Series of desktop processors. Utilizing the benefits of the 14nm FinFET technology, AMD Ryzen CPUs implement the latest technologies in processor design, modern features such as PCIE 3.0 and USB3.1 – Gen 2, and support for faster memory speeds on the DDR4 platform. Utilising Simultaneous Multithreading – also known as SMT, CPUs such as the the 1800X, 1700X and 1700 feature 8 Cores and 16 threads, giving way to improved functionality in multithreaded scenarios where each core is provided with two threads for simultaneous processing. As all Ryzen CPUs are unlocked for overclocking, AMD’s latest Extended Frequency Range technology (XFR) allows for automatic overclocking while taking into account the extra cooling capabilities of the CPU cooler, while still providing manual users with the tools for personal preference.While buyers can expect ultra-fast performance directly out-of-the-box, those who wish to gain extended performance will want an aftermarket cooler in order to maintain lower temperatures. Recommended processors within this line-up would include the FX-8350, Ryzen 1800X, 1700X and the 1700. AMD APU Designed in-mind for energy efficiency while still retaining outstanding performance, the AMD APU platform combines the benefits offered by both the CPU and the GPU – leveraging the technologies of Radeon Graphics without the need for an dedicated graphics card – everyday tasks and demanding applications can run faster and perform more efficiently all in one package, saving on power usage when the user demands it. The benefits for gamers comes in the form of the Radeon APU technology being present in the latest gaming consoles. Utilizing the APU in the PlayStation4 and the Xbox One means that PC gamers who use an APU or Discrete graphics cards of similar performance will see improved benefits when using high speed system RAM. This also means that games developed in-mind to take advantage of Radeon-based GPUs will provide PC gamers with the same benefits that’s available to the PlayStation4 and the Xbox One. ENTRY-LEVEL Utilizing dual-core and quad-core technology paired with extremely fast clock speeds the improved energy efficiency gains of the Athlon and A-Series APUs have proven time and time again to be a valuable solution for everyday multitasking and casual gaming – without the need for an additional graphics card solution. By providing direct access to the system's main system memory the performance benefits that can be leveraged from the Radeon graphics cores can give way for a greatly improved gaming experience, while still being more than capable for the needs of video playback, media entertainment and everyday computing. – Making the technology ideal for families, students, and casual users. Compatible with the FM2 and AM1 platforms APUs from the Athlon series such as the 5350 and 5150 are valuable options for building budget-oriented PCs. Casual gamers looking to make the most out of the APU Radeon cores will find their requirements met within the AMD A-Series, with models such as the A6 7400K providing entry-level overclocking features – without the need for an aftermarket cooler. HIGH-END Geared directly towards the gamers who demand a better than average experience at full HD resolutions without the means of a dedicated graphics card, the AMD A8 and A10 APUs have been built to deliver. Utilizing the energy-efficiency savings of the lower-end offerings while upping the performance gains with improved core speeds and graphical grunt – the increase of the available Radeon cores means products such as the A8-7890K and the A10-7870K are viable solutions for hardcore gamers and eSports competitors. Owners of the A8 and A10 APUs will require an FM2+ motherboard.
import { AxiosInstance } from 'axios'; import { EndpointClass } from './types'; declare const EndpointFactory: (axiosInstance: AxiosInstance) => typeof EndpointClass; export default EndpointFactory;
<filename>src/app/auth/auth.service.ts import {Injectable} from '@angular/core'; import {Store} from "@ngrx/store"; import * as authUser from './actions'; import * as fromRoot from '../core/store.reducers'; import {Headers, Http} from "@angular/http"; import {Observable} from "rxjs"; import {handleHttpError} from "../utils"; import {RcService} from "../core/rc.service"; @Injectable() export class AuthService { private _redirectUrl: string; get redirectUrl(): string { if (! this._redirectUrl || this._redirectUrl == 'login') { return ''; } return this._redirectUrl; }; set redirectUrl(v: string) { this._redirectUrl = v; } get isLoggedIn(): Observable<boolean> { return this.store.select(fromRoot.getJwt).map(jwt => jwt != null); } get isAdmin(): Observable<boolean> { return this.store.select(fromRoot.getGroups).map(groups => groups === null ? false : groups.indexOf('wheel') > -1); } constructor(private rc: RcService, private store: Store<fromRoot.State>, private http: Http) { } login(username: string, password: string): Observable<boolean> { const url = this.rc.urls.login + '?ts=' + new Date().getTime(); const body = {username, password}; return this.http.post(url, body) .map(resp => { const data = resp.json().data; const jwtTime = new Date(); this.store.dispatch(new authUser.LoggedInAction(username, password, data.jwt, jwtTime, data.groups)); return true; }) .catch(handleHttpError); } logout() { this.store.dispatch(new authUser.LoggedOutAction()); } refreshJwt(): Observable<boolean> { const url = this.rc.urls.login + '?ts=' + new Date().getTime(); return this.store.select(fromRoot.getCredentials).take(1).switchMap(cred => { return this.http.post(url, cred) .map(resp => { const data = resp.json().data; const jwtTime = new Date(); this.store.dispatch(new authUser.LoggedInAction(cred.username, cred.password, data.jwt, jwtTime, data.groups)); return true; }) .catch(handleHttpError); }); } applyHeaders(headers: Headers) { this.store.select(fromRoot.getJwt).subscribe( jwt => { if (jwt) { headers.set('Authorization', `Bearer ${jwt}`); } } ); } }
<reponame>agmcc/slate-lang<filename>src/main/java/com/github/agmcc/slate/cli/SourceExtensionValidator.java package com.github.agmcc.slate.cli; import com.beust.jcommander.IParameterValidator; import com.beust.jcommander.ParameterException; public class SourceExtensionValidator implements IParameterValidator { private static final String SOURCE_EXTENSION = ".slate"; @Override public void validate(final String name, final String value) throws ParameterException { if (!value.endsWith(SOURCE_EXTENSION)) { throw new ParameterException( String.format( "Invalid source file '%s' (Expected extension '%s')", value, SOURCE_EXTENSION)); } } }
<filename>Source/V8/Private/MallocArrayBufferAllocator.h #pragma once class FMallocArrayBufferAllocator : public v8::ArrayBuffer::Allocator { public: /** * Allocate |length| bytes. Return NULL if allocation is not successful. * Memory should be initialized to zeroes. */ virtual void* Allocate(size_t length) { auto buffer = GMalloc->Malloc(length); FMemory::Memzero(buffer, length); return buffer; } /** * Allocate |length| bytes. Return NULL if allocation is not successful. * Memory does not have to be initialized. */ virtual void* AllocateUninitialized(size_t length) { return GMalloc->Malloc(length); } /** * Free the memory block of size |length|, pointed to by |data|. * That memory is guaranteed to be previously allocated by |Allocate|. */ virtual void Free(void* data, size_t length) { GMalloc->Free(data); } };
<reponame>KKcorps/incubator-pinot<filename>pinot-core/src/main/java/org/apache/pinot/core/operator/docvaliterators/DictionaryBasedSingleValueIterator.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.pinot.core.operator.docvaliterators; import org.apache.pinot.core.common.BlockSingleValIterator; import org.apache.pinot.core.io.reader.ReaderContext; import org.apache.pinot.core.io.reader.SingleColumnSingleValueReader; import org.apache.pinot.core.segment.index.readers.Dictionary; @SuppressWarnings("unchecked") public final class DictionaryBasedSingleValueIterator extends BlockSingleValIterator { private final SingleColumnSingleValueReader _reader; private final int _numDocs; private final ReaderContext _context; private final Dictionary _dictionary; private int _nextDocId; public DictionaryBasedSingleValueIterator(SingleColumnSingleValueReader reader, Dictionary dictionary, int numDocs) { _reader = reader; _numDocs = numDocs; _context = _reader.createContext(); _dictionary = dictionary; } @Override public int nextIntVal() { return _dictionary.getIntValue(_reader.getInt(_nextDocId++, _context)); } @Override public long nextLongVal() { return _dictionary.getLongValue(_reader.getInt(_nextDocId++, _context)); } @Override public float nextFloatVal() { return _dictionary.getFloatValue(_reader.getInt(_nextDocId++, _context)); } @Override public double nextDoubleVal() { return _dictionary.getDoubleValue(_reader.getInt(_nextDocId++, _context)); } @Override public String nextStringVal() { return _dictionary.getStringValue(_reader.getInt(_nextDocId++, _context)); } @Override public byte[] nextBytesVal() { return _dictionary.getBytesValue(_reader.getInt(_nextDocId++, _context)); } @Override public boolean hasNext() { return _nextDocId < _numDocs; } @Override public void skipTo(int docId) { _nextDocId = docId; } @Override public void reset() { _nextDocId = 0; } }
import threading import time import simpleaudio as sa import rclpy from rclpy.node import Node from angel_msgs.msg import HeadsetAudioData class AudioPlayer(Node): def __init__(self): super().__init__(self.__class__.__name__) self.declare_parameter("audio_topic", "HeadsetAudioData") self._audio_topic = self.get_parameter("audio_topic").get_parameter_value().string_value self.subscription = self.create_subscription( HeadsetAudioData, self._audio_topic, self.listener_callback, 1) self.audio_stream = bytearray() self.audio_stream_lock = threading.RLock() self.audio_player_lock = threading.RLock() self.t = threading.Thread() self.audio_stream_duration = 0.0 self.playback_duration = 1.0 self.prev_timestamp = None def listener_callback(self, msg): """ Add the audio to the cumulative audio stream and spawns a new playback thread if the cumulative recording has reached more than a second and there is no ongoing playback. """ log = self.get_logger() with self.audio_stream_lock: # Check that this message comes temporally after the previous message message_order_valid = False if self.prev_timestamp is None: message_order_valid = True else: if msg.header.stamp.sec > self.prev_timestamp.sec: message_order_valid = True elif msg.header.stamp.sec == self.prev_timestamp.sec: # Seconds are same, so check nanoseconds if msg.header.stamp.nanosec > self.prev_timestamp.nanosec: message_order_valid = True if message_order_valid: self.audio_stream.extend(msg.data) self.audio_stream_duration += msg.sample_duration else: log.info("Warning! Out of order messages.\n" + f"Prev: {self.prev_timestamp} \nCurr: {msg.header.stamp}") return self.prev_timestamp = msg.header.stamp if self.audio_stream_duration >= self.playback_duration and not(self.t.is_alive()): # Make a copy of the current data so we can play it back # while more data is accumulated audio_data = self.audio_stream # Remove the data that we just copied from the stream self.audio_stream = bytearray() self.audio_stream_duration = 0.0 # Start the audio playback thread self.t = threading.Thread(target=self.audio_playback_thread, args=(audio_data, msg.channels, msg.sample_rate,)) self.t.start() def audio_playback_thread(self, audio_data, num_channels, sample_rate): """ Thread that plays back the received audio data with SimpleAudio. Waits for the audio playback to finish before exiting. """ # Ensure only one playback is happening at a time with self.audio_player_lock: audio_player_object = sa.play_buffer(audio_data, num_channels, 4, # bytes per sample sample_rate) audio_player_object.wait_done() def main(): rclpy.init() audio_player = AudioPlayer() rclpy.spin(audio_player) # Destroy the node explicitly # (optional - otherwise it will be done automatically # when the garbage collector destroys the node object) audio_player.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
export interface OEmbedInfo { version: '1.0'; url: string; type: 'video' | 'photo' | 'rich' | 'link'; // generic properties title?: string; description?: string; screenshot_url?: string; thumbnail_url?: string; thumbnail_width?: number; thumbnail_height?: number; author_name?: string; author_url?: string; provider_name?: string; provider_url?: string; cache_age?: number; // video, photo & rich types html?: string; width?: number; height?: number; }
<gh_stars>0 import { useWallet as useEthereumWallet } from './ethereum'; import { useWallet as useSolanaWallet } from './solana'; const useStatus = () => { const { connected: ethereumConnected, loading: ethereumLoading, wallet: ethereumWallet, } = useEthereumWallet(); const { connecting: solanaConnecting, disconnecting: solanaDisconnecting, connected: solanaConnected, wallet: solanaWallet, loading: solanaLoading, } = useSolanaWallet(); return { loading: ethereumLoading || solanaLoading, ethereumConnected, solanaConnected, ethereumLoading, solanaLoading: solanaConnecting || solanaDisconnecting || solanaLoading, ethereumWallet, solanaWallet, connected: ethereumConnected || solanaConnected, }; }; export default useStatus;
/** * @author Marco Ruiz * @since Dec 13, 2008 */ public class OrderInfoServlet extends GWEClusterSelectedServlet { private static final String P2EL_STATEMENT = "p2elStatement"; public OrderInfoServlet() { super("order"); } protected void specificPageModelPopulation(PageModel pageModel, Session4ClientAPIEnhancer session) { Integer orderId = pageModel.getParam(Param.ORDER_ID); if (orderId == null) return; try { OrderInfo order = session.getOrderDetails(orderId, true); pageModel.addIdentifiedObject(Param.ORDER_ID, order); pageModel.put(P2EL_STATEMENT, getP2ELStatement(order)); } catch (Exception e) { } } private PStatement getP2ELStatement(OrderInfo order) { try { return REXParser.createModel(PStatement.class, ((POrderDescriptor)order.getDescriptor()).getP2ELStatement(), true); } catch (REXException e) { } return null; } }