text
stringlengths
27
775k
package io.github.todorkrastev.pathfinder.service.impl; import io.github.todorkrastev.pathfinder.model.entity.Category; import io.github.todorkrastev.pathfinder.model.entity.enums.CategoryName; import io.github.todorkrastev.pathfinder.repository.CategoryRepository; import io.github.todorkrastev.pathfinder.service.CategoryService; import org.springframework.stereotype.Service; @Service public class CategoryServiceImpl implements CategoryService { private final CategoryRepository categoryRepository; public CategoryServiceImpl(CategoryRepository categoryRepository) { this.categoryRepository = categoryRepository; } @Override public Category findCategoryByName(CategoryName name) { return this.categoryRepository .findByName(name) .orElse(null); } }
module Houdini module TaskManager def self.register(klass, blueprint, options, task_builder=Task) @tasks ||= {} @tasks[ [klass.name, blueprint.to_sym] ] = task_builder.new(klass, blueprint, options) end def self.submit!(object, blueprint) if @tasks task = @tasks[ [object.class.name, blueprint.to_sym] ] task.submit! object end end def self.process(class_name, id, blueprint, output, verbose_output) class_name.constantize # Ensure model is loaded and any Houdini tasks registered task = @tasks[ [class_name, blueprint.to_sym] ] task.process id, output, verbose_output end end end
import type { DebouncedFunc, ThrottleSettings } from 'lodash'; import throttle from 'lodash/throttle'; import { useEffect, useRef } from 'react'; import type { Plugin } from '../types'; const useThrottlePlugin: Plugin<any, any[]> = ( fetchInstance, { throttleWait, throttleLeading, throttleTrailing }, ) => { const throttledRef = useRef<DebouncedFunc<any>>(); const options: ThrottleSettings = {}; if (throttleLeading !== undefined) { options.leading = throttleLeading; } if (throttleTrailing !== undefined) { options.trailing = throttleTrailing; } useEffect(() => { if (throttleWait) { const _originRunAsync = fetchInstance.runAsync.bind(fetchInstance); throttledRef.current = throttle( (callback) => { callback(); }, throttleWait, options, ); // throttle runAsync should be promise // https://github.com/lodash/lodash/issues/4400#issuecomment-834800398 fetchInstance.runAsync = (...args) => { return new Promise((resolve, reject) => { throttledRef.current?.(() => { _originRunAsync(...args) .then(resolve) .catch(reject); }); }); }; return () => { fetchInstance.runAsync = _originRunAsync; throttledRef.current?.cancel(); }; } }, [throttleWait, throttleLeading, throttleTrailing]); if (!throttleWait) { return {}; } return { onCancel: () => { throttledRef.current?.cancel(); }, }; }; export default useThrottlePlugin;
#pragma once #include "ScriptComponent.h" #include "AnimationComponent.h" #include <metadata\object-forward.h> #include <metadata\object.h> #include <metadata/class.h> void PlayAnimation(MonoObject* go, MonoObject* animationName) { char* animName = mono_string_to_utf8(mono_object_to_string(animationName, 0)); std::string nameState = animName; GetComponentMono<AnimationComponent*>(go)->Play(nameState); } bool HasFinished(MonoObject* go) { return GetComponentMono<AnimationComponent*>(go)->HasFinished(); }
package io.github.sevenparadigms.abac.security.context import io.github.sevenparadigms.abac.Constants.AUTHORIZE_IP import io.github.sevenparadigms.abac.Constants.PRINCIPAL import io.github.sevenparadigms.abac.Constants.REQUEST import io.github.sevenparadigms.abac.Constants.RESPONSE import org.apache.commons.lang3.StringUtils import org.springframework.http.HttpHeaders import org.springframework.security.core.context.ReactiveSecurityContextHolder import org.springframework.stereotype.Component import org.springframework.web.server.ServerWebExchange import org.springframework.web.server.WebFilter import org.springframework.web.server.WebFilterChain import reactor.core.publisher.Mono import reactor.util.context.Context @Component class ExchangeFilter( private val exchangeContext: ExchangeContext ) : WebFilter { override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> { exchange.attributes[REQUEST] = exchange.request exchange.attributes[RESPONSE] = exchange.response exchange.attributes[AUTHORIZE_IP] = exchange.request.headers.getFirst(AUTHORIZE_IP) ?: StringUtils.EMPTY if (exchange.request.headers.containsKey(HttpHeaders.AUTHORIZATION)) { return ReactiveSecurityContextHolder.getContext().flatMap { exchange.attributes[PRINCIPAL] = it.authentication.principal exchangeContext.attributes.put(it.authentication.name, exchange) chain.filter(exchange) }.contextWrite { context: Context -> context.put(ServerWebExchange::class.java, exchange) } } return chain.filter(exchange) .contextWrite { context: Context -> context.put(ServerWebExchange::class.java, exchange) } } }
import os from app.helput import get_files_under_dir, unique_filename from utils.find_article_images import get_images_list def find_missing_images(): print('Fetching images names from database...') images_list = get_images_list() images_names = map(os.path.basename, images_list) found = [] print('Starting local search...') local_files = get_files_under_dir('/', ('.jpg', '.png', '.gif')) print('Found %s local images' % len(local_files)) for local_image in local_files: try: encoded_name = unique_filename(local_image) if encoded_name in images_names: found.append((local_image, encoded_name)) except UnicodeDecodeError as e: print('Error with %s, skipping...' % local_image) print('Found: %d images of %d' % (len(found), len(images_list))) return found if __name__ == '__main__': find_missing_images()
using System; using System.Collections.Generic; using System.Text; namespace Lingu.Runtime.Structures { public interface ILexer { bool IsEnd(); ITerminalToken? Next(int stateId); } }
#!/bin/bash ## SLURM options # Options to sbatch start with '#SBATCH'. To disable an option, change # the prefix, e.g. '#xSBATCH' # Time limit after which the job will be killed. The default time limit # is 60 minutes. Specified as HH:MM:SS or D-HH:MM #SBATCH --time=30-00:00 # Prevent multithreading of the cores #SBATCH --hint=nomultithread # number of CPUs to utilize #SBATCH -c24 # Memory per core. Job will crash if this limit is exceeded. Default # is 1000M per allocated core. Use values that will permit multiple # jobs to run simultaneously when possible, e.g. a memory limit of # 2000M will allow allow all 12 processors on a node with 24000M of # RAM to be utilized, while specifying 2G (=2048M) would only allow 11 # of the processors to be used. #SBATCH --mem-per-cpu=2000M # Number of nodes to utilize #SBATCH -N 1 # Partition (queue) for the job # - "normal" has a time limit of 30 days. Per-user resource limits apply. # - "debug" has a time limit of 1 hour, and low resource limits, # but will pre-empt other jobs (memory permitting). # - "idle" has no time limit or per-user limit, but jobs can be stopped # (requeued) by jobs in the normal or debug queues. #SBATCH --partition=normal # or, for short, '-p normal' # Send email when the job begins and ends #xSBATCH [email protected] #xSBATCH --mail-type=BEGIN,END # Set a name for the job. This will appear in the output of 'squeue'. The # default is the name of the job script. This option is probably most useful # as a command-line argument to sbatch. #SBATCH -J APCEMM #SBATCH -o slurm-%j.out # To submit the job, run: # # sbatch <scriptname.sh> # # Additional options or overrides can be specified on the command line: # # sbatch --partition=debug -J case4a scriptname.sh # # Command line arguments to your script can be passed in as well: # # sbatch scriptname.sh foo bar # # in which case the variables $1 and $2 will be set to 'foo' and 'bar' # within the script. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # # # Aircraft Plume Chemistry, Emission and Microphysics Model # # (APCEMM) # # # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # # # DESCRIPTION: This bash script submits an APCEMM simulation # # # REVISION HISTORY: # 15 Sep 2018 - T. Fritz - Initial version # 20 Oct 2018 - T. Fritz - Included OMP_NUM_THREADS in slurm # environments # 21 Oct 2018 - T. Fritz - Pipe output to log # 11 Dec 2018 - T. Fritz - Created run directories # 11 Aug 2019 - T. Fritz - Properly returns exit value # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Set the proper # of threads for OpenMP # SLURM_CPUS_PER_TASK ensures this matches the number you set with -c above if [ -n "$SLURM_CPUS_PER_TASK" ]; then omp_threads=$SLURM_CPUS_PER_TASK else omp_threads=1 fi export OMP_NUM_THREADS=$omp_threads # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Initialize # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Define current directory APCEMM_runDir=${PWD##} export APCEMM_runDir echo $APCEMM_runDir if [[ -e ${APCEMM_runDir}/APCEMM ]]; then rm ${APCEMM_runDir}/APCEMM fi log=$PWD/log.build if [[ -e ${APCEMM_runDir}/$log ]]; then rm ${APCEMM_runDir}/$log fi make realclean if [ "$OMP_NUM_THREADS" -eq "1" ]; then make -j4 spbuild 2>&1 | tee $log else make -j4 mpbuild 2>&1 | tee $log fi # Change this to point to the APCEMM binary file export exepath=${APCEMM_runDir}/APCEMM # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Start the simulation # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ log=$PWD/log.run # Run APCEMM and pipe output to log file echo '' echo 'Running on' $OMP_NUM_THREADS 'core(s)' echo 'Host computer: ' `hostname` echo 'Initiation date and time: ' `date +%c` srun -c $OMP_NUM_THREADS time -p $exepath 2>&1 | tee $log didSucceed=$? # Echo end echo '' echo 'Run ended at ' `date +%c` # Report additional information if job was killed because of memory limit oom_check $didSucceed # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Clean up # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Clear variable unset id unset log unset APCEMM_runDir unset exepath exit $didSucceed
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; public class ReplayManager : MonoBehaviour { public bool isRecording = true; private bool isPausing = false; private float fixedDeltaTime; // Use this for initialization void Start() { fixedDeltaTime = Time.fixedDeltaTime; } // Update is called once per frame void Update() { if (CrossPlatformInputManager.GetButton("Fire1")) { isRecording = false; } else { isRecording = true; } if(Input.GetKeyDown(KeyCode.P)) { if(!isPausing) { PauseGame(); } else { ResumeGame(); } } } private void OnApplicationPause(bool pause) { isPausing = pause; } private void PauseGame() { Time.timeScale = 0f; Time.fixedDeltaTime = 0f; isPausing = true; } private void ResumeGame() { Time.timeScale = 1f; Time.fixedDeltaTime = fixedDeltaTime; isPausing = false; } }
package cn.henry.study.web.database; /** * description: threadlocal实现的,线程安全的datebase容器 * * @author Hlingoes * @date 2020/4/2 22:54 */ public class DatabaseContextHolder { private static ThreadLocal<String> routeKey = new ThreadLocal<String>(); /** * description: 绑定当前线程数据源路由的key,在使用完成之后,必须调用removeRouteKey()方法删除 * * @param type * @return void * @author Hlingoes 2020/4/3 */ public static void setRouteKey(String type) { routeKey.set(type); } /** * description: 获取当前线程的数据源路由的key * * @param * @return java.lang.String * @author Hlingoes 2020/4/3 */ public static String getRouteKey() { return routeKey.get(); } /** * description: 删除与当前线程绑定的数据源路由的key * * @param * @return void * @author Hlingoes 2020/4/3 */ public static void removeRouteKey() { routeKey.remove(); } }
@extends('layout'); @section('container') <div class="row justify-content-between"> <div class="col-7 bg-warning"> Book List </div> <div class="col-4 bg-warning"> Category </div> </div> <div class="row"> <div class="col-4 mt-3"> Title </div> <div class="col-4 mt-3"> Author </div> <br><br><br> <div class="row bg-light"> <div class="col-sm-4">Title 1</div> <div class="col-sm-4">Author 1</div> </div> <div class="row bg-light"> <div class="col-sm-4">Title 2</div> <div class="col-sm-4">Author 2</div> </div> <div class="row bg-light"> <div class="col-sm-4">Title 3</div> <div class="col-sm-4">Author 3</div> </div> <div class="row bg-light"> <div class="col-sm-4">Title 4</div> <div class="col-sm-4">Author 4</div> </div> <div class="row bg-light"> <div class="col-sm-4">Title 5</div> <div class="col-sm-4">Author 5</div> </div> <div class="row bg-light"> <div class="col-sm-4">Title 6</div> <div class="col-sm-4">Author 6</div> </div> <div class="row bg-light"> <div class="col-sm-4">Title 7</div> <div class="col-sm-4">Author 7</div> </div> <div class="row bg-light"> <div class="col-sm-4">Title 8</div> <div class="col-sm-4">Author 8</div> </div> <div class="row bg-light"> <div class="col-sm-4">Title 9</div> <div class="col-sm-4">Author 9</div> </div> <div class="row bg-light"> <div class="col-sm-4">Title 9</div> <div class="col-sm-4">Author 9</div> </div> <div class="row bg-light"> <div class="col-sm-4">Title 10</div> <div class="col-sm-4">Author 10</div> </div> </div> @endsection
<?php return [ 'administration' => 'Administration', 'redaction' => 'Rédaction', 'home' => 'Retour sur le site', 'logout' => 'Déconnexion', 'dashboard' => 'Tableau de bord', 'users' => 'Utilisateurs', 'see-all' => 'Voir tous', 'add' => 'Ajouter', 'messages' => 'Messages', 'comments' => 'Commentaires', 'medias' => 'Médias', 'posts' => 'Articles', 'new-messages' => 'Nouveaux messages !', 'new-registers' => 'Nouveaux inscrits !', 'new-posts' => 'Nouveaux articles !', 'new-comments' => 'Nouveaux commentaires !', 'blog-report' => 'Rapport de blog' ];
using System.Numerics; using UnitsNet; using UnitsNet.Units; namespace PiTop.MakerArchitecture.Expansion { public class RotationalSpeed3D { private const RotationalSpeedUnit UNIT = RotationalSpeedUnit.DegreePerSecond; public RotationalSpeed3D(RotationalSpeed x, RotationalSpeed y, RotationalSpeed z) { X = ConvertIfNeeded(x); Y = ConvertIfNeeded(y); Z = ConvertIfNeeded(z); static RotationalSpeed ConvertIfNeeded(RotationalSpeed rs) { return rs.Unit == UNIT ? rs : rs.ToUnit(UNIT); } } public RotationalSpeed X { get; } public RotationalSpeed Y { get; } public RotationalSpeed Z { get; } public static RotationalSpeed3D FromVector(Vector3 vector, RotationalSpeedUnit unit) { return new RotationalSpeed3D( RotationalSpeed.From(vector.X, unit), RotationalSpeed.From(vector.Y, unit), RotationalSpeed.From(vector.Z, unit)); } } }
package main import ( "bufio" "encoding/json" "flag" "fmt" "io" "log" "os" "path/filepath" "strings" "github.com/pkg/sftp" "golang.org/x/crypto/ssh" ) type Config struct { Target struct { Host string `json:"host"` Port string `json:"port"` Username string `json:"username"` Password string `json:"password"` } `json:"target"` Source []string `json:"source"` } func loadConfiguration(file string) (config Config) { configFile, err := os.Open(file) if err != nil { panic(err) } defer configFile.Close() jsonParser := json.NewDecoder(configFile) jsonParser.Decode(&config) return } var flagConfig = flag.String("c", "config.json", "Define the path to config.json file.") func main() { flag.Parse() config := loadConfiguration(*flagConfig) // Add for host key validation if you have it in known_hosts // hostKey := getHostKey(config.Target.Host) clientConfig := &ssh.ClientConfig{ User: config.Target.Username, Auth: []ssh.AuthMethod{ ssh.Password(config.Target.Password), }, // Remove for host key validation if you have it in known_hosts HostKeyCallback: ssh.InsecureIgnoreHostKey(), // Add for host key validation if you have it in known_hosts // HostKeyCallback: ssh.FixedHostKey(hostKey), } // connect conn, err := ssh.Dial("tcp", config.Target.Host+":"+config.Target.Port, clientConfig) if err != nil { log.Fatal(err) } defer conn.Close() // create new sftp client client, err := sftp.NewClient(conn) if err != nil { log.Fatal(err) } defer client.Close() for _, f := range config.Source { _, filename := filepath.Split(f) client.Remove(filename) targetFile, err := client.Create(filename) if err != nil { log.Fatal(err) } defer targetFile.Close() srcFile, err := os.Open(f) if err != nil { log.Fatal(err) } defer srcFile.Close() // not sure if this overrides existing content in target file // so client.Remove() above bytes, err := io.Copy(targetFile, srcFile) if err != nil { log.Fatal(err) } fmt.Printf("%d bytes copied\n", bytes) } } func getHostKey(host string) ssh.PublicKey { file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts")) if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) var hostKey ssh.PublicKey for scanner.Scan() { fields := strings.Split(scanner.Text(), "") if len(fields) != 3 { continue } if strings.Contains(fields[0], host) { var err error hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes()) if err != nil { log.Fatalf("error parsing %q: %v", fields[2], err) } break } } if hostKey == nil { log.Fatalf("no hostkey found for %s", host) } return hostKey }
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/wm/float/float_controller.h" #include "ash/accelerators/accelerator_controller_impl.h" #include "ash/constants/ash_features.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "base/test/scoped_feature_list.h" #include "ui/wm/core/window_util.h" namespace ash { class WindowFloatTest : public AshTestBase { public: WindowFloatTest() = default; WindowFloatTest(const WindowFloatTest&) = delete; WindowFloatTest& operator=(const WindowFloatTest&) = delete; ~WindowFloatTest() override = default; void SetUp() override { // Ensure float feature is enabled. scoped_feature_list_.InitAndEnableFeature(features::kWindowControlMenu); AshTestBase::SetUp(); } private: base::test::ScopedFeatureList scoped_feature_list_; }; // Test float/unfloat window. TEST_F(WindowFloatTest, WindowFloatingSwitch) { std::unique_ptr<aura::Window> window_1(CreateTestWindow()); std::unique_ptr<aura::Window> window_2(CreateTestWindow()); FloatController* controller = Shell::Get()->float_controller(); // Activate 'window_1' and perform floating. wm::ActivateWindow(window_1.get()); PressAndReleaseKey(ui::VKEY_F, ui::EF_ALT_DOWN | ui::EF_COMMAND_DOWN); EXPECT_TRUE(controller->IsFloated(window_1.get())); // Activate 'window_2' and perform floating. wm::ActivateWindow(window_2.get()); PressAndReleaseKey(ui::VKEY_F, ui::EF_ALT_DOWN | ui::EF_COMMAND_DOWN); EXPECT_TRUE(controller->IsFloated(window_2.get())); // Only one floated window is allowed so when a different window is floated, // the previously floated window will be unfloated. EXPECT_FALSE(controller->IsFloated(window_1.get())); // When try to float the already floated 'window_2', it will unfloat this // window. wm::ActivateWindow(window_2.get()); PressAndReleaseKey(ui::VKEY_F, ui::EF_ALT_DOWN | ui::EF_COMMAND_DOWN); EXPECT_FALSE(controller->IsFloated(window_2.get())); } } // namespace ash
module Days.Day25 (day25) where import Data.Char import Data.List import Days.ReadPuzzle day25 :: IO () day25 = do input <- readPuzzle 25 putStr "Answer: " let [row, col] = parseCoordinate input print $ foldl' (\r _ -> next r) start [1..which (row, col) - 1] start :: Integer start = 20151125 multiplier :: Integer multiplier = 252533 modulo :: Integer modulo = 33554393 next :: Integer -> Integer next n = (n * multiplier) `mod` modulo which :: (Int, Int) -> Int which (row, col) = sum [1..col] + sum (take (row - 1) [col..]) parseCoordinate :: String -> [Int] parseCoordinate = map (read . init) . filter (isNumber . head) . words
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <[email protected]> // +---------------------------------------------------------------------- Route::resource('product','api/Product'); Route::resource('employee','api/Employee'); Route::resource('customer','api/Customer'); Route::resource('order','api/Order'); Route::resource('fankui','api/Fankui'); Route::resource('cate_product','api/CateProduct'); Route::resource('area','api/Area'); Route::resource('company','api/Company'); Route::resource('weixin','api/Weixin'); Route::resource('menu','api/Menu'); Route::resource('department','api/Department'); Route::resource('user','api/User'); Route::get('admin$', 'admin/Index/index'); Route::get('admin/:mod$','admin/Index/module'); Route::resource('map_marker','api/MapMarker'); Route::get('tool/:tool$','index/Index/tool'); Route::controller('login','api/Login'); Route::controller('export','api/Export'); return [ ];
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. 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. See accompanying * LICENSE file. */ /* * Changes for SnappyData data platform. * * Portions Copyright (c) 2017-2019 TIBCO Software Inc. 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. See accompanying * LICENSE file. */ /** * ColumnDescriptor.h */ #ifndef COLUMNDESCRIPTOR_H_ #define COLUMNDESCRIPTOR_H_ #include "ColumnDescriptorBase.h" namespace io { namespace snappydata { namespace client { // TODO: SW: add move constructors for all C++ classes class ColumnDescriptor: public ColumnDescriptorBase { private: ColumnDescriptor(thrift::ColumnDescriptor& descriptor, const uint32_t columnIndex) : ColumnDescriptorBase(descriptor, columnIndex) { } friend class ResultSet; public: ~ColumnDescriptor() { } ColumnUpdatable getUpdatable() const noexcept { if (m_descriptor.updatable) { return ColumnUpdatable::UPDATABLE; } else if (m_descriptor.definitelyUpdatable) { return ColumnUpdatable::DEFINITELY_UPDATABLE; } else { return ColumnUpdatable::READ_ONLY; } } bool isAutoIncrement() const noexcept { return m_descriptor.autoIncrement; } bool isCaseSensitive() const noexcept; bool isSearchable() const noexcept { // we have no restrictions yet, so this is always true return true; } bool isCurrency() const noexcept; uint32_t getDisplaySize() const noexcept; std::string getLabel() const noexcept { if (m_descriptor.__isset.name) { return m_descriptor.name; } else { char buf[32]; ::snprintf(buf, sizeof(buf), "Column%d", m_columnIndex); return buf; } } }; } /* namespace client */ } /* namespace snappydata */ } /* namespace io */ #endif /* COLUMNDESCRIPTOR_H_ */
import { Registry } from './registry'; import { Class } from './types'; export interface RegisterOptions { identifier?: string; allowProps?: string[]; } class _ClassRegistry extends Registry<Class> { constructor() { super(c => c.name); } private classToAllowedProps = new Map<Class, string[]>(); register(value: Class, options?: string | RegisterOptions): void { if (typeof options === 'object') { if (options.allowProps) { this.classToAllowedProps.set(value, options.allowProps); } super.register(value, options.identifier); } else { super.register(value, options); } } getAllowedProps(value: Class): string[] | undefined { return this.classToAllowedProps.get(value); } } export const ClassRegistry = new _ClassRegistry();
<?php namespace FondOfSpryker\Yves\Contentful\Dependency\Client; use Spryker\Client\Search\Dependency\Plugin\QueryInterface; interface ContentfulToSearchClientInterface { /** * @param \Spryker\Client\Search\Dependency\Plugin\QueryInterface $searchQuery * @param array $resultFormatters * @param array $requestParameters * * @return array|\Elastica\ResultSet */ public function search(QueryInterface $searchQuery, array $resultFormatters = [], array $requestParameters = []); }
module Terraspace::Plugin class Finder def find_with(options) result = if options.key?(:plugin) find_with_plugin(options[:plugin]) elsif options.key?(:backend) find_with_backend(options[:backend]) elsif options.key?(:resource) find_with_resource(options[:resource]) else raise "Must provide backend, plugin, or resource option." end return unless result raw = Hash[*result] # convert result to Hash instead of an Array Meta.new(raw) end def find_with_backend(backend) meta.find do |provider, data| data[:backend] == backend end end def find_with_plugin(plugin) meta.find do |plugin_name, data| plugin_name == plugin end end def find_with_resource(resource) map = resource_map base = resource.split('_').first # google_compute_firewall => google, aws_security_group => aws plugin = map[base] || base find_with_plugin(plugin) end def resource_map Terraspace::Plugin.resource_map end def meta Terraspace::Plugin.meta end end end
--- title: The Voice Of The Unheard created: 2021-04-10T13:09:00-07:00 modified: 2021-04-10T13:09:41-07:00 --- https://youtu.be/pjYZZC5i_AU
import React from 'react'; import {StyleSheet, TouchableNativeFeedback, View} from 'react-native'; import Panel from '../ui/Panel'; import {PrimaryText, SecondaryHeader, SecondaryText} from '../ui/Text'; import { getDistanceText, getDurationText, getPaceText, getWorkoutsLabel } from '../../lib/entry'; import Separator from '../ui/Separator'; import theme from '../../theme'; import utils from '../../styles-utilities'; import {EffortIcons} from '../../types/Effort'; import {TimelineEntry} from '../../types/TimelineEntry'; import appStyles from '../../styles'; interface TimelineCardProps { timelineEntry: TimelineEntry; onPress: () => void; } function TimelineCard({timelineEntry, onPress}: TimelineCardProps) { const {title, distance, duration, effort, entryIds} = timelineEntry; return ( <TouchableNativeFeedback accessibilityLabel="Timeline card" onPress={onPress} > <View style={styles.card}> <SecondaryHeader color="primary">{title} </SecondaryHeader> <SecondaryText style={utils.marginTopS} color="secondary"> {entryIds.length} {getWorkoutsLabel(entryIds.length)} </SecondaryText> <Separator marginBottom={theme.SPACING.L} /> <View style={[utils.row]}> <View style={styles.detailsContainer}> <PrimaryText style={styles.detailsText}> {getDistanceText(distance)} </PrimaryText> <SecondaryText>Distance</SecondaryText> </View> <View style={styles.detailsContainer}> <PrimaryText style={styles.detailsText}> {getDurationText(duration)} </PrimaryText> <SecondaryText>Duration</SecondaryText> </View> <View style={styles.detailsContainer}> <PrimaryText style={styles.detailsText}> {getPaceText(duration, distance)} </PrimaryText> <SecondaryText>Avg. Pace</SecondaryText> </View> </View> <View style={[ styles.effortIndicator, {backgroundColor: EffortIcons[effort].color} ]} /> </View> </TouchableNativeFeedback> ); } const styles = StyleSheet.create({ card: { ...appStyles.panel, overflow: 'hidden' }, detailsContainer: { marginRight: theme.SPACING.XL }, detailsText: { fontFamily: 'LatoBlack', paddingBottom: theme.SPACING.XS }, effortIndicator: { position: 'absolute', right: 0, width: 1, height: 200 } }); export default TimelineCard;
package edu.gwu.algorithms.sorting; public class InsertionSort { public static void main(String[] args) { int[] nValues = { 10000, 20000, 40000, 60000, 80000, 100000 }; for (int n : nValues) { double[] inputArray = new double[n]; for (int i = 0; i < inputArray.length; i++) { inputArray[i] = Math.random() * 100000; } double t1 = System.currentTimeMillis(); sort(inputArray); double t2 = System.currentTimeMillis(); confirmSorted(inputArray); System.out.println(n + "," + (t2 - t1)); } } private static void confirmSorted(double[] inputArray) { for (int i = 0; i < inputArray.length - 1; i++) { if (inputArray[i] > inputArray[i + 1]) { throw new IllegalArgumentException("Array not sorted"); } } } public static void sort(double[] inputArray) { int n = inputArray.length; for (int j = 1; j <= n - 1; j++) { double key = inputArray[j]; // A[j] is added in the sorted sequence A[1.. j-1] int i = j - 1; while ((i >= 0) && (inputArray[i] > key)) { inputArray[i + 1] = inputArray[i]; i = i - 1; } inputArray[i + 1] = key; } } }
using System; using Newtonsoft.Json.Linq; namespace Clarifai.API.Requests { /// <summary> /// A paginated Clarifai request. It divides the results into pages. /// </summary> /// <typeparam name="T">the type of the response content</typeparam> public abstract class ClarifaiPaginatedRequest<T> : ClarifaiRequest<T> { private int? _page; private int? _perPage; /// <inheritdoc /> protected ClarifaiPaginatedRequest(IClarifaiHttpClient httpClient) : base(httpClient) { } /// <summary> /// The page of the results. Counting starts with 1. /// </summary> /// <param name="page">the page</param> /// <returns>this request instance</returns> public ClarifaiPaginatedRequest<T> Page(int page) { _page = page; return this; } /// <summary> /// Number of outputs to have per page. /// </summary> /// <param name="perPage">number per page</param> /// <returns>this request instance</returns> public ClarifaiPaginatedRequest<T> PerPage(int perPage) { _perPage = perPage; return this; } /// <inheritdoc /> protected override string BuildUrl() { if (_page == null && _perPage == null) { return Url; } else { if (Method == RequestMethod.GET) { return Url + "?" + (_page != null ? "page=" + _page : "") + (_page != null && _perPage != null ? "&" : "") + (_perPage != null ? "per_page=" + _perPage : ""); } else if (Method == RequestMethod.POST) { return Url; } else { throw new InvalidOperationException( "Pagination only supported for GET and POST"); } } } /// <summary> /// Seal this method to avoid accidentally using it instead of PaginatedHttpRequestBody /// in children ClarifaiPaginatedRequest. /// </summary> protected sealed override JObject HttpRequestBody() { return PaginatedHttpRequestBody(); } /// <summary> /// The HTTP request body used in paginated requests. /// </summary> protected virtual JObject PaginatedHttpRequestBody() { JObject body = base.HttpRequestBody(); if (Method == RequestMethod.POST) { var pagination = new JObject(); if (_page != null) { pagination["page"] = _page; } if (_perPage != null) { pagination["per_page"] = _perPage; } if (pagination.Count > 0) { body["pagination"] = pagination; } } return body; } } }
import * as React from "react"; import { Filter, FilterChips, FilterTab, FilterTabs } from "../../../components/TableFilter"; import i18n from "../../../i18n"; export type SkillListFilterTabs = | "all" | "available" | "outOfStock" | "custom"; interface SkillListFilterProps { currentTab: SkillListFilterTabs; filtersList: Filter[]; onAllSkills: () => void; onAvailable: () => void; onOfStock: () => void; onCustomFilter: () => void; } const SkillListFilter: React.StatelessComponent<SkillListFilterProps> = ({ filtersList, currentTab, onAllSkills, onAvailable, onOfStock, onCustomFilter }) => ( <> <FilterTabs currentTab={["all", "available", "outOfStock", "custom"].indexOf( currentTab )} > <FilterTab label={i18n.t("All Skills")} onClick={onAllSkills} /> <FilterTab label={i18n.t("Available")} onClick={onAvailable} /> <FilterTab label={i18n.t("Out Of Stock")} onClick={onOfStock} /> {currentTab === "custom" && filtersList && filtersList.length > 0 && ( <FilterTab onClick={onCustomFilter} value={0} label={i18n.t("Custom Filter")} /> )} </FilterTabs> {currentTab === "custom" && filtersList && filtersList.length > 0 && ( <FilterChips filtersList={filtersList} /> )} </> ); SkillListFilter.displayName = "SkillListFilter"; export default SkillListFilter;
# frozen_string_literal: true module Testing module Merced # Process a unit JSON and recursively upsert # its children before yielding back to {Testing::Merced::ProcessUnits}. # # @api private # @operation class ProcessUnit include Dry::Monads[:do, :result] include Dry::Effects.Resolve(:units) include Dry::Effects.State(:unit_ids) include WDPAPI::Deps[ upsert_page: "testing.merced.upsert_page", upsert_unit: "testing.merced.upsert_unit", ] prepend HushActiveRecord # @param [ActiveSupport::HashWithIndifferentAccess] unit_definition # @return [Dry::Monads::Result] def call(unit_definition, parent: nil) unit = yield upsert_unit.call unit_definition, parent: parent unit_definition[:pages].each_with_index do |page, index| yield upsert_page.call page, index: index, parent: unit end Array(unit_definition[:children]).uniq.each do |child_id| child = units.detect { |c| c[:id] == child_id } yield call child, parent: unit if child.present? end Success unit end end end end
from py2asm.functions.base import Function from py2asm.functions.groups import BiosProcedureCall class InputChar(Function): def __init__(self, echo=True): self.echo = echo super().__init__() def get_instructions(self): return ( BiosProcedureCall(0x01 if self.echo else 0x07), )
export enum Constants { IS_OFFLINE = "IS_OFFLINE", SET_USER = "SET_USER", SET_REPO = "SET_REPO", SET_ERROR = "SET_ERROR", RESET = "RESET", }
import 'package:RasPiFinder/models/user.dart'; import 'package:RasPiFinder/screens/auth/authenticate.dart'; import 'package:RasPiFinder/screens/onboarding/sharedPreferences.dart'; import 'package:RasPiFinder/services/database.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:RasPiFinder/navigation_screen.dart'; import 'models/rasps.dart'; class Wrapper extends StatefulWidget { @override State<StatefulWidget> createState() { return WrapperState(); } } class WrapperState extends State<Wrapper> { bool isFirstTimeOpen = true; WrapperState() { print("First time"); print(isFirstTimeOpen); MSharedPreferences.instance .getBooleanValue("firstTimeOpen") .then((value) => setState(() { isFirstTimeOpen = value; })); } @override Widget build(BuildContext context) { final user = Provider.of<MUser>(context); print("First time22"); print(isFirstTimeOpen); if ( user == null) { return Authenticate(); } else { print('Wrapper user uid=' + user.uid); return MultiProvider( providers: [ StreamProvider<List<Rasp>>.value(value: DatabaseService().rasps), StreamProvider<List<UserData>>.value(value: DatabaseService().users), StreamProvider<UserData>.value(value: DatabaseService(uid: user.uid).userData)], child: NavigationPage()); } } }
package com.yq.controller.collection; import java.math.BigDecimal; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.change.controller.base.BaseController; import org.change.entity.Page; import org.change.util.PageData; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.google.gson.Gson; import com.yq.service.collection.CollectionManager; import com.yq.service.goods.GoodsManager; import com.yq.util.DatetimeUtil; import com.yq.util.StringUtil; /** * 说明:商品收藏 * 创建人:千派网络 www.qanpai.com * 创建时间:2017-05-11 */ @Controller @RequestMapping(value="/collection") public class CollectionController extends BaseController { String menuUrl = "collection/list.do"; //菜单地址(权限用) @Resource(name="collectionService") private CollectionManager collectionService; @Resource(name="goodsService") private GoodsManager goodsService; private Gson gson = new Gson(); /**保存 * @param * @throws Exception */ @ResponseBody @RequestMapping(value="/add",produces = "application/json;charset=UTF-8") public String add() throws Exception{ int result = 0; String message = ""; Map<String, Object> map = new HashMap<String, Object>(); PageData pd = new PageData(); pd = this.getPageData(); try{ Map<String, Object> shopUser = StringUtil.shopUser(this.getRequest()); pd.put("user_id", shopUser.get("user_id")); //未收藏此商品 if(collectionService.findById(pd)==null){ PageData goods = goodsService.findById(pd); String pic =goods.getString("goods_pic"); if(StringUtils.isNotEmpty(pic)){ if(pic.contains(",")){ pic = pic.split(",")[0]; } } goods.put("goods_pic", pic); pd.put("collection_id", this.get32UUID()); //主键 pd.put("goods_pic", pic); pd.put("goods_price", (BigDecimal)goods.get("goods_price")); pd.put("goods_name", goods.get("goods_name")); pd.put("addtime", DatetimeUtil.getDatetime()); collectionService.save(pd); result = 1; message = "收藏成功"; } }catch(Exception e){ message = "收藏失败"; } map.put("result", result); map.put("message", message); return gson.toJson(map); } /**删除 * @param out * @throws Exception */ @ResponseBody @RequestMapping(value="/delete",produces = "application/json;charset=UTF-8") public String delete() throws Exception{ int result = 0; String message = ""; Map<String, Object> map = new HashMap<String, Object>(); PageData pd = new PageData(); pd = this.getPageData(); try{ Map<String, Object> shopUser = StringUtil.shopUser(this.getRequest()); pd.put("user_id", shopUser.get("user_id")); collectionService.delete(pd); result = 1; message = "取消收藏"; } catch(Exception e){ message = "提交失败"; } map.put("result", result); map.put("message", message); return gson.toJson(map); } /**列表 * @param page * @throws Exception */ @ResponseBody @RequestMapping(value="/list",produces = "application/json;charset=UTF-8") public String list(Page page) throws Exception{ Map<String, Object> map = new HashMap<String, Object>(); PageData pd = new PageData(); pd = this.getPageData(); Map<String, Object> shopUser = StringUtil.shopUser(this.getRequest()); pd.put("user_id", shopUser.get("user_id")); page.setPd(pd); List<PageData> list = collectionService.list(page); //列出Collection列表 map.put("list", list); map.put("page", page); return gson.toJson(map); } /**去列表页面 * @param * @throws Exception */ @RequestMapping(value="/tolist") public ModelAndView goAdd()throws Exception{ ModelAndView mv = this.getModelAndView(); mv.setViewName("collection/list"); mv.addObject("msg", "save"); return mv; } }
package client import ( "bufio" "errors" "fmt" "io/ioutil" "net/http" "net/url" "os" "os/user" "regexp" "strings" "code.google.com/p/goauth2/oauth" "github.com/google/go-github/github" "github.com/howeyc/gopass" "github.com/jmcvetta/napping" ) // CreateClient は認証済みの github.Client を返します func CreateClient(appName string, scopes []string) *github.Client { // 設定ファイルがあれば読み込む var accessToken string var err error user, _ := user.Current() confName := "." + strings.ToLower(appName) + ".conf" confpath := user.HomeDir + "/" + confName buf, err := ioutil.ReadFile(confpath) if err != nil { // 認証して accessToken を取得する accessToken, err = fetchAccessToken(appName, scopes) if err != nil { fmt.Println(err) os.Exit(1) } ioutil.WriteFile(confpath, []byte(accessToken), 0644) } else { // ファイルから accessToken を読み込む accessToken = fmt.Sprintf("%s", buf) } return oauthClient(accessToken) } func oauthClient(accessToken string) *github.Client { t := &oauth.Transport{ Token: &oauth.Token{AccessToken: accessToken}, } return github.NewClient(t.Client()) } func getCredentials() (string, string, string) { scan := func() string { reader := bufio.NewReader(os.Stdin) input, _ := reader.ReadString('\n') return strings.TrimSpace(input) } fmt.Print("Username: ") login := scan() fmt.Print("Password: ") password := strings.TrimSpace(fmt.Sprintf("%s", gopass.GetPasswd())) fmt.Print("Two Factor Auth: ") tfaToken := scan() return login, password, tfaToken } // 既に appName という名前のトークンがあるかどうか探す func findAccessToken(s *napping.Session, appName string) (string, error) { type authorization struct { ID int URL string Scopes []string Token string App map[string]string Note string `json:"note"` NoteURL string `json:"note_url"` UpdatedAt string `json:"updated_at"` CreatedAt string `json:"created_at"` } type httpError struct { Message string Errors []struct { Resource string Field string Code string } } fetchAuthorizations := func(url string) ([]authorization, string, error) { res := []authorization{} e := httpError{} resp, err := s.Get(url, nil, &res, &e) if err != nil { return nil, "", err } if resp.Status() == 200 { linkStr := resp.HttpResponse().Header["Link"][0] reg, _ := regexp.Compile("\\<(.*)?\\>; rel=\"next\"") subMatch := reg.FindStringSubmatch(linkStr) var nextURL string if len(subMatch) > 0 { nextURL = subMatch[1] } else { nextURL = "" } return res, nextURL, nil } return nil, "", errors.New("Failed to fetch Authentications.") } authorizations := []authorization{} url := "https://api.github.com/authorizations" for { res, nextURL, err := fetchAuthorizations(url) if err != nil { return "", err } authorizations = append(authorizations, res...) if nextURL == "" { break } url = nextURL } for _, auth := range authorizations { // "hoge (API)" という名前が付けられるようなのでそれで探す // FIXME: note 属性で探したかったが、レスポンスについてこなかった if auth.App["name"] == appName+" (API)" { return auth.Token, nil } } return "", nil } // 新しくトークンを作る func createAccessToken(s *napping.Session, appName string, scopes []string) (string, error) { res := struct { ID int URL string Scopes []string Token string App map[string]string Note string `json:"note"` NoteURL string `json:"note_url"` UpdatedAt string `json:"updated_at"` CreatedAt string `json:"created_at"` }{} e := struct { Message string Errors []struct { Resource string Field string Code string } }{} payload := struct { Scopes []string `json:"scopes"` Note string `json:"note"` }{ Scopes: scopes, Note: appName, } url := "https://api.github.com/authorizations" resp, err := s.Post(url, &payload, &res, &e) if err != nil { return "", err } if resp.Status() == 201 { return res.Token, nil } fmt.Println("Bad response status from Github server") fmt.Printf("\t Status: %v\n", resp.Status()) fmt.Printf("\t Message: %v\n", e.Message) fmt.Printf("\t Errors: %v\n", e.Message) return "", errors.New("Failed to create Access Token.") } func fetchAccessToken(appName string, scopes []string) (string, error) { login, password, tfaToken := getCredentials() // Two Factor Auth の認証をするため一度ダミーでリクエストする // https://github.com/github/hub/blob/master/lib/hub/github_api.rb#L338 if tfaToken != "" { dummySession := napping.Session{ Userinfo: url.UserPassword(login, password), } url := "https://api.github.com/authorizations" dummySession.Post(url, nil, nil, nil) } header := &http.Header{} header.Add("X-GitHub-OTP", tfaToken) s := napping.Session{ Userinfo: url.UserPassword(login, password), Header: header, } foundToken, err := findAccessToken(&s, appName) if err != nil { return "", err } if foundToken != "" { return foundToken, nil } createdToken, err := createAccessToken(&s, appName, scopes) if err != nil { return "", err } return createdToken, nil }
#!/bin/sh set -e while [ 1 ]; do sh -c "/backup.sh $POSTGRES_HOST $POSTGRES_USER $POSTGRES_PASSWORD $POSTGRES_DB /backups" sh -c "/delete_old_backup.sh $TOKEEP /backups" echo "Waiting $DELAY..." sleep $DELAY done
# Ruby bindings for zstd library. # Copyright (c) 2019 AUTHORS, MIT License. require "zstds_ext" require_relative "error" require_relative "validation" module ZSTDS class Dictionary TRAIN_DEFAULTS = { :gvl => false, :capacity => 0 } .freeze attr_reader :buffer def initialize(buffer) Validation.validate_string buffer raise ValidateError, "dictionary buffer should not be empty" if buffer.empty? @buffer = buffer end def self.train(samples, options = {}) Validation.validate_array samples samples.each do |sample| Validation.validate_string sample raise ValidateError, "dictionary sample should not be empty" if sample.empty? end Validation.validate_hash options options = TRAIN_DEFAULTS.merge options Validation.validate_bool options[:gvl] Validation.validate_not_negative_integer options[:capacity] buffer = train_buffer samples, options new buffer end def id self.class.get_buffer_id @buffer end def header_size self.class.get_header_size @buffer end end end
module StackSpec (main, spec) where import Test.Hspec import Stack main :: IO () main = hspec spec spec :: Spec spec = do describe "null" $ do it "is null when stack is empty" $ do Stack.null Stack.mkStack it "is not null when stack is empty" $ do not $ Stack.null $ Stack.cons 1 Stack.mkStack describe "head" $ do it "gets the head" $ do let stack = Stack.cons 2 $ Stack.cons 1 Stack.mkStack Stack.head stack == Just 2 it "returns nothing for an empty stack" $ do let stack = Stack.mkStack :: Stack.Stack Int Stack.head stack == Nothing describe "tail" $ do it "gets the tail" $ do let stack = Stack.cons 2 $ Stack.cons 1 Stack.mkStack Stack.head (Stack.tail stack) == Just 1 it "returns empty for an empty stack" $ do let stack = Stack.mkStack :: Stack.Stack Int Stack.head (Stack.tail stack) == Nothing describe "cons" $ do it "adds an element to the stack" $ do let stack = Stack.mkStack Stack.head (Stack.cons 1 stack) == Just 1
(global as any).__API_HOST__ = "example.com"; (global as any).__API_ENDPOINT__ = "/api"; import * as nock from "nock"; import { createAction } from "redux-actions"; import { hydrateStore, IS_DELETING, IS_UPDATING, reducer, setEndpointHost, setEndpointPath, setHeader, setHeaders } from "../src/jsonapi"; Object.defineProperty(global, "XMLHttpRequest", { value: require("xmlhttprequest").XMLHttpRequest }); import { apiRequest } from "../src/utils"; const noop = () => {}; // tslint:disable-line no-empty const apiCreated = createAction("API_CREATED"); const apiRead = createAction("API_READ"); const apiUpdated = createAction("API_UPDATED"); const apiDeleted = createAction("API_DELETED"); const apiWillUpdate = createAction("API_WILL_UPDATE"); const apiWillDelete = createAction("API_WILL_DELETE"); const apiUpdateFailed = createAction("API_UPDATE_FAILED"); const apiDeleteFailed = createAction("API_DELETE_FAILED"); const state = { endpoint: { host: null, path: null, headers: { "Content-Type": "application/vnd.api+json", Accept: "application/vnd.api+json" } }, users: { data: [ { type: "users", id: "1", attributes: { name: "John Doe" }, relationships: { companies: { data: null } } }, { type: "users", id: "2", attributes: { name: "Emily Jane" }, relationships: { companies: { data: null } } } ] }, transactions: { data: [ { type: "transactions", id: "34", attributes: { description: "ABC", createdAt: "2016-02-12T13:34:01+0000", updatedAt: "2016-02-19T11:52:43+0000" }, relationships: { task: { data: null } }, links: { self: "http://localhost/transactions/34" } } ] }, isCreating: 0, isReading: 0, isUpdating: 0, isDeleting: 0 }; const stateWithoutUsersResource = { endpoint: { host: null, path: null, headers: { "Content-Type": "application/vnd.api+json", Accept: "application/vnd.api+json" } }, transactions: { data: [ { type: "transactions", id: "34", attributes: { description: "ABC", createdAt: "2016-02-12T13:34:01+0000", updatedAt: "2016-02-19T11:52:43+0000" }, relationships: { task: { data: null } }, links: { self: "http://localhost/transactions/34" } } ] }, isCreating: 0, isReading: 0, isUpdating: 0, isDeleting: 0 }; const taskWithoutRelationship = { data: { type: "tasks", id: "43", attributes: { name: "ABC", createdAt: "2016-02-19T11:52:43+0000", updatedAt: "2016-02-19T11:52:43+0000" } } }; const taskWithTransaction = { data: { type: "tasks", id: "43", attributes: { name: "ABC", createdAt: "2016-02-19T11:52:43+0000", updatedAt: "2016-02-19T11:52:43+0000" }, relationships: { taskList: { data: { type: "taskLists", id: "1" } }, transaction: { data: { type: "transactions", id: "34" } } }, links: { self: "http://localhost/tasks/43" } } }; const taskWithTransactions = { type: "tasks", id: "43", attributes: { name: "ABC", createdAt: "2016-02-19T11:52:43+0000", updatedAt: "2016-02-19T11:52:43+0000" }, relationships: { taskList: { data: { type: "taskLists", id: "1" } }, transaction: { data: [ { type: "transactions", id: "34" } ] } }, links: { self: "http://localhost/tasks/43" } }; const transactionToDelete = { type: "transactions", id: "34", attributes: { description: "ABC", createdAt: "2016-02-12T13:34:01+0000", updatedAt: "2016-02-19T11:52:43+0000" }, relationships: { task: { data: null } }, links: { self: "http://localhost/transactions/34" } }; const transactionWithTask = { ...transactionToDelete, relationships: { task: { data: { type: "tasks", id: "43" } } } }; const updatedUser = { data: { type: "users", id: "1", attributes: { name: "Sir John Doe" }, relationships: { tasks: { data: null } } } }; const multipleResources = { data: [taskWithTransaction.data], relationships: [taskWithTransaction.data.relationships] }; const readResponse = { data: [taskWithTransaction.data] }; const readResponseWithIncluded = { ...readResponse, included: [ { type: "transactions", id: "35", attributes: { description: "DEF", createdAt: "2016-02-12T13:35:01+0000", updatedAt: "2016-02-19T11:52:43+0000" }, relationships: { task: { data: null } }, links: { self: "http://localhost/transactions/35" } } ] }; const responseDataWithSingleResource = { data: { type: "companies", id: "1", attributes: { name: "Dixie.io", slug: "dixie.io", createdAt: "2016-04-08T08:42:45+0000", updatedAt: "2016-04-08T08:42:45+0000", role: "bookkeeper" }, relationships: { users: { data: [ { type: "users", id: "1" } ] }, employees: { data: [ { type: "users", id: "1" } ] }, bookkeepers: { data: [ { type: "users", id: "4" } ] }, bookkeeper_state: { data: { type: "bookkeeper_state", id: "2" } } }, links: { self: "http://gronk.app/api/v1/companies/1" } }, included: [ { type: "users", id: "1", attributes: { name: "Ron Star", email: "[email protected]", createdAt: "2016-04-08T08:42:45+0000", updatedAt: "2016-04-13T08:28:58+0000" }, relationships: { companies: { data: [ { type: "companies", id: "1" } ] } } } ] }; const responseDataWithOneToManyRelationship = { data: [ { type: "companies", id: "1", attributes: { name: "Dixie.io", slug: "dixie.io", createdAt: "2016-04-08T08:42:45+0000", updatedAt: "2016-04-08T08:42:45+0000" }, relationships: { user: { data: { type: "users", id: "1" } } }, links: { self: "http://gronk.app/api/v1/companies/1" } }, { type: "companies", id: "2", attributes: { name: "Dixie.io", slug: "dixie.io", createdAt: "2016-04-08T08:42:45+0000", updatedAt: "2016-04-08T08:42:45+0000" }, relationships: { user: { data: { type: "users", id: "1" } } }, links: { self: "http://gronk.app/api/v1/companies/2" } } ] }; const payloadWithNonMatchingReverseRelationships = require("./payloads/withNonMatchingReverseRelationships.json"); describe("Hydration of store", () => { it("should automatically organize new resource in new key on state", () => { const updatedState = reducer(state, hydrateStore(taskWithoutRelationship)); expect(typeof updatedState.tasks).toBe("object"); }); it("should add reverse relationship when inserting new resource", () => { const updatedState = reducer(state, hydrateStore(taskWithTransaction)); const { data: taskRelationship } = updatedState.transactions.data[0].relationships.task; expect(taskRelationship.type).toEqual(taskWithTransaction.data.type); expect(taskRelationship.id).toEqual(taskWithTransaction.data.id); }); it("should handle multiple resources", () => { const updatedState = reducer(state, hydrateStore(multipleResources)); expect(typeof updatedState.tasks).toBe("object"); }); }); describe("Creation of new resources", () => { it("should automatically organize new resource in new key on state", () => { const updatedState = reducer(state, apiCreated(taskWithoutRelationship)); expect(typeof updatedState.tasks).toBe("object"); }); it("should add reverse relationship when inserting new resource", () => { const updatedState = reducer(state, apiCreated(taskWithTransaction)); const { data: taskRelationship } = updatedState.transactions.data[0].relationships.task; expect(taskRelationship.type).toEqual(taskWithTransaction.data.type); expect(taskRelationship.id).toEqual(taskWithTransaction.data.id); expect(updatedState.isCreating).toEqual(state.isCreating - 1); }); it("should handle multiple resources", () => { const updatedState = reducer(state, apiCreated(multipleResources)); expect(typeof updatedState.tasks).toBe("object"); }); }); describe("Reading resources", () => { it("should append read resources to state", () => { const updatedState = reducer(state, apiRead(readResponse)); expect(typeof updatedState.tasks).toBe("object"); expect(updatedState.tasks.data.length).toEqual(1); }); it("should append included resources in state", () => { const updatedState = reducer(state, apiRead(readResponseWithIncluded)); expect(updatedState.transactions.data.length).toEqual( state.transactions.data.length + 1 ); }); it("should handle response where data is an object", () => { const updatedState = reducer( undefined, apiRead(responseDataWithSingleResource) ); expect(typeof updatedState.users).toBe("object"); expect(typeof updatedState.companies).toBe("object"); }); it("should handle response with a one to many relationship", () => { const updatedState = reducer( state, apiRead(responseDataWithOneToManyRelationship) ); expect(typeof updatedState.users).toBe("object"); expect(typeof updatedState.companies).toBe("object"); expect( Array.isArray(updatedState.users.data[0].relationships.companies.data) ).toBe(true); }); it("should ignore reverse relationship with no matching resource", () => { const updatedState = reducer( state, apiRead(payloadWithNonMatchingReverseRelationships) ); payloadWithNonMatchingReverseRelationships.included .filter(resource => resource.type === "reports") .forEach(payloadReport => { const stateReport = updatedState.reports.data.find( r => payloadReport.id === r.id ); expect(stateReport.relationships.file.data.id).toEqual( payloadReport.relationships.file.data.id ); }); }); }); const zip = rows => rows[0].map((_, c) => rows.map(row => row[c])); describe("Updating resources", () => { it("should update a resource", () => { const updatedState = reducer( state, apiUpdated({ data: [ { type: "users", id: "2", attributes: { name: "Jane Doe" }, relationships: { companies: { data: null } } } ] }) ); expect(updatedState.users.data[1].attributes.name).toEqual("Jane Doe"); }); it("should update a resource without relationships", () => { const updatedState = reducer( state, apiUpdated({ data: [ { type: "users", id: "2", attributes: { name: "Jane Doe" } } ] }) ); expect(updatedState.users).toMatchSnapshot(); }); it("should persist in state and preserve order", () => { const updatedState = reducer(state, apiUpdated(updatedUser)); expect(state.users.data[0].attributes.name).not.toEqual( updatedUser.data.attributes.name ); expect(updatedState.users.data[0].attributes.name).toEqual( updatedUser.data.attributes.name ); zip([updatedState.users.data, state.users.data]).forEach((a, b) => expect(a.id).toEqual(b.id) ); }); it("should be able to update a resource before type is in state", () => { const userToUpdate = state.users.data[0]; const stateWithResourceType = reducer( stateWithoutUsersResource, apiWillUpdate(userToUpdate) ); const updatedState = reducer( stateWithResourceType, apiUpdated(updatedUser) ); expect(updatedState.users.data[0]).toEqual(updatedUser.data); }); }); describe("Delete resources", () => { it("should remove resource from state", () => { const updatedState = reducer(state, apiDeleted(transactionToDelete)); expect(updatedState.transactions.data.length).toEqual(0); }); it("should remove reverse relationship", () => { const stateWithTask = reducer(state, apiCreated(taskWithTransaction)); expect( stateWithTask.transactions.data[0].relationships.task.data.type ).toEqual(taskWithTransaction.data.type); const stateWithoutTask = reducer( stateWithTask, apiDeleted(taskWithTransaction.data) ); const { data: relationship } = stateWithoutTask.transactions.data[0].relationships.task; expect(relationship).toEqual(null); }); describe("when one-to-many relationship", () => { it("should update reverse relationship for transaction", () => { // Add task with transactions to state const stateWithTask = reducer( state, apiCreated({ data: taskWithTransactions }) ); expect(stateWithTask.tasks).toEqual({ data: [taskWithTransactions] }); // Update relation between transaction and task const stateWithTaskWithTransaction = reducer( stateWithTask, apiUpdated({ data: transactionWithTask }) ); expect( stateWithTaskWithTransaction.transactions.data[0].relationships.task .data.type ).toEqual(taskWithTransactions.type); const stateWithoutTask = reducer( stateWithTask, apiDeleted(taskWithTransactions) ); const { data: relationship } = stateWithoutTask.transactions.data[0].relationships.task; expect(relationship).toEqual(null); }); it("should update reverse relationship for task", () => { // Add task with transactions to state const stateWithTask = reducer( state, apiCreated({ data: taskWithTransactions }) ); // Update relation between transaction and task // TODO: check relationshiphs on create resource const stateWithTaskWithTransaction = reducer( stateWithTask, apiUpdated({ data: transactionWithTask }) ); expect(stateWithTaskWithTransaction.transactions.data[0].id).toEqual( taskWithTransactions.relationships.transaction.data[0].id ); const stateWithoutTransaction = reducer( stateWithTask, apiDeleted(transactionWithTask) ); const { data: relationship } = stateWithoutTransaction.tasks.data[0].relationships.transaction; expect(relationship).toEqual([]); }); }); }); describe("Endpoint values", () => { it("should default to jsonapi content type and accept headers", () => { const initialState = reducer(undefined, { type: "@@INIT" }); expect(initialState.endpoint.headers).toEqual({ "Content-Type": "application/vnd.api+json", Accept: "application/vnd.api+json" }); }); it("should update provided header, such as an access token", () => { const at = "abcdef0123456789"; const header = { Authorization: `Bearer ${at}` }; expect(state.endpoint.headers).not.toEqual(header); const updatedState = reducer(state, setHeader(header)); expect(updatedState.endpoint.headers).toEqual({ "Content-Type": "application/vnd.api+json", Accept: "application/vnd.api+json", Authorization: `Bearer ${at}` }); }); it("should update to provided custom headers", () => { const headers = { Custom: "headers" }; expect(state.endpoint.headers).not.toEqual(headers); const updatedState = reducer(state, setHeaders(headers)); expect(updatedState.endpoint.headers).toEqual(headers); }); it("should update to provided endpoint host and path", () => { const host = "https://api.example.com"; const path = "/api/v1"; expect(state.endpoint.host).not.toEqual(host); const stateWithHost = reducer(state, setEndpointHost(host)); expect(stateWithHost.endpoint.host).toEqual(host); expect(state.endpoint.path).not.toEqual(path); const stateWithPath = reducer(state, setEndpointPath(path)); expect(stateWithPath.endpoint.path).toEqual(path); }); }); describe("Invalidating flag", () => { it("should set before delete", () => { const updatedState = reducer(state, apiWillDelete(state.users.data[0])); expect(updatedState.users.data[0].isInvalidating).toEqual(IS_DELETING); }); it("should set before update", () => { const updatedState = reducer(state, apiWillUpdate(state.users.data[0])); expect(updatedState.users.data[0].isInvalidating).toEqual(IS_UPDATING); }); it("should be removed after update", () => { const updatedState = reducer( reducer(state, apiWillUpdate(state.users.data[0])), apiUpdated(state.users) ); expect(updatedState.users.data[0].isInvalidating).toBe(undefined); }); }); describe("apiRequest", () => { it("should parse the response body on success", done => { expect.assertions(1); nock("http://foo.com") .get("/fakeurl") .reply(200, { data: 1 }, { "Content-Type": "application/json" }); apiRequest("http://foo.com/fakeurl").subscribe( data => { expect(data).toEqual({ data: 1 }); done(); }, err => done(err) ); }); it("should support vnd.api+json content-type", done => { expect.assertions(1); nock("http://foo.com") .get("/fakeurl") .reply(200, { data: 2 }, { "Content-Type": "application/vnd.api+json" }); apiRequest("http://foo.com/fakeurl").subscribe( data => { expect(data).toEqual({ data: 2 }); done(); }, err => done(err) ); }); it("should return response object when response is 204", done => { expect.assertions(2); nock("http://foo.com") .get("/fakeurl") .reply(204, null, { "Content-Type": "application/json" }); apiRequest("http://foo.com/fakeurl").subscribe( data => { expect(data.response).toEqual(null); expect(data.status).toEqual(204); done(); }, err => done(err) ); }); it("should return response object when response is 404", done => { expect.assertions(2); nock("http://foo.com") .get("/fakeurl") .reply( 404, { error: "not found" }, { "Content-Type": "application/json" } ); apiRequest("http://foo.com/fakeurl").subscribe(noop, err => { expect(err.message).toEqual("ajax error 404"); expect(err.status).toEqual(404); done(); }); }); it("should return Body object when content-type is invalid", done => { expect.assertions(2); nock("http://foo.com") .get("/fakeurl") .reply(200, { data: "foo" }, { "Content-Type": "foo" }); apiRequest("http://foo.com/fakeurl").subscribe( data => { expect(data.response).toEqual({ data: "foo" }); expect(data.status).toEqual(200); done(); }, err => done(err) ); }); it("should return error when response is 500", done => { expect.assertions(2); nock("http://foo.com") .get("/fakeurl") .reply(500, null, { "Content-Type": "application/json" }); apiRequest("http://foo.com/fakeurl").subscribe(noop, err => { expect(err.message).toEqual("ajax error 500"); expect(err.status).toEqual(500); done(); }); }); }); const request1 = { data: [ { type: "articles", id: "1", attributes: { title: "JSON API paints my bikeshed!", body: "The shortest article. Ever.", created: "2015-05-22T14:56:29.000Z", updated: "2015-05-22T14:56:28.000Z" }, relationships: { author: { data: { id: "42", type: "people" } } } } ], included: [ { type: "people", id: "42", attributes: { name: "John", age: 80, gender: "male" }, relationships: { articles: {}, comments: {} } } ] }; const request2 = { data: [ { type: "articles", id: "1", attributes: { title: "JSON API paints my bikeshed!", body: "The shortest article. Ever.", created: "2015-05-22T14:56:29.000Z", updated: "2015-05-22T14:56:28.000Z" }, relationships: { author: {} } } ] }; describe("Relationships without data key should not be reset", () => { it("should append read resources to state", () => { const updatedState = reducer(state, apiRead(request1)); expect(typeof updatedState.articles).toBe("object"); expect(updatedState.articles.data.length).toEqual(1); expect(updatedState.articles.data[0].relationships.author).toEqual({ data: { id: "42", type: "people" } }); const updatedState2 = reducer(updatedState, apiRead(request2)); expect(typeof updatedState2.articles).toBe("object"); expect(updatedState2.articles.data.length).toEqual(1); expect(updatedState2.articles.data[0].relationships.author).toEqual({ data: { id: "42", type: "people" } }); }); }); describe("progress flags", () => { it("should update isUpdating flag properly when update fails", () => { let updatedState = reducer(state, apiWillUpdate(state.users.data[0])); expect(updatedState.isUpdating).toEqual(1); updatedState = reducer( updatedState, apiUpdateFailed({ resource: state.users.data[0] }) ); expect(updatedState.isUpdating).toEqual(0); }); it("should update isDeleting flag properly when delete fails", () => { let updatedState = reducer(state, apiWillDelete(state.users.data[0])); expect(updatedState.isDeleting).toEqual(1); updatedState = reducer( updatedState, apiDeleteFailed({ resource: state.users.data[0] }) ); expect(updatedState.isDeleting).toEqual(0); }); });
using System; using System.Collections.Generic; using System.Text; using ZoDream.Shared.Input; namespace ZoDream.Shared.OS.WinApi.Helpers { internal class CallbackData { public CallbackData(IntPtr wParam, IntPtr lParam) { WParam = wParam; LParam = lParam; } public IntPtr WParam { get; } public IntPtr LParam { get; } } internal delegate bool Callback(CallbackData data); internal delegate bool MouseCallback(MouseEventArgs args); internal delegate bool KeyboardCallback(KeyEventArgs args); }
# react-prog-web-apps Code from Progressive Web Apps with React by S. Domes. Web ISBN-13: 978-1-78829-613-7
package com.google.common.base; import javax.annotation.Nullable; class Joiner$1 extends Joiner { final /* synthetic */ Joiner this$0; final /* synthetic */ String val$nullText; Joiner$1(Joiner joiner, Joiner x0, String str) { this.this$0 = joiner; this.val$nullText = str; super(x0, null); } CharSequence toString(@Nullable Object part) { return part == null ? this.val$nullText : this.this$0.toString(part); } public Joiner useForNull(String nullText) { throw new UnsupportedOperationException("already specified useForNull"); } public Joiner skipNulls() { throw new UnsupportedOperationException("already specified useForNull"); } }
package maryk.rocksdb actual enum class CompactionReason( internal val value: Byte ) { kUnknown(0x0), kLevelL0FilesNum(0x1), kLevelMaxLevelSize(0x2), kUniversalSizeAmplification(0x3), kUniversalSizeRatio(0x4), kUniversalSortedRunNum(0x5), kFIFOMaxSize(0x6), kFIFOReduceNumFiles(0x7), kFIFOTtl(0x8), kManualCompaction(0x9), kFilesMarkedForCompaction(0x10), kBottommostFiles(0x0A), kTtl(0x0B), kFlush(0x0C), kExternalSstIngestion(0x0D); }
# frozen_string_literal: true class Rcm attr_reader :version def initialize(version:) @version = version end def install! if installed? puts "Skipped. The rcm has already installed." return end Brew.installed? ? install_from_brew! : install_from_source! end private def installed? Command.new("which rcup").runnable? end def install_from_brew! Brew.exec! :install, :rcm end def install_from_source! Command.new(<<~BASH).run! curl -LO https://thoughtbot.github.io/rcm/dist/rcm-#{version}.tar.gz && tar -xvf rcm-#{version}.tar.gz && cd rcm-#{version} && ./configure && make && sudo make install BASH end end
--- patternOptions: hugo path: /en/docs/patterns/hugo/options ---
from collections.abc import Iterable as _Iterable from typing import Iterable, Optional, Tuple, Union import numpy import judo from judo.data_types import dtype from judo.functions.api import API from judo.judo_tensor import tensor from judo.typing import Scalar, Tensor class Bounds: """ The :class:`Bounds` implements the logic for defining and managing closed intervals, \ and checking if a numpy array's values are inside a given interval. It is used on a numpy array of a target shape. """ def __init__( self, high: Union[Tensor, Scalar] = numpy.inf, low: Union[Tensor, Scalar] = numpy.NINF, shape: Optional[tuple] = None, dtype: Optional[type] = None, ): """ Initialize a :class:`Bounds`. Args: high: Higher value for the bound interval. If it is an typing_.Scalar \ it will be applied to all the coordinates of a target vector. \ If it is a vector, the bounds will be checked coordinate-wise. \ It defines and closed interval. low: Lower value for the bound interval. If it is a typing_.Scalar it \ will be applied to all the coordinates of a target vector. \ If it is a vector, the bounds will be checked coordinate-wise. \ It defines and closed interval. shape: Shape of the array that will be bounded. Only needed if `high` and `low` are \ vectors and it is used to define the dimensions that will be bounded. dtype: Data type of the array that will be bounded. It can be inferred from `high` \ or `low` (the type of `high` takes priority). Examples: Initializing :class:`Bounds` using numpy arrays: >>> import numpy >>> high, low = numpy.ones(3, dtype=float), -1 * numpy.ones(3, dtype=int) >>> bounds = Bounds(high=high, low=low) >>> print(bounds) Bounds shape float64 dtype (3,) low [-1 -1 -1] high [1. 1. 1.] Initializing :class:`Bounds` using typing_.Scalars: >>> import numpy >>> high, low, shape = 4, 2.1, (5,) >>> bounds = Bounds(high=high, low=low, shape=shape) >>> print(bounds) Bounds shape float64 dtype (5,) low [2.1 2.1 2.1 2.1 2.1] high [4. 4. 4. 4. 4.] """ # Infer shape if not specified if shape is None and hasattr(high, "shape"): shape = high.shape elif shape is None and hasattr(low, "shape"): shape = low.shape elif shape is None: raise TypeError("If shape is None high or low need to have .shape attribute.") # High and low will be arrays of target shape if not judo.is_tensor(high): high = tensor(high) if isinstance(high, _Iterable) else API.ones(shape) * high if not judo.is_tensor(low): low = tensor(low) if isinstance(low, _Iterable) else API.ones(shape) * low self.high = judo.astype(high, dtype) self.low = judo.astype(low, dtype) if dtype is not None: self.dtype = dtype elif hasattr(high, "dtype"): self.dtype = high.dtype elif hasattr(low, "dtype"): self.dtype = low.dtype else: self.dtype = type(high) if high is not None else type(low) def __repr__(self): return "{} shape {} dtype {} low {} high {}".format( self.__class__.__name__, self.dtype, self.shape, self.low, self.high, ) def __len__(self) -> int: """Return the number of dimensions of the bounds.""" return len(self.high) @property def shape(self) -> Tuple: """ Get the shape of the current bounds. Returns: tuple containing the shape of `high` and `low` """ return self.high.shape @classmethod def from_tuples(cls, bounds: Iterable[tuple]) -> "Bounds": """ Instantiate a :class:`Bounds` from a collection of tuples containing \ the higher and lower bounds for every dimension as a tuple. Args: bounds: Iterable that returns tuples containing the higher and lower \ bound for every dimension of the target bounds. Returns: :class:`Bounds` instance. Examples: >>> intervals = ((-1, 1), (-2, 1), (2, 3)) >>> bounds = Bounds.from_tuples(intervals) >>> print(bounds) Bounds shape int64 dtype (3,) low [-1 -2 2] high [1 1 3] """ low, high = [], [] for lo, hi in bounds: low.append(lo) high.append(hi) low, high = tensor(low, dtype=dtype.float), tensor(high, dtype=dtype.float) return Bounds(low=low, high=high) @staticmethod def get_scaled_intervals( low: Union[Tensor, float, int], high: Union[Tensor, float, int], scale: float, ) -> Tuple[Union[Tensor, float], Union[Tensor, float]]: """ Scale the high and low vectors by an scale factor. The value of the high and low will be proportional to the maximum and minimum values of \ the array. Scale defines the proportion to make the bounds bigger and smaller. For \ example, if scale is 1.1 the higher bound will be 10% higher, and the lower bounds 10% \ smaller. If scale is 0.9 the higher bound will be 10% lower, and the lower bound 10% \ higher. If scale is one, `high` and `low` will be equal to the maximum and minimum values \ of the array. Args: high: Higher bound to be scaled. low: Lower bound to be scaled. scale: Value representing the tolerance in percentage from the current maximum and \ minimum values of the array. Returns: :class:`Bounds` instance. """ pct = tensor(scale - 1) big_scale = 1 + API.abs(pct) small_scale = 1 - API.abs(pct) zero = judo.astype(tensor(0.0), low.dtype) if pct > 0: xmin_scaled = API.where(low < zero, low * big_scale, low * small_scale) xmax_scaled = API.where(high < zero, high * small_scale, high * big_scale) else: xmin_scaled = API.where(low < zero, low * small_scale, low * small_scale) xmax_scaled = API.where(high < zero, high * big_scale, high * small_scale) return xmin_scaled, xmax_scaled @classmethod def from_array(cls, x: Tensor, scale: float = 1.0) -> "Bounds": """ Instantiate a bounds compatible for bounding the given array. It also allows to set a \ margin for the high and low values. The value of the high and low will be proportional to the maximum and minimum values of \ the array. Scale defines the proportion to make the bounds bigger and smaller. For \ example, if scale is 1.1 the higher bound will be 10% higher, and the lower bounds 10% \ smaller. If scale is 0.9 the higher bound will be 10% lower, and the lower bound 10% \ higher. If scale is one, `high` and `low` will be equal to the maximum and minimum values \ of the array. Args: x: Numpy array used to initialize the bounds. scale: Value representing the tolerance in percentage from the current maximum and \ minimum values of the array. Returns: :class:`Bounds` instance. Examples: >>> import numpy >>> x = numpy.ones((3, 3)) >>> x[1:-1, 1:-1] = -5 >>> bounds = Bounds.from_array(x, scale=1.5) >>> print(bounds) Bounds shape float64 dtype (3,) low [ 0.5 -7.5 0.5] high [1.5 1.5 1.5] """ xmin, xmax = API.min(x, axis=0), API.max(x, axis=0) xmin_scaled, xmax_scaled = cls.get_scaled_intervals(xmin, xmax, scale) return Bounds(low=xmin_scaled, high=xmax_scaled) def clip(self, x: Tensor) -> Tensor: """ Clip the values of the target array to fall inside the bounds (closed interval). Args: x: Numpy array to be clipped. Returns: Clipped numpy array with all its values inside the defined bounds. """ return API.clip(judo.astype(x, dtype.float), self.low, self.high) def points_in_bounds(self, x: Tensor) -> Union[Tensor, bool]: """ Check if the rows of the target array have all their coordinates inside \ specified bounds. If the array is one dimensional it will return a boolean, otherwise a vector of booleans. Args: x: Array to be checked against the bounds. Returns: Numpy array of booleans indicating if a row lies inside the bounds. """ match = self.clip(x) == judo.astype(x, dtype.float) return match.all(1).flatten() if len(match.shape) > 1 else match.all() def safe_margin( self, low: Union[Tensor, Scalar] = None, high: Optional[Union[Tensor, Scalar]] = None, scale: float = 1.0, ) -> "Bounds": """ Initialize a new :class:`Bounds` with its bounds increased o decreased \ by an scale factor. This is done multiplying both high and low for a given factor. The value of the new \ high and low will be proportional to the maximum and minimum values of \ the array. Scale defines the proportion to make the bounds bigger and smaller. For \ example, if scale is 1.1 the higher bound will be 10% higher, and the lower bounds 10% \ smaller. If scale is 0.9 the higher bound will be 10% lower, and the lower bound 10% \ higher. If scale is one, `high` and `low` will be equal to the maximum and minimum values \ of the array. Args: high: Used to scale the `high` value of the current instance. low: Used to scale the `low` value of the current instance. scale: Value representing the tolerance in percentage from the current maximum and \ minimum values of the array. Returns: :class:`Bounds` with scaled high and low values. """ xmax = self.high if high is None else high xmin = self.low if low is None else low xmin_scaled, xmax_scaled = self.get_scaled_intervals(xmin, xmax, scale) return Bounds(low=xmin_scaled, high=xmax_scaled) def to_tuples(self) -> Tuple[Tuple[Scalar, Scalar], ...]: """ Return a tuple of tuples containing the lower and higher bound for each \ coordinate of the :class:`Bounds` shape. Returns: Tuple of the form ((x0_low, x0_high), (x1_low, x1_high), ...,\ (xn_low, xn_high)) Examples: >>> import numpy >>> array = numpy.array([1, 2, 5]) >>> bounds = Bounds(high=array, low=-array) >>> print(bounds.to_tuples()) ((-1, 1), (-2, 2), (-5, 5)) """ return tuple([dim for dim in zip(self.low, self.high)])
# frozen_string_literal: true # require 'data_importable' class DataImportTeam < ApplicationRecord include DataImportable belongs_to :user # [Steve, 20120212] Do not validate associated user! belongs_to :team, foreign_key: 'conflicting_id', optional: true validates :import_text, presence: true belongs_to :data_import_city, optional: true belongs_to :city, optional: true # City can be null especially in Teams added by data-import validates :name, presence: { length: { within: 1..60 }, allow_nil: false } # XXX [Steve, 20130925] :badge_number can be used as a temporary storage # for a team_affiliations.number found during data-import parsing, # skipping the need for a dedicated team_affiliations temp. table: validates :badge_number, length: { maximum: 40 } scope :sort_by_conflicting_rows_id, ->(dir) { order("conflicting_id #{dir}") } scope :sort_by_user, ->(dir) { order("users.name #{dir}, data_import_teams.name #{dir}") } scope :sort_by_city, ->(dir) { order("cities.name #{dir}, data_import_teams.name #{dir}") } delegate :name, to: :user, prefix: true # attr_accessible :data_import_session_id, :conflicting_id, :import_text, # :name, :badge_number, :data_import_city_id, :city_id, :user_id #-- ------------------------------------------------------------------------- #++ # Computes a shorter description for the name associated with this data def get_full_name name end # Computes a verbose or formal description for the name associated with this data def get_verbose_name "#{name}#{(city ? ', ' + city.get_full_name : (data_import_city ? ', ' + data_import_city.get_full_name : ''))}" end # Retrieves the user name associated with this instance def user_name user ? user.name : '' end # ---------------------------------------------------------------------------- end
 CREATE function RangeExecuteError (@Uname nvarchar(20)) returns table as return select case when ExecUsedTime < 6 then ExecUsedTime when cast(ExecUsedTime/10 as int)*10 > 50 then 9999 else (cast(ExecUsedTime/10 as int)*10)+10 end as xRange, 0 as SuccessCount, 1 as ErrorCount from plannings.dbo.tbl_102userExecMyprogTimeout where Uname like @Uname + '%'
// // Attachment+FICAttachment.h // Mage // // #import "Attachment.h" #import "FICEntity.h" extern NSString *const AttachmentFamily; extern NSString *const AttachmentSmallSquare; extern NSString *const AttachmentMediumSquare; extern CGSize const AttachmentSquareImageSize; extern CGSize const AttachmentiPadSquareImageSize; @interface Attachment (Thumbnail) <FICEntity> @end
import { execute, GraphQLSchema, parse } from 'graphql'; import { join } from 'path'; import { loadGraphQLSchemaFromOpenAPI } from '../src/loadGraphQLSchemaFromOpenAPI'; import { printSchemaWithDirectives } from '@graphql-tools/utils'; import { fetch } from 'cross-undici-fetch'; import { startServer, stopServer } from '../../../handlers/openapi/test/example_api_server'; const PORT = 3010; const oasFilePath = join(__dirname, '../../../handlers/openapi/test/fixtures/example_oas_combined.json'); const baseUrl = `http://localhost:${PORT}/api`; describe('Example API Combined', () => { let createdSchema: GraphQLSchema; beforeAll(async () => { await startServer(PORT); createdSchema = await loadGraphQLSchemaFromOpenAPI('test', { oasFilePath, baseUrl, fetch, }); }); afterAll(async () => { await stopServer(); }); it('should generate correct schema', () => { expect(printSchemaWithDirectives(createdSchema)).toMatchSnapshot('example_oas_combined-schema'); }); it('should handle allOf correctly', async () => { const query = /* GraphQL */ ` query { getAllCars { model } } `; const result = await execute({ schema: createdSchema, document: parse(query), }); expect(result).toMatchSnapshot('example_oas_combined-query-result'); }); });
(function() { 'use strict'; function ServerCommService(appConfig, $http) { this.update = function(dataType, id, data) { return $http.put(appConfig.restUrl + dataType + '/' + id, data) .then(function(response) { return response.data; }); }; this.add = function(dataType, data) { return $http.post(appConfig.restUrl + dataType, data) .then(function(response) { return response.data; }); }; this.getAll = function(dataType) { return $http.get(appConfig.restUrl + dataType) .then(function(response) { return response.data; }); }; this.remove = function(dataType, id) { return $http.delete(appConfig.restUrl + dataType + '/' + id); }; } ServerCommService.$inject = ['appConfig', '$http']; angular.module('app.common') .service('serverCommService', ServerCommService); })();
# Copyright (c) 2015, Plume Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the Plume Design Inc. nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Plume Design Inc. BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ############################################################################### # # version-lib.sh - provides version data for image creation # (meant to be sourced) # # # Interface of version.lib.sh # --------------------------- # # input: # CURDIR # OPENSYNC_TARGET_VERSION_OVERRIDE # VERSION_TARGET # TARGET # VENDOR_DIR # VERSION_FILE # BUILD_NUMBER # IMAGE_DEPLOYMENT_PROFILE # LAYER_LIST # VER_DATE # VERSION_APPEND # VERSION_APPEND_END # # output: # SHA1 (sha1 of git repository used to build) # DIRTY_STRING (local modifications string) # VERSION (target/product version) # USERNAME (user used to build the image) # HOSTNAME (hostname used to build the image) # VER_DATE (date of image build) # APP_VERSION (application version string) # BUILD_NUMBER (consecutive build number) # OSYNC_VERSION (OpenSync version - core/.version) # # Full version format: # VERSION-BUILD_NUMBER-gSHA1-DIRTY_STRING-VERSION_APPEND-IMAGE_DEPLOYMENT_PROFILE-VERSION_APPEND_END # # Version number uses the first defined value from the below list: # 1. env. var. $OPENSYNC_TARGET_VERSION_OVERRIDE # 2. file $VENDOR_DIR/.version.$VERSION_TARGET # 3. file $VENDOR_DIR/.version.$TARGET # 4. file $VENDOR_DIR/.version # 5. file core/.version if [ -z "$CURDIR" ]; then CURDIR=`dirname $0` fi cd ${CURDIR}/../../../ if [ -e .git -o -e ../.git ]; then SHA1='g'`[ -e ../.git ] && cd ..; git log --pretty=oneline --abbrev-commit -1 | awk '{ print $1 }' | cut -b1-7` DIRTY=`[ -e ../.git ] && cd ..; git status --porcelain | grep -v -e '^??' | wc -l` else echo "WARNING: version not in git" 1>&2 SHA1="notgit" DIRTY=0 fi # per vendor/product versioning: if [ -z "$VERSION_FILE" ]; then VERSION_FILE="$VENDOR_DIR/.version.$VERSION_TARGET" if [ ! -f "$VERSION_FILE" ]; then VERSION_FILE="$VENDOR_DIR/.version.$TARGET" fi if [ ! -f "$VERSION_FILE" ]; then VERSION_FILE="$VENDOR_DIR/.version" fi if [ ! -f "$VERSION_FILE" ]; then VERSION_FILE=".version" fi fi if [ -n "$OPENSYNC_TARGET_VERSION_OVERRIDE" ]; then VERSION="$OPENSYNC_TARGET_VERSION_OVERRIDE" else VERSION=`cat $VERSION_FILE` fi OSYNC_VERSION=`cat .version` DIRTY_STRING="" if [ ${DIRTY} -ne 0 ]; then DIRTY_STRING="-mods" fi USERNAME=`id -n -u` HOSTNAME=`hostname` if [ -z "$VER_DATE" ]; then VER_DATE=`date` fi # First see if BUILD_NUMBER is defined in environment by Jenkins, # then try to find it in file, and if not found use 0 if [ -z "${BUILD_NUMBER}" ]; then if [ -f "${CURDIR}/../../../.buildnum" ]; then BUILD_NUMBER=`cat ${CURDIR}/../../../.buildnum` fi fi if [ -z "${BUILD_NUMBER}" ]; then BUILD_NUMBER="0" fi APP_VERSION="${VERSION}" if [ "${VERSION_NO_BUILDNUM}" != "1" ]; then # append build number APP_VERSION="${APP_VERSION}-${BUILD_NUMBER}" fi if [ "${VERSION_NO_SHA1}" != "1" ]; then # append SHA1 APP_VERSION="${APP_VERSION}-${SHA1}" fi if [ "${VERSION_NO_MODS}" != "1" ]; then # append dirty string APP_VERSION="${APP_VERSION}${DIRTY_STRING}" fi if [ -n "${VERSION_APPEND}" ]; then # append custom string before profile APP_VERSION="${APP_VERSION}-${VERSION_APPEND}" fi # append profile if [ "${VERSION_NO_PROFILE}" != "1" ]; then if [ -z "${IMAGE_DEPLOYMENT_PROFILE}" ]; then IMAGE_DEPLOYMENT_PROFILE="development" fi if [ -n "${IMAGE_DEPLOYMENT_PROFILE}" -a "${IMAGE_DEPLOYMENT_PROFILE}" != "none" ]; then APP_VERSION="${APP_VERSION}-${IMAGE_DEPLOYMENT_PROFILE}" fi fi if [ -n "${VERSION_APPEND_END}" ]; then # append custom string after profile APP_VERSION="${APP_VERSION}-${VERSION_APPEND_END}" fi cd - >/dev/null
/* * Copyright 2019 New Vector Ltd * * 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 im.vector.fragments.verification import android.os.Bundle import android.view.ViewGroup import android.widget.TextView import androidx.core.view.isInvisible import androidx.core.view.isVisible import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import butterknife.BindView import butterknife.OnClick import im.vector.R import im.vector.fragments.VectorBaseFragment import org.matrix.androidsdk.crypto.rest.model.crypto.KeyVerificationStart import org.matrix.androidsdk.crypto.verification.IncomingSASVerificationTransaction import org.matrix.androidsdk.crypto.verification.OutgoingSASVerificationRequest class SASVerificationShortCodeFragment : VectorBaseFragment() { private lateinit var viewModel: SasVerificationViewModel companion object { fun newInstance() = SASVerificationShortCodeFragment() } @BindView(R.id.sas_decimal_code) lateinit var decimalTextView: TextView @BindView(R.id.sas_emoji_description) lateinit var descriptionTextView: TextView @BindView(R.id.sas_emoji_grid) lateinit var emojiGrid: ViewGroup @BindView(R.id.emoji0) lateinit var emoji0View: ViewGroup @BindView(R.id.emoji1) lateinit var emoji1View: ViewGroup @BindView(R.id.emoji2) lateinit var emoji2View: ViewGroup @BindView(R.id.emoji3) lateinit var emoji3View: ViewGroup @BindView(R.id.emoji4) lateinit var emoji4View: ViewGroup @BindView(R.id.emoji5) lateinit var emoji5View: ViewGroup @BindView(R.id.emoji6) lateinit var emoji6View: ViewGroup override fun getLayoutResId() = R.layout.fragment_sas_verification_display_code override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = activity?.run { ViewModelProviders.of(this).get(SasVerificationViewModel::class.java) } ?: throw Exception("Invalid Activity") viewModel.transaction?.let { if (it.supportsEmoji()) { val emojicodes = it.getEmojiCodeRepresentation(it.shortCodeBytes!!) emojicodes.forEachIndexed { index, emojiRepresentation -> when (index) { 0 -> { emoji0View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji emoji0View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId) } 1 -> { emoji1View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji emoji1View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId) } 2 -> { emoji2View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji emoji2View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId) } 3 -> { emoji3View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji emoji3View.findViewById<TextView>(R.id.item_emoji_name_tv)?.setText(emojiRepresentation.nameResId) } 4 -> { emoji4View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji emoji4View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId) } 5 -> { emoji5View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji emoji5View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId) } 6 -> { emoji6View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji emoji6View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId) } } } } //decimal is at least supported decimalTextView.text = it.getShortCodeRepresentation(KeyVerificationStart.SAS_MODE_DECIMAL) if (it.supportsEmoji()) { descriptionTextView.text = getString(R.string.sas_emoji_description) decimalTextView.isVisible = false emojiGrid.isVisible = true } else { descriptionTextView.text = getString(R.string.sas_decimal_description) decimalTextView.isVisible = true emojiGrid.isInvisible = true } } viewModel.transactionState.observe(this, Observer { if (viewModel.transaction is IncomingSASVerificationTransaction) { val uxState = (viewModel.transaction as IncomingSASVerificationTransaction).uxState when (uxState) { IncomingSASVerificationTransaction.State.SHOW_SAS -> { viewModel.loadingLiveEvent.value = null } IncomingSASVerificationTransaction.State.VERIFIED -> { viewModel.loadingLiveEvent.value = null viewModel.deviceIsVerified() } IncomingSASVerificationTransaction.State.CANCELLED_BY_ME, IncomingSASVerificationTransaction.State.CANCELLED_BY_OTHER -> { viewModel.loadingLiveEvent.value = null viewModel.navigateCancel() } else -> { viewModel.loadingLiveEvent.value = R.string.sas_waiting_for_partner } } } else if (viewModel.transaction is OutgoingSASVerificationRequest) { val uxState = (viewModel.transaction as OutgoingSASVerificationRequest).uxState when (uxState) { OutgoingSASVerificationRequest.State.SHOW_SAS -> { viewModel.loadingLiveEvent.value = null } OutgoingSASVerificationRequest.State.VERIFIED -> { viewModel.loadingLiveEvent.value = null viewModel.deviceIsVerified() } OutgoingSASVerificationRequest.State.CANCELLED_BY_ME, OutgoingSASVerificationRequest.State.CANCELLED_BY_OTHER -> { viewModel.loadingLiveEvent.value = null viewModel.navigateCancel() } else -> { viewModel.loadingLiveEvent.value = R.string.sas_waiting_for_partner } } } }) } @OnClick(R.id.sas_request_continue_button) fun didAccept() { viewModel.confirmEmojiSame() } @OnClick(R.id.sas_request_cancel_button) fun didCancel() { viewModel.cancelTransaction() } }
package hmmlearn.base import breeze.linalg.{DenseMatrix, DenseVector} import breeze.numerics.log import hmmlearn.MultinomialHMM import org.scalatest.{FlatSpec, Matchers} class MutinomialHMMTest extends FlatSpec with Matchers { "computeLogLikelihood" should "produce the right results" in { val X = DenseVector(1, 0, 3, 5, 2, 4, 1) val emissionProb = DenseMatrix( (0.5, 0.1, 0.1, 0.1, 0.1, 0.1), (0.2, 0.2, 0.1, 0.05, 0.0, 0.45) ) val model = new MultinomialHMM( nComponents = 4, nFeatures = 10, emissionProbPrior = Some(emissionProb) ) val logLikelihood = model.computeLogLikelihood(X) logLikelihood shouldBe DenseMatrix( (-2.3025850929940455, -1.6094379124341003), (-0.6931471805599453, -1.6094379124341003), (-2.3025850929940455, -2.995732273553991), (-2.3025850929940455, -0.7985076962177716), (-2.3025850929940455, -2.3025850929940455), (-2.3025850929940455, Double.NegativeInfinity), (-2.3025850929940455, -1.6094379124341003) ) } "initialiseSufficientStatistics" should "return an empty stats tuple" in { val nComponents = 10 val nFeatures = 30 val model = new MultinomialHMM(nComponents, nFeatures) val stats = model.initialiseSufficientStatistics stats._1 shouldBe 0 stats._2 shouldBe DenseVector.zeros[Double](nComponents) stats._3 shouldBe DenseMatrix.zeros[Double](nComponents, nComponents) stats._4 shouldBe DenseMatrix.zeros[Double](nComponents, nFeatures) } "accumulateSufficientStatistics" should "produce the right results with 'ste' in params" in { val nComponents: Int = 4 val nFeatures: Int = 5 val startProb: Option[DenseVector[Double]] = Some(DenseVector(0.2, 0.05, 0.6, 0.15)) val transMat: Option[DenseMatrix[Double]] = Some(DenseMatrix( (0.8, 0.1, 0.05, 0.05), (0.1, 0.7, 0.15, 0.05), (0.05, 0.1, 0.6, 0.25), (0.1, 0.05, 0.1, 0.75) )) val model = new MultinomialHMM( nComponents = nComponents, nFeatures = nFeatures, startProbPrior = startProb, transMatPrior = transMat ) val stats = new BaseHMM.Stats( 0, DenseVector.zeros[Double](nComponents), DenseMatrix.zeros[Double](nComponents, nComponents), DenseMatrix.zeros[Double](nComponents, nFeatures) ) val X = DenseVector[Int](1, 4, 3) val frameLogProb = log(DenseMatrix( (0.05, 0.01, 0.90, 0.04), (0.85, 0.02, 0.03, 0.10), (0.12, 0.03, 0.80, 0.05) )) val (loss, fwdLattice) = BaseHMM.doForwardPass(frameLogProb, startProb.get, transMat.get) val bwdLattice = BaseHMM.doBackwardPass(frameLogProb, startProb.get, transMat.get) val posteriors = BaseHMM.computePosteriors(fwdLattice, bwdLattice) val results = model.accumulateSufficientStatistics(stats, X, frameLogProb, posteriors, fwdLattice, bwdLattice) results._1 shouldBe 1 results._2 shouldBe DenseVector(0.0875428779442073, 7.649747594083709E-4, 0.8990820470485451, 0.012610100247838865) results._3 shouldBe DenseMatrix( (0.3460338435828014, 0.008403828460401856, 0.10901692000368499, 0.007357009133607575), (0.0017313803953611694, 0.0021865104888357995, 0.012039226730239348, 2.779898052155163E-4), (0.2955055316675138, 0.01762739164947898, 0.8542689284325417, 0.16897852768979024), (0.021470019698952052, 0.001960833716900792, 0.10093684687270144, 0.052205211671974075) ) results._4 shouldBe DenseMatrix( (0.0, 0.0875428779442073, 0.0, 0.2814720521083398, 0.3832687232362885), (0.0, 7.649747594083709E-4, 0.0, 0.014708431655373989, 0.015470132660243439), (0.0, 0.8990820470485451, 0.0, 0.6389635896483882, 0.437298332390779), (0.0, 0.012610100247838865, 0.0, 0.06485592658789807, 0.16396281171268937) ) } it should "produce the right results without 'ste' in params" in { val nComponents: Int = 4 val nFeatures: Int = 5 val startProb: Option[DenseVector[Double]] = Some(DenseVector(0.2, 0.05, 0.6, 0.15)) val transMat: Option[DenseMatrix[Double]] = Some(DenseMatrix( (0.8, 0.1, 0.05, 0.05), (0.1, 0.7, 0.15, 0.05), (0.05, 0.1, 0.6, 0.25), (0.1, 0.05, 0.1, 0.75) )) val model = new MultinomialHMM( nComponents = nComponents, nFeatures = nFeatures, params = "" ) val stats = new BaseHMM.Stats( 0, DenseVector.zeros[Double](nComponents), DenseMatrix.zeros[Double](nComponents, nComponents), DenseMatrix.zeros[Double](nComponents, nFeatures) ) val X = DenseVector[Int](1, 4, 3) val frameLogProb = log(DenseMatrix( (0.05, 0.01, 0.90, 0.04), (0.85, 0.02, 0.03, 0.10), (0.12, 0.03, 0.80, 0.05) )) val (loss, fwdLattice) = BaseHMM.doForwardPass(frameLogProb, startProb.get, transMat.get) val bwdLattice = BaseHMM.doBackwardPass(frameLogProb, startProb.get, transMat.get) val posteriors = BaseHMM.computePosteriors(fwdLattice, bwdLattice) val results = model.accumulateSufficientStatistics(stats, X, frameLogProb, posteriors, fwdLattice, bwdLattice) results._1 shouldBe 1 results._2 shouldBe DenseVector.zeros[Double](nComponents) results._3 shouldBe DenseMatrix.zeros[Double](nComponents, nComponents) results._4 shouldBe DenseMatrix.zeros[Double](nComponents, nFeatures) } "scoreSamples" should "compute the right logProb and posteriors" in { val nComponents: Int = 4 val nFeatures: Int = 5 val startProb: Option[DenseVector[Double]] = Some(DenseVector(0.2, 0.05, 0.6, 0.15)) val transMat: Option[DenseMatrix[Double]] = Some(DenseMatrix( (0.8, 0.1, 0.05, 0.05), (0.1, 0.7, 0.15, 0.05), (0.05, 0.1, 0.6, 0.25), (0.1, 0.05, 0.1, 0.75) )) val emissionProb: Option[DenseMatrix[Double]] = Some(DenseMatrix( (0.2, 0.2, 0.2, 0.2, 0.2), (0.1, 0.05, 0.3, 0.05, 0.5), (0.3, 0.3, 0.1, 0.1, 0.1), (0.2, 0.3, 0.1, 0.2, 0.2) )) val model = new MultinomialHMM( nComponents = nComponents, nFeatures = nFeatures, startProbPrior = startProb, transMatPrior = transMat, emissionProbPrior = emissionProb ) val X = DenseVector(1, 0, 3, 3, 2, 1, 0) val lengths = DenseVector(4, 3) val (logProb, posteriors) = model.scoreSamples(X, Some(lengths)) logProb shouldBe -11.537757324381989 posteriors shouldBe DenseMatrix( (0.15503780311906423, 0.004216295917615701, 0.6560422976892534, 0.18470360327406654), (0.1944797184015473, 0.017634949905384653, 0.43567362835023016 , .35221170334283775), (0.2640155481027297, 0.018776587941909922, 0.19426734014916416, 0.5229405238061958), (0.31222457195394043, 0.030482784874890947, 0.13275697401283462, 0.5245356691583336), (0.2366118706648984, 0.05335216051444001, 0.5774856172421355, 0.1325503515785257), (0.2262314789195997, 0.023518075047942545, 0.47799414194804085, 0.27225630408441687), (0.23455105759781697, 0.04871533111350695, 0.40869930256742987, 0.30803430872124643) ) } }
export const LANDING = "LANDING"; export const MAIN = "MAIN"; export const LOGIN = "LOGIN"; export const CATEGORY = "CATEGORY"; export const HOME = "HOME"; export const PRODUCT_LIST = "PRODUCT_LIST"; export const PRODUCT_DETAIL = "PRODUCT_DETAIL";
;;; ida.lisp ;;;; Iterative Deepening A* (IDA*) Search (defun tree-ida*-search (problem) "Iterative Deepening Tree-A* Search [p 107]." ;; The main loop does a series of f-cost-bounded depth-first ;; searches until a solution is found. After each search, the f-cost ;; bound is increased to the smallest f-cost value found that ;; exceeds the previous bound. Note that the variables here are ;; local, not static as on [p 107]. (setf (problem-iterative? problem) t) (let* ((root (create-start-node problem)) (f-limit (node-f-cost root)) (solution nil)) (loop (multiple-value-setq (solution f-limit) (DFS-contour root problem f-limit)) (dprint "DFS-contour returned" solution "at" f-limit) (if (not (null solution)) (RETURN solution)) (if (= f-limit infinity) (RETURN nil))))) (defun DFS-contour (node problem f-limit) "Return a solution and a new f-cost limit." (let ((next-f infinity)) (cond ((> (node-f-cost node) f-limit) (values nil (node-f-cost node))) ((goal-test problem (node-state node)) (values node f-limit)) (t (for each s in (expand node problem) do (multiple-value-bind (solution new-f) (DFS-contour s problem f-limit) (if (not (null solution)) (RETURN-FROM DFS-contour (values solution f-limit))) (setq next-f (min next-f new-f)))) (values nil next-f)))))
// Copyright (c) 2019, 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. // test w/ `dart test -N sort_child_properties_last` // ignore_for_file: prefer_expression_function_bodies import 'package:flutter/widgets.dart'; class W0 extends Widget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Center(), // OK ), ); } } class W1 extends Widget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Center(), // LINT key: 0, ), ); } } class W2 extends Widget { @override Widget build(BuildContext context) { return Scaffold( body: Center( key: 0, child: Center(), // OK ), ); } } class W3 extends Widget { @override Widget build(BuildContext context) { return Scaffold( body: Center( key: 0, child: Center( child: Column( key: 0, children: [], // OK ), ), ), ); } } class W4 extends Widget { @override Widget build(BuildContext context) { return Scaffold( body: Center( key: 0, child: Center( child: Column( children: [], // LINT key: 0, ), ), ), ); } } /// see: https://dart-review.googlesource.com/c/sdk/+/161624 nestedChildren() { Column( children: [ // LINT Column( children: [ // LINT Text('a'), ], crossAxisAlignment: CrossAxisAlignment.center, ), Text('b'), Text('c'), Text('d'), ], crossAxisAlignment: CrossAxisAlignment.center, ); } class WithClosure extends Widget { @override Widget build(BuildContext context) { return Scaffold( body: Center( key: 0, child: Center( // OK child: Column( key: 0, children: [], ), ), onPress: () { // some code }, ), ); } } class WithSeveralWidgetCreation extends Widget { WithSeveralWidgetCreation({ this.header, this.child, this.boldFooter, this.onFooterClick, this.footer, }); final Widget? header; final Widget? child; final bool? boldFooter; final void Function()? onFooterClick; final Widget? footer; @override Widget build(BuildContext context) { WithSeveralWidgetCreation( header: Text('a'), child: Text('b'), // OK footer: Text('c'), // LINT boldFooter: true, ); WithSeveralWidgetCreation( header: Text('a'), child: Text('b'), // OK footer: Text('c'), // OK onFooterClick: (){}, ); return null; } }
#!perl use strict; use warnings; use FindBin; BEGIN { require "$FindBin::Bin/test-helper-operation.pl" } expect_operation_object_upload_create ( 'Client / named arguments' => \& client_object_upload_create_named_arguments, 'Client / configuration hash' => \& client_object_upload_create_configuration_hash, ); had_no_warnings; done_testing; sub client_object_upload_create_named_arguments { my (%args) = @_; build_default_client_bucket (%args) ->object ( key => delete $args{key}, (exists $args{encryption} ? (encryption => delete $args{encryption}) : ()), (exists $args{object_acl} ? (acl => delete $args{object_acl}) : ()), ) ->initiate_multipart_upload (%args) ; } sub client_object_upload_create_configuration_hash { my (%args) = @_; build_default_client_bucket (%args) ->object ( key => delete $args{key}, (exists $args{encryption} ? (encryption => delete $args{encryption}) : ()), (exists $args{object_acl} ? (acl => delete $args{object_acl}) : ()), ) ->initiate_multipart_upload (\ %args) ; } sub expect_operation_object_upload_create { expect_operation_plan implementations => +{ @_ }, expect_operation => 'Net::Amazon::S3::Operation::Object::Upload::Create', plan => { "create upload with object acl" => { act_arguments => [ bucket => 'bucket-name', key => 'some-key', object_acl => 'private', ], expect_arguments => { bucket => 'bucket-name', key => 'some-key', encryption => undef, acl => obj_isa ('Net::Amazon::S3::ACL::Canned'), }, }, "create upload with overloaded acl" => { act_arguments => [ bucket => 'bucket-name', key => 'some-key', acl => 'private', ], expect_arguments => { bucket => 'bucket-name', key => 'some-key', encryption => undef, acl => 'private', }, }, "create upload with acl_short" => { act_arguments => [ bucket => 'bucket-name', key => 'some-key', acl_short => 'private', ], expect_arguments => { bucket => 'bucket-name', key => 'some-key', encryption => undef, acl => 'private', }, }, "create upload with additional headers" => { act_arguments => [ bucket => 'bucket-name', key => 'some-key', headers => { x_amz_meta_additional => 'additional-header' }, ], expect_arguments => { bucket => 'bucket-name', key => 'some-key', encryption => undef, headers => { x_amz_meta_additional => 'additional-header' }, }, }, "create upload with server-side encoding" => { act_arguments => [ bucket => 'bucket-name', key => 'some-key', encryption => 'AES256', ], expect_arguments => { bucket => 'bucket-name', key => 'some-key', encryption => 'AES256', }, }, } }
package ADAMK::Dancer2::Twittersect::Twitter; use 5.010; use strict; use warnings; use Try::Tiny 0.22; use YAML::Tiny 1.50 (); use Params::Util 1.04 ':ALL'; use Net::Twitter 4.01010 (); use ADAMK::Dancer2::Twittersect::Exception; use Object::Tiny 1.08 qw{ consumer_api consumer_secret access_token twitter }; our $VERSION = '0.01'; # Convenience function sub throw ($) { ADAMK::Dancer2::Twittersect::Exception->throw(shift); } sub new { my $class = shift; my $file = shift; # Is the config even roughly correct my $yaml = YAML::Tiny->read($file); unless ($yaml->[0] and _HASH($yaml->[0])) { die "Config file does not have keys"; } my $self = $class->SUPER::new( %{$yaml->[0]} ); # Validate unless ($self->consumer_api) { die "Config file does not provide a consumer_api"; } unless ($self->consumer_secret) { die "Config file does not provide a consumer_secret"; } # Create the twitter connector $self->{twitter} = Net::Twitter->new( traits => ["API::RESTv1_1", "AppAuth"], consumer_key => $self->consumer_api, consumer_secret => $self->consumer_secret, ); # Get the Application-Only access token $self->{access_token} = $self->twitter->request_access_token; return $self; } sub get_intersected_followers { my $self = shift; my $name1 = shift; my $name2 = shift; # Get the followers my $followers1 = $self->get_followers_by_id($name1); my $followers2 = $self->get_followers_by_id($name2); # Find the intersection my %filter = map { $_ => 1 } @$followers1; my @intersect = grep { $filter{$_} } @$followers1; # Get the user information return $self->get_users_by_id(@intersect); } ###################################################################### # Twitter Wrapper Methods sub get_user_by_name { my $self = shift; my $name = shift; my $result = eval { $self->twitter->lookup_users({ screen_name => [ $name ] })->[0]; }; if ($@) { if (_INSTANCE($@, "Net::Twitter::Error") and $@->error =~ /No user matches for specified terms/) { $result = undef; } else { die $@; } } return $result; } sub get_users_by_id { my $self = shift; my $ids = shift; return $self->twitter->lookup_users({ user_id => $ids }); } sub get_followers_by_id { my $self = shift; my $name = shift; my $result = $self->twitter->followers_ids({ screen_name => $name, cursor => -1, }); if ($result->{next_cursor} or $result->{previous_cursor}) { throw "This application only supports Twitter users with less than 5000 followers (to prevent hitting rate limits)"; } return $result->{ids}; } 1;
import React, { Component } from "react"; import { Cart } from './Cart'; import { CartProvider } from './CartContext'; import Search from './Search'; class Home extends Component { // componentDidMount(){ // fetch('http://localhost:8080/api/storeproducts/getStoreProductById/'+0, { // method: 'POST', // body: JSON.stringify(data), // headers: { // "Content-type": "application/json; charset=UTF-8" // } // }).then(res => res.json()) // .then( // (result) => { // console.log(result); // this.setState({jwt : result.jwt}); // this.setState({islogin : true}); // console.log(this.state.islogin); // } // ); // } render() { return ( <CartProvider> <div> <Search /> </div> </CartProvider> ); } } export default Home;
class Period < ActiveRecord::Base # ----- Associations ----- belongs_to :event has_many :participants, :dependent => :destroy has_many :event_reports, :dependent => :destroy has_many :messages acts_as_list :scope => :position # ----- Callbacks ----- after_create :create_smso_aar, :create_internal_aar before_destroy :remove_all_message_references # ----- Validations ----- # ----- Scopes ----- # ----- Local Methods----- # ----- support RSVP actions def remove_participant(member) participant = self.participants.by_mem_id(member.id).to_a return unless participant.present? participant.first.destroy end def add_participant(member) participant = self.participants.by_mem_id(member.id).to_a return unless participant.blank? self.participants.create(member_id: member.id) end def set_departure_time(member) return unless participant = self.participants.by_mem_id(member.id).first return if participant.en_route_at participant.update_attributes en_route_at: Time.now end def set_return_time(member) return unless participant = self.participants.by_mem_id(member.id).first return if participant.return_home_at participant.update_attributes return_home_at: Time.now end # ----- reporting ----- def create_smso_aar return if %w(social).include? self.event.typ if self.event_reports.smso_aars.all.empty? title = self.event.typ == "meeting" ? "SMSO AAR - BAMRU Meeting " : "SMSO AAR - Period #{self.position}" opts = {typ: "smso_aar", event_id: self.event.id, title: title} opts[:unit_leader] = "John Chang" opts[:signed_by] = "Eszter Tompos" opts[:description] = self.event.description self.event_reports << EventReport.create(opts) end end def create_internal_aar return if %w(social).include? self.event.typ return if self.event.typ == "meeting" if self.event_reports.internal_aars.all.empty? title = "Internal AAR - Period #{self.position}" opts = {typ: "internal_aar", event_id: self.event.id, title: title} opts[:unit_leader] = Role.member_for("UL").try(:full_name) || "TBD" opts[:signed_by] = Role.member_for("SEC").try(:full_name) || "TBD" opts[:description] = "TBD" self.event_reports << EventReport.create(opts) end end def remove_all_message_references Message.where(period_id: self.id).each do |message| message.update_attributes(period_id: nil, period_format: nil) end end end # == Schema Information # # Table name: periods # # id :integer not null, primary key # event_id :integer # position :integer # start :datetime # finish :datetime # rsvp_id :integer # created_at :datetime not null # updated_at :datetime not null #
#!/bin/sh # First time user runs the game, make sure they get an .ini file # that knows where to find skulltag.pk3 and friends. if [ ! -e ~/.skulltag/skulltag.ini ]; then mkdir -p ~/.skulltag cat /usr/share/skulltag/skulltag.ini.default > ~/.skulltag/skulltag.ini fi DIR=/usr/@LIB@/skulltag export LD_LIBRARY_PATH=$DIR exec $DIR/`basename $0` "$@"
package desiredstatefetcher_test import ( "github.com/cloudfoundry/hm9000/config" "github.com/cloudfoundry/hm9000/desiredstatefetcher" "github.com/cloudfoundry/hm9000/helpers/httpclient" "github.com/cloudfoundry/hm9000/models" "github.com/cloudfoundry/hm9000/testhelpers/appfixture" "github.com/cloudfoundry/hm9000/testhelpers/fakelogger" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "code.cloudfoundry.org/clock" ) var _ = Describe("Fetching from CC and storing the result in the Store", func() { var ( fetcher *desiredstatefetcher.DesiredStateFetcher a1 appfixture.AppFixture a2 appfixture.AppFixture a3 appfixture.AppFixture resultChan chan desiredstatefetcher.DesiredStateFetcherResult conf *config.Config appQueue *models.AppQueue ) BeforeEach(func() { resultChan = make(chan desiredstatefetcher.DesiredStateFetcherResult, 1) a1 = appfixture.NewAppFixture() a2 = appfixture.NewAppFixture() a3 = appfixture.NewAppFixture() stateServer.SetDesiredState([]models.DesiredAppState{ a1.DesiredState(1), a2.DesiredState(1), a3.DesiredState(1), }) conf, _ = config.DefaultConfig() conf.CCBaseURL = stateServer.URL() appQueue = models.NewAppQueue() fetcher = desiredstatefetcher.New(conf, httpclient.NewHttpClient(conf.SkipSSLVerification, conf.FetcherNetworkTimeout()), clock.NewClock(), fakelogger.NewFakeLogger(), ) fetcher.Fetch(resultChan, appQueue) }) It("requests for the first set of data from the CC and sends the response", func() { var desired map[string]models.DesiredAppState Eventually(appQueue.DesiredApps).Should(Receive(&desired)) Expect(desired).To(HaveKey(a1.AppGuid + "," + a1.AppVersion)) Expect(desired).To(HaveKey(a2.AppGuid + "," + a2.AppVersion)) Expect(desired).To(HaveKey(a3.AppGuid + "," + a3.AppVersion)) }) It("reports success to the channel", func() { var result desiredstatefetcher.DesiredStateFetcherResult Eventually(resultChan).Should(Receive(&result)) Expect(result.Success).To(BeTrue()) Expect(result.NumResults).To(Equal(3)) Expect(result.Message).To(BeZero()) Expect(result.Error).NotTo(HaveOccurred()) }) Context("when fetching again, and apps have been stopped and/or deleted", func() { BeforeEach(func() { Eventually(resultChan).Should(Receive()) desired1 := a1.DesiredState(1) desired1.State = models.AppStateStopped stateServer.SetDesiredState([]models.DesiredAppState{ desired1, a3.DesiredState(1), }) fetcher.Fetch(resultChan, appQueue) }) }) })
@inherits WebViewPage<PasswordPostModel> @using FormUI.Controllers.Home @{ ViewBag.Title = "Password"; } <div class="grid"><!-- --><div class="grid__item large--eight-twelfths"> <p> You have reached a <span style="text-decoration: underline">test</span> site that is password protected; please supply the password below. </p> <form method="post"> @Html.LabelledInputPassword("Password", m => m.Password) @Html.ButtonSubmit() </form> </div><!-- --></div>
-- file:sequence.sql ln:124 expect:true SELECT setval('sequence_test'::regclass, 32)
package eu.kanade.tachiyomi.data.database.tables object SearchMetadataTable { const val TABLE = "search_metadata" const val COL_MANGA_ID = "manga_id" const val COL_UPLOADER = "uploader" const val COL_EXTRA = "extra" const val COL_INDEXED_EXTRA = "indexed_extra" const val COL_EXTRA_VERSION = "extra_version" // Insane foreign, primary key to avoid touch manga table val createTableQuery: String get() = """CREATE TABLE $TABLE( $COL_MANGA_ID INTEGER NOT NULL PRIMARY KEY, $COL_UPLOADER TEXT, $COL_EXTRA TEXT NOT NULL, $COL_INDEXED_EXTRA TEXT, $COL_EXTRA_VERSION INT NOT NULL, FOREIGN KEY($COL_MANGA_ID) REFERENCES ${MangaTable.TABLE} (${MangaTable.COL_ID}) ON DELETE CASCADE )""" val createUploaderIndexQuery: String get() = "CREATE INDEX ${TABLE}_${COL_UPLOADER}_index ON $TABLE($COL_UPLOADER)" val createIndexedExtraIndexQuery: String get() = "CREATE INDEX ${TABLE}_${COL_INDEXED_EXTRA}_index ON $TABLE($COL_INDEXED_EXTRA)" }
#ifndef __DEBUG_OUTPUT_H__ #define __DEBUG_OUTPUT_H__ #include <stdint.h> #define DEBUG_OUTPUT_BASE_PORT (0x402) class DebugOutput { public: DebugOutput(); ~DebugOutput(); void write(uint32_t port, const uint32_t *value, uint8_t size); void read(uint32_t port, uint32_t *value, uint8_t size); }; #endif
bash$ declare -A myassocarray bash$ myassocarray=([apple]="red" [banana]="yellow" [carrot]="orange") bash$ printf '%s\n' "${myassocarray[banana]}" yellow
; QXL BASIC Routines section exten xdef qxl_prini xref disp_update xref ut_gxin1 xref ut_gtint xref ut_procdef xref ak_init xref smsq_xreset xref wmon_def ; to get it loaded include 'dev8_keys_err' include 'dev8_keys_qdos_sms' include 'dev8_keys_68000' include 'dev8_keys_sys' include 'dev8_smsq_qxl_keys' include 'dev8_mac_proc' ;+++ ; RES_128 ;--- res_128 move.w #128,d6 bra.s reset ;+++ ; RES_SIZE size in K ;--- res_size jsr ut_gxin1 ; get one integer bne.s qxb_rts move.w (a6,a1.l),d6 reset swap d6 ; n*64K lsr.l #2,d6 ; n*16K clr.w d6 lsr.l #4,d6 ; n*1k lea $20000,a4 ; set bottom of RAM add.l d6,a4 moveq #sms.xtop,d0 trap #1 jmp smsq_xreset qxb_rts rts section procs qxl_ext lea qxl_xprocs,a1 ; Modified TK2 procedures jmp ut_procdef qxl_prini lea qxl_procs,a1 ; QXL procs jsr ut_procdef jmp ak_init section procs qxl_xprocs proc_stt proc_def CALL,callsq proc_def LRESPR,lrespr proc_end proc_stt proc_end qxl_procs proc_stt proc_ref QXL_EXT proc_ref RES_128 proc_ref RES_SIZE proc_ref DISP_UPDATE proc_def ALTKEY proc_end proc_stt proc_end end
#ifndef VERTICALPANEL_HPP #define VERTICALPANEL_HPP namespace kgd::gui { struct VLabel : public QLabel { VLabel (const QString &text = "", QWidget *parent = nullptr) : QLabel(text, parent) {} QSize minimumSizeHint(void) const override { return QLabel::minimumSizeHint().transposed(); } QSize sizeHint(void) const override { return QLabel::sizeHint().transposed(); } void paintEvent(QPaintEvent*) { QPainter painter(this); painter.translate(rect().center()); painter.rotate(-90); painter.translate(-rect().transposed().center()); painter.drawText(rect().transposed(), alignment(), text()); } }; } // end of namespace kgd::gui #endif // VERTICALPANEL_HPP
package com.asf.appcoins.sdk.core.web3; import java.math.BigDecimal; import org.web3j.abi.datatypes.Address; import org.web3j.protocol.core.methods.request.Transaction; import p320f.p321a.C13797m; public interface AsfWeb3j { C13797m<String> call(Transaction transaction); C13797m<BigDecimal> getBalance(Address address); C13797m<Long> getGasPrice(Address address); C13797m<Long> getNonce(Address address); C13797m<com.asf.appcoins.sdk.core.transaction.Transaction> getTransactionByHash(String str); C13797m<String> sendRawTransaction(String str); }
class OpenAPIParser::SchemaValidator class FloatValidator < Base include ::OpenAPIParser::SchemaValidator::Enumable include ::OpenAPIParser::SchemaValidator::MinimumMaximum # validate float value by schema # @param [Object] value # @param [OpenAPIParser::Schemas::Schema] schema def coerce_and_validate(value, schema, **_keyword_args) value = coerce(value) if @coerce_value return validatable.validate_integer(value, schema) if value.kind_of?(Integer) coercer_and_validate_numeric(value, schema) end private def coercer_and_validate_numeric(value, schema) return OpenAPIParser::ValidateError.build_error_result(value, schema) unless value.kind_of?(Numeric) value, err = check_enum_include(value, schema) return [nil, err] if err check_minimum_maximum(value, schema) end def coerce(value) Float(value) rescue ArgumentError => e raise e unless e.message =~ /invalid value for Float/ end end end
package com.twitter.util.validation.internal import java.lang.annotation.Annotation import java.lang.reflect.Method import java.util import sun.reflect.annotation.AnnotationParser private[validation] object AnnotationFactory { /** * Creates a new Annotation (AnnotationProxy) instance of * the given annotation type with the custom values applied. * * @see [[AnnotationParser.annotationForMap]] */ def newInstance[A <: Annotation]( annotationType: Class[A], customValues: Map[String, Any] = Map.empty ): A = { val attributes: util.Map[String, Object] = new util.HashMap[String, Object]() // Extract default values from annotation val methods: Array[Method] = annotationType.getDeclaredMethods var index = 0 val length = methods.length while (index < length) { val method = methods(index) attributes.put(method.getName, method.getDefaultValue) index += 1 } // Populate custom values val keysIterator = customValues.keysIterator while (keysIterator.hasNext) { val key = keysIterator.next() attributes.put(key, customValues(key).asInstanceOf[AnyRef]) } AnnotationParser.annotationForMap(annotationType, attributes).asInstanceOf[A] } }
require "gmail_cli/version" require "gmail_cli/logger" require "gmail_cli/oauth2_helper" require "gmail_cli/shell" require "gmail_cli/imap"
/* (c) Copyright 2014 Temasys Communication, Pte Ltd. 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. * * PeerConnection.cpp * * Created on: Nov 6, 2013 * Author: Francois Temasys */ #include "PeerConnection.h" const std::string PeerConnection:: _TAG = std::string("PeerConnection| "); PeerConnection:: PeerConnection(QObject * parent): QObject(parent) { _initiator = 0; _started = false; _state = NOT_CONNECTED; _channelReady = false; _channelClient = NULL; _callback = NULL; _id = QString(""); } PeerConnection:: ~PeerConnection() { delete _channelClient; _callback = NULL; } void PeerConnection:: doConnect(QString token, QString id, QString roomid, int initiator) { _token = token; _id = id; _roomid = roomid; _channelClient = new GAEChannelClient(_token, this); _initiator = initiator; } bool PeerConnection:: isConnected() { return _state == CONNECTED; } void PeerConnection:: RegisterObserver(PeerConnectionClientObserver * callback) { assert(!_callback); _callback = callback; } bool PeerConnection:: SignOut() { if (_state == NOT_CONNECTED) { return true; } _channelClient = NULL; _channelReady = false; _started = false; _initiator = 0; Json::Value message; message["type"] = "bye"; _callback->sendMessage(message); _state = NOT_CONNECTED; return true; } void PeerConnection::OnOpen() { LOG(INFO) << _TAG + "onOpen"; LOG(INFO) << _TAG + "My id: " + _id.toLocal8Bit().constData() + " Room id: " + _roomid.toLocal8Bit().constData(); _channelReady = true; _state = CONNECTED; this->maybeStart(); } //void PeerConnection::OnMessage(talk_base::Message data) void PeerConnection::OnMessage(std::string data) { Json::Value msg; // will contains the root value after parsing. Json::Reader reader; bool parsingSuccessful = reader.parse( data, msg ); if(!parsingSuccessful) { // report to the user the failure and their locations in the document. LOG(LERROR) << "Failed to parse configuration\n"<< reader.getFormattedErrorMessages(); return; } std::string type = msg.get("type","ERROR").asString(); if (!_initiator && !_started) { if (type == "offer") { // Add offer to the beginning of msgQueue, since we can't handle // Early candidates before offer at present. _msgQueue.push_front(msg); // Callee creates PeerConnection maybeStart(); } else { _msgQueue.push_back(msg); } } else { processSignalingMessage(msg); } } void PeerConnection::OnClose() { LOG(INFO) << "onClose"; } void PeerConnection::OnError(int code,std::string description) { LOG(INFO) << "onError"; } void PeerConnection::maybeStart() { if (!_started && _channelReady ) { _callback->CreatePC(); _started = true; if (_initiator) _callback->CreateOffer(); else { while (_msgQueue.size() > 0) { this->processSignalingMessage(_msgQueue.front()); _msgQueue.pop_front(); } } } } void PeerConnection::processSignalingMessage(Json::Value msg) { std::string type = msg.get("type","ERROR").asString(); //////////////////////////////////////////////////////////////////////////////// // SDP message, either offer or answer. //////////////////////////////////////////////////////////////////////////////// if (type == "answer" || type == "offer") { LOG(INFO) << "onMessage :\n"<< msg; std::string sdp = msg.get("sdp","ERROR").asString(); _callback->SetRemoteOffer(type,sdp); } else if(type == "candidate") { LOG(INFO) << _TAG+"Received " + type; std::string sdp = msg.get("candidate","ERROR").asString(); std::string id = msg.get("id","ERROR").asString(); int label = msg.get("label","ERROR").asInt(); _callback->addIceCandidate(id,sdp,label); } //////////////////////////////////////////////////////////////////////////////// // Bye //////////////////////////////////////////////////////////////////////////////// else if (type == "bye") { LOG(INFO) << _TAG+"Received " + type; _callback->OnDisconnected(); } }
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2017-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/vsdebug/debugger.h" #include "hphp/runtime/ext/vsdebug/command.h" namespace HPHP { namespace VSDEBUG { InitializeCommand::InitializeCommand( Debugger* debugger, folly::dynamic message ) : VSCommand(debugger, message) { } InitializeCommand::~InitializeCommand() { } bool InitializeCommand::executeImpl( DebuggerSession* session, folly::dynamic* responseMsg ) { const folly::dynamic& message = getMessage(); const folly::dynamic& args = tryGetObject(message, "arguments", s_emptyArgs); ClientPreferences preferences = {0}; preferences.linesStartAt1 = tryGetBool(args, "linesStartAt1", true); preferences.columnsStartAt1 = tryGetBool(args, "columnsStartAt1", true); preferences.supportsVariableType = tryGetBool(args, "supportsVariableType", true); preferences.supportsVariablePaging = tryGetBool(args, "supportsVariablePaging", true); preferences.supportsRunInTerminalRequest = tryGetBool(args, "supportsRunInTerminalRequest", true); const auto& pathFormat = tryGetString(args, "pathFormat", "path"); if (pathFormat.compare("uri") == 0) { preferences.pathFormat = PathFormat::URI; } else { preferences.pathFormat = PathFormat::Path; } m_debugger->setClientPreferences(preferences); // Prepare a response for the client. folly::dynamic capabilities = folly::dynamic::object; capabilities["supportsConfigurationDoneRequest"] = true; capabilities["supportsConditionalBreakpoints"] = true; capabilities["supportsHitConditionalBreakpoints"] = false; capabilities["supportsEvaluateForHovers"] = true; capabilities["supportsStepBack"] = false; capabilities["supportsSetVariable"] = true; capabilities["supportsRestartFrame"] = false; capabilities["supportsGotoTargetsRequest"] = false; capabilities["supportsStepInTargetsRequest"] = false; capabilities["supportsModulesRequest"] = false; capabilities["supportsRestartRequest"] = false; capabilities["supportsExceptionOptions"] = true; capabilities["supportsValueFormattingOptions"] = true; capabilities["supportsExceptionInfoRequest"] = true; capabilities["supportTerminateDebuggee"] = false; capabilities["supportsDelayedStackTraceLoading"] = true; capabilities["supportsLoadedSourcesRequest"] = false; // TODO (Ericblue) these caps aren't supported yet but are intended to // be supported soon. // capabilities["exceptionBreakpointFilters"] = ... // capabilities["supportsFunctionBreakpoints"] = false; // capabilities["supportsCompletionsRequest"] = false; (*responseMsg)["body"] = capabilities; // Completion of this command does not resume the target. return false; } } }
--- name: Unity categories: - darkmira tags: - yellow sponsor: Darkmira Tour PHP reverse: Darkmira Tour PHP logo photos: - file: yellow-darkmira-0-400x300.jpg link: https://www.flickr.com/photos/atomictaco/48746702583/ credit: Tim Bond - file: yellow-darkmira-1-400x300.jpg link: https://www.flickr.com/photos/atomictaco/48747217772/ credit: Tim Bond --- This elePHPant was produced by a Brasilian manufacturer and was available to attendees of the [Darkmira PHP Tour](https://php.darkmiratour.rocks/).
package schedule import ( "fmt" coreScheduler "github.com/mycontroller-org/server/v2/pkg/service/core_scheduler" scheduleTY "github.com/mycontroller-org/server/v2/pkg/types/schedule" busUtils "github.com/mycontroller-org/server/v2/pkg/utils/bus_utils" "go.uber.org/zap" ) const ( schedulePrefix = "user_schedule" ) func schedule(cfg *scheduleTY.Config) { if cfg.State == nil { cfg.State = &scheduleTY.State{} } name := getScheduleID(cfg.ID) // update validity, if it is on date job, add date(with year) on validity err := updateOnDateJobValidity(cfg) if err != nil { zap.L().Error("error on updating on date job config", zap.Error(err), zap.String("id", cfg.ID)) return } cronSpec, err := getCronSpec(cfg) if err != nil { zap.L().Error("error on creating cron spec", zap.Error(err)) cfg.State.LastStatus = false cfg.State.Message = fmt.Sprintf("Error on cron spec creation: %s", err.Error()) busUtils.SetScheduleState(cfg.ID, *cfg.State) return } err = coreScheduler.SVC.AddFunc(name, cronSpec, getScheduleTriggerFunc(cfg, cronSpec)) if err != nil { zap.L().Error("error on adding schedule", zap.Error(err)) cfg.State.LastStatus = false cfg.State.Message = fmt.Sprintf("Error on adding into scheduler: %s", err.Error()) busUtils.SetScheduleState(cfg.ID, *cfg.State) } zap.L().Debug("added a schedule", zap.String("name", name), zap.String("ID", cfg.ID), zap.Any("cronSpec", cronSpec)) cfg.State.Message = fmt.Sprintf("Added into scheduler. cron spec:[%s]", cronSpec) busUtils.SetScheduleState(cfg.ID, *cfg.State) } func unschedule(id string) { name := getScheduleID(id) coreScheduler.SVC.RemoveFunc(name) zap.L().Debug("removed a schedule", zap.String("name", name), zap.String("id", id)) } func unloadAll() { coreScheduler.SVC.RemoveWithPrefix(schedulePrefix) } func getScheduleID(id string) string { return fmt.Sprintf("%s_%s", schedulePrefix, id) }
using Monobank.API.Enums; using System.Text.Json.Serialization; namespace Monobank.API.DTO { public sealed class CurrencyInfo { [JsonPropertyName("currencyCodeA")] public CurrencyCode CurrencyCodeA { get; set; } [JsonPropertyName("currencyCodeB")] public CurrencyCode CurrencyCodeB { get; set; } [JsonPropertyName("date")] public ulong Date { get; set; } [JsonPropertyName("rateSell")] public float RateSell { get; set; } [JsonPropertyName("rateBuy")] public float RateBuy { get; set; } [JsonPropertyName("rateCross")] public float RateCross { get; set; } } }
# MunicipalityDataNorway Here I have gathered municipality data from Statistics Norway Statistical Bank. I have the datasets in the following order 1. Sociodemographics. 2. 3. User charges cb stands for codebook!
package list import list.P18.slice import org.scalatest.{FlatSpec, ShouldMatchers} class P18Spec extends FlatSpec with ShouldMatchers { "slice" must "return an empty list when given any start and end and an empty list" in { val list = List() slice(3, 7, list) should be(Nil) } "slice" must "return a list of one element when given 0 as start and 1 as end and a list of one element" in { val list = List("a") slice(0, 1, list) should be(List("a")) } "slice" must "behave correctly according to the example" in { slice(3, 7, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)) should be(List('d, 'e, 'f, 'g)) } }
// Copyright 2016 Google Inc. // // 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.google.pubsub.clients.adapter; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.pubsub.clients.common.MetricsHandler; import com.google.pubsub.clients.common.Task; import com.google.pubsub.clients.common.Task.RunResult; import com.google.pubsub.flic.common.LoadtestProto; import com.google.pubsub.flic.common.LoadtestWorkerGrpc; import io.grpc.ManagedChannelBuilder; /** * A Task that proxies commands to a LoadtestWorker process on localhost. */ public class AdapterTask extends Task { private final LoadtestWorkerGrpc.LoadtestWorkerFutureStub stub; public AdapterTask( LoadtestProto.StartRequest request, MetricsHandler.MetricName metricName, Options options) { super(request, "adapter", metricName); stub = LoadtestWorkerGrpc.newFutureStub( ManagedChannelBuilder.forAddress("localhost", options.workerPort) .usePlaintext(true) .build()); try { stub.start(request).get(); } catch (Throwable t) { throw new RuntimeException("Unable to start server.", t); } } @Override public ListenableFuture<RunResult> doRun() { return Futures.transform( stub.execute(LoadtestProto.ExecuteRequest.getDefaultInstance()), response -> RunResult.fromMessages( response.getReceivedMessagesList(), response.getLatenciesList())); } /** * Contains the command line options for {@link AdapterTask}. */ @Parameters(separators = "=") public static class Options { @Parameter( names = {"--worker_port"}, description = "The port that the LoadtestWorker process server is listening on." ) int workerPort = 6000; } }
![alt tag](https://cat-on-duty.herokuapp.com/images/logo-f4f0d0edcb6b2961ca96fa914fa46964.png?vsn=d 'logo')​ Project for sentries organisation ## Bot under construction... ## License This software is released under the [MIT License](/LICENSE). © 2020 Pavel Solovev
const { Pool } = require('pg'); class PlaylistsService { constructor() { this._pool = new Pool(); } async getPlaylists(playlistId) { const playlistQuery = { text: `SELECT playlists.id, playlists.name FROM playlists WHERE playlists.id = $1`, values: [playlistId], }; const playlistResult = await this._pool.query(playlistQuery); if (!playlistResult.rowCount) { throw new Error('Playlist tidak ditemukan'); } const songsQuery = { text: `SELECT songs.id, songs.title, songs.performer FROM songs LEFT JOIN playlist_songs on playlist_songs.song_id = songs.id WHERE playlist_songs.playlist_id = $1 GROUP BY songs.id`, values: [playlistId], }; const songsResult = await this._pool.query(songsQuery); const [playlist] = playlistResult.rows; const { rows: songs } = songsResult; return { playlist, songs }; } } module.exports = PlaylistsService;
package tin.thurein.haulio_test.injection import dagger.Binds import dagger.Module import tin.thurein.data.repositories.JobRepositoryImpl import tin.thurein.domain.repositories.JobRepository @Module interface RepositoryModule { @Binds fun bindJobRepository(jobRepositoryImpl: JobRepositoryImpl): JobRepository }
"use strict" const path = require("path") const debug = require("debug")("route4me-node:examples") const chai = require("chai"); require("../init-examples-suite") const helper = require("../../test/helper") helper.describeIntegration(helper.toSuiteName(__filename), function T() { this.timeout(5000) this.slow(3000) it(path.basename(__filename), (done) => { var expect = chai.expect; const apiKey = "11111111111111111111111111111111" const route4me = new Route4Me(apiKey) const data = { "address_1": "1358 E Luzerne St, Philadelphia, PA 19124, US", "cached_lat" : 48.335991, "cached_lng" : 31.18287, "address_alias" : "Auto test address", "address_city" : "Philadelphia", "EXT_FIELD_first_name" : "Igor", "EXT_FIELD_last_name" : "Progman", "EXT_FIELD_email" : "[email protected]", "EXT_FIELD_phone" : "380380380380", "EXT_FIELD_custom_data" : [ { "order_id" : "10", "name" : "Bill Soul" } ] } route4me.Orders.create(data, (err, orderResult) => { debug("error ", err) debug("result ", orderResult) // Expectations about result expect(err).is.null expect(orderResult).exist console.log(orderResult); //expect(noteResult).has.property("order") }) done(); }) })
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.spi.security.authentication.external.impl; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterators; import org.apache.jackrabbit.api.security.user.Authorizable; import org.apache.jackrabbit.api.security.user.Group; import org.apache.jackrabbit.api.security.user.User; import org.apache.jackrabbit.api.security.user.UserManager; import org.apache.jackrabbit.oak.spi.security.authentication.external.AbstractExternalAuthTest; import org.apache.jackrabbit.oak.spi.security.authentication.external.basic.AutoMembershipConfig; import org.apache.jackrabbit.oak.spi.security.authentication.external.basic.DefaultSyncConfig; import org.apache.sling.testing.mock.osgi.junit.OsgiContext; import org.jetbrains.annotations.NotNull; import org.junit.Before; import org.junit.Test; import java.lang.reflect.Field; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class AutoMembershipAwareTest extends AbstractExternalAuthTest { private static final String GROUP_AUTOMEMBERSHIP_ID = "gr1"; private static final String USER_AUTOMEMBERSHIP_ID = "gr2"; private static final String CONFIG_AUTOMEMBERSHIP_ID_1 = "gr3"; private static final String CONFIG_AUTOMEMBERSHIP_ID_2 = "gr4"; private final DefaultSyncHandler sh = new DefaultSyncHandler(); @Before public void before() throws Exception { super.before(); Map<String, Object> properties = new HashMap<>(); properties.put(DefaultSyncConfigImpl.PARAM_NAME, DefaultSyncConfig.DEFAULT_NAME); properties.put(DefaultSyncConfigImpl.PARAM_GROUP_AUTO_MEMBERSHIP, new String[] {GROUP_AUTOMEMBERSHIP_ID}); properties.put(DefaultSyncConfigImpl.PARAM_USER_AUTO_MEMBERSHIP, new String[] {USER_AUTOMEMBERSHIP_ID}); context.registerInjectActivateService(sh, properties); } @Test public void testNotActivated() { DefaultSyncHandler sh = new DefaultSyncHandler(); assertSame(AutoMembershipConfig.EMPTY, sh.getAutoMembershipConfig()); } @Test public void testMissingAutoMembershipServices() { assertSame(AutoMembershipConfig.EMPTY, sh.getAutoMembershipConfig()); } @Test public void testNameMismatch() { AutoMembershipConfig amc = mock(AutoMembershipConfig.class); when(amc.getName()).thenReturn("nameMismatch"); context.registerService(AutoMembershipConfig.class, amc, Collections.singletonMap(AutoMembershipConfig.PARAM_SYNC_HANDLER_NAME, "nameMismatch")); assertSame(AutoMembershipConfig.EMPTY, sh.getAutoMembershipConfig()); verifyNoInteractions(amc); } @Test public void testNameMatch() { Authorizable authorizable = mock(Authorizable.class); UserManager userManager = mock(UserManager.class); Group gr = mock(Group.class); Set<String> groupIds = Collections.singleton(CONFIG_AUTOMEMBERSHIP_ID_1); AutoMembershipConfig amc = mock(AutoMembershipConfig.class); when(amc.getName()).thenReturn(sh.getName()); when(amc.getAutoMembership(any(Authorizable.class))).thenReturn(groupIds); when(amc.getAutoMembers(any(UserManager.class), any(Group.class))).thenReturn(Iterators.singletonIterator(authorizable)); context.registerService(AutoMembershipConfig.class, amc, Collections.singletonMap(AutoMembershipConfig.PARAM_SYNC_HANDLER_NAME, sh.getName())); AutoMembershipConfig config = sh.getAutoMembershipConfig(); assertNotSame(AutoMembershipConfig.EMPTY, config); assertNotSame(amc, config); assertEquals(sh.getName(), config.getName()); assertEquals(groupIds, config.getAutoMembership(authorizable)); assertTrue(Iterators.elementsEqual(Iterators.singletonIterator(authorizable), config.getAutoMembers(userManager, gr))); // verify that DefaultSyncHandler was notified about the service verify(amc).getAutoMembership(authorizable); verify(amc).getAutoMembers(userManager, gr); verifyNoMoreInteractions(amc); } @Test public void testMultipleMatches() { User user = mock(User.class); Authorizable authorizable = mock(Authorizable.class); AutoMembershipConfig amc = mock(AutoMembershipConfig.class); AutoMembershipConfig amc2 = mock(AutoMembershipConfig.class); injectAutoMembershipConfig(amc, amc2, context, sh); AutoMembershipConfig config = sh.getAutoMembershipConfig(); assertNotSame(AutoMembershipConfig.EMPTY, config); assertNotSame(amc, config); assertNotSame(amc2, config); assertEquals(sh.getName(), config.getName()); // verify that the 2 configurations get property aggregated assertEquals(ImmutableSet.of(CONFIG_AUTOMEMBERSHIP_ID_1), config.getAutoMembership(authorizable)); assertEquals(ImmutableSet.of(CONFIG_AUTOMEMBERSHIP_ID_1, CONFIG_AUTOMEMBERSHIP_ID_2, USER_AUTOMEMBERSHIP_ID), config.getAutoMembership(user)); // verify that DefaultSyncHandler was notified about the service verify(amc).getAutoMembership(authorizable); verify(amc).getAutoMembership(user); verifyNoMoreInteractions(amc); verify(amc2).getAutoMembership(authorizable); verify(amc2).getAutoMembership(user); verifyNoMoreInteractions(amc2); } @Test public void testSyncConfigIsUpdatedToCoverAutoMembershipConfig() throws Exception { User user = mock(User.class); Authorizable authorizable = mock(Authorizable.class); AutoMembershipConfig amc = mock(AutoMembershipConfig.class); AutoMembershipConfig amc2 = mock(AutoMembershipConfig.class); injectAutoMembershipConfig(amc, amc2, context, sh); Field f = DefaultSyncHandler.class.getDeclaredField("config"); f.setAccessible(true); DefaultSyncConfig syncConfig = (DefaultSyncConfig) f.get(sh); DefaultSyncConfig.User scU = syncConfig.user(); DefaultSyncConfig.Group scG = syncConfig.group(); assertEquals(ImmutableSet.of(USER_AUTOMEMBERSHIP_ID), scU.getAutoMembership()); assertEquals(ImmutableSet.of(GROUP_AUTOMEMBERSHIP_ID), scG.getAutoMembership()); assertEquals(ImmutableSet.of(CONFIG_AUTOMEMBERSHIP_ID_1, USER_AUTOMEMBERSHIP_ID), scU.getAutoMembership(authorizable)); assertEquals(ImmutableSet.of(CONFIG_AUTOMEMBERSHIP_ID_1, CONFIG_AUTOMEMBERSHIP_ID_2, USER_AUTOMEMBERSHIP_ID), scU.getAutoMembership(user)); assertEquals(ImmutableSet.of(CONFIG_AUTOMEMBERSHIP_ID_1, GROUP_AUTOMEMBERSHIP_ID), scG.getAutoMembership(authorizable)); assertEquals(ImmutableSet.of(CONFIG_AUTOMEMBERSHIP_ID_1, CONFIG_AUTOMEMBERSHIP_ID_2, USER_AUTOMEMBERSHIP_ID, GROUP_AUTOMEMBERSHIP_ID), scG.getAutoMembership(user)); } private static void injectAutoMembershipConfig(@NotNull AutoMembershipConfig amc1, @NotNull AutoMembershipConfig amc2, @NotNull OsgiContext context, @NotNull DefaultSyncHandler syncHandler) { when(amc1.getName()).thenReturn(syncHandler.getName()); when(amc1.getAutoMembership(any(Authorizable.class))).thenReturn(ImmutableSet.of(CONFIG_AUTOMEMBERSHIP_ID_1)); when(amc2.getName()).thenReturn(syncHandler.getName()); when(amc2.getAutoMembership(any(User.class))).thenReturn(ImmutableSet.of(CONFIG_AUTOMEMBERSHIP_ID_1, CONFIG_AUTOMEMBERSHIP_ID_2, USER_AUTOMEMBERSHIP_ID)); context.registerService(AutoMembershipConfig.class, amc1, Collections.singletonMap(AutoMembershipConfig.PARAM_SYNC_HANDLER_NAME, syncHandler.getName())); context.registerService(AutoMembershipConfig.class, amc2, Collections.singletonMap(AutoMembershipConfig.PARAM_SYNC_HANDLER_NAME, syncHandler.getName())); } }
/** * Copyright (C) 2011-2017 The PILE Developers <[email protected]> * * 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.pileproject.drive.app; import android.app.Application; import android.content.Context; import com.pileproject.drive.module.FlavorModule; /** * An Application class for Drive Applications. This class provides some helper methods to share global information * such as {@link Context}. */ public class DriveApplication extends Application { private static DriveApplication sInstance; private DriveComponent mDriveComponent; @Override public void onCreate() { super.onCreate(); sInstance = this; initInjection(); } /** * Gets a {@link Context} anywhere. * * @return a saved {@link Context} */ public static synchronized Context getContext() { return sInstance.getApplicationContext(); } /** * Gets a {@link DriveComponent}. The component will be used for build-flavor specific injections. * * @return a saved {@link DriveComponent} */ public DriveComponent getAppComponent() { return mDriveComponent; } private void initInjection() { mDriveComponent = DaggerDriveComponent.builder() .flavorModule(new FlavorModule()) .build(); } }
--- title: Bot Mangement description: Bot Mangement permalink: /security/bot-management layout: page --- ## Manage bots with speed and accuracy by applying several detection methods Take charge over bots by applying behavioral analysis, machine learning, and fingerprinting to stop bots. ### Demo coming soon!
/*************************************************************************** Copyright (c) 2019, Mateusz Panuś Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************/ #include <avr/io.h> #include <avr/interrupt.h> #include <stdio.h> #include "main.h" #include "text.h" #include "font.h" #include "keypad.h" #include "device.h" #include "display.h" #include "delay.h" #include "image.h" #include "buffer.h" #include "digital.h" #define DIGITAL_INVERT (1<<15) static struct { uint8_t row, column, roll, lock, end_line, hold, counter; DIGITAL_DISPLAY_t display; uint16_t idle; DIGITAL_Decode_t Decode; struct { uint8_t text[14]; uint16_t control; } buffer[5]; } DIGITAL; static void DIGITAL_Ready(void); static void DIGITAL_Loop(void); static void DIGITAL_NewLine(void); void DIGITAL_Init(DIGITAL_Decode_t Decode) { DIGITAL.Decode = Decode; MAIN_Loop(DIGITAL_Ready); BUFFER_Clear(); DIGITAL_Clear(); DIGITAL.counter = 1; DIGITAL.hold = 0; DIGITAL.idle = 0; DIGITAL.lock = 1; DIGITAL.display = DIGITAL_DISPLAY_ASCII; } static void DIGITAL_Ready(void) { if(!DISPLAY_Update()) { return; } DISPLAY_CursorPosition(28,20); puts_P(TEXT_READY); DISPLAY_Idle(); if(!BUFFER_Empty()) { MAIN_Loop(DIGITAL_Loop); DIGITAL.lock = 0; } } static void DIGITAL_Loop(void) { uint8_t overflow = 0; if(BUFFER_Overflow()) { overflow = 1; DIGITAL_PrintSymbol(FONT_SYMBOL_OVERFLOW); BUFFER_Stop(); BUFFER_Reduce(); } if(DIGITAL.Decode) { DIGITAL.Decode(); } if(overflow) { DIGITAL_PrintSymbol(FONT_SYMBOL_OVERFLOW); DIGITAL_Hold(DIGITAL.hold); } if(DISPLAY_Update()) { DIGITAL_Update(); } } void DIGITAL_Display(DIGITAL_DISPLAY_t display) { DIGITAL.display = display; } void DIGITAL_Print(uint8_t data) { if(DIGITAL.display==DIGITAL_DISPLAY_HEX) { DIGITAL_PrintHex(data>>4); DIGITAL_PrintHex(data>>0); DIGITAL_PrintTab(); } else { if(data=='\n') { DIGITAL_NewLine(); } else { DIGITAL_PrintChar(data); } } } void DIGITAL_PrintChar(uint8_t ch) { if((DIGITAL.end_line)||(DIGITAL.column>=14)) { DIGITAL.end_line = 0; DIGITAL_NewLine(); } DIGITAL.buffer[DIGITAL.row].text[DIGITAL.column] = ch; DIGITAL.column++; DIGITAL.idle = 0; } void DIGITAL_PrintSymbol(uint8_t sym) { DIGITAL_PrintChar(sym); uint16_t mask = (1<<DIGITAL.column); if(DIGITAL.display==DIGITAL_DISPLAY_HEX) { DIGITAL_PrintChar(sym); mask |= (1<<DIGITAL.column); DIGITAL_PrintTab(); } DIGITAL.buffer[DIGITAL.row].control |= mask; } void DIGITAL_PrintHex(uint8_t hex) { hex &= 0x0F; hex += '0'+((hex>9)*7); DIGITAL_PrintChar(hex); } void DIGITAL_PrintTab(void) { uint8_t tab_length = 3-(DIGITAL.column%3); if((DIGITAL.column+tab_length)>14) { return; } for(uint8_t i=0; i<tab_length; i++) { DIGITAL_PrintChar(' '); } } void DIGITAL_EndLine(void) { DIGITAL.end_line = 1; } static void DIGITAL_NewLine(void) { DIGITAL.column = 0; if(++DIGITAL.row>=5) { DIGITAL.row = 0; DIGITAL.roll = 1; } for(uint8_t i=0; i<14; i++) { DIGITAL.buffer[DIGITAL.row].text[i] = ' '; } DIGITAL.buffer[DIGITAL.row].control = 0; if(++DIGITAL.counter>DISPLAY_WIDTH) { DIGITAL.counter = 1; } } void DIGITAL_InvertLine(void) { DIGITAL.buffer[DIGITAL.row].control |= DIGITAL_INVERT; } void DIGITAL_Clear(void) { for(uint8_t y=0; y<5; y++) { for(uint8_t x=0; x<14; x++) { DIGITAL.buffer[y].text[x] = ' '; } DIGITAL.buffer[y].control = 0; } DIGITAL.row = 0; DIGITAL.column = 0; DIGITAL.roll = 0; } void DIGITAL_Blackout(void) { for(uint8_t y=0; y<5; y++) { uint16_t mask = (1<<1); for(uint8_t x=0; x<14; x++) { if(DIGITAL.buffer[y].text[x]!=' ') { DIGITAL.buffer[y].text[x] = FONT_SYMBOL_BLACK_BOX; } DIGITAL.buffer[y].control |= mask; mask<<=1; } } } uint8_t DIGITAL_Lock(void) { return DIGITAL.lock; } void DIGITAL_Hold(uint8_t hold) { DIGITAL.hold = hold; if(hold) { BUFFER_Stop(); DISPLAY_Backlight(DISPLAY_BACKLIGHT_AUX); } else { BUFFER_Start(); DISPLAY_Backlight(DISPLAY_BACKLIGHT_MAIN); } BUFFER_Clear(); if(DIGITAL.idle<DELAY_Idle()) { DIGITAL.idle = 0; } } uint8_t DIGITAL_IsHold(void) { return DIGITAL.hold; } void DIGITAL_Update(void) { DISPLAY_Clear(); uint8_t offset = 0; if(DIGITAL.roll) { offset = DIGITAL.row+1; } for(uint8_t i=0; i<5; i++) { uint8_t y = (offset+i)%5; DISPLAY_CursorPosition(1, (i*9)+1); uint16_t mask = (1<<1); for(uint8_t x=0; x<14; x++) { uint8_t ch = DIGITAL.buffer[y].text[x]; uint16_t control = DIGITAL.buffer[y].control; if(!(control&mask)) { if((ch<32)||(ch>127)) { ch = 127; } } DISPLAY_PrintChar(ch); mask<<=1; } if(DIGITAL.buffer[y].control&DIGITAL_INVERT) { DISPLAY_InvertLine(i*9); } } if(DIGITAL.hold) { DISPLAY_ProgressBar(-1); } else { DISPLAY_ProgressBar(DIGITAL.counter); } if(DIGITAL.idle>=DELAY_Idle()) { DISPLAY_Idle(); } else if(!DIGITAL.hold) { DIGITAL.idle++; } }
# frozen_string_literal: true module Bonita module Customuserinfo # API reference : http://documentation.bonitasoft.com/?page=customuserinfo-api#toc9 class ValueResource < ResourceKit::Resource include ErrorHandler resources do action :associate_definition_to_user do path 'bonita/API/customuserinfo/value/:userId/:definitionId' verb :put body { |object| object.select { |k| k == :value }.to_json } handler(200) { true } end end end end end
<?php namespace Cysha\Casino\Cards; use BadMethodCallException; use Illuminate\Support\Collection; class CardCollection extends Collection { /** * @var string * * @return static */ public static function fromString(string $cards) { $cards = explode(' ', $cards); return static::make($cards)->map(function ($card) { return Card::fromString($card); }); } /** * Get cards where Suit value is... * * @param string $name * * @return static */ public function whereSuit(string $name) { $name = rtrim($name, 's'); return $this->filter(function (Card $card) use ($name) { return $card->suit()->equals(call_user_func(Suit::class . '::' . $name)); }); } /** * Get cards where Card Value is.. * * @param int $value * * @return static */ public function whereValue(int $value) { return $this->filter(function (Card $card) use ($value) { return $card->value() === $value; }); } /** * Sort cards by Suit value. * * @param $sort * * @return static */ public function sortBySuitValue() { return $this->sortBy(function (Card $card) { return $card->suit()->value(); }); } /** * Sum cards by their value. * * @param int $sort * * @return static */ public function sumByValue() { return $this->sum(function (Card $card) { return $card->value(); }); } /** * Sort cards by their value, and then by Suit. * * @param int $sort * * @return static */ public function sortByValue($sort = SORT_NUMERIC) { return $this ->groupBy(function (Card $card) { return $card->value(); }) ->map(function (CardCollection $valueGroup) { return $valueGroup->sortBySuitValue(); }) ->flatten() ->sortBy(function (Card $card) { return $card->value(); }, $sort) ->values(); } /** * Group cards by the value and sort by highest card count first. * * @return static */ public function groupByValue() { return $this ->sortByDesc(function (Card $card) { return $card->value(); }, SORT_NUMERIC) ->groupBy(function (Card $card) { return $card->value(); }) ->sortByDesc(function ($group) { return count($group); }, SORT_NUMERIC) ->values(); } /** * Filter out duplicate card values out of the collection. * * @return static */ public function uniqueByValue() { return $this ->sortByDesc(function (Card $card) { return $card->value(); }, SORT_NUMERIC) ->groupBy(function (Card $card) { return $card->value(); }) ->map(function($group) { return $group->first(); }) ->reverse() ->values(); } /** * Replaces any Aces found in the collection with values of 14. * * @return static */ public function switchAceValue() { return $this->map(function (Card $card) { if ($card->isAce() === false) { return $card; } return new Card(14, $card->suit()); }); } /** * @param string $name * @param array $arguments * * @return static * * @throws BadMethodCallException */ public function __call($name, $arguments) { if (in_array($name, ['hearts', 'diamonds', 'clubs', 'spades'], true) !== false) { return $this->whereSuit($name); } throw new BadMethodCallException(); } /** * @return string */ public function __toString() { return $this->map(function (Card $card) { return $card->__toString(); })->implode(' '); } }
<?php namespace Tests\Feature; use App\Models\Contract; use App\Models\Job; use App\Models\User; use Illuminate\Foundation\Testing\LazilyRefreshDatabase; use Tests\TestCase; class JobSortTest extends TestCase { use LazilyRefreshDatabase; public function setUp() :void { parent::setUp(); Contract::factory()->create(); User::factory()->create(); } public function test_sort_job() { Job::factory()->create([ 'title' => 'latest', 'created_at' => now(), 'updated_at' => now() ]); Job::factory()->create([ 'title' => 'oldest', 'created_at' => now()->subHour(), 'updated_at' => now()->subHour() ]); $response = $this->getJson('/api/jobs?sort=oldest'); $response ->assertStatus(200) ->assertJson(function($json) { $json ->has('meta') ->has('links') ->has('data', 2) ->has('data.0', function($json) { $json ->where('title', 'oldest') ->etc(); }); }); } }
//---------------------------------------------- // Flip Web Apps: Game Framework // Copyright © 2016 Flip Web Apps / Mark Hewitt // // Please direct any bugs/comments/suggestions to http://www.flipwebapps.com // // The copyright owner grants to the end user a non-exclusive, worldwide, and perpetual license to this Asset // to integrate only as incorporated and embedded components of electronic games and interactive media and // distribute such electronic game and interactive media. End user may modify Assets. End user may otherwise // not reproduce, distribute, sublicense, rent, lease or lend the Assets. It is emphasized that the end // user shall not be entitled to distribute or transfer in any way (including, without, limitation by way of // sublicense) the Assets in any other way than as integrated components of electronic games and interactive media. // The above copyright notice and this permission notice must not be removed from any files. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //---------------------------------------------- using System.Collections; using UnityEngine; #if BEAUTIFUL_TRANSITIONS using BeautifulTransitions.Scripts.Transitions; #endif namespace GameFramework.Animation.ObjectModel { /// <summary> /// Used for animating between two different gameobjects. /// </summary> [System.Serializable] public class GameObjectToGameObjectAnimation { #region Enums /// <summary> /// The type of animation to run /// </summary> public enum AnimationModeType { Immediate, BeautifulTransitions } // , Animation } /// <summary> /// The order in which to run transitions /// </summary> /// OutIn - Run a transition out then when complete a transition in. /// Parallel - Run a out and at the same time a transition in (use a delay to offset). public enum TransitionOrderType { OutIn, Parallel } #endregion Enums #region Editor Parameters /// <summary> /// The animation mode for swapping between gameobjects. /// </summary> public AnimationModeType AnimationMode { get { return _animationMode; } set { _animationMode = value; } } [Tooltip("The animation mode for swapping between gameobjects.")] [SerializeField] AnimationModeType _animationMode; /// <summary> /// The order in which to run transitions /// </summary> public TransitionOrderType TransitionOrder { get { return _transitionOrder; } set { _transitionOrder = value; } } [Tooltip("The order in which to run transitions")] [SerializeField] TransitionOrderType _transitionOrder; ///// <summary> ///// An optional transition that should be run to transition in / out. If not specified and TransitionChanges is set then the first attached transition will be used. ///// </summary> ///// You might want to use different transitions from when this item is first shown and when changes occur. //public TransitionBase Transition //{ // get { return _transition; } // set { _transition = value; } //} //[Tooltip("An optional transition that should be run to transition in / out. If not specified and TransitionChanges is set then the first attached transition will be used.")] //[SerializeField] //TransitionBase _transition; #endregion Editor Parameters public void AnimatedSwap(MonoBehaviour controller, GameObject fromGameObject, GameObject toGameObject, bool isStart = false) { // Option to not animate onStart #if BEAUTIFUL_TRANSITIONS if (AnimationMode == AnimationModeType.BeautifulTransitions) { if (TransitionOrder == TransitionOrderType.OutIn) controller.StartCoroutine(TransitionOutIn(fromGameObject, toGameObject)); else controller.StartCoroutine(TransitionParallel(fromGameObject, toGameObject)); return; } //else if (AnimationType == GameItemContextConditionallyEnable.AnimationType.Animation) { // if (!isStart) { // activateImmediately = false; // } //} #endif // default to swap immediately SwapImmediately(fromGameObject, toGameObject); } public void SwapImmediately(GameObject fromGameObject, GameObject toGameObject) { if (fromGameObject != null) fromGameObject.SetActive(false); if (toGameObject != null) toGameObject.SetActive(true); } #if BEAUTIFUL_TRANSITIONS IEnumerator TransitionOutIn(GameObject fromGameObject, GameObject toGameObject) { if (fromGameObject != null) { // is an out transition then run and wait for completion if (TransitionHelper.ContainsTransition(fromGameObject)) { var transitions = TransitionHelper.TransitionOut(fromGameObject); var transitionOutTime = TransitionHelper.GetTransitionOutTime(transitions); yield return new WaitForSeconds(transitionOutTime); } fromGameObject.SetActive(false); } if (toGameObject != null) { toGameObject.SetActive(true); if (TransitionHelper.ContainsTransition(toGameObject)) { TransitionHelper.TransitionIn(toGameObject); } } } #endif #if BEAUTIFUL_TRANSITIONS IEnumerator TransitionParallel(GameObject fromGameObject, GameObject toGameObject) { float transitionOutTime = 0; if (fromGameObject != null) { if (TransitionHelper.ContainsTransition(fromGameObject)) { var transitions = TransitionHelper.TransitionOut(fromGameObject); transitionOutTime = TransitionHelper.GetTransitionOutTime(transitions); } } if (toGameObject != null) { toGameObject.SetActive(true); if (TransitionHelper.ContainsTransition(toGameObject)) { TransitionHelper.TransitionIn(toGameObject); } } // wait for transition out to complete before we disable. if (!Mathf.Approximately(0, transitionOutTime)) yield return new WaitForSeconds(transitionOutTime); if (fromGameObject != null) fromGameObject.SetActive(false); } #endif } }
import { SchemaComposer, ObjectTypeComposer, InputTypeComposer, InterfaceTypeComposer, ObjectTypeComposerFieldConfigMapDefinition, } from "graphql-compose" import { getFieldsEnum } from "./sort" import { addDerivedType } from "./derived-types" import { distinct, group, max, min, sum } from "../resolvers" export const getPageInfo = <TContext = any>({ schemaComposer, }: { schemaComposer: SchemaComposer<TContext> }): ObjectTypeComposer => schemaComposer.getOrCreateOTC(`PageInfo`, tc => { tc.addFields({ currentPage: `Int!`, hasPreviousPage: `Boolean!`, hasNextPage: `Boolean!`, itemCount: `Int!`, pageCount: `Int!`, perPage: `Int`, totalCount: `Int!`, }) }) export const getEdge = <TContext = any>({ schemaComposer, typeComposer, }: { schemaComposer: SchemaComposer<TContext> typeComposer: ObjectTypeComposer | InterfaceTypeComposer }): ObjectTypeComposer => { const typeName = `${typeComposer.getTypeName()}Edge` addDerivedType({ typeComposer, derivedTypeName: typeName }) return schemaComposer.getOrCreateOTC(typeName, tc => { tc.addFields({ next: typeComposer, node: typeComposer.getTypeNonNull(), previous: typeComposer, }) }) } const createPagination = <TSource = any, TContext = any>({ schemaComposer, typeComposer, fields, typeName, }: { schemaComposer: SchemaComposer<TContext> typeComposer: ObjectTypeComposer | InterfaceTypeComposer fields: ObjectTypeComposerFieldConfigMapDefinition<TSource, TContext> typeName: string }): ObjectTypeComposer => { const paginationTypeComposer: ObjectTypeComposer = schemaComposer.getOrCreateOTC( typeName, tc => { tc.addFields({ totalCount: `Int!`, edges: [getEdge({ schemaComposer, typeComposer }).getTypeNonNull()], nodes: [typeComposer.getTypeNonNull()], pageInfo: getPageInfo({ schemaComposer }).getTypeNonNull(), ...fields, }) } ) paginationTypeComposer.makeFieldNonNull(`edges`) paginationTypeComposer.makeFieldNonNull(`nodes`) addDerivedType({ typeComposer, derivedTypeName: typeName }) return paginationTypeComposer } export const getGroup = <TContext = any>({ schemaComposer, typeComposer, }: { schemaComposer: SchemaComposer<TContext> typeComposer: ObjectTypeComposer | InterfaceTypeComposer }): ObjectTypeComposer => { const typeName = `${typeComposer.getTypeName()}GroupConnection` const fields = { field: `String!`, fieldValue: `String`, } return createPagination({ schemaComposer, typeComposer, fields, typeName }) } export const getPagination = <TContext = any>({ schemaComposer, typeComposer, }: { schemaComposer: SchemaComposer<TContext> typeComposer: ObjectTypeComposer | InterfaceTypeComposer }): ObjectTypeComposer => { const inputTypeComposer: InputTypeComposer = typeComposer.getInputTypeComposer() const typeName = `${typeComposer.getTypeName()}Connection` const fieldsEnumTC = getFieldsEnum({ schemaComposer, typeComposer, inputTypeComposer, }) const fields: { [key: string]: any } = { distinct: { type: [`String!`], args: { field: fieldsEnumTC.getTypeNonNull(), }, resolve: distinct, }, max: { type: `Float`, args: { field: fieldsEnumTC.getTypeNonNull(), }, resolve: max, }, min: { type: `Float`, args: { field: fieldsEnumTC.getTypeNonNull(), }, resolve: min, }, sum: { type: `Float`, args: { field: fieldsEnumTC.getTypeNonNull(), }, resolve: sum, }, group: { type: [getGroup({ schemaComposer, typeComposer }).getTypeNonNull()], args: { skip: `Int`, limit: `Int`, field: fieldsEnumTC.getTypeNonNull(), }, resolve: group, }, } const paginationTypeComposer: ObjectTypeComposer = createPagination({ schemaComposer, typeComposer, fields, typeName, }) paginationTypeComposer.makeFieldNonNull(`distinct`) paginationTypeComposer.makeFieldNonNull(`group`) return paginationTypeComposer }
# frozen_string_literal: true if ENV['COVERAGE'] =~ /\Atrue\z/i require 'simplecov' require 'cadre/simplecov' SimpleCov.start do add_filter '/.bundle/' add_filter '/spec/' add_filter '/config/' add_group 'Libraries', 'lib' add_group 'Ignored Code' do |src_file| File.readlines(src_file.filename).grep(/:nocov:/).any? end end SimpleCov.formatters = [ SimpleCov::Formatter::HTMLFormatter, Cadre::SimpleCov::VimFormatter ] # SimpleCov.minimum_coverage 95 SimpleCov.command_name 'Rspec' end $LOAD_PATH.unshift File.expand_path('../lib', __dir__) require 'capybara_error_intel' require 'capybara/spec/spec_helper' RSpec.configure do |config| Capybara::SpecHelper.configure(config) end
package com.youran.generate.pojo.vo; import com.youran.common.pojo.vo.AbstractVO; import com.youran.generate.pojo.dto.LabelDTO; import io.swagger.annotations.ApiModelProperty; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import java.util.List; import static com.youran.generate.pojo.example.MetaProjectExample.*; /** * 项目列表展示对象 * * @author: cbb * @date 2017/5/24 */ public class MetaProjectListVO extends AbstractVO { @ApiModelProperty(notes = N_PROJECTID, example = E_PROJECTID) private Integer projectId; @ApiModelProperty(notes = N_PACKAGENAME, example = E_PACKAGENAME) private String packageName; @ApiModelProperty(notes = N_PROJECTNAME, example = E_PROJECTNAME) private String projectName; @ApiModelProperty(notes = N_PROJECTDESC, example = E_PROJECTDESC) private String projectDesc; @ApiModelProperty(notes = N_GROUPID, example = E_GROUPID) private String groupId; @ApiModelProperty(notes = N_AUTHOR, example = E_AUTHOR) private String author; @ApiModelProperty(notes = N_REMOTE, example = E_REMOTE) private Boolean remote; @ApiModelProperty(notes = N_TEMPLATEID, example = E_TEMPLATEID) private Integer templateId; @ApiModelProperty(notes = N_TEMPLATEID, example = E_TEMPLATEID) private Integer templateId2; @ApiModelProperty(notes = N_TEMPLATEID, example = E_TEMPLATEID) private Integer templateId3; @ApiModelProperty(notes = N_REMOTEURL, example = E_REMOTEURL) private String remoteUrl; @ApiModelProperty(notes = N_REMOTEURL, example = E_REMOTEURL) private String remoteUrl2; @ApiModelProperty(notes = N_REMOTEURL, example = E_REMOTEURL) private String remoteUrl3; @ApiModelProperty(notes = N_USERNAME, example = E_USERNAME) private String username; @ApiModelProperty(notes = "标签") private List<LabelDTO> labels; @ApiModelProperty(notes = N_TEAM_ID, example = E_TEAM_ID) private Integer teamId; @ApiModelProperty(notes = N_CREATEDBY, example = E_CREATEDBY) private String createdBy; public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public Boolean getRemote() { return remote; } public void setRemote(Boolean remote) { this.remote = remote; } public String getRemoteUrl() { return remoteUrl; } public void setRemoteUrl(String remoteUrl) { this.remoteUrl = remoteUrl; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getProjectId() { return projectId; } public void setProjectId(Integer projectId) { this.projectId = projectId; } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public Integer getTemplateId() { return templateId; } public void setTemplateId(Integer templateId) { this.templateId = templateId; } public Integer getTemplateId2() { return templateId2; } public void setTemplateId2(Integer templateId2) { this.templateId2 = templateId2; } public Integer getTemplateId3() { return templateId3; } public void setTemplateId3(Integer templateId3) { this.templateId3 = templateId3; } public String getRemoteUrl2() { return remoteUrl2; } public void setRemoteUrl2(String remoteUrl2) { this.remoteUrl2 = remoteUrl2; } public String getRemoteUrl3() { return remoteUrl3; } public void setRemoteUrl3(String remoteUrl3) { this.remoteUrl3 = remoteUrl3; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getProjectDesc() { return projectDesc; } public void setProjectDesc(String projectDesc) { this.projectDesc = projectDesc; } public List<LabelDTO> getLabels() { return labels; } public void setLabels(List<LabelDTO> labels) { this.labels = labels; } public Integer getTeamId() { return teamId; } public void setTeamId(Integer teamId) { this.teamId = teamId; } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.JSON_STYLE) .append("projectId", projectId) .append("packageName", packageName) .append("projectName", projectName) .append("projectDesc", projectDesc) .append("groupId", groupId) .append("author", author) .append("remote", remote) .toString(); } }
import { connect } from 'react-redux' import BlockDetails from '../components/BlockDetails' const mapStateToProps = (state) => { return { configuration: state.configuration.wallet, blockchain: state.blockchain } }   const BlockContainer = connect( mapStateToProps )(BlockDetails)   export default BlockContainer
IF OBJECT_ID('social.count_comments') IS NOT NULL DROP FUNCTION social.count_comments; GO CREATE FUNCTION social.count_comments(@feed_id bigint) RETURNS bigint AS BEGIN DECLARE @count bigint; WITH all_comments AS ( SELECT social.feeds.feed_id FROM social.feeds WHERE social.feeds.parent_feed_id = @feed_id UNION ALL SELECT feed_comments.feed_id FROM social.feeds AS feed_comments INNER JOIN all_comments ON all_comments.feed_id = feed_comments.parent_feed_id ) SELECT @count = COUNT(*) FROM all_comments; RETURN @count; END GO --SELECT social.count_comments(87);
export default [ { path: '/', redirect: { name: 'Login' } }, { path: '/login', name: 'Login', component: resolve => require(['@/components/login'], resolve), meta: { showInMenu: false } }, { path: '/main', name: 'Main', component: resolve => require(['@/components/main'], resolve), meta: { showInMenu: false } }, { path: '/401', name: 'Error401', component: resolve => require(['@/components/error/401'], resolve), meta: { showInMenu: false } }, { path: '*', name: 'Error404', component: resolve => require(['@/components/error/404'], resolve), meta: { showInMenu: false } } ]
apm install file-icons apm install file-types apm install language-latex apm install latex-autocomplete apm install latextools apm install linter apm install linter-ui-default apm install plist-converter apm install teletype
# generated by 'rake generate' require 'cocoa/bindings/NSCell' module Cocoa class NSBrowserCell < Cocoa::NSCell attach_method :alternateImage, :args=>0, :names=>[], :types=>[], :retval=>"@" attach_singular_method :branchImage, :args=>0, :names=>[], :types=>[], :retval=>"@" attach_method :highlightColorInView, :args=>1, :names=>[], :types=>["@"], :retval=>"@" attach_singular_method :highlightedBranchImage, :args=>0, :names=>[], :types=>[], :retval=>"@" attach_method :image, :args=>0, :names=>[], :types=>[], :retval=>"@" attach_method :isLeaf, :args=>0, :names=>[], :types=>[], :retval=>"B" attach_method :isLoaded, :args=>0, :names=>[], :types=>[], :retval=>"B" attach_method :reset, :args=>0, :names=>[], :types=>[], :retval=>"v" attach_method :set, :args=>0, :names=>[], :types=>[], :retval=>"v" attach_method :setAlternateImage, :args=>1, :names=>[], :types=>["@"], :retval=>"v" attach_method :setImage, :args=>1, :names=>[], :types=>["@"], :retval=>"v" attach_method :setLeaf, :args=>1, :names=>[], :types=>["B"], :retval=>"v" attach_method :setLoaded, :args=>1, :names=>[], :types=>["B"], :retval=>"v" end end
package io.scalanator.robot.environment import io.scalanator.robot.BuildInfo object Environment { def info: Seq[String] = Seq( "Environment:", s" OS : $osVersion", s" Java : $javaVersion", s" Scala version: $scalaVersion", s" Built with Scala version: ${BuildInfo.scalaVersion}", s" Built with sbt version: ${BuildInfo.sbtVersion}", s" Built from git sha: ${BuildInfo.gitSha}", s" Built on: ${BuildInfo.builtAtString}" ) private def osVersion: String = System.getProperty("os.name") private def javaVersion: String = { val vmInfo = System.getProperty("java.vm.name") + " " + System.getProperty("java.vm.version") val rtInfo = System.getProperty("java.runtime.name") + " " + System.getProperty("java.runtime.version") vmInfo + ", " + rtInfo } private def scalaVersion: String = scala.util.Properties.versionString }