text
stringlengths
27
775k
<?php $finder = (new PhpCsFixer\Finder()) ->in(__DIR__); return (new PhpCsFixer\Config()) ->setFinder($finder);
// Copyright (c) 2018 Eyro Labs. // Licensed under Apache License v2.0 that can be // found in the LICENSE file. part of flutter_beacon; /// Enum class for showing status about authorization. class AuthorizationStatus { /// The defined [String] value of the authorization status. final String value; /// This will `true` only if this authorization status suit Android system. final bool isAndroid; /// This will `true` only if this authorization status suit iOS system. final bool isIOS; @visibleForTesting const AuthorizationStatus.init( this.value, { this.isAndroid = false, this.isIOS = false, }); @visibleForTesting factory AuthorizationStatus.parse(String value) { switch (value) { case 'ALLOWED': return allowed; case 'ALWAYS': return always; case 'WHEN_IN_USE': return whenInUse; case 'DENIED': return denied; case 'RESTRICTED': return restricted; case 'NOT_DETERMINED': return notDetermined; } throw Exception('invalid authorization status $value'); } /// Shows that user allowed the authorization. /// /// Only for Android static const AuthorizationStatus allowed = AuthorizationStatus.init( 'ALLOWED', isAndroid: true, isIOS: false, ); /// Shows that user always authorize app. /// /// Only for iOS static const AuthorizationStatus always = AuthorizationStatus.init( 'ALWAYS', isAndroid: false, isIOS: true, ); /// Shows that user authorize when in use app. /// /// Only for iOS static const AuthorizationStatus whenInUse = AuthorizationStatus.init( 'WHEN_IN_USE', isAndroid: false, isIOS: true, ); /// Shows that user denied authorization request. static const AuthorizationStatus denied = AuthorizationStatus.init( 'DENIED', isAndroid: true, isIOS: true, ); /// Shows that authorization has been restricted by system. /// /// Only for iOS static const AuthorizationStatus restricted = AuthorizationStatus.init( 'RESTRICTED', isAndroid: false, isIOS: true, ); /// Shows that authorization has not been determined by user. /// static const AuthorizationStatus notDetermined = AuthorizationStatus.init( 'NOT_DETERMINED', isAndroid: true, isIOS: true, ); @override bool operator ==(Object other) => identical(this, other) || other is AuthorizationStatus && runtimeType == other.runtimeType && value == other.value && isAndroid == other.isAndroid && isIOS == other.isIOS; @override int get hashCode => value.hashCode ^ isAndroid.hashCode ^ isIOS.hashCode; @override String toString() { return value; } }
import { randomColor } from 'randomcolor'; import { SET_SAMPLE, SET_SAMPLE_LAYERS, } from '../actions'; import sampleInitialState from './sampleInitialState'; export function create_normalized_thickness(olist) { let out = {} let total_thickness = 0 let z = 0 const layers = olist.slice().reverse(); layers.forEach((obj, idx, array) => { obj.Thickness = parseFloat(obj.Thickness); z = z + obj.Thickness / 2 out[obj.index] = [obj.Thickness, z] z = z + obj.Thickness / 2 total_thickness += obj.Thickness }) for (let key in out) { out[key][0] /= total_thickness out[key][1] /= total_thickness } return out; } function unique_sample_colors(layers) { const unique_colors = [...new Set(layers.map(layer => layer.Color))]; const colors = {}; if (unique_colors.length === 1 && !unique_colors[0]) { const unique_layers = [...new Set(layers.map(layer => layer.Name))]; unique_layers.forEach((obj, idx, array) => { colors[obj] = randomColor(); }) } return colors; } function redefine_sample_layers(layers) { const new_layers = layers.slice(); const normalized_thickness = create_normalized_thickness(new_layers); const colors = unique_sample_colors(new_layers); return new_layers.map((layer, idx) => { layer.NormalizedThickness = normalized_thickness[layer.index]; layer.index = idx; layer.Thickness = parseFloat(layer.Thickness); if (!layer.Color) { layer.Color = colors[layer.Name] || randomColor(); } return layer; }); } export default function sampleReducer(state = sampleInitialState, action) { switch (action.type) { case SET_SAMPLE_LAYERS: return {...state, layers: redefine_sample_layers(action.payload)}; case SET_SAMPLE: return { vacuum: action.payload.vacuum, layers: redefine_sample_layers(action.payload.layers), substrate: action.payload.substrate, } default: return state; } }
--- ask_me_about: General Help contact: email: kbelcher@playford.sa.gov.au linkedin: http://au.linkedin.com/in/ gid: kath-belcher jurisdiction: sa name: Kath Belcher organisation: Playford Library location: playford position_title: Library Customer Service type: Business Mentor --- I have many years of public library experience with a passion for Customer Service.
mod key_chord_event; mod key_chord_producer; mod key_chord_producer_handle; mod key_chord_producer_settings; pub use key_chord_event::*; pub use key_chord_producer::*; pub use key_chord_producer_handle::*; pub use key_chord_producer_settings::*;
## note: make Score top-level and use like Date - yes, yes, yes - why? why not? class Score SCORE_SPLIT_RE = %r{^ [ ]* ([0-9]+) [ ]* [:x–-] ## note: allow some unicode dashes too [ ]* ([0-9]+) [ ]* $}xi def self.split( str ) ## note: return array of two integers or empty array ## e.g. allow/support ## 1-1 or 1 - 1 - "english" style ## 1:1 - "german / deutsch" style ## 1x1 1X1 - "brazil - português / portuguese" style ## note: add unicode "fancy" dash too (e.g. –) ## add some more - why? why not? if m=SCORE_SPLIT_RE.match(str) [m[1].to_i, m[2].to_i] else # no match - warn if str is NOT empty? why? why not? if str.empty? || ['-', '-:-', '?'].include?( str ) ## do NOT warn for known "good" empty scores for now - why? why not? ## add some more?? use Score.empty? or such - why? why not? else puts "!! WARN - cannot match (split) score format >#{str}<" end [] end end attr_reader :score1i, :score2i, # half time (ht) score :score1, :score2, # full time (ft) score :score1et, :score2et, # extra time (et) score :score1p, :score2p # penalty (p) score ## todo/fix: add :score1agg, score2agg too - why? why not?!!! ## add state too e.g. canceled or abadoned etc - why? why not? ## alternate accessor via array e.g. ft[0] and ft[1] def ft() [@score1, @score2]; end ## e.g. 90 mins (in football) def ht() [@score1i, @score2i]; end ## e.g. 45 mins def et() [@score1et, @score2et]; end ## e.g. 90+15mins def p() [@score1p, @score2p]; end ## e.g. note - starts "fresh" score from 0-0 alias_method :pen, :p ## add alias - why? why not? alias_method :full_time, :ft alias_method :half_time, :ht alias_method :extra_time, :et alias_method :penalties, :p ## penalties - use a different word(ing)? why? why not? ## todo/check: allow one part missing why? why not? ## e.g. 1-nil or nil-1 - why? why not? def ft?() @score1 && @score2; end def ht?() @score1i && @score2i; end def et?() @score1et && @score2et; end def p?() @score1p && @score2p; end alias_method :pen?, :p? alias_method :full_time?, :ft? alias_method :half_time?, :ht? alias_method :extra_time?, :et? alias_method :penalties?, :p? def initialize( *values ) ## note: for now always assumes integers ## todo/check - check/require integer args - why? why not? ### todo/fix: add more init options ## allow kwargs (keyword args) via hash - why? why not? ## use kwargs for "perfect" init where you can only set the half time (ht) score ## or only the penalty or other "edge" cases ## allow int pairs e.g. [1,2], [2,2] ## allow values array MUST be of size 8 (or 4 or 6) - why? why not? raise ArgumentError, "expected even integer number (pairs), but got #{values.size}" if values.size % 2 == 1 if values.size == 2 @score1 = values[0] # full time (ft) score @score2 = values[1] @score1i = @score2i = nil @score1et = @score2et = nil @score1p = @score2p = nil else @score1i = values[0] # half time (ht) score @score2i = values[1] @score1 = values[2] # full time (ft) score @score2 = values[3] @score1et = values[4] # extra time (et) score @score2et = values[5] @score1p = values[6] # penalty (p) score @score2p = values[7] end end def to_h( format = :default ) case format.to_sym when :default, :std ## check/todo: only add entries if ft, ht, etc. have values (non-null) or always - why? why not? h = {} h[:ht] = [@score1i, @score2i] if @score1i || @score2i h[:ft] = [@score1, @score2] if @score1 || @score2 h[:et] = [@score1et, @score2et] if @score1et || @score2et h[:p] = [@score1p, @score2p] if @score1p || @score2p h when :db ## use a "flat" structure with "internal" std names { score1i: @score1i, score2i: @score2i, score1: @score1, score2: @score2, score1et: @score1et, score2et: @score2et, score1p: @score1p, score2p: @score2p } else puts "!! ERROR: unknown score to_h format >#{format}<" exit 1 end end def values ## todo/ fix: always return complete array ## e.g. [score1i, score2i, score1, score2, score1et, score2et, score1p, score2p] ## todo: how to handle game w/o extra time # but w/ optional penalty ??? e.g. used in copa liberatores, for example # retrun 0,0 or nil,nil for extra time score ?? or -1, -1 ?? # for now use nil,nil score = [] score += [@score1i, @score2i] if @score1p || @score2p || @score1et || @score2et || @score1 || score2 || score1i || score2i score += [@score1, @score2] if @score1p || @score2p || @score1et || @score2et || @score1 || score2 score += [@score1et, @score2et] if @score1p || @score2p || @score1et || @score2et score += [@score1p, @score2p] if @score1p || @score2p score end def to_a ## pairs with values pairs = [] ## note: allow 1-nil, nil-1 for now in pairs (or use && and NOT ||) - why? why not? pairs << [@score1i, @score2i] if @score1i || @score2i pairs << [@score1, @score2] if @score1 || @score2 pairs << [@score1et, @score2et] if @score1et || @score2et pairs << [@score1p, @score2p] if @score1p || @score2p if pairs.empty? pairs # e.g. return [] elsif pairs.size == 1 pairs[0] # return single pair "unwrapped" e.g. [0,1] instead of [[0,1]] - why? why not? else pairs end end end # class Score
use super::Instance; macro_rules! interrupts { ( $( $doc:expr, $field:ident, $enable:ident, $disable:ident; )* ) => { /// Used to enable or disable I2C interrupts /// /// See [`I2C::enable_interrupts`] or [`I2C::disable_interrupts`]. /// /// [`I2C::enable_interrupts`]: struct.I2C.html#method.enable_interrupts /// [`I2C::disable_interrupts`]: struct.I2C.html#method.disable_interrupts pub struct Interrupts { $( #[doc = $doc] pub $field: bool, )* } impl Interrupts { pub(super) fn enable<I: Instance>(&self, i2c: &I) { i2c.intenset.modify(|_, w| { $( if self.$field { w.$enable().enabled(); } )* w }) } pub(super) fn disable<I: Instance>(&self, i2c: &I) { i2c.intenclr.write(|w| { $( if self.$field { w.$disable().set_bit(); } )* w }) } } impl Default for Interrupts { fn default() -> Self { Self { $( $field: false, )* } } } }; } interrupts!( "Master Pending", master_pending, mstpendingen, mstpendingclr; "Master Arbitration Loss", master_arbitration_loss, mstarblossen, mstarblossclr; "Master Start/Stop Error", master_start_stop_error, mstststperren, mstststperrclr; "Slave Pending", slave_pending, slvpendingen, slvpendingclr; "Slave Not Stretching", slave_not_stretching, slvnotstren, slvnotstrclr; "Slave Deselect", slave_deselect, slvdeselen, slvdeselclr; "Monitor Ready", monitor_ready, monrdyen, monrdyclr; "Monitor Overrun", monitor_overrun, monoven, monovclr; "Monitor Idle", monitor_idle, monidleen, monidleclr; "Event Timeout", event_timeout, eventtimeouten, eventtimeoutclr; "SCL Timeout", scl_timeout, scltimeouten, scltimeoutclr; );
#!/bin/bash #shellcheck disable=SC1091,SC2034 THIS_DIR=$(readlink -f "${BASH_SOURCE[0]}") THIS_DIR=$(dirname "${THIS_DIR}") if [[ -f "${THIS_DIR}/functions.sh" ]]; then source "${THIS_DIR}/functions.sh" fi if [[ -n ${BASE_URL_PREFIX} ]]; then BASE_URL="${BASE_URL_PREFIX}/releases/${VERSION}/targets/ramips/mt7621" fi
{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} module Requests ( Handler(..) , sendGet , hContentType , sendPost , urlEncode ) where import Control.Exception (tryJust) import Data.Aeson (Value, decode) import Data.Aeson.Encode.Pretty (encodePretty) import qualified Data.ByteString.Char8 as S8 (ByteString, pack) import qualified Data.ByteString.Lazy.Char8 as L8 (ByteString, pack) import Network.HTTP.Client import Network.HTTP.Client.TLS (tlsManagerSettings) import Network.HTTP.Types (RequestHeaders, hContentType, urlEncode) import Prelude hiding (log) data Handler = Handler { url :: String , body :: S8.ByteString , headers :: RequestHeaders , logger :: S8.ByteString -> IO () } instance Eq Handler where Handler url1 body1 headers1 _ == Handler url2 body2 headers2 _ = url1 == url2 && body1 == body2 && headers1 == headers2 instance Show Handler where show Handler{url, body, headers} = "Handler{ url=" <> show url <> ", body=" <> show body <> ", headers=" <> show headers <> "}" sendPost :: Handler -> IO (Either L8.ByteString L8.ByteString) sendPost Handler{..} = do log url body send request { method = "POST" , requestBody = RequestBodyBS body , requestHeaders = headers } where log u b = logger $ "\n URL: " <> S8.pack u <> "\n Request body: " <> b request = parseRequest_ url sendGet :: String -> IO (Either L8.ByteString L8.ByteString) sendGet url = send $ parseRequest_ url -- | Send request and check if response is JSON. send :: Request -> IO (Either L8.ByteString L8.ByteString) send request = do response <- sendRequest request pure $ response >>= decodeJSON where decodeJSON resp = case decode resp :: Maybe Value of Just v -> Right $ encodePretty v _ -> Left $ "Response is not JSON: " <> resp sendRequest :: Request -> IO (Either L8.ByteString L8.ByteString) sendRequest request = do -- A Manager is present to keep track of open connections, so that multiple -- requests to the same server use the same connection. manager <- newManager tlsManagerSettings tryJust selectHttpException (responseBody <$> httpLbs request manager) where selectHttpException :: HttpException -> Maybe L8.ByteString selectHttpException = \case HttpExceptionRequest failedRequest content -> Just . L8.pack $ show failedRequest <> show content InvalidUrlException url reason -> Just . L8.pack $ "A URL '" <> url <> "': " <> reason <> "."
package com.rafaelturse.simpleschool.model.repository; import java.util.Optional; import org.assertj.core.api.Assertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import com.rafaelturse.simpleschool.model.entity.UserORM; @RunWith(SpringRunner.class) @ActiveProfiles("test") @DataJpaTest @AutoConfigureTestDatabase(replace = Replace.NONE) public class UserRepositoryTest { @Autowired UserRepository repository; @Autowired TestEntityManager entityManager; public static UserORM setUser() { // scenery return UserORM.builder().name("john").password("123").email("john@school.com").build(); } @Test public void mustVerifyEmailExistence() { // scenery entityManager.persist(setUser()); // action boolean result = repository.existsByEmail("john@school.com"); // verification Assertions.assertThat(result).isTrue(); } @Test public void mustVerifyEmailNonExistence() { // action boolean result = repository.existsByEmail("john@school.com"); // verification Assertions.assertThat(result).isFalse(); } @Test public void mustPersistUser() { // action UserORM savedUser = repository.save(setUser()); // verification Assertions.assertThat(savedUser.getId()).isNotNull(); } @Test public void mustGetUserByEmail() { // scenery UserORM user = setUser(); entityManager.persist(user); // action Optional<UserORM> result = repository.findByEmail(user.getEmail()); // verification Assertions.assertThat(result.isPresent()).isTrue(); } @Test public void mustReturnEmptyWhenCantFindUserByEmail() { // action Optional<UserORM> result = repository.findByEmail(setUser().getEmail()); // verification Assertions.assertThat(result.isPresent()).isFalse(); } }
{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-} module Compiler.Linearizer where import Prelude hiding (traverse) import Control.Arrow ((***)) import Control.Monad.Writer import qualified Data.List as List import Data.Expr (DefnKw(..), Expr(..)) import qualified Data.Expr as Expr import qualified Data.Name as Name import Monad.NameT (MonadName(..)) data Position = Binding | NonBinding deanonymizeExpr :: MonadName m => Position -> Expr -> m Expr deanonymizeExpr _ (AnnotationE expr typ) = flip AnnotationE typ <$> deanonymizeExpr NonBinding expr deanonymizeExpr _ (AppE fn arg) = AppE <$> deanonymizeExpr NonBinding fn <*> deanonymizeExpr NonBinding arg deanonymizeExpr _ (CondE matches) = CondE <$> mapM deanonym matches where deanonym (predicate, body) = do predicate' <- deanonymizeExpr NonBinding predicate body' <- deanonymizeExpr NonBinding body return (predicate', body') deanonymizeExpr _ (FnDecl kw name body) = FnDecl kw name <$> deanonymizeExpr Binding body deanonymizeExpr _ expr@IdE {} = return expr deanonymizeExpr bind@Binding (LambdaE arg body) = LambdaE arg <$> deanonymizeExpr bind body deanonymizeExpr NonBinding (LambdaE arg body) = do expr' <- LambdaE arg <$> deanonymizeExpr Binding body fnName <- genName $ Name.untyped "lambda" return $ LetE (FnDecl NrDef fnName expr') (IdE fnName) deanonymizeExpr _ (LetE defn body) = LetE <$> deanonymizeExpr NonBinding defn <*> deanonymizeExpr NonBinding body deanonymizeExpr _ expr@LiteralE {} = return expr deanonymize :: MonadName m => Expr -> m Expr deanonymize = deanonymizeExpr NonBinding substitute :: Expr -> Expr -> Expr -> Expr substitute source target = sub where traverse (AnnotationE expr typ) = AnnotationE (sub expr) typ traverse (AppE expr1 expr2) = AppE (sub expr1) (sub expr2) traverse (CondE matches) = CondE $ map (sub *** sub) matches traverse (FnDecl kw name expr) = FnDecl kw name $ sub expr traverse expr@IdE {} = expr traverse (LambdaE arg body) = LambdaE arg $ sub body traverse (LetE defn body) = LetE (sub defn) (sub body) traverse expr@LiteralE {} = expr sub expr | expr == source = target | otherwise = traverse expr uncapture :: MonadName m => Expr -> Expr -> m (Expr, Expr) uncapture enclosing@(LambdaE arg body) fnDecl@(FnDecl fnKw fnName fnBody) = if arg `List.elem` Expr.freeVars fnDecl then do captureName <- genName arg let body' = substitute (IdE fnName) (AppE (IdE fnName) (IdE arg)) body let enclosing' = LambdaE arg body' let fnBody' = substitute (IdE fnName) (AppE (IdE fnName) (IdE captureName)) $ substitute (IdE arg) (IdE captureName) $ fnBody let fnDecl' = FnDecl fnKw fnName (LambdaE captureName fnBody') return (enclosing', fnDecl') else return (enclosing, fnDecl) uncapture enclosing nested = return (enclosing, nested) data Scope = Toplevel | Local unnestExpr :: (MonadName m, MonadWriter [Expr] m) => Scope -> Expr -> m Expr unnestExpr scope (AnnotationE expr typ) = flip AnnotationE typ <$> unnestExpr scope expr unnestExpr scope (AppE fn arg) = AppE <$> unnestExpr Local fn <*> unnestExpr scope arg unnestExpr scope (CondE matches) = CondE <$> mapM unnestMatch matches where unnestMatch (predicate, body) = do predicate' <- unnestExpr scope predicate body' <- unnestExpr scope body return (predicate', body') unnestExpr _ (FnDecl _ name body) = do body' <- unnestExpr Local body let kw | name `List.elem` Expr.freeVars body' = Def | otherwise = NrDef return $ FnDecl kw name body' unnestExpr _ expr@IdE {} = return expr unnestExpr scope (LambdaE arg body) = do (body', fnDecls) <- runWriterT $ unnestExpr scope body let expr' = LambdaE arg body' foldM (\enclosing nested -> do (enclosing', nested') <- uncapture enclosing nested tell [nested'] return enclosing') expr' fnDecls unnestExpr scope@Local (LetE defn@(FnDecl _ _ LambdaE {}) body) = do tell [defn] unnestExpr scope body unnestExpr scope (LetE defn body) = LetE <$> unnestExpr Local defn <*> unnestExpr scope body unnestExpr _ expr@LiteralE {} = return expr unnest :: MonadName m => Expr -> m [Expr] unnest expr = do (expr', exprs) <- runWriterT $ unnestExpr Toplevel expr exprs' <- concat <$> mapM unnest exprs return $ exprs' ++ [expr'] linearize :: MonadName m => Expr -> m [Expr] linearize expr = (unnest =<< deanonymize expr)
# Optimize Profile https://devblogs.microsoft.com/powershell/optimizing-your-profile/ ```powershell Install-Module PSProfiler Import-Module PSProfiler Measure-Script -Path $profile -Top 5 ```
# # 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. import copy from oslo_log import log as logging from heat.common import exception from heat.common.i18n import _ from heat.common.i18n import _LW from heat.engine import constraints from heat.engine import properties from heat.engine.resources.openstack.nova import server try: import pyrax # noqa PYRAX_INSTALLED = True except ImportError: PYRAX_INSTALLED = False LOG = logging.getLogger(__name__) class CloudServer(server.Server): """Resource for Rackspace Cloud Servers. This resource overloads existent integrated OS::Nova::Server resource and is used for Rackspace Cloud Servers. """ # Managed Cloud automation statuses MC_STATUS_IN_PROGRESS = 'In Progress' MC_STATUS_COMPLETE = 'Complete' MC_STATUS_BUILD_ERROR = 'Build Error' # RackConnect automation statuses RC_STATUS_DEPLOYING = 'DEPLOYING' RC_STATUS_DEPLOYED = 'DEPLOYED' RC_STATUS_FAILED = 'FAILED' RC_STATUS_UNPROCESSABLE = 'UNPROCESSABLE' properties_schema = copy.deepcopy(server.Server.properties_schema) properties_schema.update( { server.Server.USER_DATA_FORMAT: properties.Schema( properties.Schema.STRING, _('How the user_data should be formatted for the server. For ' 'HEAT_CFNTOOLS, the user_data is bundled as part of the ' 'heat-cfntools cloud-init boot configuration data. For RAW ' 'the user_data is passed to Nova unmodified. ' 'For SOFTWARE_CONFIG user_data is bundled as part of the ' 'software config data, and metadata is derived from any ' 'associated SoftwareDeployment resources.'), default=server.Server.RAW, constraints=[ constraints.AllowedValues( server.Server._SOFTWARE_CONFIG_FORMATS), ] ), } ) def __init__(self, name, json_snippet, stack): super(CloudServer, self).__init__(name, json_snippet, stack) self._managed_cloud_started_event_sent = False self._rack_connect_started_event_sent = False def _config_drive(self): user_data = self.properties.get(self.USER_DATA) config_drive = self.properties.get(self.CONFIG_DRIVE) if user_data or config_drive: return True else: return False def _check_managed_cloud_complete(self, server): if not self._managed_cloud_started_event_sent: msg = _("Waiting for Managed Cloud automation to complete") self._add_event(self.action, self.status, msg) self._managed_cloud_started_event_sent = True if 'rax_service_level_automation' not in server.metadata: LOG.debug("Managed Cloud server does not have the " "rax_service_level_automation metadata tag yet") return False mc_status = server.metadata['rax_service_level_automation'] LOG.debug("Managed Cloud automation status: %s" % mc_status) if mc_status == self.MC_STATUS_IN_PROGRESS: return False elif mc_status == self.MC_STATUS_COMPLETE: msg = _("Managed Cloud automation has completed") self._add_event(self.action, self.status, msg) return True elif mc_status == self.MC_STATUS_BUILD_ERROR: raise exception.Error(_("Managed Cloud automation failed")) else: raise exception.Error(_("Unknown Managed Cloud automation " "status: %s") % mc_status) def _check_rack_connect_complete(self, server): if not self._rack_connect_started_event_sent: msg = _("Waiting for RackConnect automation to complete") self._add_event(self.action, self.status, msg) self._rack_connect_started_event_sent = True if 'rackconnect_automation_status' not in server.metadata: LOG.debug("RackConnect server does not have the " "rackconnect_automation_status metadata tag yet") return False rc_status = server.metadata['rackconnect_automation_status'] LOG.debug("RackConnect automation status: %s" % rc_status) if rc_status == self.RC_STATUS_DEPLOYING: return False elif rc_status == self.RC_STATUS_DEPLOYED: self._server = None # The public IP changed, forget old one return True elif rc_status == self.RC_STATUS_UNPROCESSABLE: # UNPROCESSABLE means the RackConnect automation was not # attempted (eg. Cloud Server in a different DC than # dedicated gear, so RackConnect does not apply). It is # okay if we do not raise an exception. reason = server.metadata.get('rackconnect_unprocessable_reason', None) if reason is not None: LOG.warn(_LW("RackConnect unprocessable reason: %s"), reason) msg = _("RackConnect automation has completed") self._add_event(self.action, self.status, msg) return True elif rc_status == self.RC_STATUS_FAILED: raise exception.Error(_("RackConnect automation FAILED")) else: msg = _("Unknown RackConnect automation status: %s") % rc_status raise exception.Error(msg) def check_create_complete(self, server): """Check if server creation is complete and handle server configs.""" if not super(CloudServer, self).check_create_complete(server): return False self.client_plugin().refresh_server(server) if ('rack_connect' in self.context.roles and not self._check_rack_connect_complete(server)): return False if ('rax_managed' in self.context.roles and not self._check_managed_cloud_complete(server)): return False return True def resource_mapping(): return {'OS::Nova::Server': CloudServer} def available_resource_mapping(): if PYRAX_INSTALLED: return resource_mapping() return {}
# Contributing Guide ## System Requirements - make - docker - git - nodejs >= 10 ## Begin After install system requirements run the following commands. ```Shell npm install ``` ## Shellcheck The code syntax is verified by shellcheck. > Before commit ## Commit Message The project uses [conventional commit](https://www.conventionalcommits.org/en/v1.0.0/) for validate commit message. > After commit ## Unit Testing ```Shell make test.unit ``` ## Integration tests and compatibility matrix To run all tests locally use: ```Shell ./pipeline.sh ``` > You can test the code at github, just enable pipeline at your fork.
#include <stdio.h> #include <unistd.h> #include <stdlib.h> void read_input(char *buf,unsigned int size){ int ret ; ret = __read_chk(0,buf,size,size); if(ret <= 0){ puts("read error"); _exit(1); } if(buf[ret-1] == '\n') buf[ret-1] = '\x00'; } char buf[0x10]; int main(){ setvbuf(stdin,0,_IONBF,0); setvbuf(stdout,0,_IONBF,0); setvbuf(stderr,0,_IONBF,0); for(unsigned int i = 4 ; i >= 0 ; i--){ printf("Input:"); read_input(buf,0x10); printf(buf); puts(""); close(i); } }
import csv import json import urllib from datetime import datetime, timedelta from io import StringIO from typing import List, Dict, Union, Optional from urllib.parse import urljoin import logging from xml.etree import ElementTree as ET import traceback import requests from pycounter import sushi from pycounter.csvhelper import UnicodeWriter from .counter5 import Counter5TRReport, Counter5DRReport, Counter5ReportBase from .exceptions import SushiException logger = logging.getLogger(__name__) ns_soap = 'http://schemas.xmlsoap.org/soap/envelope/' ns_sushi = 'http://www.niso.org/schemas/sushi' ns_counter = 'http://www.niso.org/schemas/sushi/counter' namespaces = { 's': ns_soap, 'sushi': ns_sushi, 'counter': ns_counter } class SushiError(object): def __init__(self, code='', text='', full_log='', raw_data=None, severity=None): self.code = code self.severity = severity self.text = text self.full_log = full_log self.raw_data = raw_data def __str__(self): return self.full_log class SushiErrorMeaning(object): RETRY_IN_MINUTES = 1 RETRY_IN_HOURS = 2 RETRY_IN_DAYS = 3 RETRY_IN_WEEKS = 4 RETRY_IN_MONTHS = 5 RETRY_AFTER_CHECKUP = 100 RETRY_INTERVAL_TO_TIMEDELTA = { RETRY_IN_MINUTES: timedelta(minutes=1), RETRY_IN_HOURS: timedelta(hours=1), RETRY_IN_DAYS: timedelta(days=1), RETRY_IN_WEEKS: timedelta(weeks=1), RETRY_IN_MONTHS: timedelta(days=30), } def __init__(self, should_retry=False, needs_checking=True, setup_ok=False, retry_interval=RETRY_AFTER_CHECKUP): """ :param should_retry: :param needs_checking: the credentials or the whole setup should be checked - no sense in retrying before changing something :param retry_interval: how fast should be retry :param setup_ok: if true, it means the credentials and report type are OK, just that there was something other with the request (wrong date, etc.) - we can try other dates """ self.should_retry = should_retry self.needs_checking = needs_checking self.retry_interval = retry_interval self.setup_ok = setup_ok @property def retry_interval_timedelta(self): return self.RETRY_INTERVAL_TO_TIMEDELTA.get(self.retry_interval) class SushiClientBase(object): def __init__(self, url, requestor_id, customer_id=None, extra_params=None, auth=None): self.url = url self.requestor_id = requestor_id self.customer_id = customer_id self.extra_params = extra_params self.auth = auth def extract_errors_from_data(self, report_data) -> [SushiError]: raise NotImplementedError() def report_to_string(self, report_data): raise NotImplementedError() def get_report_data(self, report_type, begin_date, end_date, params=None): raise NotImplementedError() @classmethod def explain_error_code(cls, error_code) -> SushiErrorMeaning: try: error_code = int(error_code) except ValueError: return SushiErrorMeaning(should_retry=True, needs_checking=True, setup_ok=False) if error_code in (3000, 3010): # report is not supported, so it was successful, but no data return SushiErrorMeaning(should_retry=False, needs_checking=False, setup_ok=False) elif error_code in (3030,): # no usage data for the requested period, it is success, but again no data # unfortunately, some providers, such as Clarivate (Web Of Science) use this # wrongly in cases when 3031 should be used, so we need to treat it like this return SushiErrorMeaning(should_retry=True, needs_checking=False, setup_ok=True, retry_interval=SushiErrorMeaning.RETRY_IN_WEEKS) elif error_code in (1010, 1011, 1020): # some forms of 'try it later' errors return SushiErrorMeaning(should_retry=True, needs_checking=False, setup_ok=True, retry_interval=SushiErrorMeaning.RETRY_IN_MINUTES) elif error_code in (3031,): # the data is not yet available - usually some months are missing return SushiErrorMeaning(should_retry=True, needs_checking=False, setup_ok=True, retry_interval=SushiErrorMeaning.RETRY_IN_WEEKS) elif error_code >= 4000: # some other stuff for which we want to check later if the data exists # in the wild, we have seen 4010 return SushiErrorMeaning(should_retry=True, needs_checking=False, setup_ok=True, retry_interval=SushiErrorMeaning.RETRY_IN_WEEKS) else: return SushiErrorMeaning(should_retry=True, needs_checking=True, setup_ok=False) class Sushi5Client(SushiClientBase): """ Client for SUSHI and COUNTER 5 protocol """ CUSTOMER_ID_PARAM = 'customer_id' REQUESTOR_ID_PARAM = 'requestor_id' report_types = { 'tr': { 'name': 'Title report', 'subreports': { 'b1': 'Book requests excluding OA_Gold', 'b2': 'Books - access denied', 'b3': 'Book Usage by Access Type', 'j1': 'Journal requests excluding OA_Gold', 'j2': 'Journal articles - access denied', 'j3': 'Journal usage by Access Type', 'j4': 'Journal Requests by YOP (Excluding OA_Gold)', }, }, 'dr': { 'name': 'Database report', 'subreports': { 'd1': 'Search and Item usage', 'd2': 'Database Access Denied' }, }, 'ir': { 'name': 'Item report', 'subreports': { 'a1': 'Journal article requests', 'm1': 'Multimedia item requests', }, }, 'pr': { 'name': 'Platform report', 'subreports': { 'p1': 'View by Metric_Type', }, } } # sets of additional parameters for specific setups EXTRA_PARAMS = { # split data in TR report to most possible dimensions for most granular data 'maximum_split': { 'tr': {'attributes_to_show': 'YOP|Access_Method|Access_Type|Data_Type|Section_Type'}, 'pr': {'attributes_to_show': 'Access_Method|Data_Type'}, 'dr': {'attributes_to_show': 'Access_Method|Data_Type'}, } } def __init__(self, url, requestor_id, customer_id=None, extra_params=None, auth=None): super().__init__(url, requestor_id, customer_id, extra_params, auth) self.session = requests.Session() self.session.headers.update( {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0' }) @classmethod def _encode_date(cls, value) -> str: """ >>> Sushi5Client._encode_date('2018-02-30') '2018-02' >>> Sushi5Client._encode_date(datetime(2018, 7, 6, 12, 25, 30)) '2018-07' """ if hasattr(value, 'isoformat'): return value.isoformat()[:7] return value[:7] def _construct_url_params(self, extra=None): result = { self.CUSTOMER_ID_PARAM: self.customer_id if self.customer_id else self.requestor_id, } if self.requestor_id: result[self.REQUESTOR_ID_PARAM] = self.requestor_id if self.extra_params: result.update(self.extra_params) if extra: result.update(extra) return result def _make_request(self, url, params): logger.debug('Making request to :%s?%s', url, urllib.parse.urlencode(params)) kwargs = {} if self.auth: kwargs['auth'] = self.auth return self.session.get(url, params=params, **kwargs) def get_available_reports_raw(self, params=None) -> bytes: """ Return a list of available reports :return: """ url = '/'.join([self.url.rstrip('/'), 'reports/']) params = self._construct_url_params(extra=params) response = self._make_request(url, params) response.raise_for_status() return response.content def get_available_reports(self, params=None) -> list: content = self.get_available_reports_raw(params=params) reports = self.report_to_data(content) return reports def get_report(self, report_type, begin_date, end_date, params=None): """ Return a SUSHI report based on the provided params :param report_type: :param begin_date: :param end_date: :param params: :return: """ report_type = self._check_report_type(report_type) url = '/'.join([self.url.rstrip('/'), 'reports', report_type]) params = self._construct_url_params(extra=params) params['begin_date'] = self._encode_date(begin_date) params['end_date'] = self._encode_date(end_date) response = self._make_request(url, params) response.raise_for_status() return response.content def get_report_data(self, report_type, begin_date, end_date, params=None) -> \ Counter5ReportBase: content = self.get_report(report_type, begin_date, end_date, params=params) if report_type.lower() == 'tr': report_class = Counter5TRReport elif report_type.lower() == 'dr': report_class = Counter5DRReport else: report_class = Counter5ReportBase data = json.loads(content) return report_class(data) def report_to_data(self, report: bytes, validate=True): try: data = json.loads(report) except ValueError as e: raise SushiException(str(e), content=report) if validate: self.validate_data(data) return data @classmethod def validate_data(cls, data: Union[Dict, List]): """ Checks that the provided data contain valid COUNTER data and not an error. If the data contains an error message, it will raise SushiException :param data: :return: """ if type(data) is list: # for list, we validate the whole list for item in data: cls.validate_data(item) return if 'Exception' in data: exc = data['Exception'] raise SushiException(cls._format_error(exc), content=data) if 'Severity' in data and data['Severity'] == 'Error': raise SushiException(cls._format_error(data), content=data) header = data.get('Report_Header', {}) errors = [] for exception in header.get('Exceptions', []): if exception.get('Severity') in ('Info', 'Warning'): logging.warning("Warning Exception in COUNTER 5 report: %s", cls._format_error(exception)) else: errors.append(exception) if errors: message = '; '.join(cls._format_error(error).full_log for error in errors) raise SushiException(message, content=data) def extract_errors_from_data(self, report_data): if 'Exception' in report_data: exc = report_data['Exception'] return self._format_error(exc) if 'Severity' in report_data and report_data['Severity'] == 'Error': return self._format_error(report_data) header = report_data.get('Report_Header', {}) errors = [] for exception in header.get('Exceptions', []): if exception.get('Severity') in ('Info', 'Warning'): logging.warning("Warning Exception in COUNTER 5 report: %s", self._format_error(exception)) else: errors.append(self._format_error(exception)) return errors @classmethod def _format_error(cls, exc: dict): message = '{Severity} error {Code}: {Message}'.format(**exc) if 'Data' in exc: message += '; {}'.format(exc['Data']) error = SushiError( code=exc.get('Code', ''), text=exc.get('Message' ''), full_log=message, severity=exc.get('Severity'), raw_data=exc, ) return error def _check_report_type(self, report_type): report_type = report_type.lower() if '_' in report_type: main_type, subtype = report_type.split('_', 1) else: main_type = report_type subtype = None if main_type not in self.report_types: raise ValueError(f'Report type {main_type} is not supported.') if subtype and subtype not in self.report_types[main_type]['subreports']: raise ValueError(f'Report subtype {subtype} is not supported for type {main_type}.') return report_type def report_to_string(self, report_data): return json.dumps(report_data, ensure_ascii=False, indent=2) class Sushi4Client(SushiClientBase): """ Client for SUSHI and COUNTER 4 protocol - a simple proxy for the pycounter.sushi implementation """ # remap of extra params into names that have special meaning for the pycounter client extra_params_remap = { 'Name': 'requestor_name', 'Email': 'requestor_email', } def __init__(self, url, requestor_id, customer_id=None, extra_params=None, auth=None): super().__init__(url, requestor_id, customer_id, extra_params, auth) @classmethod def _encode_date(cls, value) -> str: if hasattr(value, 'isoformat'): return value.isoformat()[:7] return value[:7] def get_report_data(self, report_type, begin_date, end_date, params=None): kwargs = {'customer_reference': self.customer_id} if self.requestor_id: kwargs['requestor_id'] = self.requestor_id if params: # recode params that have special meaning for orig, new in self.extra_params_remap.items(): if orig in params: kwargs[new] = params.pop(orig) # put the rest in as it is kwargs.update(params) if self.auth: kwargs['auth'] = self.auth report = sushi.get_report(self.url, begin_date, end_date, report=report_type, **kwargs) return report def extract_errors_from_data(self, report_data): try: envelope = ET.fromstring(report_data) body = envelope[0] response = body[0] if len(body) > 0 else None except Exception as e: log = f'Exception: {e}\nTraceback: {traceback.format_exc()}' return [SushiError( code='non-sushi', text=str(e), full_log=log, severity='Exception', )] else: errors = [] if response is not None: for exception in response.findall('sushi:Exception', namespaces): code = exception.find('sushi:Number', namespaces) code = code.text if code is not None else '' message = exception.find('sushi:Message', namespaces) message = message.text if message is not None else '' severity = exception.find('sushi:Severity', namespaces) severity = severity.text if severity is not None else 'Unknown' full_log = f'{severity}: #{code}; {message}' errors.append(SushiError( code=code, text=message, severity=severity, full_log=full_log, raw_data=str(exception), )) if not errors: errors.append(SushiError( code='non-sushi', text='Could not find Exception data in XML, probably wrong format', full_log='Could not find Exception data in XML, probably wrong format', severity='Exception',) ) return errors def report_to_string(self, report_data): lines = report_data.as_generic() out = StringIO() writer = csv.writer(out, dialect='excel', delimiter="\t") writer.writerows(lines) return out.getvalue()
package net.adoptium.api.v3.models import java.time.ZonedDateTime abstract class DbStatsEntry<T>( val date: ZonedDateTime ) { abstract fun getMetric(): Long abstract fun getId(): T }
# memory [![GoDoc](https://godoc.org/github.com/vardius/go-api-boilerplate/pkg/commandbus/memory?status.svg)](https://godoc.org/github.com/vardius/go-api-boilerplate/pkg/commandbus/memory) Package memory provides memory implementation of command bus Download: ```shell go get -u github.com/vardius/go-api-boilerplate/pkg/commandbus/memory ``` * * * Package memory provides command bus interfaces
package repositories_test import ( "encoder/application/repositories" "encoder/domain" "encoder/framework/database" "testing" "time" "github.com/jaswdr/faker" uuid "github.com/satori/go.uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestIfJobRepositoryCanInsertAJob(t *testing.T) { fake := faker.New() db := database.NewTestDB() video := domain.NewVideo() video.ID = uuid.NewV4().String() video.ResourceID = uuid.NewV4().String() video.FilePath = fake.File().FilenameWithExtension() video.CreatedAt = time.Now() if err := video.Validate(); err != nil { t.Errorf("error while validating the video: %s", err.Error()) } job, err := domain.NewJob(fake.File().FilenameWithExtension(), "OnGoing", video) if err != nil { t.Errorf("error while creating the new job: %s", err.Error()) } repo := repositories.NewJobRepository(db) _, err = repo.Insert(job) if err != nil { t.Errorf("error while inserting the new job: %s", err.Error()) } var foundJob domain.Job db.Raw("SELECT * FROM jobs WHERE id = ?", job.ID).Scan(&foundJob) require.Equal(t, job.ID, foundJob.ID) } func TestIfJobRepositoryDoesNotReturnErrorWhenInsert(t *testing.T) { fake := faker.New() db := database.NewTestDB() video := domain.NewVideo() video.ID = uuid.NewV4().String() video.FilePath = fake.File().FilenameWithExtension() video.CreatedAt = time.Now() job, err := domain.NewJob(fake.File().FilenameWithExtension(), "status", video) if err != nil { t.Errorf("error while creating the new job: %s", err.Error()) } repo := repositories.NewJobRepository(db) _, err = repo.Insert(job) require.Nil(t, err) } func TestIJobRepositoryReturnVideoWhenItInserted(t *testing.T) { fake := faker.New() db := database.NewTestDB() video := domain.NewVideo() video.ID = uuid.NewV4().String() video.FilePath = fake.File().FilenameWithExtension() video.CreatedAt = time.Now() job, err := domain.NewJob(fake.File().FilenameWithExtension(), "status", video) if err != nil { t.Errorf("error while creating the new job: %s", err.Error()) } repo := repositories.NewJobRepository(db) returnedJob, err := repo.Insert(job) if err != nil { t.Errorf("error while inserting the video, %s", err.Error()) } require.Equal(t, job.ID, returnedJob.ID) } func TestIfJobRepositoryReturnErrorWhenSearchForAnNonexistentVideo(t *testing.T) { db := database.NewTestDB() id := uuid.NewV4().String() repo := repositories.NewJobRepository(db) _, err := repo.FindById(id) if err == nil { t.Error("error: find by id should return an error") } require.Error(t, err) } func TestIfJobRepositoryReturnNilVideoWhenSearchForAnNonexistentVideo(t *testing.T) { db := database.NewTestDB() id := uuid.NewV4().String() repo := repositories.NewJobRepository(db) foundJob, err := repo.FindById(id) if err == nil { t.Error("error: find by id should return an error") } require.Nil(t, foundJob) } func TestIfJobRepositoryCanFindByIdAnExistentVideo(t *testing.T) { fake := faker.New() db := database.NewTestDB() video := domain.NewVideo() video.ID = uuid.NewV4().String() video.FilePath = fake.File().FilenameWithExtension() video.CreatedAt = time.Now() job, err := domain.NewJob(fake.File().FilenameWithExtension(), "status", video) if err != nil { t.Errorf("error while creating the new job: %s", err.Error()) } if err := db.Create(job); err.Error != nil { t.Errorf("error while inserting the video, %s", err.Error) } repo := repositories.NewJobRepository(db) foundJob, err := repo.FindById(job.ID) if err != nil { t.Errorf("error while searching for the video, %s", err.Error()) } require.Equal(t, job.ID, foundJob.ID) } func TestIfJobRepositoryCanPopulateVideoWhenFind(t *testing.T) { fake := faker.New() db := database.NewTestDB() video := domain.NewVideo() video.ID = uuid.NewV4().String() video.FilePath = fake.File().FilenameWithExtension() video.CreatedAt = time.Now() job, err := domain.NewJob(fake.File().FilenameWithExtension(), "status", video) if err != nil { t.Errorf("error while creating the new job: %s", err.Error()) } if err := db.Create(job); err.Error != nil { t.Errorf("error while inserting the video, %s", err.Error) } repo := repositories.NewJobRepository(db) foundJob, err := repo.FindById(job.ID) if err != nil { t.Errorf("error while searching for the video, %s", err.Error()) } require.Equal(t, job.Video.ResourceID, foundJob.Video.ResourceID) } func TestUpdateShouldReturnAnErrorIfJobDoesNotExists(t *testing.T) { fake := faker.New() db := database.NewTestDB() video := domain.NewVideo() video.ID = uuid.NewV4().String() video.FilePath = fake.File().FilenameWithExtension() video.CreatedAt = time.Now() job, err := domain.NewJob(fake.File().FilenameWithExtension(), "status", video) if err != nil { t.Errorf("error while creating the new job: %s", err.Error()) } repo := repositories.NewJobRepository(db) _, err = repo.Update(job) require.Error(t, err) } func TestUpdateShouldReturnAnNullJobIfJobDoesNotExists(t *testing.T) { fake := faker.New() db := database.NewTestDB() video := domain.NewVideo() video.ID = uuid.NewV4().String() video.FilePath = fake.File().FilenameWithExtension() video.CreatedAt = time.Now() job, err := domain.NewJob(fake.File().FilenameWithExtension(), "status", video) if err != nil { t.Errorf("error while creating the new job: %s", err.Error()) } repo := repositories.NewJobRepository(db) updatedJob, _ := repo.Update(job) assert.Nil(t, updatedJob) } func TestShouldNotReturnErrorIfJobExistsWhenUpdating(t *testing.T) { fake := faker.New() db := database.NewTestDB() video := domain.NewVideo() video.ID = uuid.NewV4().String() video.FilePath = fake.File().FilenameWithExtension() video.CreatedAt = time.Now() job, err := domain.NewJob(fake.File().FilenameWithExtension(), "status", video) if err != nil { t.Errorf("error while creating the new job: %s", err.Error()) } repo := repositories.NewJobRepository(db) _, err = repo.Insert(job) if err != nil { t.Errorf("error while inserting the video, %s", err.Error()) } job.Status = "altered status" _, err = repo.Update(job) assert.Nil(t, err) } func TestShouldNotReturnAnNilJobIfJobExistsWhenUpdating(t *testing.T) { fake := faker.New() db := database.NewTestDB() video := domain.NewVideo() video.ID = uuid.NewV4().String() video.FilePath = fake.File().FilenameWithExtension() video.CreatedAt = time.Now() job, err := domain.NewJob(fake.File().FilenameWithExtension(), "status", video) if err != nil { t.Errorf("error while creating the new job: %s", err.Error()) } repo := repositories.NewJobRepository(db) _, err = repo.Insert(job) if err != nil { t.Errorf("error while inserting the video, %s", err.Error()) } job.Status = "altered status" updatedJob, err := repo.Update(job) if err != nil { t.Errorf("error while updating the job: %s\n", err.Error()) } assert.NotNil(t, updatedJob) } func TestShouldUpdateStatusWhenJobExists(t *testing.T) { fake := faker.New() db := database.NewTestDB() video := domain.NewVideo() video.ID = uuid.NewV4().String() video.FilePath = fake.File().FilenameWithExtension() video.CreatedAt = time.Now() job, err := domain.NewJob(fake.File().FilenameWithExtension(), "status", video) if err != nil { t.Errorf("error while creating the new job: %s", err.Error()) } repo := repositories.NewJobRepository(db) _, err = repo.Insert(job) if err != nil { t.Errorf("error while inserting the video, %s", err.Error()) } job.Status = "altered status" if _, err = repo.Update(job); err != nil { t.Errorf("error while updating the job: %s\n", err.Error()) } var foundJob domain.Job db.First(&foundJob, "id = ?", job.ID) assert.Equal(t, "altered status", foundJob.Status) }
export async function getMeta(url: string) { const res = await fetch(`https://oge.now.sh/api?url=${decodeURIComponent(url)}`) const jsonRes = await res.json() return jsonRes }
use std; use failure; use zicsv; use print_err; pub struct SelectOptions { pub ipv4: bool, pub ipv4_network: bool, pub domain: bool, pub wildcard_domain: bool, pub url: bool, } pub fn select<StreamWriter>( options: &SelectOptions, mut reader: Box<zicsv::GenericReader>, writer: &mut StreamWriter, ) -> Result<(), failure::Error> where StreamWriter: std::io::Write, { let mut n_errors = 0usize; for record in reader.iter() { match record { Ok(record) => for address in &record.addresses { let selected = match *address { zicsv::Address::IPv4(_) => options.ipv4, zicsv::Address::IPv4Network(_) => options.ipv4_network, zicsv::Address::DomainName(_) => options.domain, zicsv::Address::WildcardDomainName(_) => options.wildcard_domain, zicsv::Address::URL(_) => options.url, // Do nothing on unknown type of address. _ => false, }; if selected { writeln!(writer, "{}", address)?; } }, Err(error) => { n_errors += 1; print_err::print_error(&error); }, } } ensure!(n_errors == 0, "{} errors occur while reading list", n_errors); Ok(()) }
export declare const help: () => string; export declare function main(): Promise<void>; //# sourceMappingURL=status.d.ts.map
import React from 'react'; import logoImg from '@@/assets/img/logo.svg'; const Logo: React.FC = () => <img src={logoImg} />; export default Logo;
import {Component} from '@angular/core'; @Component({ selector: 'demo-stack-overflow', template: ` <demo-hide-custom-bp></demo-hide-custom-bp> <demo-moz-holy-grail class='small-demo'></demo-moz-holy-grail> <demo-complex-column-ordering></demo-complex-column-ordering> <demo-grid-area-row-span></demo-grid-area-row-span> <demo-grid-column-span></demo-grid-column-span> ` }) export class StackOverflowComponent {}
# pyomeka-s import json import logging import hashlib import os import pdb import requests # setup logger logging.basicConfig(level=logging.DEBUG) # parso shims logging.getLogger('parso.python.diff').disabled = True logging.getLogger('parso.cache').disabled = True logger = logging.getLogger(__name__) # look for config.json at ~/pyomeka-s.json config_json_path = os.path.join(os.path.expanduser("~"),'pyomeka-s.json') if os.path.exists(config_json_path): logger.debug('pyomeka-s.json located, using...') with open(config_json_path,'r') as f: config = json.loads(f.read()) else: config = None class Repository(object): ''' Class to represent Omeka-S instance ''' def __init__(self): # if config loaded, use if config: self.api_endpoint = config['repository']['api_endpoint'] self.api_key_identity = config['repository']['api_key_identity'] self.api_key_credential = config['repository']['api_key_credential'] # API instance self.api = API( api_endpoint=self.api_endpoint, api_key_identity=self.api_key_identity, api_key_credential=self.api_key_credential) def get_items(self, per_page=25, use_cache=False): ''' Method to list items in Repository Returns: generator ''' # api GET request response = self.api.get('items', params={'per_page':per_page}, use_cache=use_cache) # return if response.status_code == 200: # parse JSON response = response.json() # yield for item_json in response: yield Item(self, item_json) def get_item(self, item_id, use_cache=False): ''' Method to return single item ''' # api GET request response = self.api.get('items/%s' % item_id, params={}, use_cache=use_cache) # return if response.status_code == 200: # return Item return Item(self, response.json()) else: return None def get_vocabularies(self, per_page=100): ''' Method to return info about vocabularies ''' # api GET request response = self.api.get('vocabularies', params={'per_page':per_page}) # return if response.status_code == 200: # return as Vocabulary instances return [ Vocabulary(self, vocab) for vocab in response.json() ] def get_vocabulary(self, prefix=None, uri=None): ''' Retrieve Vocabulary by prefix or URI ''' # api GET request if prefix != None: response = self.api.get('vocabularies', params={'prefix':prefix}) elif uri != None: response = self.api.get('vocabularies', params={'namespace_uri':uri}) if response.status_code == 200: # parse for length vocabs = response.json() if len(vocabs) == 1: return Vocabulary(self, vocabs[0]) else: logger.debug('multiple vocabularies found, returning as list') return [ Vocabulary(self, vocab) for vocab in vocabs ] def get_property(self, term): ''' Method to return Property based on term - assume full prefix:local_name as this level ''' # api GET request response = self.api.get('properties', params={'term':term}) # parse if response.status_code == 200: properties = response.json() # if one, return as single Property if len(properties) == 1: return Property(self, properties[0]) elif len(properties) == 0: raise Exception('property not found: %s' % term) else: raise Exception('expecting 1 but found %s properties for qualified term: %s' % (len(properties), term)) class API(object): ''' Class to handle API requests/responses ''' def __init__(self, api_endpoint=None, api_key_identity=None, api_key_credential=None, authenticate_all_requests=True): self.api_endpoint = api_endpoint self.api_key_identity = api_key_identity self.api_key_credential = api_key_credential self.authenticate_all_requests = authenticate_all_requests # init cache self.cache = APICache() self.use_cache = True def _merge_credentials(self, params): params.update({ 'key_identity':self.api_key_identity, 'key_credential':self.api_key_credential }) return params def get(self, path, params = {}, use_cache=None): ''' GET requsts to API ''' # handle caching flag if use_cache == None: use_cache = self.use_cache # credential if self.authenticate_all_requests: params = self._merge_credentials(params) # check cache if use_cache: cache_hit = self.cache.cache_check('get', {'path':path,'params':params}) if cache_hit != None: return cache_hit # issue GET request response = requests.get('%s/%s' % (self.api_endpoint, path.lstrip('/')), params=params) # store cache if response.status_code == 200: if use_cache and cache_hit == None: self.cache.cache_store('get', {'path':path,'params':params}, response) # return return response def patch(self, path, json_body, params = {}): ''' PATCH requsts to API - for PATCH requests, credentials are needed ''' # credential params = self._merge_credentials(params) logger.debug(params) # issue GET request response = requests.patch('%s/%s' % (self.api_endpoint, path.lstrip('/')), params=params, json=json_body) return response class APICache(object): ''' Class for API Cache - naive, lightweight - only cache Property and Vocabulary queries - unlikely to change ''' def __init__(self): self.store = { 'get':{}, 'patch':{} } def _calc_cache_hash(self, dict): ''' Calcuate MD5 hash based on dictionary ''' return hashlib.md5(json.dumps(dict, sort_keys=True).encode('utf-8')).hexdigest() def cache_check(self, http_verb, dict): ''' Check cache based on dict ''' cache_hit = self.store.get(http_verb).get(self._calc_cache_hash(dict), None) return cache_hit def cache_store(self, http_verb, dict, response): ''' Store response ''' self.store[http_verb][self._calc_cache_hash(dict)] = response class Item(object): ''' Class to represent an Omeka-S Item ''' def __init__(self, repo, item_json): # store repository instance self.repo = repo # store json self.json = item_json # init rollback versions with 0th version self.versions = { 0:self.json.copy() } @property def id(self): return self.json.get('o:id') @property def uri(self): return self.json.get('@id') def __repr__(self): return '<Item: #%s, "%s">' % (self.id, self.title) def _calc_last_version_id(self): ''' Method to return most recent version id Returns: (int): integer key of self.versions ''' vkeys = list(self.versions.keys()) vkeys.sort() return vkeys[-1] @property def title(self): ''' Return title based on Omeka-S default to dcterms:title ''' title = self.get_property('dcterms:title') if title != []: return title[0].value else: return '[Untitled]' def get_properties(self): ''' Return metadata properties ''' _omeka_internal = ['@context','@id','@type'] # loop and create subset props = {} for property_name in self.json.keys(): if property_name not in _omeka_internal and not property_name.startswith('o:'): props[property_name] = [ Value(self.repo, value_json) for value_json in self.json.get(property_name) ] # return return props def get_property(self, property_input, default=[]): ''' Return instance of single Property ''' # handle property_input prop = self._handle_property_arg(property_input) value_instances = self.json.get(prop.term, default) return [ Value(self.repo, value_json) for value_json in value_instances ] def _handle_property_arg(self, property_input): ''' Method to return Property instance given equivocal input ''' # handle property_input if type(property_input) == Property: prop = property_input elif type(property_input) == str: # query for property_input id prop = self.repo.get_property(property_input) else: raise Exception('expecting str or Property instance as property') # return return prop def add_property(self, property_input, value, is_public=True, property_type='literal'): ''' Method to add Property - literal values may repeat Args: term (str|Property): if string, assume prefix:local_name, else use Property value: value to set for @value Value instance: { '@value': '...', 'is_public': True, 'property_id': 1, 'property_label': 'Title', 'type': 'literal' } ''' # handle property_input prop = self._handle_property_arg(property_input) # build value dictionary val_dict = { '@value': value, 'is_public': True, 'property_id': prop.id, 'property_label': prop.label, 'type': property_type } # append if term exists, else create if prop.term in self.get_properties().keys(): self.json[prop.term].append(val_dict) else: self.json[prop.term] = [val_dict] def remove_value(self, property_input, value): ''' Method to remove property from Item ''' # handle property_input prop = self._handle_property_arg(property_input) # check self for property AND value e_values = self.get_property(prop) # comprehend values sans matches values_keep = [ e_value for e_value in e_values if e_value.value != value ] # update property self.json[prop.term] = [ value.json for value in values_keep ] def update(self): ''' Method to update Item in Repository ''' # PATCH with self.json response = self.repo.api.patch('items/%s' % self.id, self.json) if response.status_code == 200: # write version self.write_version(response.json()) # return return True def write_version(self, item_version_json): ''' Method to write version ''' # get new version to write last_version_id = self._calc_last_version_id() + 1 # write logger.debug('writing item v%s' % last_version_id) self.versions[last_version_id] = item_version_json def refresh(self): ''' Methdo to refresh Item ''' # get self from repository _item = self.repo.get_item(self.id, use_cache=False) # write version self.write_version(_item.json.copy()) # set self.json = _item.json.copy() class Property(object): ''' Class to represent Property Property Model example: { "@context": "http://example.com/api-context", "@id": "http://example.com/api/properties/1", "@type": "o:Property", "o:id": 1, "o:local_name": "title", "o:label": "Title", "o:comment": "A name given to the resource.", "o:term": "dcterms:title", "o:vocabulary": { "@id": "http://example.com/api/vocabularies/1", "o:id": 1 } } ''' def __init__(self, repo, property_json): # store repository instance self.repo = repo # store json self.json = property_json @property def id(self): return self.json.get('o:id') @property def term(self): return self.json.get('o:term') @property def label(self): return self.json.get('o:label') @property def comment(self): return self.json.get('o:comment') @property def vocabulary_id(self): return self.json.get('o:vocabulary').get('o:id') def __repr__(self): return '<Property: #%s, %s, "%s">' % (self.id, self.term, self.label) @property def vocabulary(self): ''' Return instance of associated Vocabulary ''' # query response = self.repo.api.get('vocabularies', params={'id':self.vocabulary_id}) if response.status_code == 200: return Vocabulary(self.repo, response.json()) class Value(object): ''' Class to represent value of property Value Instance: { '@value': '...', 'is_public': True, 'property_id': 1, 'property_label': 'Title', 'type': 'literal' } ''' def __init__(self, repo, value_json): # store repo self.repo = repo # store json self.json = value_json def __repr__(self, tlen=50): if self.value != None: if type(self.value) == str: value_repr = self.value[:tlen] + '..' if len(self.value) > tlen else self.value else: value_repr = self.value else: value_repr = None return '<Value: "%s">' % (value_repr) @property def value(self): return self.json.get('@value', None) @property def property_label(self): return self.json.get('property_label') @property def property_id(self): return self.json.get('property_id', None) @property def property(self): ''' Property to return Property instance associated with Value ''' # query response = self.repo.api.get('properties', params={'id':self.property_id}) if response.status_code == 200: return Property(self.repo, response.json()) class Vocabulary(object): ''' Class to represent Omeka-S Vocabulary ''' def __init__(self, repo, vocab_json): # store repository instance self.repo = repo # store json self.json = vocab_json @property def id(self): return self.json.get('o:id') @property def uri(self): return self.json.get('@id') @property def uri(self): return self.json.get('o:namespace_uri') @property def prefix(self): return self.json.get('o:prefix') @property def label(self): return self.json.get('o:label') @property def comment(self): return self.json.get('o:comment') def __repr__(self): return '<Vocabulary: #%s, %s, prefix:%s, uri:%s>' % (self.id, self.label, self.prefix, self.uri) def get_properties(self): ''' Method to return all associated Properties - query /properties endpoint, searching by vocab id Returns: generator ''' # api GET request response = self.repo.api.get('properties', params={'vocabulary_id':self.id}) # return if response.status_code == 200: # parse JSON response = response.json() # yield for property_json in response: yield Property(self.repo, property_json) def get_property(self, term): ''' Method to return property Args: term (str): term, with or without Vocabulary namespace prefex ''' # remove prefix if added if self.prefix in term: term = term.split('%s:')[-1] # api GET request response = self.repo.api.get('properties', params={'vocabulary_id':self.id, 'local_name':term}) # return if response.status_code == 200: # should only be one, confirm and return properties = response.json() if len(properties) == 1: return Property(self.repo, properties[0]) else: raise Exception('only expecting on property for this vocabulary for term: %s' % term)
#!/usr/bin/env bash source lib/* items=( "first item" "second item" "third item" "some another item" ) menu "${items[@]}" messagebox "Selected item is: $SELECTED_ITEM"
## Attendance.mvc A CodeIgniter based attendance system.<br /> It follows mvc architecture so all components are present in *"Application/their-respective-directory's"* All app logic's are presented in form of controller mainly we have following controllers. 1. AttendancePanel.php 2. Login.php 3. SaveAttendance.php 4. Search.php 5. Selector.php 6. ViewAttendance.php
# ExonCov ExonCov: Exon coverage statistics from BAM files ### Requirements - [Python 2.7](https://www.python.org/) - [Virtualenv](https://virtualenv.pypa.io/en/stable/) - [MYSQL](https://www.mysql.com/) - [sambamba](https://github.com/biod/sambamba) - [Dx Tracks](https://github.com/UMCUGenetics/Dx_tracks) ### Setup ```bash # Clone git repository git clone git@github.com:UMCUGenetics/ExonCov.git cd ExonCov # Setup python virtual environment and install python dependencies virtualenv venv . venv/bin/activate pip install -r requirements.txt ``` #### Edit config.py Change the following lines in config.py ```python SQLALCHEMY_DATABASE_URI = 'mysql://<user>:<password>@localhost/exoncov3' SECRET_KEY = <generate_key> SECURITY_PASSWORD_SALT = <generate_salt> EXON_BED_FILE = 'path/to/Dx_tracks/Tracks/ENSEMBL_UCSC_merged_collapsed_sorted_v3_20bpflank.bed' GENE_TRANSCRIPT_FILE = 'path/to/Dx_tracks/Exoncov/NM_ENSEMBL_HGNC.txt' PREFERRED_TRANSCRIPTS_FILE = 'path/to/Dx_tracks/Exoncov/Preferred_transcript_list.txt' GENE_PANEL_FILE = 'path/to/Dx_tracks/Exoncov/gpanels.txt' SAMBAMBA = 'path/to/sambamba' EXON_MEASUREMENTS_RSYNC_PATH = 'rsync/path/for/data' ``` ### Load design ```bash cd /path/to/Exoncov . venv/bin/activate python ExonCov.py load_design ``` ### Import bam file ```bash cd /path/to/Exoncov . venv/bin/activate python ExonCov.py import_bam <project_name> <bam_file> ``` ### Run development webserver ```bash python ExonCov.py runserver -r -d ``` ### Export and Import existing ExonCov db Ignore large tables, samples should be imported using cli. ```bash mysqldump --user=<user> --password --no-data --tab=<dir_name> exoncov mysqldump --user=<user> --password --no-data --tab=<dir_name> exoncov \ --ignore-table=exoncov.custom_panels \ --ignore-table=exoncov.custom_panels_samples \ --ignore-table=exoncov.custom_panels_transcripts \ --ignore-table=exoncov.sample_projects \ --ignore-table=exoncov.sample_sets \ --ignore-table=exoncov.sample_sets_samples \ --ignore-table=exoncov.samples \ --ignore-table=exoncov.samples_sequencingRun \ --ignore-table=exoncov.sequencing_runs \ --ignore-table=exoncov.transcript_measurements cat <dir_name>/*.sql > tables.sql mysql --init-command="SET SESSION FOREIGN_KEY_CHECKS=0;" --user=exoncov --password exoncov < tables.sql mysql --init-command="SET SESSION FOREIGN_KEY_CHECKS=0;" --user=exoncov --password exoncov ``` Execute following mysql statements to import data from txt files. ```mysql LOAD DATA LOCAL INFILE 'alembic_version.txt' INTO TABLE alembic_version; LOAD DATA LOCAL INFILE 'exons.txt' INTO TABLE exons; LOAD DATA LOCAL INFILE 'exons_transcripts.txt' INTO TABLE exons_transcripts; LOAD DATA LOCAL INFILE 'gene_aliases.txt' INTO TABLE gene_aliases; LOAD DATA LOCAL INFILE 'genes.txt' INTO TABLE genes; LOAD DATA LOCAL INFILE 'panel_versions.txt' INTO TABLE panel_versions; LOAD DATA LOCAL INFILE 'panels.txt' INTO TABLE panels; LOAD DATA LOCAL INFILE 'panels_transcripts.txt' INTO TABLE panels_transcripts; LOAD DATA LOCAL INFILE 'role.txt' INTO TABLE role; LOAD DATA LOCAL INFILE 'roles_users.txt' INTO TABLE roles_users; LOAD DATA LOCAL INFILE 'transcripts.txt' INTO TABLE transcripts; LOAD DATA LOCAL INFILE 'user.txt' INTO TABLE user; ```
<?php namespace SimplyCodedSoftware\Messaging\Store; use SimplyCodedSoftware\Messaging\Message; use SimplyCodedSoftware\Messaging\MessagingException; /** * Interface MessageGroup - used in multiple messages scenarios * @package SimplyCodedSoftware\Messaging\Store * @author Dariusz Gafka <dgafka.mail@gmail.com> */ interface MessageGroup { /** * @param Message $message * @throws MessagingException */ public function add(Message $message) : void; /** * @param Message $message */ public function remove(Message $message) : void; /** * @param Message $message * @return bool */ public function canBeAdded(Message $message) : bool; /** * @return array|Message[] */ public function messages() : array; /** * @return string */ public function groupId() : string; /** * @return bool */ public function isEmpty() : bool; /** * @return int */ public function size() : int; /** * Clears group from messages */ public function clear() : void; }
using System; namespace Rapidity.Http.Attributes { /// <summary> /// 表示这个是一个UriQuery参数 /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)] public class QueryAttribute : NamedAttribute, ICanNullable { public QueryAttribute() { } public QueryAttribute(string name) { this.Name = name; } public bool CanNull { get; set; } } }
USE mysqldb; CREATE TABLE calendars ( calendar_id BIGINT NOT NULL PRIMARY KEY, user_id BIGINT NOT NULL FOREIGN KEY, calendar_name TEXT, creation_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, modified_time TIMESTAMP );
var structdg_1_1_d_i_r_k_step = [ [ "container_type", "structdg_1_1_d_i_r_k_step.html#a98341634bfdb8fe04c9e070f0e2f27f2", null ], [ "value_type", "structdg_1_1_d_i_r_k_step.html#a3bb2291b84fb2d21aa768dcbf0ea1251", null ], [ "DIRKStep", "structdg_1_1_d_i_r_k_step.html#a67cfce7f4cc710888a1964cb33d39f2a", null ], [ "DIRKStep", "structdg_1_1_d_i_r_k_step.html#aa20c463b07dc5c101e45bdca018bcd4a", null ], [ "construct", "structdg_1_1_d_i_r_k_step.html#aa40ae61e48b2ba0c19d1340ef941049b", null ], [ "copyable", "structdg_1_1_d_i_r_k_step.html#a8fcdef709b53b5e066a0a60c7a0860fb", null ], [ "embedded_order", "structdg_1_1_d_i_r_k_step.html#a257537ded3172f6b427a1bf6bfe65834", null ], [ "num_stages", "structdg_1_1_d_i_r_k_step.html#a0bcf51d1a6af7481b813d537307c6f6e", null ], [ "order", "structdg_1_1_d_i_r_k_step.html#a5553738ecbbb386c6034989bab531b27", null ], [ "solver", "structdg_1_1_d_i_r_k_step.html#a9ee45afca16b7c1215b787c63e58f193", null ], [ "solver", "structdg_1_1_d_i_r_k_step.html#a9f95b594b6194a4a2892f4f2a34e2ee3", null ], [ "step", "structdg_1_1_d_i_r_k_step.html#a09e46597bda385581eb7c4cef4e56907", null ] ];
package main import ( "log" "net/http" "net/url" "strings" "time" ) type HttpRequestWorker struct { Id int } func (worker HttpRequestWorker) Proceed(url string, job HttpJob) { job.StartTime = time.Now().UnixNano() client := http.Client{} request, err := generateRequest(url, job) if err != nil { log.Print(err) return } response, err := client.Do(request) if err != nil { log.Print(err) return } defer response.Body.Close() job.EndTime = time.Now().UnixNano() log.Printf("%s %s %d %d", job.Method, job.Path, response.StatusCode, (job.EndTime-job.StartTime)/1000) } func generateRequest(url string, job HttpJob) (*http.Request, error) { if strings.ToUpper(job.Method) == "GET" { return get(url, job) } return post(url, job) } func get(url string, job HttpJob) (request *http.Request, err error) { req, reqErr := http.NewRequest("GET", url+job.Path, nil) if reqErr != nil { log.Print(reqErr) err = reqErr return } params := generateParameters(job) req.URL.RawQuery = params.Encode() request = req err = nil return } func post(url string, job HttpJob) (request *http.Request, err error) { params := generateParameters(job) req, reqErr := http.NewRequest("POST", url+job.Path, strings.NewReader(params.Encode())) if reqErr != nil { log.Print(reqErr) err = reqErr return } req.Header.Add("Content-Type", "application/x-www-form-urlencoded") request = req err = nil return } func generateParameters(job HttpJob) url.Values { values := url.Values{} for _, parameter := range job.Parameters { values.Add(parameter.Key, parameter.Value) } return values }
module TD::Types # Describes an available stream in a group call. # # @attr channel_id [Integer] Identifier of an audio/video channel. # @attr scale [Integer] Scale of segment durations in the stream. # The duration is 1000/(2**scale) milliseconds. # @attr time_offset [Integer] Point in time when the stream currently ends; Unix timestamp in milliseconds. class GroupCallStream < Base attribute :channel_id, TD::Types::Coercible::Integer attribute :scale, TD::Types::Coercible::Integer attribute :time_offset, TD::Types::Coercible::Integer end end
@using IGCV_Protokoll.util @model IGCV_Protokoll.ViewModels.AccessControlEditorDisplayViewModel @{ var aclElementId = $"standaloneEditor_{Model.ID}"; } <div id="@aclElementId"> <div class="row"> <div class="col-sm-6"> <h4>Bearbeiten:</h4> @{ Html.RenderPartial("_AclEditorFor", Model.Editor); } <div style="text-align: right"> <button class="btn btn-primary" onclick="submitEditedAcl();">Speichern</button> </div> <div id="responseMessage" class="text-danger"></div> </div> <div class="col-sm-6"> <h4>Aktuell berechtigt:</h4> <div id="authorizedDisplay_@Model.ID"> @{ Html.RenderPartial("_DisplayAuthorized", Model.Display); } </div> </div> </div> </div> <script type="text/javascript"> function submitEditedAcl() { $('#@aclElementId').fadeTo(200, 0.3, function () { var data = $('#@Model.Editor.HtmlName').jstree(true).get_json('#', { flat: true }); var aclJson = JSON.stringify(data, AclPropertyFilter); $.ajax({ url: '@Url.Action("_SaveExistingAcl", "Acl")', type: 'POST', data: { aclID: @Model.ID, aclTree: aclJson, "X-Requested-With": "XMLHttpRequest" }, success: function(responseData) { $('#authorizedDisplay_@Model.ID').html(responseData); $('#responseMessage').empty(); }, error: function(xhr, errorType) { $('#responseMessage').html(xhr.responseText); }, complete: function(xhr, statusText) { $('#standaloneEditor_@Model.ID').fadeTo(200, 1); } }); //end ajax }); } </script>
//import styles from './Viagem.module.css' import TabelaViagem from "../viagem-table/TabelaViagem" function Viagem() { return ( <div className="container rounded p-5"> <TabelaViagem /> </div > ) } export default Viagem
# Copyright 2015 ClusterHQ. See LICENSE file for details. """ Python bindings for ``libnvpair``. """ CDEF = """ typedef ... nvlist_t; typedef ... nvpair_t; typedef enum { DATA_TYPE_UNKNOWN = 0, DATA_TYPE_BOOLEAN, DATA_TYPE_BYTE, DATA_TYPE_INT16, DATA_TYPE_UINT16, DATA_TYPE_INT32, DATA_TYPE_UINT32, DATA_TYPE_INT64, DATA_TYPE_UINT64, DATA_TYPE_STRING, DATA_TYPE_BYTE_ARRAY, DATA_TYPE_INT16_ARRAY, DATA_TYPE_UINT16_ARRAY, DATA_TYPE_INT32_ARRAY, DATA_TYPE_UINT32_ARRAY, DATA_TYPE_INT64_ARRAY, DATA_TYPE_UINT64_ARRAY, DATA_TYPE_STRING_ARRAY, DATA_TYPE_HRTIME, DATA_TYPE_NVLIST, DATA_TYPE_NVLIST_ARRAY, DATA_TYPE_BOOLEAN_VALUE, DATA_TYPE_INT8, DATA_TYPE_UINT8, DATA_TYPE_BOOLEAN_ARRAY, DATA_TYPE_INT8_ARRAY, DATA_TYPE_UINT8_ARRAY } data_type_t; typedef enum { B_FALSE, B_TRUE } boolean_t; typedef unsigned char uchar_t; typedef unsigned int uint_t; int nvlist_alloc(nvlist_t **, uint_t, int); void nvlist_free(nvlist_t *); int nvlist_unpack(char *, size_t, nvlist_t **, int); void dump_nvlist(nvlist_t *, int); int nvlist_dup(nvlist_t *, nvlist_t **, int); int nvlist_add_boolean(nvlist_t *, const char *); int nvlist_add_boolean_value(nvlist_t *, const char *, boolean_t); int nvlist_add_byte(nvlist_t *, const char *, uchar_t); int nvlist_add_int8(nvlist_t *, const char *, int8_t); int nvlist_add_uint8(nvlist_t *, const char *, uint8_t); int nvlist_add_int16(nvlist_t *, const char *, int16_t); int nvlist_add_uint16(nvlist_t *, const char *, uint16_t); int nvlist_add_int32(nvlist_t *, const char *, int32_t); int nvlist_add_uint32(nvlist_t *, const char *, uint32_t); int nvlist_add_int64(nvlist_t *, const char *, int64_t); int nvlist_add_uint64(nvlist_t *, const char *, uint64_t); int nvlist_add_string(nvlist_t *, const char *, const char *); int nvlist_add_nvlist(nvlist_t *, const char *, nvlist_t *); int nvlist_add_boolean_array(nvlist_t *, const char *, boolean_t *, uint_t); int nvlist_add_byte_array(nvlist_t *, const char *, uchar_t *, uint_t); int nvlist_add_int8_array(nvlist_t *, const char *, int8_t *, uint_t); int nvlist_add_uint8_array(nvlist_t *, const char *, uint8_t *, uint_t); int nvlist_add_int16_array(nvlist_t *, const char *, int16_t *, uint_t); int nvlist_add_uint16_array(nvlist_t *, const char *, uint16_t *, uint_t); int nvlist_add_int32_array(nvlist_t *, const char *, int32_t *, uint_t); int nvlist_add_uint32_array(nvlist_t *, const char *, uint32_t *, uint_t); int nvlist_add_int64_array(nvlist_t *, const char *, int64_t *, uint_t); int nvlist_add_uint64_array(nvlist_t *, const char *, uint64_t *, uint_t); int nvlist_add_string_array(nvlist_t *, const char *, char *const *, uint_t); int nvlist_add_nvlist_array(nvlist_t *, const char *, nvlist_t **, uint_t); nvpair_t *nvlist_next_nvpair(nvlist_t *, nvpair_t *); nvpair_t *nvlist_prev_nvpair(nvlist_t *, nvpair_t *); char *nvpair_name(nvpair_t *); data_type_t nvpair_type(nvpair_t *); int nvpair_type_is_array(nvpair_t *); int nvpair_value_boolean_value(nvpair_t *, boolean_t *); int nvpair_value_byte(nvpair_t *, uchar_t *); int nvpair_value_int8(nvpair_t *, int8_t *); int nvpair_value_uint8(nvpair_t *, uint8_t *); int nvpair_value_int16(nvpair_t *, int16_t *); int nvpair_value_uint16(nvpair_t *, uint16_t *); int nvpair_value_int32(nvpair_t *, int32_t *); int nvpair_value_uint32(nvpair_t *, uint32_t *); int nvpair_value_int64(nvpair_t *, int64_t *); int nvpair_value_uint64(nvpair_t *, uint64_t *); int nvpair_value_string(nvpair_t *, char **); int nvpair_value_nvlist(nvpair_t *, nvlist_t **); int nvpair_value_boolean_array(nvpair_t *, boolean_t **, uint_t *); int nvpair_value_byte_array(nvpair_t *, uchar_t **, uint_t *); int nvpair_value_int8_array(nvpair_t *, int8_t **, uint_t *); int nvpair_value_uint8_array(nvpair_t *, uint8_t **, uint_t *); int nvpair_value_int16_array(nvpair_t *, int16_t **, uint_t *); int nvpair_value_uint16_array(nvpair_t *, uint16_t **, uint_t *); int nvpair_value_int32_array(nvpair_t *, int32_t **, uint_t *); int nvpair_value_uint32_array(nvpair_t *, uint32_t **, uint_t *); int nvpair_value_int64_array(nvpair_t *, int64_t **, uint_t *); int nvpair_value_uint64_array(nvpair_t *, uint64_t **, uint_t *); int nvpair_value_string_array(nvpair_t *, char ***, uint_t *); int nvpair_value_nvlist_array(nvpair_t *, nvlist_t ***, uint_t *); """ SOURCE = """ #include <libzfs/sys/nvpair.h> """ LIBRARY = "nvpair" # vim: softtabstop=4 tabstop=4 expandtab shiftwidth=4
import * as React from 'react'; import { create } from 'react-test-renderer'; import { createMediaMatcher } from '../src'; describe('Specs', () => { it('all false branches - defaults to last', () => { const SideMatch = createMediaMatcher({ client: false, server: false, }); const wrapper = create(<SideMatch.Matcher client="client" server="server" />); expect(wrapper.toJSON()).toEqual('server'); }); it('all true branches - defaults to first', () => { const SideMatch = createMediaMatcher({ client: true, server: true, }); const wrapper = create(<SideMatch.Matcher client="client" server="server" />); expect(wrapper.toJSON()).toEqual('client'); }); it('emulate ServerSideOnly component - pick last true', () => { const SideMatch = createMediaMatcher({ client: false, server: true, random: false, }); const wrapper = create(<SideMatch.Matcher client="client" server="server" random="random" />); expect(wrapper.toJSON()).toEqual('server'); }); it('emulate ClientSideOnly component - pick first true', () => { const SideMatch = createMediaMatcher({ random: false, client: true, server: false, }); const wrapper = create(<SideMatch.Matcher client="client" server="server" random="random" />); expect(wrapper.toJSON()).toEqual('client'); }); it('shall swap to client', () => { const SideMatch = createMediaMatcher({ client: false, server: true, }); const Component = () => { const [client, setClient] = React.useState(false); React.useEffect(() => { setClient(true); }, []); return ( <SideMatch.Mock client={client} server={true}> <SideMatch.Matcher client="client" server="server" /> </SideMatch.Mock> ); }; const wrapper = create(<Component />); expect(wrapper.toJSON()).toEqual('server'); wrapper.update(<Component />); expect(wrapper.toJSON()).toEqual('client'); }); it('mock should bypass provider', () => { const Match = createMediaMatcher({ a: false, b: false, c: false, }); expect(create(<Match.Matcher a={1} b={2} c={3} />).toJSON()).toEqual('3'); expect( create( <Match.Provider> <Match.Matcher a={1} b={2} c={3} /> </Match.Provider> ).toJSON() ).toEqual('3'); expect( create( <Match.Mock a={true}> <Match.Provider> <Match.Matcher a={1} b={2} c={3} /> </Match.Provider> </Match.Mock> ).toJSON() ).toEqual('1'); }); });
#!/usr/bin/env bash main() { avtest avtest version avtest version oneliner avtest version dev avtest version dev-details avtest version dev oneliner avtest version debug-check } avtest() { echo "\n ......... now testing 'app $@'\n" go run main.go $@ } main
//----------------------------------------------------------------------------- class ItemSuppressor extends InventoryItemSuper { }; typedef ItemSuppressor SuppressorBase; //----------------------------------------------------------------------------- class ItemWatch extends InventoryItemSuper { }; //----------------------------------------------------------------------------- class ItemTransmitter extends InventoryItemSuper { proto native void SetNextChannel(); proto native void SetPrevChannel(); proto native float GetTunedFrequency(); proto native void EnableBroadcast(bool state); proto native void EnableReceive(bool state); proto native bool IsBroadcasting(); proto native bool IsReceiving(); }; //----------------------------------------------------------------------------- class ItemMegaphone extends InventoryItemSuper { } //----------------------------------------------------------------------------- class ItemRadio extends InventoryItemSuper { proto native void TuneNext(); proto native void TunePrev(); }; //----------------------------------------------------------------------------- class ItemBarrel extends InventoryItemSuper { }; //----------------------------------------------------------------------------- class UnderSlugLauncher extends Weapon { }; //----------------------------------------------------------------------------- class ItemGPS extends InventoryItemSuper { }; //----------------------------------------------------------------------------- class ItemCompass extends InventoryItemSuper { }; //----------------------------------------------------------------------------- class CarWheel extends InventoryItemSuper { //! Returns current wheel radius. proto native float GetRadius(); //! Returns wheel width. proto native float GetWidth(); }; class CarDoor extends InventoryItemSuper { }; //----------------------------------------------------------------------------- class Clothing extends ItemBase { override bool IsClothing() { return true; } // Conditions override bool CanPutInCargo( EntityAI parent ) { if( !super.CanPutInCargo(parent) ) {return false;} if ( ( GetNumberOfItems() == 0 || !parent || parent.IsMan() ) && super.CanPutInCargo( parent ) ) { return true; } return false; } }; typedef Clothing ClothingBase; //----------------------------------------------------------------------------- class ItemBook extends InventoryItemSuper { override void EEUsed(Man owner) { if ( GetGame().IsServer() ) { RPCSingleParam(ERPCs.RPC_READ_A_BOOK, NULL, true, owner.GetIdentity()); } } override event bool OnUseFromInventory(Man owner) { return false; } override void OnRPC( PlayerIdentity sender, int rpc_type, ParamsReadContext ctx) { super.OnRPC(sender, rpc_type, ctx); if (rpc_type == ERPCs.RPC_READ_A_BOOK) { super.EEUsed(NULL); } } }; //----------------------------------------------------------------------------- class ItemGrenade extends InventoryItemSuper { /**@fn SetPinned * @brief sets grenade to state GR_PINNED (if the state transition is possible) * @return true if state already set or if state transition performed, false otherwise **/ proto native bool SetPinned (); /**@fn SetUnpinned * @brief sets grenade to state GR_UNPINNED (if the state transition is possible) * @return true if state already set or if state transition performed, false otherwise **/ proto native bool SetUnpinned (); /**@fn SetIgnited * @brief sets grenade to state GR_TRIGGERED (if the state transition is possible) * @return true if state already set or if state transition performed, false otherwise **/ proto native bool SetIgnited (); /**@fn IsPinned * @return true if grenade is pinned **/ proto native bool IsPinned (); /**@fn IsActivated * @return true if grenade is GR_TRIGGERED or GR_EXPLODED **/ proto native bool IsActivated (); }; typedef ItemGrenade GrenadeBase; //----------------------------------------------------------------------------- class ItemMap extends InventoryItemSuper { };
. $PSScriptroot\Get-Hypervisor.ps1 . $PSScriptroot\Fakes\Fake_HypervisorFactory.ps1 Describe "Get-Hypervisor" { Context "Calling function will return whatever HypervisorFactory returns." { It "Returns what Hypervisor factory returns" { $script:HypervisorFactory = New-FakeHypervisorFactory -GetHypervisorNames { @("Hypervisor1", "Hypervisor2")} $results = Get-Hypervisor $results[0] | should be "Hypervisor1" $results[1] | should be "Hypervisor2" } } }
require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/object/blank' require 'logger' require 'active_support/logger' module Perty # BetterTaggedLogging is based on ActiveSupport::TaggedLogging to make log # messages pretty and useful. # # See also https://goo.gl/907QWS module Logger module Formatter # :nodoc: # This method is invoked when a log event occurs. def call(severity, timestamp, progname, msg) parts = [] modules.each do |mod| parts << ["[#{mod}]"] end parts << ["request_id=#{context[:request_id]}"] if context[:request_id] parts << msg super(severity, timestamp, progname, parts.join(' ')) end def with_module(mod) modules << mod yield self ensure modules.pop end def with_request_id(request_id) context[:request_id] = request_id yield self ensure context[:request_id] = nil end def modules context[:modules] ||= [] end def context Thread.current[:perty] ||= {} end end def self.new(logger) # Ensure we set a default formatter so we aren't extending nil! logger.formatter ||= ActiveSupport::Logger::SimpleFormatter.new logger.formatter.extend Formatter logger.extend(self) end delegate :with_request_id, :with_module, to: :formatter end end
export const COLOR_BLACK = '#000000'; export const COLOR_FIORD = '#3c4560'; export const COLOR_GRAY_HEATHER = '#b8bece'; export const COLOR_GRAY_ATHENS = '#f0f3f5'; export const COLOR_WHITE = '#ffffff'; export const COLOR_RGB_FIORD = 'rgb(60, 69, 96)'; export const COLOR_RGB_GRAY_ATHENS = 'rgb(240, 243, 245)'; export const COLOR_RGB_WHITE = 'rgb(255, 255, 255)';
/******************************************************************************* * Copyright (c) 2015 - 2016 - 2016, Andreas Hefti, inarisoft@yahoo.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.inari.commons.geom; import java.util.StringTokenizer; import com.inari.commons.StringUtils; /** A simple Rectangle with integer precision */ public final class Rectangle extends Position { /** The width of the Rectangle */ public int width; /** The height of the Rectangle */ public int height; /** Use this ti create a Rectangle with default attributes: x=0,y=0,width=0,height=0 */ public Rectangle() { super( 0, 0 ); width = 0; height = 0; } /** Use this as a copy constructor */ public Rectangle ( Rectangle source ) { super( source.x, source.y ); this.width = source.width; this.height = source.height; } /** Use this to create a Rectangle on specified Position with specified width and height * * @param pos the Position of the new Rectangle * @param width the width of the new Rectangle * @param height the height of the new Rectangle */ public Rectangle( Position pos, int width, int height ) { super( pos ); this.width = width; this.height = height; } /** Use this to create a new Rectangle with specified attributes. * * @param xpos the x axis position of the new Rectangle * @param ypos the y axis position of the new Rectangle * @param width the width of the new Rectangle * @param height the height of the new Rectangle */ public Rectangle( int xpos, int ypos, int width, int height ) { super( xpos, ypos ); this.width = width; this.height = height; } /** Use this to create a new Rectangle form configuration String value. * * @param rectString configuration String value. See also fromConfigString method documentation */ public Rectangle( String rectString ) { fromConfigString( rectString ); } /** Use this to get the area value (width * height) form this Rectangle. * @return the area value (width * height) form this Rectangle. */ public final int area() { return width * height; } public final void set( int x, int y, int w, int h ) { this.x = x; this.y = y; this.width = w; this.height = h; } /** Use this to set the attributes of this Rectangle by another Rectangle. * @param other the other Rectangle to get/take the attributes from */ public void setFrom( Rectangle other ) { super.setFrom( other ); width = other.width; height = other.height; } public final void setFrom( Rectangle other, int x, int y ) { super.setFrom( other ); this.x += x; this.y += y; width = other.width; height = other.height; } public final void clear() { x = 0; y = 0; width = 0; height = 0; } /** Use this to set the Rectangle attributes from specified configuration String value with the * format: [x],[y],[width],[height]. * * @param stringValue the configuration String value * @throws IllegalArgumentException If the String value as a invalid format * @throws NumberFormatException if the x/y/width/height values from the String value aren't numbers */ @Override public void fromConfigString( String stringValue ) { if ( !StringUtils.isBlank( stringValue ) ) { StringTokenizer st = new StringTokenizer( stringValue, StringUtils.VALUE_SEPARATOR_STRING ); x = Integer.valueOf( st.nextToken() ).intValue(); y = Integer.valueOf( st.nextToken() ).intValue(); width = Integer.valueOf( st.nextToken() ).intValue(); height = Integer.valueOf( st.nextToken() ).intValue(); } } /** Use this to get a configuration String value that represents this Rectangle * and can be used to reset the attributes of a Rectangle by using fromConfigString * The format is: [x],[y],[width],[height]. * @return A configuration String value that represents this Rectangle */ @Override public String toConfigString() { StringBuilder sb = new StringBuilder(); sb.append( x ).append( StringUtils.VALUE_SEPARATOR ).append( y ).append( StringUtils.VALUE_SEPARATOR ); sb.append( width ).append( StringUtils.VALUE_SEPARATOR ).append( height ); return sb.toString(); } @Override public final int hashCode() { int result = 1; result = 37 * result + x; result = 37 * result + y; result = 37 * result + width; result = 37 * result + height; return result; } @Override public boolean equals( Object obj ) { if (obj instanceof Rectangle) { Rectangle r = (Rectangle) obj; return ( ( this.x == r.x ) && ( this.y == r.y ) && ( this.width == r.width ) && ( this.height == r.height ) ); } else { return false; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append( "[x=" ); builder.append( x ); builder.append( ",y=" ); builder.append( y ); builder.append( ",width=" ); builder.append( width ); builder.append( ",height=" ); builder.append( height ); builder.append( "]" ); return builder.toString(); } }
using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Sample.API.Cmdlets { [Cmdlet(VerbsLifecycle.Invoke, @"LinqGroupBy")] [Alias("LinqGroupBy")] [OutputType(typeof(PSDeferredEnumerable))] [Description(@"Groups the elements of a sequence.")] public class InvokeLinqGroupBy : LinqCmdlet { [Parameter(Mandatory = true, Position = 0, HelpMessage = "A script to test each element for a condition.")] [ValidateNotNull] public ScriptBlock KeySelector { get; set; } protected override void EndProcessing() { base.EndProcessing(); DeferredEnumerable.Collection = DeferredEnumerable.Collection .GroupBy(e => (KeySelector.InvokeReturnAsIs(e) as PSObject)?.ImmediateBaseObject) .Select(g => new PSObject(new KeyValuePair<object, IEnumerable<PSObject>>(g.Key, g))); WriteObject(DeferredEnumerable); } } }
/* * author:symbolspace * e-mail:symbolspace@outlook.com */ namespace Symbol.Encryption { /// <summary> /// CRC32校验码处理类 /// </summary> /// <remarks>如果需要得到16进制的CRC码,请用ulong的ToString("X2")</remarks> public static class CRC32EncryptionHelper { #region fields /// <summary> /// 空白的CRC32值。 /// </summary> public const ulong Empty = 0xFFFFFFFF; private static readonly ulong[] _crc32Table;//采用static readonly 防止被AppDomain回收。 #endregion #region cctor static CRC32EncryptionHelper() { //生成CRC32码表,有的算法是写死的,这里偷点懒,直接算出来的 // 如果觉得这个会影响的话,可以自己写死_crc32Table // 这是在类调用前执行的,只会执行一次 _crc32Table = new ulong[256]; ulong crc; for (int i = 0; i < 256; i++) { crc = (ulong)i; for (int j = 8; j > 0; j--) { if ((crc & 1) == 1) crc = (crc >> 1) ^ 0xEDB88320; else crc >>= 1; } _crc32Table[i] = crc; } } #endregion #region methods #region Encrypt /// <summary> /// 获取字符串的CRC32校验码(UTF-8) /// </summary> /// <param name="value">需要校验的字符串,null或"" 不会报错。</param> /// <returns>返回CRC32校验码</returns> /// <remarks>为了获得最好的兼容性,所以采用通用的UTF-8编码,如果需要用别的编码,请转为byte[]后调用另外的重载。</remarks> public static ulong Encrypt(string value) { return Encrypt(string.IsNullOrEmpty(value) ? null : System.Text.Encoding.UTF8.GetBytes(value), -1, -1); } /// <summary> /// 获取二进制数组的CRC32校验码 /// </summary> /// <param name="buffer">为null或空数组时不会报错。</param> /// <returns>返回CRC32校验码</returns> public static ulong Encrypt(byte[] buffer) { return Encrypt(buffer, -1, -1); } /// <summary> /// 获取二进制数组的CRC32校验码 /// </summary> /// <param name="buffer">为null或空数组时不会报错。</param> /// <param name="offset">从什么位置开始,-1表示从0开始</param> /// <param name="length">需要多长,-1表示剩下的长度。</param> /// <returns>返回CRC32校验码</returns> public static ulong Encrypt(byte[] buffer, int offset, int length) { ulong result = 0xffffffff; if (buffer!=null) { if(offset<0) offset=0; if(length>0) length= offset+length; else length= buffer.Length; for (int i = offset; i < length; i++) { result = (result >> 8) ^ _crc32Table[(result & 0xFF) ^ buffer[i]]; } } return result; } /// <summary> /// 获取二进制数组的CRC32校验码 /// </summary> /// <param name="stream">需要处理的流对象,null或不可读的流不会报错。</param> /// <returns>返回CRC32校验码</returns> public static ulong Encrypt(System.IO.Stream stream) { ulong result = 0xffffffff; if (stream != null && stream.CanRead) { int b = -1; while ((b = stream.ReadByte()) != -1) { result = (result >> 8) ^ _crc32Table[(result & 0xFF) ^ (byte)b]; } } return result; } #endregion #region CRC /// <summary> /// 获取字符串的CRC32校验码(UTF-8) /// </summary> /// <param name="value">需要校验的字符串,null或"" 不会报错。</param> /// <returns>返回CRC32校验码</returns> /// <remarks>为了获得最好的兼容性,所以采用通用的UTF-8编码,如果需要用别的编码,请转为byte[]后调用另外的重载。</remarks> [System.Obsolete("请改用 Symbol.Encryption.CRC32EncryptionHelper.Encrypt(string value)")] public static ulong CRC(string value) { return Encrypt(string.IsNullOrEmpty(value) ? null : System.Text.Encoding.UTF8.GetBytes(value), -1, -1); } /// <summary> /// 获取二进制数组的CRC32校验码 /// </summary> /// <param name="buffer">为null或空数组时不会报错。</param> /// <returns>返回CRC32校验码</returns> [System.Obsolete("请改用 Symbol.Encryption.CRC32EncryptionHelper.Encrypt(byte[] buffer)")] public static ulong CRC(byte[] buffer) { return Encrypt(buffer, -1, -1); } /// <summary> /// 获取二进制数组的CRC32校验码 /// </summary> /// <param name="buffer">为null或空数组时不会报错。</param> /// <param name="offset">从什么位置开始,-1表示从0开始</param> /// <param name="length">需要多长,-1表示剩下的长度。</param> /// <returns>返回CRC32校验码</returns> [System.Obsolete("请改用 Symbol.Encryption.CRC32EncryptionHelper.Encrypt(byte[] buffer, int offset, int length)")] public static ulong CRC(byte[] buffer, int offset, int length) { return Encrypt(buffer, offset, length); } /// <summary> /// 获取二进制数组的CRC32校验码 /// </summary> /// <param name="stream">需要处理的流对象,null或不可读的流不会报错。</param> /// <returns>返回CRC32校验码</returns> [System.Obsolete("请改用 Symbol.Encryption.CRC32EncryptionHelper.Encrypt(System.IO.Stream stream)")] public static ulong CRC(System.IO.Stream stream) { return Encrypt(stream); } #endregion #endregion } }
import React, { Component } from 'react' import Immutable from 'seamless-immutable' import { Trans } from 'react-i18next' import * as api from '../API' import HeroPageLayout from './HeroPageLayout' export default class HeroPage extends Component { constructor(props) { super(props) this.state = { heroId: props.match.params.id, hero: null, heroLoading: false, error: null } } /** * Load when component is created. */ componentDidMount = () => { this.setState({ hero: null, heroLoading: true, error: null }) this.handleHeroResponse( api.fetchHero({ id: this.state.heroId }) ) } handleHeroChange = (updatedField) => { const oldHero = this.state.hero let newJson = oldHero if (updatedField.profile) { newJson = Immutable.merge(oldHero, { profile: Immutable.merge(oldHero.profile, updatedField.profile) }) } else if (updatedField.condition) { newJson = Immutable.merge(oldHero, { condition: Immutable.merge(oldHero.condition, updatedField.condition) }) } else if (updatedField.protections) { newJson = Immutable.merge(oldHero, { protections: Immutable.merge(oldHero.protections, updatedField.protections) }) } else if (updatedField.extra) { newJson = Immutable.merge(oldHero, { extra: updatedField.extra }) } this.handleHeroResponse( api.updateHero({ id: this.state.heroId, hero: newJson }) ) } handleHeroResponse = (promise) => { promise .then((response) => { this.setState({ hero: response.data, heroLoading: false, error: null }) }) .catch((error) => { this.setState({ hero: null, heroLoading: false, error: error.toString() }) }) } render() { const { hero, heroLoading, error } = this.state // Show loading bar if HTTP request is not completed if (heroLoading) { return (<Trans>Загрузка</Trans>) } // Show error if HTTP request failed if (error) { return (<div>{error}</div>) } return ( <HeroPageLayout hero={hero} onHandleHeroChange={this.handleHeroChange} /> ) } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Diagnostics.Runtime { /// <summary> /// Contains information about a range of memory. /// </summary> public readonly struct MemoryRegionInfo { /// <summary> /// Gets the base address of the allocation. /// </summary> public ulong BaseAddress { get; } /// <summary> /// Gets the size of the allocation. /// </summary> public ulong Size { get; } /// <summary> /// Constructor. /// </summary> /// <param name="addr">Base address of the memory range.</param> /// <param name="size">The size of the memory range.</param> public MemoryRegionInfo(ulong addr, ulong size) { BaseAddress = addr; Size = size; } } }
#ifndef GATEWAY_MONITOR_H_ #define GATEWAY_MONITOR_H_ namespace tensorflow { namespace serving{ } //serving } //tensorflow #endif
#[doc = "Reader of register SIZE_AND_DIS_FLAGS"] pub type R = crate::R<u32, super::SIZE_AND_DIS_FLAGS>; #[doc = "Reader of field `SIZE_OF_CCFG`"] pub type SIZE_OF_CCFG_R = crate::R<u16, u16>; #[doc = "Reader of field `DISABLE_FLAGS`"] pub type DISABLE_FLAGS_R = crate::R<u16, u16>; #[doc = "Reader of field `DIS_GPRAM`"] pub type DIS_GPRAM_R = crate::R<bool, bool>; #[doc = "Reader of field `DIS_ALT_DCDC_SETTING`"] pub type DIS_ALT_DCDC_SETTING_R = crate::R<bool, bool>; #[doc = "Reader of field `DIS_XOSC_OVR`"] pub type DIS_XOSC_OVR_R = crate::R<bool, bool>; impl R { #[doc = "Bits 16:31 - SIZE_OF_CCFG"] #[inline(always)] pub fn size_of_ccfg(&self) -> SIZE_OF_CCFG_R { SIZE_OF_CCFG_R::new(((self.bits >> 16) & 0xffff) as u16) } #[doc = "Bits 3:15 - DISABLE_FLAGS"] #[inline(always)] pub fn disable_flags(&self) -> DISABLE_FLAGS_R { DISABLE_FLAGS_R::new(((self.bits >> 3) & 0x1fff) as u16) } #[doc = "Bit 2 - DIS_GPRAM"] #[inline(always)] pub fn dis_gpram(&self) -> DIS_GPRAM_R { DIS_GPRAM_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - DIS_ALT_DCDC_SETTING"] #[inline(always)] pub fn dis_alt_dcdc_setting(&self) -> DIS_ALT_DCDC_SETTING_R { DIS_ALT_DCDC_SETTING_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - DIS_XOSC_OVR"] #[inline(always)] pub fn dis_xosc_ovr(&self) -> DIS_XOSC_OVR_R { DIS_XOSC_OVR_R::new((self.bits & 0x01) != 0) } }
export { RequestError } from './RequestError'; export { RequestException } from './RequestException';
module Operations class OpDef < Struct.new(:order, :func) end def to_symbol(c) c.to_s.to_sym end def operator?(c) operations.include?(to_symbol(c)) end def operand?(token) !operator?(token) end def op_orders operation_orders.uniq.sort end def matching_order?(op_order, operator) op = find_operation(operator) if op op_order == op.order else false end end def find_op_func(operator) find_operation(operator).func end private def find_operation(operator) operations[operator] end def operation_orders operations.values.map { |v| v.order } end def operations @operations ||= { :+ => OpDef.new(1, ->(l, r) { l + r }), :- => OpDef.new(1, ->(l, r) { l - r }), :* => OpDef.new(0, ->(l, r) { l * r }), :/ => OpDef.new(0, ->(l, r) { l / r }) } end end
# This is how I'm awesome(ish). Below is a _list_ of my **skills**: ## Programming Skills - HTML - CSS - JS ## Web Sites 1. CovertCurmudgeon (WordPress) 2. Floating Bed and Breakfast (WordPress) 3. I have 2 others, but they're down at the moment ## Other Skills - Mediocre Chess Player - _Dry, Snarky_ **Curmudgeon** - _I know what **wine** tastes like_
using System.Runtime.Serialization; namespace EncompassApi.Loans.Enums { /// <summary> /// ScsrsClaus /// </summary> public enum ScsrsClaus { /// <summary> /// Its Successors And/Or Assigns /// </summary> [EnumMember(Value = "Its Successors And/Or Assigns")] ItsSuccessorsAndOrAssigns = 0, /// <summary> /// Its Successors And/Or Assigns, As Their Interest May Appear /// </summary> [EnumMember(Value = "Its Successors And/Or Assigns, As Their Interest May Appear")] ItsSuccessorsAndOrAssignsAsTheirInterestMayAppear = 1, /// <summary> /// Its Successors And/Or Assigns, A.T.I.M.A. /// </summary> [EnumMember(Value = "Its Successors And/Or Assigns, A.T.I.M.A.")] ItsSuccessorsAndOrAssignsATIMA = 2 } }
package e2e import ( "fmt" "testing" "github.com/stretchr/testify/require" "github.com/kube-reporting/metering-operator/test/reportingframework" "github.com/kube-reporting/metering-operator/test/testhelpers" ) const ( prometheusPodName = "presto-k8s-0" prometheusNamespace = "openshift-monitoring" prometheusContainerName = "prometheus" prometheusQueryEndpoint = "http://127.0.0.1:9090/api/v1/query" ) // testMeteringAnsibleOperatorMetricsWork ensures that the ServiceMonitor object the ansible-operator // creates for the metering-ansible-operator is exposing metrics correctly. It execs in the prometheus-k8s-0 // Pod in the openshift-monitoring namespace and fires off a known metric that gets collected in the test // namespace. This is a follow-up to the fixes made in https://github.com/kube-reporting/metering-operator/pull/1235. func testMeteringAnsibleOperatorMetricsWork(t *testing.T, rf *reportingframework.ReportingFramework) { query := fmt.Sprintf("query=workqueue_work_duration_seconds_count{namespace='%s',job='metering-operator-metrics'}", rf.Namespace) cmd := []string{ "curl", "-k", "-G", "-s", "--data-urlencode", query, prometheusQueryEndpoint, } options := testhelpers.NewExecOptions(prometheusPodName, prometheusNamespace, prometheusContainerName, false, cmd) stdoutBuf, stderrBuf, err := testhelpers.ExecPodCommandWithOptions(rf.KubeConfig, rf.KubeClient, options) t.Logf("Stdout output: %s", stdoutBuf.String()) t.Logf("Stderr output: %s", stderrBuf.String()) require.Nil(t, err, "expected running the prometheus query would produce no error") require.Containsf(t, stdoutBuf.String(), "workqueue_work_duration_seconds_count", "expected the prometheus query would return the 'workqueue_work_duration_seconds_count' job name") require.Containsf(t, stdoutBuf.String(), "success", "expected the prometheus query would return a successful status") require.Len(t, stderrBuf.String(), 0, "expected that the stderr buffer would return nothing") }
SUBROUTINE FORSAV(TIME,DELDIP,IPT,N3,FMATRX, COORD,NVAR,REFH, 1 EVECS,JSTART,FCONST) IMPLICIT DOUBLE PRECISION (A-H,O-Z) INCLUDE 'SIZES' DIMENSION FMATRX(*), DELDIP(3,*), COORD(*), EVECS(*), FCONST(*) ************************************************************************ * * FORSAV SAVES AND RESTORES DATA USED IN THE FORCE CALCULATION. * * ON INPUT TIME = TOTAL TIME ELAPSED SINCE THE START OF THE CALCULATION. * IPT = LINE OF FORCE MATRIX REACHED, IF IN WRITE MODE, * = 0 IF IN READ MODE. * FMATRX = FORCE MATRIX ************************************************************************ COMMON /DENSTY/ P(MPACK), PA(MPACK), PB(MPACK) COMMON /MOLKST/ NUMAT,NAT(NUMATM),NFIRST(NUMATM),NMIDLE(NUMATM), 1 NLAST(NUMATM), NORBS, NELECS,NALPHA,NBETA, 2 NCLOSE,NOPEN,NDUMY,FRACT OPEN(UNIT=9,FILE='FOR009',STATUS='UNKNOWN',FORM='UNFORMATTED') REWIND 9 OPEN(UNIT=10,FILE='FOR010',STATUS='UNKNOWN',FORM='UNFORMATTED') REWIND 10 IR=9 IW=9 IF( IPT .EQ. 0 ) THEN C C READ IN FORCE DATA C READ(IR,END=20,ERR=20)TIME,IPT,REFH LINEAR=(NVAR*(NVAR+1))/2 READ(IR)(COORD(I),I=1,NVAR) READ(IR,END=10,ERR=10)(FMATRX(I),I=1,LINEAR) READ(IR)((DELDIP(J,I),J=1,3),I=1,IPT) N33=NVAR*NVAR READ(IR)(EVECS(I),I=1,N33) READ(IR)JSTART,(FCONST(I),I=1,NVAR) RETURN ELSE C C WRITE FORCE DATA C REWIND IW IF(TIME.GT.1.D6)TIME=TIME-1.D6 WRITE(IW)TIME,IPT,REFH LINEAR=(NVAR*(NVAR+1))/2 WRITE(IW)(COORD(I),I=1,NVAR) WRITE(IW)(FMATRX(I),I=1,LINEAR) WRITE(IW)((DELDIP(J,I),J=1,3),I=1,IPT) N33=NVAR*NVAR WRITE(IR)(EVECS(I),I=1,N33) WRITE(IR)JSTART,(FCONST(I),I=1,NVAR) LINEAR=(NORBS*(NORBS+1))/2 WRITE(10)(PA(I),I=1,LINEAR) IF(NALPHA.NE.0)WRITE(10)(PB(I),I=1,LINEAR) CLOSE(9) CLOSE(10) ENDIF RETURN 10 WRITE(6,'(''INSUFFICIENT DATA ON DISK FILES FOR A FORCE '', 1''CALCULATION'',/10X,''RESTART. PERHAPS THIS STARTED OF AS A '', 2''FORCE CALCULATION '')') WRITE(6,'(10X,''BUT THE GEOMETRY HAD TO BE OPTIMIZED FIRST, '', 1''IN WHICH CASE '',/10X,''REMOVE THE KEY-WORD "FORCE".'')') STOP 20 WRITE(6,'(//10X,''NO RESTART FILE EXISTS!'')') STOP END
# coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """ FILE: sample_batching.py DESCRIPTION: These samples demonstrate how to use the batching API to perform multiple operations within a single request USAGE: python sample_batching.py Set the environment variables with your own values before running the sample: 1) AZURE_STORAGE_CONNECTION_STRING - the connection string to your storage account """ from datetime import datetime, timedelta import os import asyncio class CreateClients(object): connection_string = os.getenv("AZURE_TABLES_CONNECTION_STRING") my_table = os.getenv("AZURE_TABLES_NAME") or "" async def sample_batching(self): # Instantiate a TableServiceClient using a connection string entity1 = { 'PartitionKey': 'pk001', 'RowKey': 'rk001', 'Value': 4, 'day': "Monday", 'float': 4.003 } entity2 = { 'PartitionKey': 'pk001', 'RowKey': 'rk002', 'Value': 4, 'day': "Tuesday", 'float': 4.003 } entity3 = { 'PartitionKey': 'pk001', 'RowKey': 'rk003', 'Value': 4, 'day': "Wednesday", 'float': 4.003 } entity4 = { 'PartitionKey': 'pk001', 'RowKey': 'rk004', 'Value': 4, 'day': "Thursday", 'float': 4.003 } # [START batching] from azure.data.tables.aio import TableClient from azure.data.tables import UpdateMode table_client = TableClient.from_connection_string(conn_str=self.connection_string, table_name="tableName") batch = table_client.create_batch() batch.create_entity(entity1) batch.delete_entity(entity2) batch.upsert_entity(entity3) batch.update_entity(entity4, mode=UpdateMode.REPLACE) try: await table_client.send_batch(batch) except BatchErrorException as e: print("There was an error with the batch operation") print("Error: {}".format(e)) # [END batching] async def main(): sample = CreateClients() await sample.sample_batching() if __name__ == '__main__': asyncio.run(main())
using System; using System.Threading.Tasks; using DataProcessor; using Grpc.Core; namespace GrpcServerCommon { public class IngestorService : Ingestor.IngestorBase { public override Task<DataResponse> ProcessData(DataRequest request, ServerCallContext context) { Console.WriteLine($"Object id: {request.Id}"); Console.WriteLine($"Object name: {request.Name}"); Console.WriteLine($"Object description: {request.Description}"); return Task.FromResult(new DataResponse { Success = true }); } } }
No information available about domain name likexian-no-money-registe.pl in the Registry NASK database. WHOIS database responses: https://dns.pl/en/whois WHOIS displays data with a delay not exceeding 15 minutes in relation to the .pl Registry system
package edu.virginia.vcgr.genii.client.alarms; import java.util.Calendar; import java.util.Collection; import java.util.LinkedList; import java.util.PriorityQueue; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class InMemoryAlarmManager { static private Log _logger = LogFactory.getLog(InMemoryAlarmManager.class); static public InMemoryAlarmManager MANAGER = new InMemoryAlarmManager(); private PriorityQueue<AlarmInformation> _queue = new PriorityQueue<AlarmInformation>(); private InMemoryAlarmManager() { Thread th = new Thread(new InMemoryAlarmManagerWorker(), "In Memory Alarm Manager Worker Thread"); th.setDaemon(true); th.start(); } final private AlarmToken addAlarm(AlarmHandler handler, Object userData, Calendar nextOccurance, Long repeatInterval) { AlarmInformation info = new AlarmInformation(handler, userData, nextOccurance, repeatInterval); synchronized (_queue) { _queue.add(info); _queue.notify(); } return info; } final public AlarmToken addAlarm(AlarmHandler handler, Object userData, Calendar occurance) { return addAlarm(handler, userData, occurance, null); } final public AlarmToken addAlarm(AlarmHandler handler, Calendar occurance) { return addAlarm(handler, null, occurance); } final public AlarmToken addAlarm(AlarmHandler handler, Object userData, long repeatInterval) { if (repeatInterval <= 0) throw new IllegalArgumentException("Repeat interval must be positive."); Calendar nextOccurance = Calendar.getInstance(); nextOccurance.setTimeInMillis(nextOccurance.getTimeInMillis() + repeatInterval); return addAlarm(handler, userData, nextOccurance, repeatInterval); } final public AlarmToken addAlarm(AlarmHandler handler, long repeatInterval) { return addAlarm(handler, null, repeatInterval); } private class InMemoryAlarmManagerWorker implements Runnable { private InMemoryAlarmManagerWorker() { } @Override public void run() { Collection<AlarmInformation> alarmsToRun = new LinkedList<AlarmInformation>(); AlarmInformation info; while (true) { alarmsToRun.clear(); Calendar now = Calendar.getInstance(); synchronized (_queue) { while (true) { info = _queue.peek(); if (info != null) { Calendar when = info.nextOccurance(); if (when == null) _queue.remove(); else if (when.compareTo(now) <= 0) alarmsToRun.add(_queue.remove()); else break; } else break; } } for (AlarmInformation alarm : alarmsToRun) alarm.handleAlarm(); synchronized (_queue) { for (AlarmInformation alarm : alarmsToRun) { if (alarm.nextOccurance() != null) _queue.add(alarm); } try { info = _queue.peek(); if (info == null) _queue.wait(); else { Calendar when = info.nextOccurance(); long sleepTime; if (when == null) sleepTime = 1L; else sleepTime = when.getTimeInMillis() - Calendar.getInstance().getTimeInMillis(); if (sleepTime <= 0L) sleepTime = 1L; _queue.wait(sleepTime); } } catch (InterruptedException ie) { _logger.warn("In Memory Alarm Thread interrupted.", ie); } } } } } }
function Get-ScriptCopPatrol { <# .Synopsis Gets the currently defined script cop patrols. .Description Gets the currently defined script cop patrols. A Script Cop patrol groups a number of rules to help easily fix a set of issues. .Example Get-ScriptCopPatrol .Link Register-ScriptCopPatrol #> [CmdletBinding(DefaultParameterSetName='All')] [OutputType([PSObject])] param( # The name of the patrol. [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName='Name')] [string] $Name ) begin { # Declare Control Cache if it Doesn't Exist if (-not ($script:ScriptCopPatrols)) { $script:ScriptCopPatrols = @{} } } process { if ($psCmdlet.parameterSetName -eq 'Name' -and $script:ScriptCopPatrols[$name]) { #region Create a PSObject to hold the results $result = New-Object PSObject $result.psObject.Properties.add( (New-Object Management.Automation.PSNoteProperty "Name", $Name) ) $result.psObject.Properties.add( (New-Object Management.Automation.PSNoteProperty "Description", $script:ScriptCopPatrols[$name].Description) ) $result.psObject.Properties.add( (New-Object Management.Automation.PSNoteProperty "CommandRule", $script:ScriptCopPatrols[$name].CommandRule) ) $result.psObject.Properties.add( (New-Object Management.Automation.PSNoteProperty "ModuleRule", $script:ScriptCopPatrols[$name].ModuleRule) ) $result #endregion } elseif ($psCmdlet.parameterSetName -eq 'All') { #region Use Recursion to get the PSObject for each patrol $script:ScriptCopPatrols.Keys | Get-ScriptCopPatrol #endregion } } }
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 14.10.2015 */ namespace skeeks\cms\helpers; use skeeks\cms\models\CmsTree; use skeeks\cms\models\Tree; use yii\caching\TagDependency; /** * Class TreeOptions * @package skeeks\cms\helpers */ class TreeOptions extends \skeeks\cms\models\Tree { /** * @var string символ будет добавляться перед називанием раздела. */ public $repeat = '. '; /** * @var array */ private $_filter = []; /** * * @param CmsTree $parentTree * @return array|mixed */ public static function getAllMultiOptions($parentTree = null) { $key = [ ROOT_DIR, static::className() ]; if ($parentTree) { if ($parentTree instanceof CmsTree) { $parentTreeId = $parentTree->id; } else { $parentTreeId = $parentTree; } $key[] = $parentTreeId; } $cacheKey = md5(implode($key)); $dependency = new TagDependency([ 'tags' => [ (new CmsTree())->getTableCacheTag(), ], ]); $options = \Yii::$app->cache->get($cacheKey); if (!$options) { if ($parentTree) { $options = \yii\helpers\ArrayHelper::map( self::findOne($parentTreeId)->getMultiOptions(), "id", "name" ); } else { $options = \yii\helpers\ArrayHelper::map( (new static())->getMultiOptions(), "id", "name" ); } \Yii::$app->cache->set($cacheKey, $options, 0, $dependency); } return $options; } /** * Строит массив для селекта * @param array $tree * @return array */ public function getMultiOptions($includeSelf = true) { $this->_tmpResult = []; if (!$this->isNewRecord && $includeSelf) { $this->_tmpResult[$this->id] = $this; } return $this->_buildTreeArrayRecursive($this, $this->_filter); } protected $_tmpResult = []; /** * Строит рекурсивно массив дерева * @param \skeeks\cms\models\Tree $model * @param array $filter * @return array */ private function _buildTreeArrayRecursive(Tree $model, $filter) { $is_filter_set = !empty($filter); if ($model->isNewRecord) { $childs = static::findRoots()->all(); } else { $childs = $model->children; } foreach ($childs as $child) { $level = $child->level; $id = $child->id; if (!$is_filter_set || in_array($id, $filter)) { $name = $child->name; if ($level == 0) { $name = "[" . $child->site->name . "] " . $child->name; } $child->name = str_repeat($this->repeat, $level) . $name; $this->_tmpResult[$id] = $child; } $this->_buildTreeArrayRecursive($child, $filter); } return $this->_tmpResult; } /** * Фильтрует дерево по заданному условию * @param $condition */ public function filter($condition) { $items = $this->find()->where($condition)->all(); $this->_filter = $this->_getTreeNodesIds($items); } /** * Возвращает массив id элементов дерева * @param $nodes * @return array */ private function _getTreeNodesIds($nodes) { $result = []; foreach ($nodes as $node) { $result[] = $node->id; } return $result; } }
<html> <head> <meta charset="utf-8"> <title>30s</title> </head> <body > <button onclick="post_data()">send var from js to php</button> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script> <?php if(!empty($_POST)){ $obj=json_decode($_POST["myData"],true); print_r($obj["var_name"]); } ?> <div class="roulette" style="display:none;"> <img src="http://example.com/star.png"/> <img src="http://example.com/flower.png"/> <img src="http://example.com/coin.png"/> <img src="http://example.com/mshroom.png"/> <img src="http://example.com/chomp.png"/> </div> <script> function post_data(){ var dataPost = { var_name: "ecrire ici la valeur de variable" }; var dataString = JSON.stringify(dataPost); $.ajax({ url: 'ch1.php', data: {myData: dataString}, type: 'POST', success: function(response) { console.log("send succes"); } }); }; </script> <script> var option = { speed : 10, duration : 3, stopImageNumber : 0, startCallback : function() { console.log('start'); }, slowDownCallback : function() { console.log('slowDown'); }, stopCallback : function($stopElm) { console.log('stop'); } } $('div.roulette').roulette(option); </script> </body> </html>
#!/bin/bash sudo ethtool -s eth3 speed 10000 duplex full sudo ethtool -s eth4 speed 10000 duplex full sudo ethtool -s eth5 speed 10000 duplex full sleep 30
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.Framework.Internal; namespace Microsoft.AspNet.Mvc.ModelBinding.Metadata { /// <summary> /// A context for an <see cref="IBindingMetadataProvider"/>. /// </summary> public class BindingMetadataProviderContext { /// <summary> /// Creates a new <see cref="BindingMetadataProviderContext"/>. /// </summary> /// <param name="key">The <see cref="ModelMetadataIdentity"/> for the <see cref="ModelMetadata"/>.</param> /// <param name="attributes">The attributes for the <see cref="ModelMetadata"/>.</param> public BindingMetadataProviderContext( [NotNull] ModelMetadataIdentity key, [NotNull] IReadOnlyList<object> attributes) { Key = key; Attributes = attributes; BindingMetadata = new BindingMetadata(); } /// <summary> /// Gets the attributes. /// </summary> public IReadOnlyList<object> Attributes { get; } /// <summary> /// Gets the <see cref="ModelMetadataIdentity"/>. /// </summary> public ModelMetadataIdentity Key { get; } /// <summary> /// Gets the <see cref="Metadata.BindingMetadata"/>. /// </summary> public BindingMetadata BindingMetadata { get; } } }
name 'heat-api' description 'OpenStack heat api service' run_list( 'role[openstack-base]', 'recipe[heat::api]' )
///<reference path="../node_modules/grafana-sdk-mocks/app/headers/common.d.ts" /> import $ from 'jquery'; import _ from 'lodash'; import './css/html-panel.css!'; import {MetricsPanelCtrl} from 'app/plugins/sdk'; class HtmlCtrl extends MetricsPanelCtrl { static templateUrl = 'partials/module.html'; static scrollable = true; ngTemplate: any = null; panelDefaults = { name: 'Echo Service with Template', text: 'Format the response with an angular template', editorTabIndex: 2, scroll: true, config: { template: ` <div ng-if="response && !response[0].columns"> Default: <div ng-repeat="item in response"> <div ng-repeat="datapoint in item.datapoints"> {{ datapoint }} </div> </div> </div> <div ng-if="response && response[0].columns"> MySQL columns: <div ng-repeat="item in response"> <div ng-repeat="column in item.columns"> {{ column.text }} </div> </div> </div> `, showTime: true, }, }; pageIndex: number; dataRaw: any; constructor($scope, $injector, public $compile) { super($scope, $injector); _.defaults(this.panel, this.panelDefaults.config); this.events.on('panel-initialized', this.onPanelInitialized.bind(this)); this.events.on('init-edit-mode', this.onInitEditMode.bind(this)); this.events.on('data-received', this.onDataReceived.bind(this)); this.events.on('data-error', this.onDataError.bind(this)); this.events.on('data-snapshot-load', this.onDataReceived.bind(this)); this.onDataReceived.bind(this); } onPanelInitialized() { this.updateTemplate(); $(window).on( 'resize', _.debounce(fn => { this.refresh(); }, 150) ); } onDataReceived(dataList) { this.dataRaw = dataList; this.pageIndex = 0; this.$scope.response = this.dataRaw; this.render(); } onDataError(err) { this.dataRaw = []; this.render(); } onInitEditMode() { this.addEditorTab( 'Display', 'public/plugins/' + this.pluginId + '/partials/editor.display.html', 2 ); } updateTemplate() { if (!this.panel.template) { this.panel.template = '<pre>{{ response }}</pre>'; } this.ngTemplate.html(this.panel.template); this.$compile(this.ngTemplate.contents())(this.$scope); if (this.$scope.response) { this.render(); this.refresh(); } } link(scope, elem, attrs, ctrl) { this.ngTemplate = $(elem.find('.ngTemplate')[0]); } } export {HtmlCtrl, HtmlCtrl as PanelCtrl};
/* Copyright 2019 Esri 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. */ using System; using System.Windows.Forms; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.GlobeCore; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.SystemUI; using ESRI.ArcGIS.Analyst3D; using ESRI.ArcGIS; using System.IO; namespace GlobeControlEffects { /// <summary> /// Summary description for Form1. /// </summary> public class Effects : System.Windows.Forms.Form { public System.Windows.Forms.GroupBox Frame2_1; public System.Windows.Forms.Label lblDelay; public System.Windows.Forms.TextBox TxtTipDelay; public System.Windows.Forms.ComboBox cmbTipType; public System.Windows.Forms.CheckBox ChkHUD; public System.Windows.Forms.CheckBox ChkArrow; public System.Windows.Forms.CheckBox ChkTip; public System.Windows.Forms.Label LblTips; public System.Windows.Forms.GroupBox Frame2; public System.Windows.Forms.Label lblLatVal; public System.Windows.Forms.Label LblLonVal; public System.Windows.Forms.Label LblAltVal; public System.Windows.Forms.Label LblLat; public System.Windows.Forms.Label LblLon; public System.Windows.Forms.Label LblALt; public System.Windows.Forms.GroupBox _Frame2_0; public System.Windows.Forms.Button CmdAmbient; public System.Windows.Forms.TextBox TxtAmbient; public System.Windows.Forms.Button CmdSetSun; public System.Windows.Forms.CheckBox chkSun; public System.Windows.Forms.Label Label2; private esriGlobeTipsType m_penumTips; private System.Windows.Forms.ColorDialog colorDialog1; private IGlobeDisplayEvents_AfterDrawEventHandler afterDrawE; private IGlobeDisplay m_globeDisplay; private IGlobeDisplayEvents_Event globeDisplayEvents; private ESRI.ArcGIS.Controls.AxToolbarControl axToolbarControl1; private ESRI.ArcGIS.Controls.AxTOCControl axTOCControl1; private ESRI.ArcGIS.Controls.AxGlobeControl axGlobeControl1; private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public Effects() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { //Release COM objects ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown(); if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Effects)); this.Frame2_1 = new System.Windows.Forms.GroupBox(); this.lblDelay = new System.Windows.Forms.Label(); this.TxtTipDelay = new System.Windows.Forms.TextBox(); this.cmbTipType = new System.Windows.Forms.ComboBox(); this.ChkHUD = new System.Windows.Forms.CheckBox(); this.ChkArrow = new System.Windows.Forms.CheckBox(); this.ChkTip = new System.Windows.Forms.CheckBox(); this.LblTips = new System.Windows.Forms.Label(); this.Frame2 = new System.Windows.Forms.GroupBox(); this.lblLatVal = new System.Windows.Forms.Label(); this.LblLonVal = new System.Windows.Forms.Label(); this.LblAltVal = new System.Windows.Forms.Label(); this.LblLat = new System.Windows.Forms.Label(); this.LblLon = new System.Windows.Forms.Label(); this.LblALt = new System.Windows.Forms.Label(); this._Frame2_0 = new System.Windows.Forms.GroupBox(); this.CmdAmbient = new System.Windows.Forms.Button(); this.TxtAmbient = new System.Windows.Forms.TextBox(); this.CmdSetSun = new System.Windows.Forms.Button(); this.chkSun = new System.Windows.Forms.CheckBox(); this.Label2 = new System.Windows.Forms.Label(); this.colorDialog1 = new System.Windows.Forms.ColorDialog(); this.axToolbarControl1 = new ESRI.ArcGIS.Controls.AxToolbarControl(); this.axTOCControl1 = new ESRI.ArcGIS.Controls.AxTOCControl(); this.axGlobeControl1 = new ESRI.ArcGIS.Controls.AxGlobeControl(); this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl(); this.Frame2_1.SuspendLayout(); this.Frame2.SuspendLayout(); this._Frame2_0.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axGlobeControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit(); this.SuspendLayout(); // // Frame2_1 // this.Frame2_1.BackColor = System.Drawing.SystemColors.Control; this.Frame2_1.Controls.Add(this.lblDelay); this.Frame2_1.Controls.Add(this.TxtTipDelay); this.Frame2_1.Controls.Add(this.cmbTipType); this.Frame2_1.Controls.Add(this.ChkHUD); this.Frame2_1.Controls.Add(this.ChkArrow); this.Frame2_1.Controls.Add(this.ChkTip); this.Frame2_1.Controls.Add(this.LblTips); this.Frame2_1.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Frame2_1.ForeColor = System.Drawing.SystemColors.ControlText; this.Frame2_1.Location = new System.Drawing.Point(256, 376); this.Frame2_1.Name = "Frame2_1"; this.Frame2_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Frame2_1.Size = new System.Drawing.Size(224, 69); this.Frame2_1.TabIndex = 16; this.Frame2_1.TabStop = false; this.Frame2_1.Text = "HUD"; // // lblDelay // this.lblDelay.BackColor = System.Drawing.SystemColors.Control; this.lblDelay.Cursor = System.Windows.Forms.Cursors.Default; this.lblDelay.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblDelay.ForeColor = System.Drawing.SystemColors.ControlText; this.lblDelay.Location = new System.Drawing.Point(136, 9); this.lblDelay.Name = "lblDelay"; this.lblDelay.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblDelay.Size = new System.Drawing.Size(72, 13); this.lblDelay.TabIndex = 18; this.lblDelay.Text = "Delay(mSec.)"; // // TxtTipDelay // this.TxtTipDelay.AcceptsReturn = true; this.TxtTipDelay.AutoSize = false; this.TxtTipDelay.BackColor = System.Drawing.SystemColors.Window; this.TxtTipDelay.Cursor = System.Windows.Forms.Cursors.IBeam; this.TxtTipDelay.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.TxtTipDelay.ForeColor = System.Drawing.SystemColors.WindowText; this.TxtTipDelay.Location = new System.Drawing.Point(160, 24); this.TxtTipDelay.MaxLength = 0; this.TxtTipDelay.Name = "TxtTipDelay"; this.TxtTipDelay.RightToLeft = System.Windows.Forms.RightToLeft.No; this.TxtTipDelay.Size = new System.Drawing.Size(48, 15); this.TxtTipDelay.TabIndex = 16; this.TxtTipDelay.Text = "500"; // // cmbTipType // this.cmbTipType.BackColor = System.Drawing.SystemColors.Window; this.cmbTipType.Cursor = System.Windows.Forms.Cursors.Default; this.cmbTipType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbTipType.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.cmbTipType.ForeColor = System.Drawing.SystemColors.WindowText; this.cmbTipType.Location = new System.Drawing.Point(69, 42); this.cmbTipType.Name = "cmbTipType"; this.cmbTipType.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmbTipType.Size = new System.Drawing.Size(139, 22); this.cmbTipType.TabIndex = 17; this.cmbTipType.SelectedIndexChanged += new System.EventHandler(this.cmbTipType_SelectedIndexChanged); // // ChkHUD // this.ChkHUD.BackColor = System.Drawing.SystemColors.Control; this.ChkHUD.Cursor = System.Windows.Forms.Cursors.Default; this.ChkHUD.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.ChkHUD.ForeColor = System.Drawing.SystemColors.ControlText; this.ChkHUD.Location = new System.Drawing.Point(13, 19); this.ChkHUD.Name = "ChkHUD"; this.ChkHUD.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ChkHUD.Size = new System.Drawing.Size(51, 16); this.ChkHUD.TabIndex = 15; this.ChkHUD.Text = "HUD"; this.ChkHUD.CheckedChanged += new System.EventHandler(this.ChkHUD_CheckedChanged); // // ChkArrow // this.ChkArrow.BackColor = System.Drawing.SystemColors.Control; this.ChkArrow.Cursor = System.Windows.Forms.Cursors.Default; this.ChkArrow.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.ChkArrow.ForeColor = System.Drawing.SystemColors.ControlText; this.ChkArrow.Location = new System.Drawing.Point(13, 33); this.ChkArrow.Name = "ChkArrow"; this.ChkArrow.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ChkArrow.Size = new System.Drawing.Size(59, 31); this.ChkArrow.TabIndex = 14; this.ChkArrow.Text = "North Arrow"; this.ChkArrow.CheckedChanged += new System.EventHandler(this.ChkArrow_CheckedChanged); // // ChkTip // this.ChkTip.BackColor = System.Drawing.SystemColors.Control; this.ChkTip.Cursor = System.Windows.Forms.Cursors.Default; this.ChkTip.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.ChkTip.ForeColor = System.Drawing.SystemColors.ControlText; this.ChkTip.Location = new System.Drawing.Point(69, 25); this.ChkTip.Name = "ChkTip"; this.ChkTip.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ChkTip.Size = new System.Drawing.Size(14, 15); this.ChkTip.TabIndex = 20; this.ChkTip.Text = "Check1"; this.ChkTip.CheckedChanged += new System.EventHandler(this.ChkTip_CheckedChanged); // // LblTips // this.LblTips.BackColor = System.Drawing.SystemColors.Control; this.LblTips.Cursor = System.Windows.Forms.Cursors.Default; this.LblTips.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.LblTips.ForeColor = System.Drawing.SystemColors.ControlText; this.LblTips.Location = new System.Drawing.Point(84, 16); this.LblTips.Name = "LblTips"; this.LblTips.RightToLeft = System.Windows.Forms.RightToLeft.No; this.LblTips.Size = new System.Drawing.Size(58, 28); this.LblTips.TabIndex = 19; this.LblTips.Text = "Enable Globe Tips"; // // Frame2 // this.Frame2.BackColor = System.Drawing.SystemColors.Control; this.Frame2.Controls.Add(this.lblLatVal); this.Frame2.Controls.Add(this.LblLonVal); this.Frame2.Controls.Add(this.LblAltVal); this.Frame2.Controls.Add(this.LblLat); this.Frame2.Controls.Add(this.LblLon); this.Frame2.Controls.Add(this.LblALt); this.Frame2.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Frame2.ForeColor = System.Drawing.SystemColors.ControlText; this.Frame2.Location = new System.Drawing.Point(488, 376); this.Frame2.Name = "Frame2"; this.Frame2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Frame2.Size = new System.Drawing.Size(236, 69); this.Frame2.TabIndex = 15; this.Frame2.TabStop = false; this.Frame2.Text = "Alternate HUD"; // // lblLatVal // this.lblLatVal.BackColor = System.Drawing.SystemColors.Control; this.lblLatVal.Cursor = System.Windows.Forms.Cursors.Default; this.lblLatVal.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblLatVal.ForeColor = System.Drawing.SystemColors.ControlText; this.lblLatVal.Location = new System.Drawing.Point(33, 30); this.lblLatVal.Name = "lblLatVal"; this.lblLatVal.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblLatVal.Size = new System.Drawing.Size(86, 13); this.lblLatVal.TabIndex = 9; this.lblLatVal.Text = "lblLatVal"; // // LblLonVal // this.LblLonVal.BackColor = System.Drawing.SystemColors.Control; this.LblLonVal.Cursor = System.Windows.Forms.Cursors.Default; this.LblLonVal.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.LblLonVal.ForeColor = System.Drawing.SystemColors.ControlText; this.LblLonVal.Location = new System.Drawing.Point(33, 45); this.LblLonVal.Name = "LblLonVal"; this.LblLonVal.RightToLeft = System.Windows.Forms.RightToLeft.No; this.LblLonVal.Size = new System.Drawing.Size(86, 13); this.LblLonVal.TabIndex = 7; this.LblLonVal.Text = "LblLonVal"; // // LblAltVal // this.LblAltVal.BackColor = System.Drawing.SystemColors.Control; this.LblAltVal.Cursor = System.Windows.Forms.Cursors.Default; this.LblAltVal.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.LblAltVal.ForeColor = System.Drawing.SystemColors.ControlText; this.LblAltVal.Location = new System.Drawing.Point(134, 44); this.LblAltVal.Name = "LblAltVal"; this.LblAltVal.RightToLeft = System.Windows.Forms.RightToLeft.No; this.LblAltVal.Size = new System.Drawing.Size(86, 11); this.LblAltVal.TabIndex = 8; this.LblAltVal.Text = "LblAltVal"; // // LblLat // this.LblLat.BackColor = System.Drawing.SystemColors.Control; this.LblLat.Cursor = System.Windows.Forms.Cursors.Default; this.LblLat.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.LblLat.ForeColor = System.Drawing.SystemColors.ControlText; this.LblLat.Location = new System.Drawing.Point(8, 32); this.LblLat.Name = "LblLat"; this.LblLat.RightToLeft = System.Windows.Forms.RightToLeft.No; this.LblLat.Size = new System.Drawing.Size(24, 15); this.LblLat.TabIndex = 12; this.LblLat.Text = "Lat:"; // // LblLon // this.LblLon.BackColor = System.Drawing.SystemColors.Control; this.LblLon.Cursor = System.Windows.Forms.Cursors.Default; this.LblLon.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.LblLon.ForeColor = System.Drawing.SystemColors.ControlText; this.LblLon.Location = new System.Drawing.Point(9, 46); this.LblLon.Name = "LblLon"; this.LblLon.RightToLeft = System.Windows.Forms.RightToLeft.No; this.LblLon.Size = new System.Drawing.Size(27, 16); this.LblLon.TabIndex = 11; this.LblLon.Text = "Lon:"; // // LblALt // this.LblALt.BackColor = System.Drawing.SystemColors.Control; this.LblALt.Cursor = System.Windows.Forms.Cursors.Default; this.LblALt.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.LblALt.ForeColor = System.Drawing.SystemColors.ControlText; this.LblALt.Location = new System.Drawing.Point(133, 23); this.LblALt.Name = "LblALt"; this.LblALt.RightToLeft = System.Windows.Forms.RightToLeft.No; this.LblALt.Size = new System.Drawing.Size(83, 19); this.LblALt.TabIndex = 10; this.LblALt.Text = "Alt (in Kms.)"; // // _Frame2_0 // this._Frame2_0.BackColor = System.Drawing.SystemColors.Control; this._Frame2_0.Controls.Add(this.CmdAmbient); this._Frame2_0.Controls.Add(this.TxtAmbient); this._Frame2_0.Controls.Add(this.CmdSetSun); this._Frame2_0.Controls.Add(this.chkSun); this._Frame2_0.Controls.Add(this.Label2); this._Frame2_0.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this._Frame2_0.ForeColor = System.Drawing.SystemColors.ControlText; this._Frame2_0.Location = new System.Drawing.Point(8, 376); this._Frame2_0.Name = "_Frame2_0"; this._Frame2_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Frame2_0.Size = new System.Drawing.Size(236, 69); this._Frame2_0.TabIndex = 14; this._Frame2_0.TabStop = false; this._Frame2_0.Text = "Sun and Ambient Light Prop"; // // CmdAmbient // this.CmdAmbient.BackColor = System.Drawing.SystemColors.Control; this.CmdAmbient.Cursor = System.Windows.Forms.Cursors.Default; this.CmdAmbient.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.CmdAmbient.ForeColor = System.Drawing.SystemColors.ControlText; this.CmdAmbient.Location = new System.Drawing.Point(10, 43); this.CmdAmbient.Name = "CmdAmbient"; this.CmdAmbient.RightToLeft = System.Windows.Forms.RightToLeft.No; this.CmdAmbient.Size = new System.Drawing.Size(78, 22); this.CmdAmbient.TabIndex = 4; this.CmdAmbient.Text = "Set Ambient"; this.CmdAmbient.Click += new System.EventHandler(this.CmdAmbient_Click); // // TxtAmbient // this.TxtAmbient.AcceptsReturn = true; this.TxtAmbient.AutoSize = false; this.TxtAmbient.BackColor = System.Drawing.SystemColors.Window; this.TxtAmbient.Cursor = System.Windows.Forms.Cursors.IBeam; this.TxtAmbient.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.TxtAmbient.ForeColor = System.Drawing.SystemColors.WindowText; this.TxtAmbient.Location = new System.Drawing.Point(168, 45); this.TxtAmbient.MaxLength = 0; this.TxtAmbient.Name = "TxtAmbient"; this.TxtAmbient.RightToLeft = System.Windows.Forms.RightToLeft.No; this.TxtAmbient.Size = new System.Drawing.Size(48, 20); this.TxtAmbient.TabIndex = 3; this.TxtAmbient.Text = ""; // // CmdSetSun // this.CmdSetSun.BackColor = System.Drawing.SystemColors.Control; this.CmdSetSun.Cursor = System.Windows.Forms.Cursors.Default; this.CmdSetSun.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.CmdSetSun.ForeColor = System.Drawing.SystemColors.ControlText; this.CmdSetSun.Location = new System.Drawing.Point(144, 15); this.CmdSetSun.Name = "CmdSetSun"; this.CmdSetSun.RightToLeft = System.Windows.Forms.RightToLeft.No; this.CmdSetSun.Size = new System.Drawing.Size(80, 20); this.CmdSetSun.TabIndex = 2; this.CmdSetSun.Text = "Set Sun Color"; this.CmdSetSun.Click += new System.EventHandler(this.CmdSetSun_Click); // // chkSun // this.chkSun.BackColor = System.Drawing.SystemColors.Control; this.chkSun.Cursor = System.Windows.Forms.Cursors.Default; this.chkSun.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.chkSun.ForeColor = System.Drawing.SystemColors.ControlText; this.chkSun.Location = new System.Drawing.Point(15, 17); this.chkSun.Name = "chkSun"; this.chkSun.RightToLeft = System.Windows.Forms.RightToLeft.No; this.chkSun.Size = new System.Drawing.Size(81, 22); this.chkSun.TabIndex = 1; this.chkSun.Text = "Enable Sun"; this.chkSun.CheckedChanged += new System.EventHandler(this.chkSun_CheckedChanged); // // Label2 // this.Label2.BackColor = System.Drawing.SystemColors.Control; this.Label2.Cursor = System.Windows.Forms.Cursors.Default; this.Label2.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Label2.ForeColor = System.Drawing.SystemColors.ControlText; this.Label2.Location = new System.Drawing.Point(96, 48); this.Label2.Name = "Label2"; this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label2.Size = new System.Drawing.Size(64, 16); this.Label2.TabIndex = 5; this.Label2.Text = "Values 0 -1"; // // axToolbarControl1 // this.axToolbarControl1.Location = new System.Drawing.Point(8, 8); this.axToolbarControl1.Name = "axToolbarControl1"; this.axToolbarControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axToolbarControl1.OcxState"))); this.axToolbarControl1.Size = new System.Drawing.Size(720, 28); this.axToolbarControl1.TabIndex = 17; // // axTOCControl1 // this.axTOCControl1.Location = new System.Drawing.Point(8, 40); this.axTOCControl1.Name = "axTOCControl1"; this.axTOCControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axTOCControl1.OcxState"))); this.axTOCControl1.Size = new System.Drawing.Size(192, 328); this.axTOCControl1.TabIndex = 18; // // axGlobeControl1 // this.axGlobeControl1.Location = new System.Drawing.Point(208, 40); this.axGlobeControl1.Name = "axGlobeControl1"; this.axGlobeControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axGlobeControl1.OcxState"))); this.axGlobeControl1.Size = new System.Drawing.Size(520, 328); this.axGlobeControl1.TabIndex = 19; this.axGlobeControl1.OnGlobeReplaced += new ESRI.ArcGIS.Controls.IGlobeControlEvents_Ax_OnGlobeReplacedEventHandler(this.axGlobeControl1_OnGlobeReplaced); // // axLicenseControl1 // this.axLicenseControl1.Enabled = true; this.axLicenseControl1.Location = new System.Drawing.Point(512, 56); this.axLicenseControl1.Name = "axLicenseControl1"; this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState"))); this.axLicenseControl1.Size = new System.Drawing.Size(200, 50); this.axLicenseControl1.TabIndex = 20; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(736, 454); this.Controls.Add(this.axLicenseControl1); this.Controls.Add(this.axGlobeControl1); this.Controls.Add(this.axTOCControl1); this.Controls.Add(this.axToolbarControl1); this.Controls.Add(this.Frame2_1); this.Controls.Add(this.Frame2); this.Controls.Add(this._Frame2_0); this.Name = "Form1"; this.Text = "GlobeControl"; this.Load += new System.EventHandler(this.Form1_Load); this.Frame2_1.ResumeLayout(false); this.Frame2.ResumeLayout(false); this._Frame2_0.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axGlobeControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit(); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { if (!RuntimeManager.Bind(ProductCode.Engine)) { if (!RuntimeManager.Bind(ProductCode.Desktop)) { MessageBox.Show("Unable to bind to ArcGIS runtime. Application will be shut down."); return; } } Application.Run(new Effects()); } private void Form1_Load(object sender, System.EventArgs e) { //relative file path to the sample data from project location string sGlbData = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); sGlbData = Path.Combine(sGlbData, @"ArcGIS\data\Globe\World Imagery.3dd"); var filePath = new DirectoryInfo(sGlbData); System.Diagnostics.Debug.WriteLine(string.Format("File path for data root: {0} [{1}]", filePath.FullName, Directory.GetCurrentDirectory())); if (!File.Exists(sGlbData)) throw new Exception(string.Format("Fix code to point to your sample data: {0} [{1}] was not found", filePath.FullName, Directory.GetCurrentDirectory())); if (axGlobeControl1.Check3dFile(sGlbData)) axGlobeControl1.Load3dFile(sGlbData); //Enable north arrow, HUD and GlobeTips. bool bChkArrow = axGlobeControl1.GlobeViewer.NorthArrowEnabled; bool bHUD = axGlobeControl1.GlobeViewer.HUDEnabled; ChkHUD.Checked = bHUD; ChkArrow.Checked = bChkArrow; //get the state of globetips from the loaded doc..... m_penumTips = axGlobeControl1.GlobeViewer.GlobeDisplay.Globe.ShowGlobeTips; //if no tip value (not set) in the loaded doc set it to default.. if (m_penumTips <= 0) { m_penumTips = esriGlobeTipsType.esriGlobeTipsTypeLatLon; } cmbTipType.Items.Insert(0, "esriGlobeTipsTypeNone"); cmbTipType.Items.Insert(1, "esriGlobeTipsTypeLatLon"); cmbTipType.Items.Insert(2, "esriGlobeTipsTypeElevation"); cmbTipType.Items.Insert(3, "esriGlobeTipsTypeLatLonElevation"); ChkTip.Checked = true;//tip value of the doc... //set the list... cmbTipType.SelectedIndex = (int) m_penumTips; //populate tip type values.. axGlobeControl1.TipStyle = esriTipStyle.esriTipStyleSolid; axGlobeControl1.TipDelay = 500; //default.. axGlobeControl1.GlobeViewer.GlobeDisplay.Globe.ShowGlobeTips = m_penumTips; axGlobeControl1.GlobeDisplay.RefreshViewers(); //Get current sun property.. IGlobeDisplayRendering pglbDispRend = (IGlobeDisplayRendering)axGlobeControl1.GlobeDisplay; bool bsun = pglbDispRend.IsSunEnabled; if (bsun == true) chkSun.Checked = true; //checked //Get Ambient light... TxtAmbient.Text = pglbDispRend.AmbientLight.ToString(); //Listen to events.. m_globeDisplay = axGlobeControl1.GlobeDisplay; globeDisplayEvents = (IGlobeDisplayEvents_Event)m_globeDisplay; globeDisplayEvents.AfterDraw += new IGlobeDisplayEvents_AfterDrawEventHandler(OnAfterDraw); //globeDisplayEvents += new IGlobeDisplayEvents_AfterDrawEventHandler(OnAfterDraw); //afterDrawE = new IGlobeDisplayEvents_AfterDrawEventHandler(OnAfterDraw); //((IGlobeDisplayEvents_Event)axGlobeControl1.GlobeDisplay).AfterDraw+=afterDrawE; //globeDisplayEvents.AfterDraw += new (globeDisplayEvents_AfterDraw); } private void cmbTipType_SelectedIndexChanged(object sender, System.EventArgs e) { m_penumTips = (esriGlobeTipsType) cmbTipType.SelectedIndex; if (ChkTip.Checked == true) { string sVal = TxtTipDelay.Text; if (Convert.ToSingle(sVal) == 0) sVal="500"; //set it to default..miliseconds axGlobeControl1.TipDelay = Convert.ToInt32(sVal); axGlobeControl1.TipStyle = esriTipStyle.esriTipStyleSolid; axGlobeControl1.ShowGlobeTips = m_penumTips; axGlobeControl1.GlobeDisplay.RefreshViewers(); } } private void CmdAmbient_Click(object sender, System.EventArgs e) { string sVal = TxtAmbient.Text; if (Convert.ToSingle(sVal) > (double) 1.0) sVal = "1"; if (Convert.ToSingle(sVal) < (double) 0.0) sVal = "0"; IGlobeDisplayRendering pglbDispRend = (IGlobeDisplayRendering) axGlobeControl1.GlobeDisplay; pglbDispRend.AmbientLight = Convert.ToSingle(sVal); //update textbox TxtAmbient.Text = sVal; axGlobeControl1.GlobeDisplay.RefreshViewers(); } private void CmdSetSun_Click(object sender, System.EventArgs e) { IRgbColor pCmDRgb = new RgbColorClass(); if (colorDialog1.ShowDialog() == DialogResult.Cancel) return; pCmDRgb.Red = colorDialog1.Color.R; pCmDRgb.Blue = colorDialog1.Color.B; pCmDRgb.Green = colorDialog1.Color.G; ChangeIllumination(pCmDRgb); } private void ChangeIllumination(IRgbColor prgb) { IGlobeDisplayRendering pglbDispRend = (IGlobeDisplayRendering) axGlobeControl1.GlobeDisplay; double platitude=0; double plongitude=0; Single pSunred; Single pSungreen; Single pSunblue; Single pAmbientLght; if ((pglbDispRend.IsSunEnabled == true) & (chkSun.Checked == true)) { //get the Default position and color... pglbDispRend.GetSunPosition(out platitude, out plongitude); pglbDispRend.GetSunColor(out pSunred, out pSungreen, out pSunblue); //Set AmbientLght string sVal = TxtAmbient.Text; if (Convert.ToSingle(sVal) > 1) sVal = "1"; if (Convert.ToSingle(sVal) < 0) sVal = "0"; pglbDispRend.AmbientLight = Convert.ToSingle(sVal); //update textbox TxtAmbient.Text = sVal; pAmbientLght = pglbDispRend.AmbientLight; IColor pIcolor = prgb; IGlobeDisplay pglbDisp = EnableSetSun(pAmbientLght, platitude, plongitude, pIcolor); axGlobeControl1.GlobeDisplay = pglbDisp; axGlobeControl1.GlobeDisplay.RefreshViewers(); } } private IGlobeDisplay EnableSetSun(Single pAmbientLght, double platitude, double plongitude, IColor pColor ) { Single pSunred; Single pSungreen; Single pSunblue; IRgbColor pRgbColor = new RgbColorClass(); pRgbColor.RGB = Convert.ToInt32(pColor.RGB); pSunred = pRgbColor.Red; pSungreen = pRgbColor.Green; pSunblue = pRgbColor.Blue; IGlobeDisplayRendering pglbDispRend = (IGlobeDisplayRendering) axGlobeControl1.GlobeDisplay; pglbDispRend.SetSunColor(pSunred, pSungreen, pSunblue); pglbDispRend.SetSunPosition(platitude, plongitude); pglbDispRend.AmbientLight = pAmbientLght; return axGlobeControl1.GlobeDisplay; } private void ChkArrow_CheckedChanged(object sender, System.EventArgs e) { bool bChkArrow = axGlobeControl1.GlobeViewer.NorthArrowEnabled; if ((ChkArrow.Checked == false) & (bChkArrow == true)) { axGlobeControl1.GlobeViewer.NorthArrowEnabled = false; //unchecked axGlobeControl1.GlobeDisplay.RefreshViewers(); } else if ((ChkArrow.Checked == true) & (bChkArrow == false)) { axGlobeControl1.GlobeViewer.NorthArrowEnabled = true; //checked axGlobeControl1.GlobeDisplay.RefreshViewers(); } } private void ChkHUD_CheckedChanged(object sender, System.EventArgs e) { //Default HUD bool bHUD = axGlobeControl1.GlobeViewer.HUDEnabled; if ((ChkHUD.Checked == false) & (bHUD == true)) { axGlobeControl1.GlobeViewer.HUDEnabled = false; //unchecked axGlobeControl1.GlobeDisplay.RefreshViewers(); } else if ((ChkHUD.Checked == true) & (bHUD==false)) { axGlobeControl1.GlobeViewer.HUDEnabled = true; //checked axGlobeControl1.GlobeDisplay.RefreshViewers(); } } private void chkSun_CheckedChanged(object sender, System.EventArgs e) { IGlobeDisplayRendering pglbDispRend = (IGlobeDisplayRendering) axGlobeControl1.GlobeDisplay; bool bsun = pglbDispRend.IsSunEnabled; if ((chkSun.Checked == false) & (bsun == true)) { pglbDispRend.IsSunEnabled = false; //unchecked CmdSetSun.Enabled = false; } else if ((chkSun.Checked == true) & (bsun==false)) { pglbDispRend.IsSunEnabled = true; //checked CmdSetSun.Enabled = true; } } private void ChkTip_CheckedChanged(object sender, System.EventArgs e) { if (ChkTip.Checked == false) { axGlobeControl1.ShowGlobeTips = esriGlobeTipsType.esriGlobeTipsTypeNone; axGlobeControl1.GlobeDisplay.RefreshViewers(); cmbTipType.Enabled = false; TxtTipDelay.Enabled = false; } else { cmbTipType.Enabled = true; TxtTipDelay.Enabled = true; string sVal = TxtTipDelay.Text; if (Convert.ToInt32(sVal) == 0) sVal="500"; //set it to default..miliseconds if (cmbTipType.SelectedIndex >= 0) m_penumTips = (esriGlobeTipsType) cmbTipType.SelectedIndex; axGlobeControl1.TipDelay = Convert.ToInt32(sVal); axGlobeControl1.TipStyle = esriTipStyle.esriTipStyleSolid; axGlobeControl1.GlobeViewer.GlobeDisplay.Globe.ShowGlobeTips = m_penumTips; axGlobeControl1.GlobeDisplay.RefreshViewers(); } } private void GetObserVerLatLong(ISceneViewer pViewer, out double pLatDD, out double pLonDD, out double pAltKms, out double pRoll, out double pIncl) { IGlobeCamera pCam = (IGlobeCamera) pViewer.Camera; pCam.GetObserverLatLonAlt( out pLatDD, out pLonDD, out pAltKms); ICamera pIcam = (ICamera) pCam; pRoll = pIcam.RollAngle; pIncl = pIcam.Inclination; } private void UpdateCustomHUD(double pLatDD, double pLonDD, double pAltKms, double pRoll, double pIncl) { LblAltVal.Text = pAltKms.ToString(); lblLatVal.Text = pLatDD.ToString(); LblLonVal.Text = pLonDD.ToString(); } private void OnAfterDraw(ISceneViewer pViewer) { double pLatDD=0; double pLonDD=0; double pAltKms=0; double pRoll=0; double pIncl=0; GetObserVerLatLong(pViewer, out pLatDD, out pLonDD, out pAltKms, out pRoll, out pIncl); UpdateCustomHUD(pLatDD, pLonDD, pAltKms, pRoll, pIncl); } private void axGlobeControl1_OnGlobeReplaced(object sender, ESRI.ArcGIS.Controls.IGlobeControlEvents_OnGlobeReplacedEvent e) { IGlobeDisplayRendering pglbbDispRend = (IGlobeDisplayRendering) axGlobeControl1.GlobeDisplay; bool bsun = pglbbDispRend.IsSunEnabled; if (bsun==true) chkSun.Checked = true; //checked //get the state of globetips from the loaded doc..... m_penumTips = axGlobeControl1.GlobeViewer.GlobeDisplay.Globe.ShowGlobeTips; } } }
import R from 'ramda'; import immutable from 'seamless-immutable'; const isImmutable = R.has('asMutable'); const convertToJs = state => state.asMutable({ deep: true }); const fromImmutable = R.when(isImmutable, convertToJs); const toImmutable = raw => immutable(raw); export default { out: (state) => { if (state) { state.mergeDeep = R.identity; // eslint-disable-line } return toImmutable(state); }, in: raw => fromImmutable(raw), };
package com.thecode.infotify.database import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.thecode.infotify.database.article.ArticleEntity import com.thecode.infotify.database.article.ArticlesDao import com.thecode.infotify.database.source.SourceConverter import com.thecode.infotify.database.source.SourceEntity import com.thecode.infotify.database.source.SourcesDao @Database(entities = [ArticleEntity::class, SourceEntity::class], version = 1, exportSchema = false) @TypeConverters(SourceConverter::class) abstract class AppDatabase : RoomDatabase() { abstract fun getArticlesDao(): ArticlesDao abstract fun getSourcesDao(): SourcesDao companion object { /** The only instance */ private var sInstance: AppDatabase? = null /** * Gets the singleton instance of AppDatabase. * * @param context The context. * @return The singleton instance of AppDatabase. */ @Synchronized fun getInstance(context: Context): AppDatabase { if (sInstance == null) { sInstance = Room .databaseBuilder( context.applicationContext, AppDatabase::class.java, "infotify.db" ) .build() } return sInstance as AppDatabase } } }
import 'package:fish_redux/fish_redux.dart'; import 'package:flutter/material.dart' hide Action; import 'package:movie/actions/http/tmdb_api.dart'; import 'action.dart'; import 'state.dart'; Effect<SeasonDetailPageState> buildEffect() { return combineEffects(<Object, Effect<SeasonDetailPageState>>{ SeasonDetailPageAction.action: _onAction, Lifecycle.initState: _onInit, }); } void _onAction(Action action, Context<SeasonDetailPageState> ctx) {} Future _onInit(Action action, Context<SeasonDetailPageState> ctx) async { ctx.state.scrollController = new ScrollController(); final _tmdb = TMDBApi.instance; if (ctx.state.tvid != null && ctx.state.seasonNumber != null) { final _detail = await _tmdb.getTVSeasonDetail( ctx.state.tvid, ctx.state.seasonNumber, appendToResponse: 'credits'); if (_detail.success) ctx.dispatch( SeasonDetailPageActionCreator.onSeasonDetailChanged(_detail.result)); final _videos = await _tmdb.getTvShowSeasonVideo( ctx.state.tvid, ctx.state.seasonNumber); if (_videos.success) ctx.dispatch(SeasonDetailPageActionCreator.setVideos(_videos.result)); final _images = await _tmdb.getTvShowSeasonImages( ctx.state.tvid, ctx.state.seasonNumber); if (_images.success) ctx.dispatch(SeasonDetailPageActionCreator.setImages(_images.result)); } }
// +build amd64 // +build windows package w32syscall import "syscall" var ( procGetClassLongPtrW = moduser32.NewProc("GetClassLongPtrW") ) func GetClassLongPtr(hwnd syscall.Handle, index int) (result uintptr, err error) { result, _, e1 := syscall.Syscall(procGetClassLongPtrW.Addr(), 2, uintptr(hwnd), uintptr(index), 0) if result == 0 { err = error(e1) } return }
#!/usr/bin/ruby # encoding: utf-8 $:.unshift( File.dirname( __FILE__ ) ) require 'CalculatorLexer' require 'CalculatorParser' fetch = begin require 'readline' proc do Readline.readline( ">>> ", true ) end rescue LoadError proc do print( ">>> " ) l = $stdin.gets and l.chomp end end puts( "enter calculator expressions or `quit' to exit") loop do case line = fetch.call when /q(uit)?/i, /e(xit)?/i, nil then break else printf( "\t=> %s\n", Calculator::Parser.new( line ).evaluate ) end end
import AudipPlayer from './audio-player' import Collapse from './collapse' import LetterBlock from './letter-block' import PropTypes from 'prop-types' import React from 'react' // import styled from 'styled-components' import Waypoint from 'react-waypoint' import Container from '../content-container' import mq from '../../utils/media-query' const ContentContainer = Container.extend` background: #fff; ${mq.tabletAbove` padding-left: 47px; padding-right: 70px; `} box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.1); ` class AudioSection extends React.PureComponent { static propTypes = { content: PropTypes.object.isRequired, playing: PropTypes.string, setPlaying: PropTypes.func.isRequired, } static defaultProps = { playing: null, } constructor(props) { super(props) this.state = { enterInlinePlayer: false, expand: false, } } togglePlaying = () => { const { content, playing, setPlaying } = this.props const { id } = content const isPlaying = playing === id if (!this.state.expand) { this.setState({ expand: true, }) } return setPlaying(isPlaying ? null : id) } handleEnterInlinePlayer = () => { this.setState({ enterInlinePlayer: true, }) } handleLeaveInlinePlayer = () => { this.setState({ enterInlinePlayer: false, }) } // handleLeaveSection = () => { // const { setPlaying } = this.props // setPlaying(null) // } // <Waypoint // scrollableAncestor="window" // onLeave={this.handleLeaveSection} // > // </Waypoint> render() { const { content, playing } = this.props const { enterInlinePlayer } = this.state const { id, letter, audioSrc, lang, translator, title } = content const { chinese, origin } = letter const isPlaying = playing === id const showPopup = isPlaying && !enterInlinePlayer return ( <div style={{ background: '#fff', padding: '36px 0' }}> <ContentContainer wide> <Waypoint scrollableAncestor="window" onEnter={this.handleEnterInlinePlayer} onLeave={this.handleLeaveInlinePlayer} > <div> <AudipPlayer audioSrc={audioSrc} isPlaying={isPlaying} togglePlaying={this.togglePlaying} title={title} lang={lang} showPopup={showPopup} /> </div> </Waypoint> <Collapse show={this.state.expand}> <LetterBlock translator={translator} chinese={chinese} origin={origin} lang={lang} /> </Collapse> </ContentContainer> </div> ) } } export default AudioSection
const cheerio = require("cheerio"); const { nanoid } = require('nanoid'); function getCases(pageContent) { const $ = cheerio.load(pageContent); let casesArray = []; $('.result-box').each(function (i, item) { const name = $(item).find('h4').text(); const id = nanoid(); if (name) { casesArray.push({ id, name, image: $(item).find('img').attr('src'), contentLink: $(item).children('a').attr('href'), marketLink: $(item).find('.market-button-item').attr('href') }) } }); return casesArray; } module.exports = getCases;
package com.klony.formatters import com.klony.organiser.OrganisedResult import com.klony.utils.resolveToRealPath import com.klony.utils.terminal.Terminal import com.klony.utils.toStringShortened class ChecksumMapFormatterSummary: ChecksumMapFormatter { override fun toString(result: OrganisedResult): String { val terminalDimension = Terminal.getDimensionOrDefault() val fullLine = "-".repeat(terminalDimension.width) val setSeparator = "${System.lineSeparator()}$fullLine${System.lineSeparator()}" val prefix = "The following files are clones (each clone set is divided):" return result .joinToString(prefix = prefix, separator = setSeparator) { files -> files.joinToString(separator = System.lineSeparator()) { file -> file.toPath().resolveToRealPath().toStringShortened(terminalDimension.width) } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(HMDRecorder))] public class HMDRecorderEditor : Editor { public override void OnInspectorGUI() { DrawDefaultInspector(); var hmdRecorder = (HMDRecorder)target; if (GUILayout.Button("Save to File")) { var path = EditorUtility.SaveFilePanel("Save logs", "", "", ".csv"); hmdRecorder.Dump(path); } } }
using System; using System.Xml; using System.Data; using System.Globalization; using System.Windows.Forms; public class Form1: Form { protected DataSet DataSet1; protected DataGrid dataGrid1; // <Snippet1> private void ChangeCultureInfo(DataTable table) { // Print the LCID of the present CultureInfo. Console.WriteLine(table.Locale.LCID); // Create a new CultureInfo for the United Kingdom. CultureInfo myCultureInfo = new CultureInfo("en-gb"); table.Locale = myCultureInfo; // Print the new LCID. Console.WriteLine(table.Locale.LCID); } // </Snippet1> }
<?php $COOKIE_NAME = "quiz_done"; // check for cookie -- redirect if necessary if (isset($_COOKIE[$COOKIE_NAME])) { header('Location: results.php'); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/> <title>Survey</title> <!-- This one is for the material design icons --> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- For the main materialize stuff --> <link href="../css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/> <!-- For my own stuff --> <link href="../css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/> </head> <body> <div class="section"> <div class="container"> <h1 class="header center orange-text">A few questions . . .</h1> <div class="center"> <a href="results.php" class="center">Or you can just see the results</a> </div> <form action="saveresults.php" method="POST"> <!-- Question 1 --> <h5 class="light">Favorite color scheme</h5> <p> <input class="with-gap" name="q1" type="radio" id="rainbow" value="0" checked /> <label for="rainbow">Rainbow</label> </p> <p> <input class="with-gap" name="q1" type="radio" id="team-colors" value="1" /> <label for="team-colors">My team's colors</label> </p> <p> <input class="with-gap" name="q1" type="radio" id="light-dark" value="2" /> <label for="light-dark">Some light, some dark</label> </p> <p> <input class="with-gap" name="q1" type="radio" id="black" value="3" /> <label for="black">Black</label> </p> <br /> <!-- Question 2 --> <h5 class="light">Favorite language</h5> <p> <input class="with-gap" name="q2" type="radio" id="english" value="0" checked /> <label for="english">English</label> </p> <p> <input class="with-gap" name="q2" type="radio" id="c" value="1" /> <label for="c">C</label> </p> <p> <input class="with-gap" name="q2" type="radio" id="haskell" value="2" /> <label for="haskell">Haskell</label> </p> <p> <input class="with-gap" name="q2" type="radio" id="mission" value="3" /> <label for="mission">My mission language</label> </p> <br /> <!-- Question 3 --> <h5 class="light">Favorite operating system</h5> <p> <input class="with-gap" name="q3" type="radio" id="windows" value="0" checked /> <label for="windows">Windows</label> </p> <p> <input class="with-gap" name="q3" type="radio" id="mac" value="1" /> <label for="mac">Mac</label> </p> <p> <input class="with-gap" name="q3" type="radio" id="linux" value="2" /> <label for="linux">Linux</label> </p> <p> <input class="with-gap" name="q3" type="radio" id="emacs" value="3" /> <label for="emacs">Emacs</label> </p> <br /> <!-- Question 4 --> <h5 class="light">Favorite pizza</h5> <p> <input class="with-gap" name="q4" type="radio" id="pepperoni" value="0" checked /> <label for="pepperoni">Pepperoni</label> </p> <p> <input class="with-gap" name="q4" type="radio" id="hawaiian" value="1" /> <label for="hawaiian">Hawaiian</label> </p> <p> <input class="with-gap" name="q4" type="radio" id="anchovies" value="2" /> <label for="anchovies">Anchovies</label> </p> <p> <input class="with-gap" name="q4" type="radio" id="mushroom" value="3" /> <label for="mushroom">Mushroom</label> </p> <br /> <!-- Question 5 --> <h5 class="light">Favorite season</h5> <p> <input class="with-gap" name="q5" type="radio" id="spring" value="0" checked /> <label for="spring">Spring</label> </p> <p> <input class="with-gap" name="q5" type="radio" id="summer" value="1" /> <label for="summer">Summer</label> </p> <p> <input class="with-gap" name="q5" type="radio" id="fall" value="2" /> <label for="fall">Fall</label> </p> <p> <input class="with-gap" name="q5" type="radio" id="winter" value="3" /> <label for="winter">Winter</label> </p> <br /> <br /> <!-- Submit Button --> <button class="btn waves-effect waves-light" type="submit">Submit <i class="material-icons right">send</i> </button> </form> </div> </div> <!-- Scripts--> <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="js/materialize.js"></script> </body> </html>
/******************************************************************************* * Copyright (coffee) 2014 Vienna University of Technology. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Stefan Weghofer (Vienna University of Technology) - DSL and petri nets implementation * Alexander Bergmayr (Vienna University of Technology) - initial API and implementation * * Initially developed in the context of ARTIST EU project www.artist-project.eu *******************************************************************************/ package org.moola.emf.atl.emftvm; import org.moola.emf.atl.AbstractAtlTransformation; import org.moola.emf.atl.AtlExecStrategie; public class AtlEmftvmTransformation extends AbstractAtlTransformation { protected String module; private static ExecEnvPoolRepository poolRepo; static { poolRepo = new ExecEnvPoolRepository(); } public AtlEmftvmTransformation() { } @Override protected AtlExecStrategie getStrategie() { this.src = this.path(this.src); log.verbose("Full path for ATL file of " + this.name + " is: " + this.src); return new EmftvmAtlExecStrategie(this.src, this.module, poolRepo, this.log); } }
using UnityEngine; using UnityEngine.UI; public class HighScoreMainGame : MonoBehaviour { public Text highScoreText; void Update () { highScoreText.text = "High \n Score \n" + string.Format("{0:00.00}", GameManager.manager.highScore); } }
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /* * FusionInvoice * * A free and open source web based invoicing system * * @package FusionInvoice * @author Jesse Terry * @copyright Copyright (c) 2012 - 2013 FusionInvoice, LLC * @license http://www.fusioninvoice.com/license.txt * @link http://www.fusioninvoice.com * */ class Reports extends Admin_Controller { public function __construct() { parent::__construct(); $this->load->model('mdl_reports'); } public function sales_by_client() { if ($this->input->post('btn_submit')) { $data = array( 'results' => $this->mdl_reports->sales_by_client($this->input->post('from_date'), $this->input->post('to_date')) ); $html = $this->load->view('reports/sales_by_client', $data, TRUE); $this->load->helper('mpdf'); pdf_create($html, lang('sales_by_client'), TRUE); } $this->layout->buffer('content', 'reports/sales_by_client_index')->render(); } public function payment_history() { if ($this->input->post('btn_submit')) { $data = array( 'results' => $this->mdl_reports->payment_history($this->input->post('from_date'), $this->input->post('to_date')) ); $html = $this->load->view('reports/payment_history', $data, TRUE); $this->load->helper('mpdf'); pdf_create($html, lang('payment_history'), TRUE); } $this->layout->buffer('content', 'reports/payment_history_index')->render(); } public function invoice_aging() { if ($this->input->post('btn_submit')) { $data = array( 'results' => $this->mdl_reports->invoice_aging() ); $html = $this->load->view('reports/invoice_aging', $data, TRUE); $this->load->helper('mpdf'); pdf_create($html, lang('invoice_aging'), TRUE); } $this->layout->buffer('content', 'reports/invoice_aging_index')->render(); } } ?>
rootProject.name = "kmmApp" include(":androidApp") include(":alog") include(":utils") include(":PlatformMMKV") include(":business") include(":sdkframework") project(":sdkframework").projectDir = File(rootDir, "shared/sdkframework") project(":alog").projectDir = File(rootDir, "shared/alog") project(":utils").projectDir = File(rootDir, "shared/utils") project(":PlatformMMKV").projectDir = File(rootDir, "shared/PlatformMMKV") project(":business").projectDir = File(rootDir, "shared/business")
<?php use \Rapd\Router\Route; use \Rapd\View; Router::add(new Route( "home", "/", function(){ $user = User::current(); $lists = $user->getShopLists(); return View::render("home", [ "user" => $user, "lists" => $lists, ]); } ));
package org.amshove.kluent.tests.collections import kotlin.test.assertFails import org.amshove.kluent.tests.Person import org.amshove.kluent.shouldNotBeIn import kotlin.test.Test class ShouldNotBeInShould { @Test fun passWhenTestingAnObjectWhichIsNotInAnArray() { val person = Person("Jon", "Doe") val array = arrayOf(Person("Foo", "Bar"), Person("Foo", "Bar")) person shouldNotBeIn array } @Test fun failWhenTestingAnObjectWhichIsInAnArray() { val person = Person("Jon", "Doe") val array = arrayOf(Person("Jon", "Doe"), Person("Foo", "Bar")) assertFails { person shouldNotBeIn array } } @Test fun passWhenTestingAnObjectWhichIsNotInAnIterable() { val person = Person("Jon", "Doe") val iterable = listOf(Person("Foo", "Bar"), Person("Foo", "Bar")) person shouldNotBeIn iterable } @Test fun failWhenTestingAnObjectWhichIsInAnIterable() { val person = Person("Jon", "Doe") val array = listOf(Person("Jon", "Doe"), Person("Foo", "Bar")) assertFails { person shouldNotBeIn array } } @Test fun passWhenTestingAPrimitiveIntegerWhichIsNotWithinAnArray() { val theArray = intArrayOf(1, 5, 7, 13) 4 shouldNotBeIn theArray } @Test fun failWhenTestingAPrimitiveIntegerWhichIsWithinAnArray() { val theArray = intArrayOf(1, 5, 7, 13) assertFails { 7 shouldNotBeIn theArray } } @Test fun passWhenTestingAPrimitiveLongWhichIsNotWithinAnArray() { val theArray = longArrayOf(1, 5, 7, 13) 4L shouldNotBeIn theArray } @Test fun failWhenTestingAPrimitiveLongWhichIsWithinAnArray() { val theArray = longArrayOf(1, 5, 7, 13) assertFails { 7L shouldNotBeIn theArray } } @Test fun passWhenTestingAPrimitiveShortWhichIsNotWithinAnArray() { val theArray = shortArrayOf(1, 5, 7, 13) 4.toShort() shouldNotBeIn theArray } @Test fun failWhenTestingAPrimitiveShortWhichIsWithinAnArray() { val theArray = shortArrayOf(1, 5, 7, 13) assertFails { 7.toShort() shouldNotBeIn theArray } } @Test fun passWhenTestingAPrimitiveDoubleWhichIsNotWithinAnArray() { val theArray = doubleArrayOf(1.0, 5.0, 7.0, 13.0) (4.0) shouldNotBeIn theArray } @Test fun failWhenTestingAPrimitiveDoubleWhichIsWithinAnArray() { val theArray = doubleArrayOf(1.0, 5.0, 7.0, 13.0) assertFails { (7.0) shouldNotBeIn theArray } } @Test fun passWhenTestingAPrimitiveFloatWhichIsNotWithinAnArray() { val theArray = floatArrayOf(1.0f, 5.0f, 7.0f, 13.0f) (4.0f) shouldNotBeIn theArray } @Test fun failWhenTestingAPrimitiveFloatWhichIsWithinAnArray() { val theArray = floatArrayOf(1.0f, 5.0f, 7.0f, 13.0f) assertFails { (7.0f) shouldNotBeIn theArray } } @Test fun passWhenTestingAPrimitiveCharWhichIsNotWithinAnArray() { val theArray = charArrayOf('a', 'b', 'c') 'd' shouldNotBeIn theArray } @Test fun failWhenTestingAPrimitiveCharWhichIsWithinAnArray() { val theArray = charArrayOf('a', 'b', 'c') assertFails { 'b' shouldNotBeIn theArray } } @Test fun passWhenTestingAPrimitiveBooleanWhichIsNotWithinAnArray() { val theArray = booleanArrayOf(true, true) false shouldNotBeIn theArray } @Test fun failWhenTestingAPrimitiveBooleanWhichIsWithinAnArray() { val theArray = booleanArrayOf(true, true) assertFails { true shouldNotBeIn theArray } } }
#include <stdint.h> #include <string.h> #include "spman.h" #define SPMAN_PAT_UNUSED 0xff #define SPMAN_MAX_SPRITES 32 #define SPMAN_MAX_PATTERNS 64 uint8_t sp_last_sprite, sp_last_fixed_sprite, sp_idx; struct sprite_attr sp_fixed[SPMAN_MAX_SPRITES]; struct sprite_attr sp_buffer[SPMAN_MAX_SPRITES * 2]; uint8_t sp_pat_map[SPMAN_MAX_PATTERNS]; uint8_t sp_last_pat; void spman_init() { sp_last_pat = 0; memset(sp_pat_map, SPMAN_PAT_UNUSED, SPMAN_MAX_PATTERNS); spman_sprite_flush(); } uint8_t spman_alloc_pat(uint8_t type, uint8_t *data, uint8_t len, uint8_t flip) { uint8_t i; if (sp_pat_map[type] == SPMAN_PAT_UNUSED) { sp_pat_map[type] = sp_last_pat; for (i = 0; i < len; ++i) { if (flip) ubox_set_sprite_pat16_flip(data, sp_last_pat); else ubox_set_sprite_pat16(data, sp_last_pat); data += 32; sp_last_pat++; } #ifdef SPMAN_DEBUG if (sp_last_pat > 63) ubox_set_colors(15, 0, 0); #endif } return sp_pat_map[type] * 4; } void spman_sprite_flush() { sp_last_fixed_sprite = 0; sp_last_sprite = 0; } void spman_alloc_fixed_sprite(struct sprite_attr *sp) { #ifdef SPMAN_DEBUG if (sp_last_fixed_sprite + sp_last_sprite > 30) { ubox_set_colors(15, 0, 0); return; } #endif memcpy(&sp_fixed[sp_last_fixed_sprite++], sp, 4); } void spman_alloc_sprite(struct sprite_attr *sp) { #ifdef SPMAN_DEBUG if (sp_last_fixed_sprite + sp_last_sprite > 30) { ubox_set_colors(15, 0, 0); return; } #endif memcpy(&sp_buffer[sp_last_sprite++], sp, 4); } static const struct sprite_attr hide = { 208, 0, 0, 0 }; static uint8_t *p; void spman_update() { p = (uint8_t*) 0x1b00; if (sp_last_sprite) { memcpy(&sp_buffer[sp_last_sprite], sp_buffer, sp_last_sprite * 4); if (sp_last_sprite > 2) sp_idx += 2; if (sp_idx >= sp_last_sprite) sp_idx -= sp_last_sprite; } else sp_idx = 0; memcpy(&sp_buffer[sp_idx + sp_last_sprite], &hide, 4); ubox_wait_vsync(); if (sp_last_fixed_sprite) { ubox_write_vm(p, sp_last_fixed_sprite * 4, (uint8_t *)sp_fixed); p += sp_last_fixed_sprite * 4; } ubox_write_vm(p, 4 + sp_last_sprite * 4, (uint8_t *)&sp_buffer[sp_idx]); spman_sprite_flush(); } void spman_hide_all_sprites() { ubox_wait_vsync(); ubox_write_vm((uint8_t *)0x1b00, 4, (uint8_t *)hide); }
/* * Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file * for details. All rights reserved. Use of this source code is governed by a * BSD-style license that can be found in the LICENSE file. */ /** * @assertion void writeAll(Iterable objects, [String separator = ""]) * Iterates over the given objects and writes them in sequence. * @description Checks that this method iterates over the given objects and * writes them in sequence. * @author sgrekhov@unipro.ru */ import "dart:convert"; import "../../../Utils/expect.dart"; class C { String value; C(this.value); String toString() => "C:" + this.value; } main() { StringBuffer stringSink = new StringBuffer(); var toWrite = [new C("test"), "test", 1, 3.14]; ClosableStringSink sink = new ClosableStringSink.fromStringSink(stringSink, () {}); sink.writeAll(toWrite); sink.close(); Expect.equals("C:testtest13.14", stringSink.toString()); }
/*++ Copyright (c) 1997 Microsoft Corporation Module Name: list.c Abstract: List Entry manipulation functions Author: Based on code by Mike Tsang (MikeTs) Stephane Plante (Splante) Environment: User mode only Revision History: --*/ #include "pch.h" VOID EXPORT ListRemoveEntry( PLIST List, PPLIST ListHead ) /*++ Routine Description: Remove an Entry from the list Arguments: List - Entry to be removed ListHead - List to be removed from Return Value: None --*/ { ASSERT(ListHead); ASSERT(List != NULL); if (List->plistNext == List) { // // This is the only object in the list, it must be the head too. // ASSERT(List == *ListHead); *ListHead = NULL; } else { if (List == *ListHead) { // // The entry is at the head, so the next one becomes the new // head. // *ListHead = (*ListHead)->plistNext; } List->plistNext->plistPrev = List->plistPrev; List->plistPrev->plistNext = List->plistNext; } } PLIST EXPORT ListRemoveHead( PPLIST ListHead ) /*++ Routine Description: Remove the head entry of the list Arguments: ListHead - List to remove entry from Return Value: PLIST - Removed Item --*/ { PLIST list; list = *ListHead; if ( list != NULL) { ListRemoveEntry(list, ListHead); } return list; } PLIST EXPORT ListRemoveTail( PPLIST ListHead ) /*++ Routine Description: Remove the tail entry from the list Arguments: ListHead - List to remove entry from Return Value: PLIST - Removed Item --*/ { PLIST list; if (*ListHead == NULL) { list = NULL; } else { // // List is not empty, so find the tail. // list = (*ListHead)->plistPrev; ListRemoveEntry(list, ListHead); } return list; } VOID EXPORT ListInsertHead( PLIST List, PPLIST ListHead ) /*++ Routine Description: Insert an Entry at the head of the list Arguments: List List object to be inserted ListHead The list where to insert the object Return Value: None --*/ { ListInsertTail(List, ListHead); *ListHead = List; } VOID EXPORT ListInsertTail( PLIST List, PPLIST ListHead ) /*++ Routine Description: Insert an Entry at the tail of the list Arguments: List List object to be inserted ListHead The list where to insert the object Return Value: None --*/ { if (*ListHead == NULL) { // // List is empty, so this becomes the head. // *ListHead = List; List->plistPrev = List->plistNext = List; } else { List->plistNext = *ListHead; List->plistPrev = (*ListHead)->plistPrev; (*ListHead)->plistPrev->plistNext = List; (*ListHead)->plistPrev = List; } }
import {inspect} from 'util' import * as browserHacks from './browser-hacks' class CasinocoinError extends Error { name: string message: string data?: any constructor(message = '', data?: any) { super(message) this.name = browserHacks.getConstructorName(this) this.message = message this.data = data if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor) } } toString() { let result = '[' + this.name + '(' + this.message if (this.data) { result += ', ' + inspect(this.data) } result += ')]' return result } /* console.log in node uses util.inspect on object, and util.inspect allows us to customize its output: https://nodejs.org/api/util.html#util_custom_inspect_function_on_objects */ inspect() { return this.toString() } } class CasinocoindError extends CasinocoinError {} class UnexpectedError extends CasinocoinError {} class LedgerVersionError extends CasinocoinError {} class ConnectionError extends CasinocoinError {} class NotConnectedError extends ConnectionError {} class DisconnectedError extends ConnectionError {} class CasinocoindNotInitializedError extends ConnectionError {} class TimeoutError extends ConnectionError {} class ResponseFormatError extends ConnectionError {} class ValidationError extends CasinocoinError {} class NotFoundError extends CasinocoinError { constructor(message = 'Not found') { super(message) } } class MissingLedgerHistoryError extends CasinocoinError { constructor(message?: string) { super(message || 'Server is missing ledger history in the specified range') } } class PendingLedgerVersionError extends CasinocoinError { constructor(message?: string) { super(message || 'maxLedgerVersion is greater than server\'s most recent' + ' validated ledger') } } export { CasinocoinError, UnexpectedError, ConnectionError, CasinocoindError, NotConnectedError, DisconnectedError, CasinocoindNotInitializedError, TimeoutError, ResponseFormatError, ValidationError, NotFoundError, PendingLedgerVersionError, MissingLedgerHistoryError, LedgerVersionError }
+++ title = "Project Brochure" date = 2018-12-21T00:00:00 # Authors. Comma separated list, e.g. `["Bob Smith", "David Jones"]`. authors = ["Shiva Prasad Reddy Katta"] #List format. #0 = Simple #1 = Detailed #2 = Stream list_format = 2 # Tags (optional). # Set `tags = []` for no tags, or use the form `tags = ["A Tag", "Another Tag"]` for one or more tags. tags = ["Server","Installation"] url_pdf = "files/movieREC.pdf" # Step to follow. #Optional featured image (relative to static/img/ folder). [header] image = "" caption = "" +++ The above link fetches the brochure I have designed for my movie recommender application.
# dyon_interactive A library for interactive coding with the Piston game engine ![snake](../images/snake.png) 1. [Install Rust](https://www.rust-lang.org/) (Rust Nightly is required at the moment) 2. Fork the repo to your local hard drive 3. In Terminal, go to "dyon/interactive" and type `cargo run --release --example piston_window` 4. Edit "source/piston_window/snake.rs" while running the demo ### Made with dyon_interactive - [dyon_asteroids](https://github.com/pistondevelopers/dyon_asteroids) ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option.
import type { SymbolTable } from '@spyglassmc/core' import type { ModuleNode } from '../../lib/index.js' export const TestContent = ` /// Doc comment. compound Foo { Bar: byte, Baz: Qux } enum(int) Qux { One = 1 } enum(float) Eww { One = 1.0 } enum(string) Huh { One = "One" } Foo describes minecraft:block; inject compound Foo { Injected: [Eww] @ 4 } ` export const TestNode: ModuleNode = {} as any export declare const TestSymbolTable: SymbolTable
package com.twitter.utility; public class FrontendViews { public static class HealthView{ } public static class CreateSessionView{ } public static class CreateUserView{ } public static class LoginUserView{ } }
;;;; ------------------------------- ;;;; Copyright (c) Corman Technologies Inc. ;;;; See LICENSE.txt for license information. ;;;; ------------------------------- ;;;; ;;;; File: random.lisp ;;;; Contents: Random number functions for Corman Lisp. ;;;; History: 3/20/97 RGC Created. ;;;; 1/1/99 RGC Modified to work correctly with ;;;; short-float, double-float and single-float. ;;;; 12/06/01 FAA Now that :type in structure slots is working, defined index type. ;;;; ;;; -*- Mode: Lisp; Package: Kernel -*- ;;; ;;; ********************************************************************** ;;; This code was written as part of the CMU Common Lisp project at ;;; Carnegie Mellon University, and has been placed in the public domain. ;;; ;;; ;;; ********************************************************************** ;;; ;;; Functions to random number functions for Spice Lisp ;;; ;;; Originally written by David Adam. Python tuning, better large integer ;;; randomness and efficient IEEE float support by Rob MacLachlan. ;;; (in-package :common-lisp) #| (in-package "CORMANLISP") (export '(%random-single-float %random-double-float random-chunk random-fixnum-max)) |# ;;;; Random state hackery: (defconstant random-const-a 8373) (defconstant random-const-c 101010101) (defconstant random-max 54) (defconstant short-float-digits (float-precision 1.0s0)) (defconstant single-float-digits (float-precision 1.0f0)) (defconstant double-float-digits (float-precision 1.0d0)) (defconstant word-bits 32) (defconstant short-float-significand-byte (byte 21 0)) (defconstant single-float-significand-byte (byte 23 0)) (defconstant double-float-significand-byte (byte 52 0)) ;;; Inclusive upper bound on the size of fixnum kept in the state (and returned ;;; by random-chunk.) Must be even. ;;; (defconstant random-upper-bound (- most-positive-fixnum 3)) (defconstant random-chunk-length (integer-length random-upper-bound)) (deftype random-chunk () `(integer 0 ,random-upper-bound)) (deftype index () `(integer 0 ,random-max)) (defvar rand-seed 0) (declaim (ftype (function () real) rand1)) ;; forward reference (defstruct (random-state (:constructor make-random-object)) (j 24 :type index) (k 0 :type index) (seed (make-array (1+ random-max) :initial-contents (do ((list-rands () (cons (rand1) list-rands)) (i 0 (1+ i))) ((> i random-max) list-rands) (declare (fixnum i)))) :type simple-vector)) ;;; Generates a random number from rand-seed. (defun rand1 () (setq rand-seed (mod (+ (* rand-seed random-const-a) random-const-c) (1+ random-upper-bound)))) (defvar *random-state* (make-random-object)) (defun copy-state (cur-state) (let ((state (make-random-object :seed (make-array 55) :j (random-state-j cur-state) :k (random-state-k cur-state)))) (do ((i 0 (1+ i))) ((= i 55) state) (declare (fixnum i)) (setf (aref (random-state-seed state) i) (aref (random-state-seed cur-state) i))))) (defun make-random-state (&optional state) "Make a random state object. If State is not supplied, return a copy of the default random state. If State is a random state, then return a copy of it. If state is T then return a random state generated from the universal time." (cond ((not state) (copy-state *random-state*)) ((random-state-p state) (copy-state state)) ((eq state t) (setq rand-seed (get-universal-time)) (make-random-object)) (t (error "Argument is not a RANDOM-STATE, T or NIL: ~S" state)))) ;;;; Random entries: (declaim (special start-block random %random-single-float %random-double-float random-chunk)) ;;; random-chunk -- Internal ;;; ;;; This function generates fixnums between 0 and random-upper-bound, ;;; inclusive. For the algorithm to work random-upper-bound must be an ;;; even positive fixnum. State is the random state to use. ;;; (declaim (ftype (function (random-state) random-chunk) random-chunk)) (defun random-chunk (state) (let* ((seed (random-state-seed state)) (j (random-state-j state)) (k (random-state-k state)) (a (- (- random-upper-bound (the random-chunk (svref seed (setf (random-state-j state) (if (= j 0) random-max (1- j)))))) (the random-chunk (svref seed (setf (random-state-k state) (if (= k 0) random-max (1- k)))))))) (declare (fixnum a)) (setf (svref seed k) (the random-chunk (if (minusp a) (- a) (- random-upper-bound a)))))) ;;; %RANDOM-SINGLE-FLOAT, %RANDOM-DOUBLE-FLOAT -- Interface ;;; ;;; Handle the single or double float case of RANDOM. We generate a float ;;; between 0.0 and 1.0 by clobbering the significand of 1.0 with random bits, ;;; then subtracting 1.0. This hides the fact that we have a hidden bit. ;;; ;;(declaim (inline %random-single-float %random-double-float)) (defun %random-single-float (arg state) (declare (type (single-float (0f0)) arg) (type (or random-state null) state)) (* arg (- (%make-single-float (dpb (ash (random-chunk (or state *random-state*)) (- single-float-digits random-chunk-length)) single-float-significand-byte (%single-float-bits 1.0f0))) 1.0f0))) (defun %random-short-float (arg state) (declare (type (short-float (0s0)) arg) (type (or random-state null) state)) (* arg (- (%make-short-float (dpb (ash (random-chunk (or state *random-state*)) (- short-float-digits random-chunk-length)) short-float-significand-byte (%short-float-bits 1.0s0))) 1.0s0))) (defun %random-double-float (arg state) (declare (type (double-float (0d0)) arg) (type (or random-state null) state)) (let ((state (or state *random-state*))) (* arg (- (%make-double-float (dpb (logxor (ash (random-chunk state) (- 53 random-chunk-length)) (random-chunk state)) double-float-significand-byte (%double-float-bits 1d0))) 1d0)))) ;;;; Random integers: ;;; Amount we overlap chunks by when building a large integer to make up for ;;; the loss of randomness in the low bits. ;;; (defconstant random-integer-overlap 3) ;;; Extra bits of randomness that we generate before taking the value MOD the ;;; limit, to avoid loss of randomness near the limit. ;;; (defconstant random-integer-extra-bits 10) ;;; Largest fixnum we can compute from one chunk of bits. ;;; (defconstant random-fixnum-max (1- (ash 1 (- random-chunk-length random-integer-extra-bits)))) ;;; %RANDOM-INTEGER -- Internal ;;; (defun %random-integer (arg state) (declare (type (integer 1) arg) (type random-state state)) (let ((shift (- random-chunk-length random-integer-overlap))) (do ((bits (random-chunk state) (logxor (ash bits shift) (random-chunk state))) (count (+ (integer-length arg) (- random-integer-extra-bits shift)) (- count shift))) ((minusp count) (rem bits arg)) (declare (fixnum count))))) (defun random (arg &optional (state *random-state*)) "Generate a uniformly distributed pseudo-random number between zero and Arg. State, if supplied, is the random state to use." (declare (inline %random-single-float %random-double-float)) (cond ((and (fixnump arg)(<= arg random-fixnum-max)) (rem (random-chunk state) arg)) ((typep arg 'single-float)(%random-single-float arg state)) ((typep arg 'double-float)(%random-double-float arg state)) ((typep arg 'short-float)(%random-short-float arg state)) ((integerp arg)(%random-integer arg state)) (t (error "Argument is not a positive real number: ~S" arg)))) ;;(( (t (error 'simple-type-error :expected-type '(real (0)) :datum arg ;; :format-control "Argument is not a positive real number: ~S" ;; :format-arguments (list arg)))))
// Copyright 2020 The nfgo Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ndb import ( "errors" "fmt" "nfgo.ga/nfgo/nconf" "nfgo.ga/nfgo/nlog" "nfgo.ga/nfgo/nutil/ntypes" "gorm.io/driver/mysql" "gorm.io/gorm" "gorm.io/gorm/schema" ) type dbOptions struct { dialector gorm.Dialector } // DBOption - type DBOption func(*dbOptions) // DialectorOption - func DialectorOption(dialector gorm.Dialector) DBOption { return func(opts *dbOptions) { opts.dialector = dialector } } // NewDB - func NewDB(dbConfig *nconf.DbConfig, opt ...DBOption) (*gorm.DB, error) { if dbConfig == nil { return nil, errors.New("dbConfig is nil") } gormConfig := &gorm.Config{ NamingStrategy: schema.NamingStrategy{ SingularTable: true, }, Logger: newLogger(dbConfig), PrepareStmt: ntypes.BoolValue(dbConfig.PrepareStmt), SkipDefaultTransaction: ntypes.BoolValue(dbConfig.SkipDefaultTransaction), } opts := &dbOptions{} for _, o := range opt { o(opts) } if ntypes.IsNil(opts.dialector) { dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=true&loc=Local", dbConfig.Username, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.Database, dbConfig.Charset) opts.dialector = mysql.Open(dsn) } db, err := gorm.Open(opts.dialector, gormConfig) if err != nil { return nil, fmt.Errorf("fail to open db: %w", err) } sqlDB, err := db.DB() if err != nil { return nil, err } sqlDB.SetMaxIdleConns(int(dbConfig.MaxIdle)) sqlDB.SetMaxOpenConns(int(dbConfig.MaxOpen)) return db, nil } // MustNewDB - func MustNewDB(dbConfig *nconf.DbConfig, opt ...DBOption) *gorm.DB { db, err := NewDB(dbConfig, opt...) if err != nil { nlog.Fatal("fail to new db: ", err) } return db }
package com.jinwoo.memoapplication import com.jinwoo.memoapplication.Model.MemoModel interface RecyclerViewClickListener{ fun onItemClicked(position: Int, memo: MemoModel, key: String) fun onItemLongClicked(position: Int, memo: MemoModel, key: String) }
require 'json' RSpec.describe ServerlessHelpers::Event::Aws::Sns do let (:mock_event) { JSON.parse(file_fixture('aws/sns_event.json')) } let (:event) { described_class.new(mock_event) } it "lists messages" do expect(event.messages.count).to be 1 end it "parses messages from JSON" do expect(event.messages[0].message).to eql "Test Message" end end
(in-package #:cl-user) (defpackage #:parsley (:use #:cl) (:export #:*buffer* #:buffer-bytes #:buffer-bits #:buffer-sequence #:buffer-stream #:buffer-position #:with-buffer-read #:octets= #:read-bits #:read-bytes #:read-uint-be #:read-uint-le #:read-int-be #:read-int-le #:read-string #:uncompress-bzip2 #:uncompress-gzip #:uncompress-zlib #:uncompress-deflate #:split-string))
import Immutable from 'immutable' import execute_reducer from "./reducer_helper"; const initialState = Immutable.Map({ food_list_browser:Immutable.List(), food_list_like:Immutable.List() }) function profile_load_like(state,data) { return state.set("food_list_like",Immutable.fromJS(data.food_list_like)); } function profile_data_add_like(state,data) { let food_list_like = state.get("food_list_like") food_list_like = food_list_like.push(Immutable.fromJS(data.food_data)) return state.set("food_list_like",food_list_like); } function profile_load_browser(state,data) { return state.set("food_list_browser",Immutable.fromJS(data.food_list_browser)) } function profile_data_add_browser(state,data) { let food_list_browser = state.get("food_list_browser") food_list_browser = food_list_browser.push(Immutable.fromJS(data.food_data)) return state.set("food_list_browser",food_list_browser); } function profile_delete_like(state,data) { let food_list_like = state.get("food_list_like") food_list_like = food_list_like.delete(data.index) return state.set("food_list_like",food_list_like); } function profile_delete_browser(state,data) { let food_list_browser = state.get("food_list_browser") food_list_browser = food_list_browser.delete(data.index) return state.set("food_list_browser",food_list_browser); } const tables = { "Food_Like_Load_Data":profile_load_like, "Food_Browser_Load_Data":profile_load_browser, "Food_Browser_Add_Data":profile_data_add_browser, "Food_Like_Add_Data":profile_data_add_like, "Food_Like_Delete_Data":profile_delete_like, "Food_Browser_Delete_Data":profile_delete_browser } export default function profile_reducer(state=initialState,action) { return execute_reducer(state,action,tables) }
using LitJson; using UnityEngine; using System.Collections; using System.Collections.Generic; public class SelectGameModel { private SelectGameController m_selectGameController; private int m_selectedListIndex; public bool IsGameListRequestPending { get; private set; } public bool IsGameDeleteRequestPending { get; private set; } public SelectGameModel(SelectGameController selectGameController) { m_selectGameController = selectGameController; m_selectedListIndex = 0; IsGameListRequestPending = false; IsGameDeleteRequestPending = false; } public int SelectedListIndex { get { return m_selectedListIndex; } set { SessionData sessionData = SessionData.GetInstance(); m_selectedListIndex = value; sessionData.GameID = sessionData.GameList[value].game_id; sessionData.GameName = sessionData.GameList[value].game_name; } } public List<object> GetGameList() { SessionData sessionData = SessionData.GetInstance(); List<object> gameList = new List<object>(); if (sessionData.Authenticated) { foreach (object gameEntry in sessionData.GameList) { gameList.Add(gameEntry); } } return gameList; } public GameResponseEntry GetGameEntry(int index) { SessionData sessionData = SessionData.GetInstance(); return sessionData.Authenticated ? sessionData.GameList[index] : null; } public int GetGameCount() { SessionData sessionData = SessionData.GetInstance(); return sessionData.Authenticated ? sessionData.GameList.Count : 0; } public void RequestGameList() { if (!IsGameListRequestPending) { AsyncJSONRequest gameListRequest = AsyncJSONRequest.Create(m_selectGameController.gameObject); IsGameListRequestPending = true; gameListRequest.GET( ServerConstants.gameListRequestURL, (AsyncJSONRequest asyncRequest) => { if (asyncRequest.GetRequestState() == AsyncJSONRequest.eRequestState.succeded) { JsonData response = asyncRequest.GetResult(); string responseResult = (string)response["result"]; if (responseResult== "Success") { SessionData sessionData = SessionData.GetInstance(); JsonData gamesList = response["game_list"]; sessionData.GameList= new List<GameResponseEntry>(); for (int listIndex = 0; listIndex < gamesList.Count; listIndex++) { sessionData.GameList.Add(GameResponseEntry.FromObject(gamesList[listIndex])); } if (sessionData.GameList.Count > 0) { SelectedListIndex = 0; } m_selectGameController.OnGameListUpdated(); } else { m_selectGameController.OnRequestFailed(responseResult); Debug.LogError("Get Game List Failed: " + asyncRequest.GetFailureReason()); } } else { m_selectGameController.OnRequestFailed("Connection Failure!"); Debug.LogError("Get Game List Failed: " + asyncRequest.GetFailureReason()); } IsGameListRequestPending = false; }); } } public void RequestSelectedGameDeletion() { SessionData sessionData = SessionData.GetInstance(); if (!IsGameDeleteRequestPending && sessionData.GameList.Count > 0) { AsyncJSONRequest gameDeleteRequest = AsyncJSONRequest.Create(m_selectGameController.gameObject); Dictionary<string, object> requestParameters = new Dictionary<string, object>(); requestParameters["game_id"] = sessionData.GameID; IsGameDeleteRequestPending = true; gameDeleteRequest.POST( ServerConstants.gameDeleteRequestURL, requestParameters, (AsyncJSONRequest asyncRequest) => { if (asyncRequest.GetRequestState() == AsyncJSONRequest.eRequestState.succeded) { JsonData response = asyncRequest.GetResult(); string responseResult = (string)response["result"]; if (responseResult == "Success") { // Request an updated game list now that we deleted a game m_selectGameController.OnGameDeleted(); } else { m_selectGameController.OnRequestFailed(responseResult); Debug.LogError("Get Game List Failed: " + asyncRequest.GetFailureReason()); } } else { m_selectGameController.OnRequestFailed("Connection Failure!"); Debug.LogError("Get Game List Failed: " + asyncRequest.GetFailureReason()); } IsGameDeleteRequestPending = false; }); } } }