text
stringlengths
1
1.05M
'use strict'; /* This file contains verifying specs for: https://github.com/sindresorhus/atom-editorconfig/issues/67 */ const path = require('path'); const generateConfig = require('../commands/generate-config.js'); const {poll} = AtomMocha.utils; const {punch} = require('./utils.js'); describe('Issue #67', () => { when('generating an .editorconfig file', () => { beforeEach('Activating package', () => { attachToDOM(atom.views.getView(atom.workspace)); return atom.packages.activatePackage(path.join(__dirname, '..')); }); when('there is no project and no file open', () => { let originalAddError = null; let callCount = 0; before(() => { expect(originalAddError).to.be.null; callCount = 0; [originalAddError] = punch(atom.notifications, 'addError', function (fn, args) { ++callCount; return fn.call(this, args); }); }); afterEach(() => { expect(originalAddError).to.be.a('function'); atom.notifications.addError = originalAddError; originalAddError = null; }); it('doesn\'t throw an exception', async () => { if (typeof atom.workspace.getActivePaneItem() !== 'undefined') { for (const editor of atom.workspace.getPaneItems()) { editor.shouldPromptToSave = () => false; editor.destroy(); } } await poll(() => { return typeof atom.workspace.getActiveTextEditor() === 'undefined'; }); atom.project.setPaths([]); expect(atom.project.getPaths().length).to.equal(0); expect(atom.workspace.getActiveTextEditor()).to.be.undefined; expect(generateConfig).not.to.throw(); expect(callCount).to.be.at.least(1); }); }); }); });
class SmartHomeAdapter: def __init__(self): self.devices = {} def register_device(self, device_name, device_class): self.devices[device_name] = device_class def control_device(self, device_name, command): if device_name in self.devices: device = self.devices[device_name]() method_to_call = getattr(device, command, None) if method_to_call: method_to_call() else: print(f"Command '{command}' not supported for device '{device_name}'.") else: print(f"Device '{device_name}' not found in the registry.") # Example usage class BRT100TRV: def __init__(self): pass def turn_on(self): print("Turning on BRT-100-TRV radiator valve.") def turn_off(self): print("Turning off BRT-100-TRV radiator valve.") adapter = SmartHomeAdapter() adapter.register_device('BRT-100-TRV', BRT100TRV) adapter.control_device('BRT-100-TRV', 'turn_on') # Output: Turning on BRT-100-TRV radiator valve. adapter.control_device('BRT-100-TRV', 'turn_off') # Output: Turning off BRT-100-TRV radiator valve. adapter.control_device('BRT-100-TRV', 'set_temperature') # Output: Command 'set_temperature' not supported for device 'BRT-100-TRV'. adapter.control_device('UnknownDevice', 'turn_on') # Output: Device 'UnknownDevice' not found in the registry.
# Download IndicLink test data
#!/bin/bash build='builder/builder' src_dir='data/animations/' dst_dir='data/animations/' actor_dir='data/built/' ybot_dir='data/animations/ybot_retargeted/fbx/' sampling_frequency='--sampling_frequency 120' $build 'data/animations/16_01.bvh' 'data/built/16' '--actor' '--root_bone' 'Hips' '--scale' '0.056444' for i in $src_dir*.bvh; do if [[ $i == *"16"*".bvh" ]]; then echo "building " $i $build $i $dst_dir`basename $i .bvh` '--animation' '--target_actor' 'data/built/16.actor' $sampling_frequency fi done $build 'data/animations/69_01.bvh' 'data/built/69' '--actor' '--root_bone' 'Hips' '--scale' '0.056444' for i in $src_dir*.bvh; do if [[ $i == *"69"*".bvh" ]]; then echo "building " $i $build $i $dst_dir`basename $i .bvh` '--animation' '--target_actor' 'data/built/69.actor' $sampling_frequency fi done $build 'data/animations/127_01.bvh' 'data/built/127' '--actor' '--root_bone' 'Hips' '--scale' '0.056444' for i in $src_dir*.bvh; do if [[ $i == *"127"*".bvh" ]]; then echo "building " $i $build $i $dst_dir`basename $i .bvh` '--animation' '--target_actor' 'data/built/127.actor' $sampling_frequency fi done printf "\n" $build 'data/animations/91_01.bvh' 'data/built/91' '--actor' '--root_bone' 'Hips' '--scale' '0.056444' printf "\n" $build 'data/animations/91_01.bvh' 'data/built/01_91' '--actor' '--root_bone' 'Hips' '--scale' '0.056444' $sampling_frequency printf "\n" for i in $src_dir*.bvh; do if [[ $i == *"91"*".bvh" ]]; then echo "building " $i $build $i $dst_dir`basename $i .bvh` '--animation' '--target_actor' 'data/built/91.actor' $sampling_frequency fi done
/** * @file 获取节点 stump 的 comment * @author errorrik(<EMAIL>) */ var getNodeStumpParent = require('./get-node-stump-parent'); /** * 获取节点 stump 的 comment * * @param {Node} node 节点对象 * @return {Comment} */ function getNodeStump(node) { if (typeof node.el === 'undefined') { var parentNode = getNodeStumpParent(node); var el = parentNode.firstChild; while (el) { if (el.nodeType === 8 && el.data.indexOf('san:') === 0 && el.data.replace('san:', '') === node.id ) { break; } el = el.nextSibling; } node.el = el; } return node.el; } exports = module.exports = getNodeStump;
<filename>src/se/chalmers/watchme/notifications/Notifiable.java /** * Notifiable.java * * Interface for describing classes that may be used in * notifications on a specific date. * * @author <NAME> * @copyright (c) 2012 <NAME>, <NAME>, <NAME>, <NAME> * @license MIT */ package se.chalmers.watchme.notifications; public interface Notifiable { /** * The notification id for this object. * * Must be unique within the system (suggestion is to use hashCode()). * * @return An id */ public int getNotificationId(); /** * Get the date in milliseconds. Used to set the timestamp * of the notification. * * @return The date to trigger */ public long getDateInMilliSeconds(); /** * The short string representation of this notifiable object. * * @return The title to represent in the notification */ public String getTitle(); }
#ifndef KSERV_H #define KSERV_H #include "package.h" typedef void (*kserv_func_t) (package_t* pkg, void *p); bool kserv_run(const char* reg_name, kserv_func_t servFunc, void* p); int kserv_get_pid(const char* reg_name); void kserv_wait(const char* reg_name); #endif
#!/usr/bin/env bash cd "${TRAVIS_BUILD_DIR}" build/bin/tests if [ $? -eq 0 ] then echo "Successfully ran Catch2 tests" else echo "Error in running Catch2 tests" >&2 exit 1 fi exit 0
jQuery(document).ready(function ($) { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $('#register').click(function() { $.post( "register", { email: $('#email-r').val(), password: <PASSWORD>').val(), re_password: $('#<PASSWORD>').val() }, function( data ) { console.log(data); if (data == 'success') { location.href('http://minhthien.site88.net/'); } else { if (data.errorEmail != null) { $('.email').addClass('has-error'); $('.errorEmail').html(data.errorEmail); } else { $('.errorEmail').empty(); } if (data.errorPassword != null) { $('.password').addClass('has-error'); $('.errorPassword').html(data.errorPassword); } else { $('.errorPassword').empty(); } if (data.errorPasswordConfirm != null) { $('.passwordConfirm').addClass('has-error'); $('.errorPasswordConfirm').html(data.errorPasswordConfirm); } else { $('.errorPasswordConfirm').empty(); } $('input[type="password"]').val(''); } } ); }); checkCheckbox(); $("input[name='remember']").click(function() { if ($(this).is(":checked")) $(this).val('true'); else $(this).val('false'); }); function checkCheckbox() { if ($(".remember").val() == 'true') $(".remember").prop('checked', true); else $(".remember").prop('checked', false); } function setCheckbox() { if ($(".remember").is(":checked")) $(".remember").val('true'); else $(".remember").val('false'); } // $("#remember").click(function() { // setCheckbox(); // }); // function checkCheckbox() { // if ($("#remember").val() == 'true') // $("#remember").prop('checked', true); // else // $("#remember").prop('checked', false); // } // function setCheckbox() { // if ($("#remember").is(":checked")) // $("#remember").val('true'); // else // $("#remember").val('false'); // } })
#!/bin/bash # entrypoint.sh file for starting the xvfb with better screen resolution, configuring and running the vnc server, pulling the code from git and then running the test. export DISPLAY=:20 Xvfb :20 -screen 0 1366x768x16 & x11vnc -passwd wail -display :20 -N -forever & wait
<filename>src/core/stats/StatsService.js import { getDocAndRefs, isEmptyOrNonExistentDoc } from '../util/DocManagement' const USERS_COLLECTION = 'users' const MINISTRY_COLLECTION = 'ministries' const GLOBAL_COLLECTION = 'global' const GLOBAL_DOCUMENT = 'global' export default class StatsService { static incrementConvosForUser = async uid => { const { doc, docRef } = await getDocAndRefs(USERS_COLLECTION, uid) const currentStats = await getOrCreateStatsForDoc(doc, docRef) currentStats.convos = await incrementFieldValueForDoc(doc, docRef, 'convos') return currentStats } static incrementConversionsForUser = async uid => { const { doc, docRef } = await getDocAndRefs(USERS_COLLECTION, uid) const currentStats = await getOrCreateStatsForDoc(doc, docRef) currentStats.conversions = await incrementFieldValueForDoc(doc, docRef, 'conversions') return currentStats } static getOrCreateAllStatsForUser = async uid => { const { doc, docRef } = await getDocAndRefs(USERS_COLLECTION, uid) return getOrCreateStatsForDoc(doc, docRef) } static incrementConvosForMinistry = async mid => { const { doc, docRef } = await getDocAndRefs(MINISTRY_COLLECTION, mid) const currentStats = await getOrCreateStatsForDoc(doc, docRef) currentStats.convos = await incrementFieldValueForDoc(doc, docRef, 'convos') return currentStats } static incrementConversionsForMinistry = async mid => { const { doc, docRef } = await getDocAndRefs(MINISTRY_COLLECTION, mid) const currentStats = await getOrCreateStatsForDoc(doc, docRef) currentStats.conversions = await incrementFieldValueForDoc(doc, docRef, 'conversions') return currentStats } static getOrCreateAllStatsForMinistry = async mid => { const { doc, docRef } = await getDocAndRefs(MINISTRY_COLLECTION, mid) return getOrCreateStatsForDoc(doc, docRef) } static incrementConvosForGlobal = async () => { const { doc, docRef } = await getDocAndRefs(GLOBAL_COLLECTION, GLOBAL_DOCUMENT) const currentStats = await StatsService.getAllStatsForGlobal() currentStats.convos = await incrementFieldValueForDoc(doc, docRef, 'convos') return currentStats } static incrementConversionsForGlobal = async () => { const { doc, docRef } = await getDocAndRefs(GLOBAL_COLLECTION, GLOBAL_DOCUMENT) const currentStats = await StatsService.getAllStatsForGlobal() currentStats.conversions = await incrementFieldValueForDoc(doc, docRef, 'conversions') return currentStats } static getAllStatsForGlobal = async () => { // Global should always exist const { doc, docRef } = await getDocAndRefs(GLOBAL_COLLECTION, GLOBAL_DOCUMENT) console.log(doc) console.log(docRef) return { convos: doc.data().convos, conversions: doc.data().conversions } } } async function getOrCreateStatsForDoc(doc, docRef) { if (doc.id == GLOBAL_DOCUMENT) { throw new Error('Cannot overwrite global stats!') } if (doc.data().convos && doc.data().conversions) { // Already exists return { convos: doc.data().convos, conversions: doc.data().conversions } } const stats = { convos: doc.data().convos ? doc.data().convos : 0, conversions: doc.data().conversions ? doc.data().conversions : 0 } await docRef.update(stats) return stats } async function incrementFieldValueForDoc(doc, docRef, fieldName) { let newCount if (!doc.data()[fieldName]) { newCount = 1 } else { newCount = doc.data()[fieldName] + 1 } await docRef.update({ [fieldName]: newCount }) return newCount }
#!/usr/bin/env bash set -e NPROC=1 # OS detection if [ "$(uname)" = "Linux" ]; then NPROC=$(nproc) CC=clang-10 elif [ "$(uname)" = "Darwin" ]; then NPROC=$(sysctl -n hw.ncpu) CC=clang elif [ "$(uname)" = "FreeBSD" ]; then NPROC=$(sysctl -n hw.ncpu) CC=cc else echo "Error: $(uname) not supported, sorry!" exit 1 fi # Check if we have a compiler if ! [ -x "$(command -v $CC)" ]; then echo "Error: $CC is not installed!" >&2 exit 1 fi echo "OS :" $(uname) echo "CC :" $CC echo "NP :" $NPROC # Go to script directory SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" cd "$SCRIPT_DIR" cd ".." pwd # Find and then delete all files under current directory (.) that: # 1. contains "cmake" (case-&insensitive) in its path (wholename) # 2. name is not CMakeLists.txt find . -iwholename '*cmake*' -not -name CMakeLists.txt -delete # Build with ASAN / MSAN cmake -Dsctp_build_fuzzer=1 -Dsctp_build_programs=0 -Dsctp_invariants=1 -Dsctp_sanitizer_address=1 -DCMAKE_LINKER="$CC" -DCMAKE_C_COMPILER="$CC" . #cmake -Dsctp_build_fuzzer=1 -Dsctp_build_programs=0 -Dsctp_invariants=1 -Dsctp_sanitizer_memory=1 -DCMAKE_LINKER="$CC" -DCMAKE_C_COMPILER="$CC" . make -j"$NPROC"
<gh_stars>0 # frozen_string_literal: true # Flattened view of the events database with one row per subject. # Metadata is excluded class AddFlatView < ActiveRecord::Migration[6.0] def up event_wh_db = Rails.application.config.event_wh_db ViewsSchema.create_view( 'flat_events_view', <<~SQL SELECT #{event_wh_db}.events.id AS wh_event_id, #{event_wh_db}.events.uuid AS event_uuid_bin, INSERT(INSERT(INSERT(INSERT(LOWER(HEX(#{event_wh_db}.events.uuid)),9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-') AS event_uuid, #{event_wh_db}.event_types.key AS event_type, #{event_wh_db}.events.occured_at AS occured_at, #{event_wh_db}.events.user_identifier AS user_identifier, #{event_wh_db}.role_types.key AS role_type, #{event_wh_db}.subject_types.key AS subject_type, #{event_wh_db}.subjects.friendly_name AS subject_friendly_name, INSERT(INSERT(INSERT(INSERT(LOWER(HEX(#{event_wh_db}.subjects.uuid)),9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-') AS subject_uuid, #{event_wh_db}.subjects.uuid AS subject_uuid_bin FROM #{event_wh_db}.events LEFT OUTER JOIN #{event_wh_db}.event_types ON events.event_type_id = event_types.id LEFT OUTER JOIN #{event_wh_db}.roles ON roles.event_id = events.id LEFT OUTER JOIN #{event_wh_db}.role_types ON roles.role_type_id = role_types.id LEFT OUTER JOIN #{event_wh_db}.subjects ON roles.subject_id = subjects.id LEFT OUTER JOIN #{event_wh_db}.subject_types ON subjects.subject_type_id = subject_types.id SQL ) end def down ViewsSchema.drop_view('flat_events_view') end end
import { useQuery } from '@apollo/client'; import { GET_NODE_BOS_HISTORY } from './graphql'; // Assuming the GraphQL query is defined in a separate file const useGetNodeBosHistoryQuery = ({ skip, variables, onError }) => { const { pubkey } = variables; const { data, loading, error } = useQuery(GET_NODE_BOS_HISTORY, { variables: { pubkey }, skip: skip || !user?.subscribed, onError: () => onError(), }); return { data, loading, error }; }; export default useGetNodeBosHistoryQuery;
if [ $SPIN ]; then if ! command -v rcm &> /dev/null; then sudo apt-get install -y rcm fi if ! command -v rg &> /dev/null; then sudo apt-get install -y ripgrep fi if ! command -v tig &> /dev/null; then sudo apt-get install -y tig fi sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" rcup -d ~/dotfiles -x install.sh -x gitconfig echo "source ~/.spin.zsh" >> ~/.zshrc fi
package org.apache.tomcat.jni; public class SSLSocket { public static native int attach(long paramLong1, long paramLong2) throws Exception; public static native int handshake(long paramLong); public static native int renegotiate(long paramLong); public static native byte[] getInfoB(long paramLong, int paramInt) throws Exception; public static native String getInfoS(long paramLong, int paramInt) throws Exception; public static native int getInfoI(long paramLong, int paramInt) throws Exception; } /* Location: C:\Users\lgoldstein\.m2\repository\tomcat\tomcat-apr\5.5.23\tomcat-apr-5.5.23.jar!\org\apache\tomcat\jni\SSLSocket.class * Java compiler version: 2 (46.0) * JD-Core Version: 0.7.1 */
#!/bin/bash find $1 -print0 | while IFS= read -r -d '' filename do if file $filename | grep -q -i 'elf 64'; then output=$(echo $filename | sed -e 's/.*\/\(.*\)$/\1/') echo $output.o objcopy -O binary --only-section=.text $filename $output.o fi done
<gh_stars>0 #include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> using namespace std; bool bp[1000002]={false}; int p[100000]; int main(){ int k=2; bp[2]=false; bp[3]=false; p[1]=2; p[2]=3; int l; for(int q=4;q<1000000;q++){ l=sqrt(q); for(int w=1;w<=k&&p[w]<=l;w++){ if(q%p[w]==0){ bp[q]=true; break; } } if(bp[q]==false){ p[++k]=q; } } long long int a,b; int t; scanf("%d",&t); while(t--){ scanf("%lld %lld",&a,&b); a=a*b; int now=1; long long int ans=1; while(a!=1){ int z=0; while(a%p[now]==0){ z++; a/=p[now]; } ans*=(z+1); now++; } printf("%lld\n",ans); } return 0; }
declare module '@freshie/ui.preact' { import type { Props } from 'freshie'; import type { ComponentChild, ComponentChildren } from 'preact'; export { Props }; export function render(Tags: ComponentChildren, props: Props, target: HTMLElement): void; export function hydrate(Tags: ComponentChildren, props: Props, target: HTMLElement): void; export function layout(Tags: ComponentChildren, props?: Props): ComponentChild; export function ssr(Tags: ComponentChildren, props?: Props): Record<'head'|'body', string>; }
<filename>src/model/redis/redisDbNode.ts import { Constants, ModelType } from "@/common/constants"; import { RedisDBMeta } from "@/common/typeDef"; import { Cluster } from "ioredis"; import * as path from "path"; import * as vscode from "vscode"; import { Node } from "../interface/node"; import { RedisFolderNode } from "./folderNode"; import RedisBaseNode from "./redisBaseNode"; import { RemainNode } from "./remainNode"; export class RedisDbNode extends RedisBaseNode { private loadingMore = false; contextValue = ModelType.REDIS_DB; iconPath: string | vscode.ThemeIcon = new vscode.ThemeIcon("database", new vscode.ThemeColor('dropdown.foreground')); keys: string[]; constructor(readonly meta: RedisDBMeta, readonly parent: Node) { super(meta.name); this.init(parent) this.database = meta.name; this.description = meta.keys ? `(${meta.keys})` : ''; } async getChildren(isRresh?: boolean): Promise<RedisBaseNode[]> { if (isRresh) { this.cursor = '0'; this.cursorHolder = {}; } if (this.loadingMore) { this.loadingMore = false; } else { this.keys = await this.getKeys() } const childens = RedisFolderNode.buildChilds(this, this.keys); if (this.hasMore()) { childens.unshift(new RemainNode(this)) } return childens; } private hasMore() { if (!this.isCluster) { return this.cursor != '0'; } for (const key in this.cursorHolder) { const cursor = this.cursorHolder[key]; if (cursor != '0') return true; } return false; } public async loadMore() { if (!this.hasMore()) { vscode.window.showErrorMessage("Has no more keys!") return; } this.loadingMore = true; this.keys.push(...(await this.getKeys())) this.provider.reload(this) } public async getKeys() { const client = await this.getClient() if (this.isCluster) { return await this.keysCluster(client as Cluster, this.pattern) } const scanResult = await client.scan(this.cursor, "COUNT", 3000, "MATCH", this.pattern + "*"); this.cursor = scanResult[0] return scanResult[1]; } private async keysCluster(client: Cluster, pattern: string): Promise<string[]> { const masters = client.nodes("master"); const maxKeys = 3000 / masters.length | 0; const mastersScan = await Promise.all(masters.map(async (master) => { const mKey = master.options.host + "@" + master.options.port; const cursor = this.cursorHolder[mKey] || 0; if (cursor === '0') return null; const scanResult = await master.scan(cursor, "COUNT", maxKeys, "MATCH", pattern + '*') this.cursorHolder[mKey] = scanResult[0]; return scanResult[1] })); return [...new Set(mastersScan.filter(keys => keys).flat())]; } }
#!/bin/bash if [ "$SWIFTC_VERSION" != "" ]; then if [ "$SWIFTC_VERSION" == "4" ]; then echo "$SWIFTC_VERSION.0" > .swift-version else echo "$SWIFTC_VERSION" > .swift-version fi elif [ "$SWIFT_VERSION" != "" ]; then echo "$SWIFT_VERSION" > .swift-version fi echo "Swift fersion in file:" cat .swift-version
#!/usr/bin/env bash # TODO: # thing of to make this root unaffected # get the theme in file theme_file="/tmp/vim-colorschemes" prev_theme_name="/tmp/vim-prev-theme" vim_colors_file="/home/$(logname)/.config/nvim/modules/color_settings.vim" # vim_colors_file="${HOME}/.cache/temp/sh_files/.vimrc" PS3="Select the file: " function gen_file() { [ -f "${theme_file}" ] && rm "${theme_file}" nvim -esc \ "put=getcompletion('', 'color') \ |put=globpath('~/.config/nvim/plugged/*/colors', '*.vim', 0, 1) \ |execute('%s/.*\/\([^/]*\).vim*$/\1/')" "${theme_file}" -c wq echo "Theme file created" } # update the file with latest colorschemes touch "${prev_theme_name}" SELECTED_THEME_NAME=$(cat "${prev_theme_name}") function change_colorschme() { [ -f "${theme_file}" ] && rm "${theme_file}" # get the current colorscheme theme_in_file=$(grep -o "^colorscheme\s[-_a-zA-Z0-9]\+$" "${vim_colors_file}" | cut -d' ' -f 2) echo "Your current nvim colorscheme is ${theme_in_file}" sleep 0.05 # put the theme names in the file nvim -esc \ "put=getcompletion('', 'color') \ |put=globpath('~/.config/nvim/plugged/*/colors', '*.vim', 0, 1) \ |execute('%s/.*\/\([^/]*\).vim*$/\1/')" "${theme_file}" -c wq if [ -n $(echo "${PATH}" | grep -io fzf) ]; then scheme_name=$(cat "${theme_file}" \ | fzf \ --prompt "Select theme name: " \ --border sharp \ --height 45%) else scheme_names=($(cat "${theme_file}" | sed 's/\n/ /g')) select scheme_name in "${scheme_names[@]}"; do echo "Selected theme for vim: ${scheme_name}" break done fi if [ "${scheme_name}" != "${theme_in_file}" ]; then if [ -z "${scheme_name}" ]; then echo "No colorscheme choosen" else sed -i -e "s/^\(colorscheme\s\)[-_[:alpha:]]\+$/\1${scheme_name}/g" "${vim_colors_file}" theme_in_file=$(grep -o "^colorscheme\s[-_a-zA-Z0-9]\+$" "${vim_colors_file}" | cut -d' ' -f 2) echo "New colorscheme set to ${theme_in_file}" fi else echo "${scheme_name} is already set as your default colorscheme for n/vim" fi echo "${scheme_name}" > "${prev_theme_name}" SELECTED_THEME_NAME="${scheme_name}" } function set_background() { current_background=$(sed -n -e "s/^set\sbackground\s\?=\s\?\([dark|light]\+\)/\1/p" "${vim_colors_file}") if [ "${current_background}" != $1 ]; then sed -i -e "s/^\(set\sbackground\s\?=\s\?\)[dark|light]\+$/\1$1/g" "${vim_colors_file}" current_background=$(sed -n -e "s/^set\sbackground\s\?=\s\?\([dark|light]\)/\1/p" "${vim_colors_file}") echo "Now, background set to \"${current_background}\"" else echo "You already have $1 background set" fi } function get_help() { cat << EOH Usage: vcolor.sh [arguments] -h, --help shows this help -bg, --background changes the background between light and dark -c, --colorscheme shows fzf menu containing installed colorschemes to Choose colorscheme from it --gen generate file with installed themes of n/vim to use with other scripts Note: if no argument is provided then it'll be default to changing colorscheme EOH } case "$1" in --help|-h) get_help ;; -bg|--background) set_background $2 ;; --gen) gen_file ;; -c|--colorscheme|'') change_colorschme ;; *) printf "Invalid option\tTry: --help\n" ;; esac export SELECTED_THEME_NAME
<filename>xdr/allow_trust_op_asset.go package xdr import ( "fmt" ) // ToAsset converts `a` to a proper xdr.Asset func (a AllowTrustOpAsset) ToAsset(issuer AccountId) (ret Asset) { var err error switch a.Type { case AssetTypeAssetTypeCreditAlphanum4: ret, err = NewAsset(AssetTypeAssetTypeCreditAlphanum4, AssetAlphaNum4{ AssetCode: a.MustAssetCode4(), Issuer: issuer, }) case AssetTypeAssetTypeCreditAlphanum12: ret, err = NewAsset(AssetTypeAssetTypeCreditAlphanum12, AssetAlphaNum12{ AssetCode: a.MustAssetCode12(), Issuer: issuer, }) default: err = fmt.Errorf("Unexpected type for AllowTrustOpAsset: %d", a.Type) } if err != nil { panic(err) } return }
/* * Copyright [2020-2030] [https://www.stylefeng.cn] * * 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. * * Guns采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点: * * 1.请不要删除和修改根目录下的LICENSE文件。 * 2.请不要删除和修改Guns源码头部的版权声明。 * 3.请保留源码和相关描述文件的项目出处,作者声明等。 * 4.分发源码时候,请注明软件出处 https://gitee.com/stylefeng/guns * 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/stylefeng/guns * 6.若您的项目无法满足以上几点,可申请商业授权 */ package cn.stylefeng.roses.kernel.system.modular.organization.service; import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult; import cn.stylefeng.roses.kernel.rule.tree.ztree.ZTreeNode; import cn.stylefeng.roses.kernel.system.api.OrganizationServiceApi; import cn.stylefeng.roses.kernel.system.api.pojo.organization.HrOrganizationRequest; import cn.stylefeng.roses.kernel.system.api.pojo.organization.OrganizationTreeNode; import cn.stylefeng.roses.kernel.system.modular.organization.entity.HrOrganization; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; import java.util.Set; /** * 系统组织机构服务 * * @author fengshuonan * @date 2020/11/04 11:05 */ public interface HrOrganizationService extends IService<HrOrganization>, OrganizationServiceApi { /** * 添加系统组织机构 * * @param hrOrganizationRequest 组织机构请求参数 * @author fengshuonan * @date 2020/11/04 11:05 */ void add(HrOrganizationRequest hrOrganizationRequest); /** * 删除系统组织机构 * * @param hrOrganizationRequest 组织机构请求参数 * @author fengshuonan * @date 2020/11/04 11:05 */ void del(HrOrganizationRequest hrOrganizationRequest); /** * 编辑系统组织机构 * * @param hrOrganizationRequest 组织机构请求参数 * @author fengshuonan * @date 2020/11/04 11:05 */ void edit(HrOrganizationRequest hrOrganizationRequest); /** * 修改组织机构状态 * * @param hrOrganizationRequest 请求参数 * @author fengshuonan * @date 2020/11/18 22:38 */ void updateStatus(HrOrganizationRequest hrOrganizationRequest); /** * 查看详情系统组织机构 * * @param hrOrganizationRequest 组织机构请求参数 * @return 组织机构详情 * @author fengshuonan * @date 2020/11/04 11:05 */ HrOrganization detail(HrOrganizationRequest hrOrganizationRequest); /** * 分页查询系统组织机构 * * @param hrOrganizationRequest 组织机构请求参数 * @return 组织机构详情分页列表 * @author fengshuonan * @date 2020/11/04 11:05 */ PageResult<HrOrganization> findPage(HrOrganizationRequest hrOrganizationRequest); /** * 查询所有系统组织机构 * * @param hrOrganizationRequest 组织机构请求参数 * @return 组织机构详情列表 * @author fengshuonan * @date 2020/11/04 11:05 */ List<HrOrganization> findList(HrOrganizationRequest hrOrganizationRequest); /** * 获取全部系统组织机构树(用于新增,编辑组织机构时选择上级节点,用于获取用户管理界面左侧组织机构树) * * @param hrOrganizationRequest 查询参数 * @return 系统组织机构树 * @author chenjinlong * @date 2020/11/6 13:41 */ List<OrganizationTreeNode> organizationTree(HrOrganizationRequest hrOrganizationRequest); /** * 获取ztree形式的组织机构树(用于角色配置数据范围类型,并且数据范围类型是指定组织机构时)(layui版本) * * @param hrOrganizationRequest 请求参数 * @param buildTree 是否构建成树结构的节点,true-带树结构,false-不带 * @return ztree形式的组织机构树 * @author fengshuonan * @date 2021/1/9 18:40 */ List<ZTreeNode> orgZTree(HrOrganizationRequest hrOrganizationRequest, boolean buildTree); /** * 查询所有参数组织架构id集合的所有层级的父id,包含父级的父级等 * * @param organizationIds 组织架构id集合 * @return 被查询参数id集合的所有层级父级id,包含他们本身 * @author fengshuonan * @date 2020/11/6 14:24 */ Set<Long> findAllLevelParentIdsByOrganizations(Set<Long> organizationIds); }
const express = require('express'); const _ = require('lodash'); const simpleCrud = require('./genericCRUD'); const extendedCrud = (Model) => { return simpleCrud(Model, router => { router.delete('/:id',(req,res,next) => { //..... }); }); } module.exports = extendedCrud;
const mongoose = require('mongoose'); let AuthorSchema = new mongoose.Schema({ id: { type: String, required: true }, name: { type: String, required: true }, email: { type: String, required: true }, books: { type: [String] } }); module.exports = AuthorSchema;
/* Press <Ctrl-R> to invoke the function. Along with C and Windows libraries Remarks: Refer at util/lib/obj/src/cli_io_beta.c Run.. */ # define CBR # define CLI_W32 # include <stdio.h> # include "../../../incl/config.h" signed(__cdecl cli_ctrl_r_beta(CLI_W32_STAT(*argp))) { auto signed char *b; auto signed i,r; auto signed short flag; if(!argp) return(0x00); if(CLI_DBG_D<(CLI_DBG)) printf("%s ","<Ctrl-R>"); return(0x01); }
<reponame>rubenqba/gearman-java<filename>gearman-server/src/main/java/net/johnewart/gearman/server/JobManagerTest.java<gh_stars>0 package net.johnewart.gearman.server; import io.netty.channel.Channel; import net.johnewart.gearman.common.JobStatus; import net.johnewart.gearman.common.interfaces.Client; import net.johnewart.gearman.common.interfaces.Worker; import net.johnewart.gearman.server.core.NetworkClient; import net.johnewart.gearman.server.core.NetworkWorker; import net.johnewart.gearman.server.core.QueuedJob; import net.johnewart.gearman.server.factories.JobFactory; import net.johnewart.gearman.server.persistence.MemoryQueue; import net.johnewart.gearman.server.storage.JobManager; import net.johnewart.gearman.server.storage.JobQueue; import net.johnewart.gearman.common.Job; import org.junit.Before; import org.junit.Test; import java.util.HashSet; import java.util.Map; import java.util.Set; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; public class JobManagerTest { private JobManager jobManager; private MemoryQueue memoryQueue; private NetworkWorker worker; public JobManagerTest() { } @Before public void initialize() { memoryQueue = new MemoryQueue(); jobManager = new JobManager(memoryQueue); worker = new NetworkWorker(mock(Channel.class)); worker.addAbility("reverseString"); worker.addAbility("computeBigStuff"); } @Test public void insertsJobsIntoJobStore() throws Exception { Job job = JobFactory.generateForegroundJob("reverseString"); jobManager.storeJob(job); assertThat("There are no completed jobs", jobManager.getCompletedJobsCounter().count(), is(0L)); assertThat("There is one pending job", jobManager.getPendingJobsCounter().count(), is(1L)); assertThat("One job has been enqueued", jobManager.getQueuedJobsCounter().count(), is(1L)); } @Test public void fetchesJobsFromStorage() throws Exception { Job job = JobFactory.generateForegroundJob("reverseString"); jobManager.storeJob(job); Job nextJob = jobManager.nextJobForWorker(worker); byte[] result = {'r','e','s','u','l','t'}; assertThat("The jobs are the same", job.equals(nextJob), is(true)); assertThat("The job store is now empty", jobManager.getPendingJobsCounter().count(), is(0L)); assertThat("There is one active job", jobManager.getActiveJobsCounter().count(), is(1L)); assertThat("The job store has no complete jobs", jobManager.getCompletedJobsCounter().count(), is(0L)); // Complete the job jobManager.workComplete(nextJob, result); assertThat("The job store has one complete job", jobManager.getCompletedJobsCounter().count(), is(1L)); } @Test public void reQueuesBackgroundJobsWhenWorkersDisconnect() throws Exception { Job job = JobFactory.generateBackgroundJob("reverseString"); jobManager.storeJob(job); jobManager.nextJobForWorker(worker); assertThat("Job queue has no jobs", jobManager.getJobQueue("reverseString").size(), is(0)); // Simulate abort before completion jobManager.unregisterWorker(worker); assertThat("Job queue has one job", jobManager.getJobQueue("reverseString").size(), is(1)); // Re-fetch the job, make sure it's the same one Job nextJob = jobManager.nextJobForWorker(worker); assertThat("The job was returned to the queue", nextJob.equals(job), is(true)); } @Test public void reQueuesForegroundJobWhenClientConnected() throws Exception { Client mockClient = mock(NetworkClient.class); Job job = JobFactory.generateForegroundJob("reverseString"); jobManager.storeJobForClient(job, mockClient); jobManager.nextJobForWorker(worker); assertThat("Job queue has no jobs", jobManager.getJobQueue("reverseString").size(), is(0)); // Simulate abort before completion jobManager.unregisterWorker(worker); assertThat("Job queue has one job", jobManager.getJobQueue("reverseString").size(), is(1)); // Re-fetch the job, make sure it's the same one Job nextJob = jobManager.nextJobForWorker(worker); assertThat("The job was returned to the queue", nextJob.equals(job), is(true)); } @Test public void dropsForegroundJobWhenNoClientAttached() throws Exception { Job job = JobFactory.generateForegroundJob("reverseString"); jobManager.storeJob(job); jobManager.nextJobForWorker(worker); assertThat("Job queue has no jobs", jobManager.getJobQueue("reverseString").size(), is(0)); // Simulate abort before completion jobManager.unregisterWorker(worker); assertThat("Job queue has no jobs", jobManager.getJobQueue("reverseString").size(), is(0)); } @Test public void wakesUpWorkerWhenJobComesIn() throws Exception { Job job = JobFactory.generateBackgroundJob("reverseString"); Worker spyWorker = spy(worker); jobManager.registerWorkerAbility("reverseString", spyWorker); jobManager.sleepingWorker(spyWorker); jobManager.storeJob(job); verify(spyWorker).wakeUp(); } @Test public void handlesExceptionsWhenWakingWorkers() throws Exception { Job job = JobFactory.generateBackgroundJob("reverseString"); Worker mockWorker = mock(Worker.class); //when(mockWorker.wakeUp()).thenThrow(new Exception("Can't send that packet")); //jobManager.registerWorkerAbility("reverseString", spyWorker); //jobManager.sleepingWorker(spyWorker); //jobManager.storeJob(job); //verify(spyWorker).wakeUp(); } @Test public void checksAndUpdatesJobStatus() throws Exception { Job job = JobFactory.generateBackgroundJob("reverseString"); jobManager.storeJob(job); JobStatus jobStatus = jobManager.checkJobStatus(job.getJobHandle()); assertThat("Job status denominator is 0", jobStatus.getDenominator(), is(0)); assertThat("Job status numerator is 0", jobStatus.getNumerator(), is(0)); assertThat("Job is not running", jobStatus.isRunning(), is(false)); assertThat("Job status is unknown yet", jobStatus.isStatusKnown(), is(false)); jobManager.nextJobForWorker(worker); jobStatus = jobManager.checkJobStatus(job.getJobHandle()); assertThat("Job is running", jobStatus.isRunning(), is(true)); assertThat("Job status is still not known", jobStatus.isStatusKnown(), is(false)); jobManager.updateJobStatus(job.getJobHandle(), 5, 100); jobStatus = jobManager.checkJobStatus(job.getJobHandle()); assertThat("Job status denominator is 100", jobStatus.getDenominator(), is(100)); assertThat("Job status numerator is 5", jobStatus.getNumerator(), is(5)); assertThat("Job is running", jobStatus.isRunning(), is(true)); assertThat("Job status is known", jobStatus.isStatusKnown(), is(true)); } @Test public void loadQueuedJobsFromPersistenceEngine() throws Exception { final String[] jobQueueNames = { "delayedJobs", "immediateJobs", "gearmanJobs" }; final int jobsCount = 100; final Set<QueuedJob> allJobs = new HashSet<>(); Job currentJob; for(String jobQueueName : jobQueueNames) { for(int i = 0; i < jobsCount; i++) { currentJob = JobFactory.generateBackgroundJob(jobQueueName); memoryQueue.write(currentJob); allJobs.add(new QueuedJob(currentJob)); } } Set<QueuedJob> jobsInPersistentStorage = new HashSet(memoryQueue.readAll()); assertThat("The jobs in the persistent engine match what was put in", allJobs.equals(jobsInPersistentStorage), is(true)); assertThat("There were 300 jobs put in the storage engine", allJobs.size(), is(300)); assertThat("There are 300 jobs read from the storage engine", jobsInPersistentStorage.size(), is(300)); jobManager.loadAllJobs(); Map<String, JobQueue> jobQueueMap = jobManager.getJobQueues(); assertThat("There are three job queues in the storage", jobQueueMap.keySet().size(), is(3)); for(String jobQueueName : jobQueueNames) { assertThat("The job queues contains a queue named '" + jobQueueName + "'", jobQueueMap.containsKey(jobQueueName), is(true)); } assertThat("There are 300 jobs pending in the job store", jobManager.getPendingJobsCounter().count(), is(300L)); } @Test public void coalescesResultsForMultipleClients() throws Exception { Client mockClientOne = mock(NetworkClient.class); Client mockClientTwo = mock(NetworkClient.class); Job jobOne = JobFactory.generateForegroundJob("reverseString"); Job jobTwo = JobFactory.generateForegroundJob("reverseString"); jobTwo.setUniqueID(jobOne.getUniqueID()); jobManager.storeJobForClient(jobOne, mockClientOne); jobManager.storeJobForClient(jobTwo, mockClientTwo); assertThat("Job queue has one job because they had the same unique id", jobManager.getJobQueue("reverseString").size(), is(1)); assertThat("There is 1 job pending in the job store", jobManager.getPendingJobsCounter().count(), is(1L)); assertThat("There has been 1 job queued in the job store", jobManager.getQueuedJobsCounter().count(), is(1L)); Job nextJob = jobManager.nextJobForWorker(worker); byte[] result = {'r','e','s','u','l','t'}; assertThat("Job pulled out is equal to job #1", nextJob.equals(jobOne), is(true)); // Complete the job jobManager.workComplete(nextJob, result); verify(mockClientOne).sendWorkResults(jobOne.getJobHandle(), result); verify(mockClientTwo).sendWorkResults(jobOne.getJobHandle(), result); } // TODO: Verify that it will coalesce results if a job is submitted while a worker is working on the same one @Test public void sendsWorkDataResultsToClients() throws Exception { Client mockClient = mock(NetworkClient.class); Job jobOne = JobFactory.generateForegroundJob("reverseString"); jobManager.storeJobForClient(jobOne, mockClient); Job nextJob = jobManager.nextJobForWorker(worker); byte[] data = {'r','e','s','u','l','t'}; // Send back some data jobManager.workData(nextJob, data); verify(mockClient).sendWorkData(jobOne.getJobHandle(), data); } }
package org.rs2server.rs2.content.api.bank; import org.rs2server.rs2.model.player.Player; import javax.annotation.concurrent.Immutable; /** * Represents a click on the bank settings widget. * @author twelve */ @Immutable public final class BankSettingsClickEvent { /** * The player who initiated the click event. */ private final Player player; /** * The child id of the button clicked. */ private final int child; public BankSettingsClickEvent(Player player, int child) { this.player = player; this.child = child; } public final Player getPlayer() { return player; } public final int getChild() { return child; } }
<filename>tests/typings/webdriverio/config.ts<gh_stars>1000+ class CustomService { onPrepare() { // TODO: something before all workers launch } } const configA: WebdriverIO.Config = { // @ts-expect-error should not be available beforeFeature () { }, async beforeCommand (name) { name.toLowerCase() const title = await browser.getTitle() title.slice(0, 1) } } const config: WebdriverIO.Config = { services: [ ['sauce', { sauceConnect: true, sauceConnectOpts: { directDomains: 'some.domain' }, scRelay: true, // @ts-expect-error test wrong parameter parentTunnel: 123 }], ['appium', { args: { basePath: 'some/path', // @ts-expect-error test wrong parameter port: true } }], ['browserstack', { browserstackLocal: true, // @ts-expect-error test wrong parameter forcedStop: 'no' }], ['devtools', { coverageReporter: { enable: true, // @ts-expect-error test wrong parameter type: 'foo' } }], ['selenium-standalone', { logs: 'string', installArgs: { version: '' }, args: { basePath: '' }, skipSeleniumInstall: true, drivers: { chrome: 'yes', // @ts-expect-error test wrong parameter brave: 'no' } }], ['crossbrowsertesting', { // @ts-expect-error test wrong parameter cbtTunnel: 'true', cbtTunnelOpts: { foo: 'bar' } }], ['firefox-profile', { extensions: [], profileDirectory: '/foo/bar', proxy: { proxyType: 'direct' }, legay: false }], ['static-server', { folders: [{ mount: '', path: '' }], port: 1234, middleware: [{ mount: '', middleware: '' }] }], ['testingbot', { tbTunnel: true, tbTunnelOpts: { tunnelIdentifier: 'identifier', // @ts-expect-error tunnelVersion: 0, apiKey: 'key', apiSecret: 'secret', } }], [CustomService, { someOption: true }] ], reporters: [ ['allure', { issueLinkTemplate: 'foo', // @ts-expect-error useCucumberStepReporter: 'wrong-param' }], ['sumologic', { // @ts-expect-error syncInterval: 'wrong param', sourceAddress: 'http://foo' }] ], automationProtocol: 'webdriver', logLevels: { webdriver: 'info', }, capabilities: [{ browserName: 'chrome', 'goog:chromeOptions': { binary: 'path/to/chrome', args: ['--no-first-run', '--enable-automation'], prefs: { 'profile.managed_default_content_settings.popups': 1, 'profile.managed_default_content_settings.notifications': 1, } } }, { browserName: 'firefox', 'moz:firefoxOptions': { binary: 'path/to/firefox', profile: 'path/to/profile', args: ['-headless'], prefs: { 'browser.tabs.remote.autostart': false, 'toolkit.telemetry.reportingpolicy.firstRun': false, }, log: { level: 'error' } } }, { 'selenoid:options': { enableVNC: true, enableVideo: true, enableLog: true, logName: 'test.log', videoName: 'test.mp4' } }, { 'wdio:devtoolsOptions': { ignoreDefaultArgs: false } }] as WebDriver.DesiredCapabilities[], filesToWatch: [ '/foo/page-objects/**/*.page.js', ] }
class Competition: def __init__(self, cmap, json): self.cmap = cmap self.json = json @classmethod def make(cls, cmap, json): return cls(cmap, json) def ignore(d, *keys_to_ignore): for key in keys_to_ignore: d.pop(key, None) def competition_generator(data): for c in data: ignore(c, 'handle', 'ratingUpdateTimeSeconds') # Ignore specific keys yield Competition.make(cmap=cmap, json=c) # Yield Competition object # Example usage cmap = {} # Assuming cmap is a dictionary used in Competition.make method competition_data = [ {'name': 'Competition 1', 'type': 'Online', 'participants': 100, 'handle': 'handle1'}, {'name': 'Competition 2', 'type': 'Offline', 'participants': 50, 'ratingUpdateTimeSeconds': 3600}, {'name': 'Competition 3', 'type': 'Hybrid', 'participants': 75, 'handle': 'handle3', 'ratingUpdateTimeSeconds': 7200} ] # Iterate through the Competition objects yielded by the generator for competition in competition_generator(competition_data): print(competition.json) # Accessing the json attribute of the Competition object
<gh_stars>10-100 package com.vlkan.hrrs.replayer.base64; import com.vlkan.hrrs.replayer.cli.Replayer; import java.io.IOException; public enum Base64Replayer {; public static void main(String[] args) throws IOException { Base64ReplayerModuleFactory moduleFactory = new Base64ReplayerModuleFactory(); Replayer.main(args, moduleFactory); } }
<filename>www/actors/stalfos.js /** * @fileoverview Provide the Stalfos class. * @author <EMAIL> (<NAME>) */ /** * Constructor for the Stalfos class, baddie who walks around and hurls rocks. * @constructor * @extends {ace.BaseClass} */ ace.Stalfos = function(game, room) { ace.base(this, game, room); this.name = 'Stalfos'; this.isEvenFrame = true; this.facing = ace.randomFacing(); this.walkSpeed = 1; this.rotX = -.4; this.hitPoints = 2; }; ace.inherits(ace.Stalfos, ace.Enemy); /** * What to do every frame. * @param {ace.Game} The game. */ ace.Stalfos.prototype.onTick = function(game) { if (this.standardDeathCheck(game)) return; // We're walking. There's a small chance we'll change directions. if (ace.randomInt(100) < 2) { this.facing = ace.randomFacing(); } var dX = this.walkSpeed * ace.xMultByFacing[this.facing]; var dY = this.walkSpeed * ace.yMultByFacing[this.facing]; if (this.canWalk(dX, dY)) { this.x += dX; this.y += dY; } else { this.facing = ace.randomFacing(); } //this.rotZ = this.angleTo(game.avatar.x, game.avatar.y); //this.zOffset = 1 + Math.floor(this.rotZ * 30) % 2; if (game.isBlinkFrame) { this.isEvenFrame = !this.isEvenFrame; } if (this.isEvenFrame) { this.draw('stalfos'); } else { this.draw('stalfos2'); } if (this.carrying) { this.draw(this.carrying.toLowerCase()); } game.engine.drawLight($('shadow-obstacle'), this.x, this.y+8,21,.5); }; /** * What happens when the avatar touches us. * @param {ace.Runner} The game Runner. */ ace.Stalfos.prototype.onTouchAvatar = function(runner) { // Do the "usual" thing, in case we're a coin or something. if (this.standardOnTouchAvatar(runner)) return; // Otherwise, dose out some damage... runner.avatar.takeDamage(.5); };
package br.com.digidev.messenger4j.send; import br.com.digidev.messenger4j.send.templates.Template; import java.util.Objects; /** * @author Messenger4J - http://github.com/messenger4j */ final class TemplateAttachment extends Message.Attachment { private final Type type; private final Template payload; TemplateAttachment(Template payload) { this.type = Type.TEMPLATE; this.payload = payload; } public Template getPayload() { return payload; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TemplateAttachment that = (TemplateAttachment) o; return type == that.type && Objects.equals(payload, that.payload); } @Override public int hashCode() { return Objects.hash(type, payload); } @Override public String toString() { return "TemplateAttachment{" + "type=" + type + ", payload=" + payload + "} super=" + super.toString(); } /** * @author Messenger4J - http://github.com/messenger4j */ private enum Type { TEMPLATE } }
import { Component, OnInit, Input } from '@angular/core'; import { NbDialogRef } from '@nebular/theme'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { PriceBookService } from '../../../../@core/data/pricebook.service'; @Component({ selector: 'ngx-line-item-group', templateUrl: './group.component.html', styleUrls: ['./group.component.scss'], }) export class CreateLineItemGroupComponent implements OnInit { @Input() title: string; constructor( protected ref: NbDialogRef<CreateLineItemGroupComponent>, protected pricebookService: PriceBookService, ) { } lineitemGroupForm: FormGroup; groupName: FormControl; lineItems: FormControl; items: string[] = ['item1', 'item2', 'item3']; createFormControls() { this.groupName = new FormControl('', Validators.required); this.lineItems = new FormControl('', Validators.required); } createForm() { this.lineitemGroupForm = new FormGroup({ groupName: this.groupName, lineItems: this.lineItems, }); } ngOnInit() { this.createFormControls(); this.createForm(); this.items = this.pricebookService.getPriceBook(); } onSubmit() { if (this.lineitemGroupForm.valid) { this.pricebookService.addPriceBookGroup(this.lineitemGroupForm.value); this.lineitemGroupForm.reset(); this.dismiss(); } else { window.alert('Form fields are not valid'); } } dismiss() { this.ref.close(); } }
import { VersionScope } from '../../../interface/Version'; import { ProjectV1Parser } from './ProjectV1Parser'; import { ProjectV2Parser } from './ProjectV2Parser'; import { Parser } from '../Parser'; import { IStorableCompactProject } from '../../../interface/Storage'; export declare class ProjectParser extends Parser<IStorableCompactProject> { protected getScope(): VersionScope; protected getWorkersMap(): { '1': typeof ProjectV1Parser; '2': typeof ProjectV2Parser; }; }
def translate_to_pig_latin(sentence): words = sentence.split(" ") translated_words = [] vowels = ["a", "e", "i", "o", "u"] for word in words: if word[0] in vowels: translated_words.append(word + "way") else: translated_words.append(word[1:] + word[0] + "ay") return " ".join(translated_words) print(translate_to_pig_latin("I am happy"))
// Copyright 2017-2019 @polkadot/ui-reactive authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import { AccountId, AccountIndex, Address, Option, StakingLedger } from '@polkadot/types'; import { BareProps, CallProps } from '@polkadot/ui-api/types'; import React from 'react'; import { withCalls } from '@polkadot/ui-api'; import { formatBalance } from '@polkadot/util'; type Props = BareProps & CallProps & { children?: React.ReactNode, params?: AccountId | AccountIndex | Address | string | Uint8Array | null, label?: string, staking_ledger?: Option<StakingLedger> }; export class BondedDisplay extends React.PureComponent<Props> { render () { const { children, className, label = '', style, staking_ledger } = this.props; if (!staking_ledger || staking_ledger.isNone) { return null; } const { active: bonded } = staking_ledger.unwrap(); return ( <div className={className} style={style} > {label}{ bonded ? formatBalance(bonded) : '0' }{children} </div> ); } } export default withCalls<Props>( ['query.staking.bonded', { paramName: 'params', propName: 'controllerId', transform: (value) => value.unwrapOr(null) }], ['query.staking.ledger', { paramName: 'controllerId' }] )(BondedDisplay);
<reponame>santaswarup/scala<filename>src/reflect/scala/reflect/internal/util/Statistics.scala package scala package reflect.internal.util import scala.collection.mutable import scala.reflect.internal.SymbolTable import scala.reflect.internal.settings.MutableSettings import java.lang.invoke.{SwitchPoint, MethodHandle, MethodHandles, MethodType} abstract class Statistics(val symbolTable: SymbolTable, settings: MutableSettings) { initFromSettings(settings) def initFromSettings(currentSettings: MutableSettings): Unit = { enabled = currentSettings.YstatisticsEnabled hotEnabled = currentSettings.YhotStatisticsEnabled } type TimerSnapshot = (Long, Long) /** If enabled, increment counter by one */ @inline final def incCounter(c: Counter) { if (areStatisticsLocallyEnabled && c != null) c.value += 1 } /** If enabled, increment counter by given delta */ @inline final def incCounter(c: Counter, delta: Int) { if (areStatisticsLocallyEnabled && c != null) c.value += delta } /** If enabled, increment counter in map `ctrs` at index `key` by one */ @inline final def incCounter[K](ctrs: QuantMap[K, Counter], key: K) = if (areStatisticsLocallyEnabled && ctrs != null) ctrs(key).value += 1 /** If enabled, start subcounter. While active it will track all increments of * its base counter. */ @inline final def startCounter(sc: SubCounter): (Int, Int) = if (areStatisticsLocallyEnabled && sc != null) sc.start() else null /** If enabled, stop subcounter from tracking its base counter. */ @inline final def stopCounter(sc: SubCounter, start: (Int, Int)) { if (areStatisticsLocallyEnabled && sc != null) sc.stop(start) } /** If enabled, start timer */ @inline final def startTimer(tm: Timer): TimerSnapshot = if (areStatisticsLocallyEnabled && tm != null) tm.start() else null /** If enabled, stop timer */ @inline final def stopTimer(tm: Timer, start: TimerSnapshot) { if (areStatisticsLocallyEnabled && tm != null) tm.stop(start) } /** If enabled, push and start a new timer in timer stack */ @inline final def pushTimer(timers: TimerStack, timer: => StackableTimer): TimerSnapshot = if (areStatisticsLocallyEnabled && timers != null) timers.push(timer) else null /** If enabled, stop and pop timer from timer stack */ @inline final def popTimer(timers: TimerStack, prev: TimerSnapshot) { if (areStatisticsLocallyEnabled && timers != null) timers.pop(prev) } /** Create a new counter that shows as `prefix` and is active in given phases */ def newCounter(prefix: String, phases: String*) = new Counter(prefix, phases) /** Create a new relative counter that shows as `prefix` and is active * in the same phases as its base counter. Relative counters print as percentages * of their base counters. */ def newRelCounter(prefix: String, ctr: Counter): Counter = new RelCounter(prefix, ctr) /** Create a new subcounter that shows as `prefix` and is active * in the same phases as its base counter. Subcounters can track * increments of their base counters and print as percentages * of their base counters. */ def newSubCounter(prefix: String, ctr: Counter): SubCounter = new SubCounter(prefix, ctr) /** Create a new counter that shows as `prefix` and is active in given phases */ def newTimer(prefix: String, phases: String*): Timer = new Timer(prefix, phases) /** Create a new subtimer that shows as `prefix` and is active * in the same phases as its base timer. Subtimers can track * increments of their base timers and print as percentages * of their base timers. */ def newSubTimer(prefix: String, timer: Timer): Timer = new SubTimer(prefix, timer) /** Create a new stackable that shows as `prefix` and is active * in the same phases as its base timer. Stackable timers are subtimers * that can be stacked in a timerstack, and that print aggregate, as well as specific * durations. */ def newStackableTimer(prefix: String, timer: Timer): StackableTimer = new StackableTimer(prefix, timer) /** Create a new view that shows as `prefix` and is active in given phases. * The view always reflects the current value of `quant` as a quantity. */ def newView(prefix: String, phases: String*)(quant: => Any): View = new View(prefix, phases, quant) /** Create a new quantity map that shows as `prefix` and is active in given phases. */ def newQuantMap[K, V <% Ordered[V]](prefix: String, phases: String*)(initValue: => V): QuantMap[K, V] = new QuantMap(prefix, phases, initValue) /** Same as newQuantMap, where the key type is fixed to be Class[_] */ def newByClass[V <% Ordered[V]](prefix: String, phases: String*)(initValue: => V): QuantMap[Class[_], V] = new QuantMap(prefix, phases, initValue) /** Create a new timer stack */ def newTimerStack() = new TimerStack() def allQuantities: Iterable[Quantity] = for ((_, q) <- qs if q.underlying == q; r <- q :: q.children.toList if r.prefix.nonEmpty) yield r private def showPercent(x: Long, base: Long) = if (base == 0) "" else f" (${x.toDouble / base.toDouble * 100}%2.1f%%)" /** The base trait for quantities. * Quantities with non-empty prefix are printed in the statistics info. */ trait Quantity { if (prefix.nonEmpty) { val key = s"${if (underlying != this) underlying.prefix else ""}/$prefix" qs(key) = this } val prefix: String val phases: Seq[String] def underlying: Quantity = this def showAt(phase: String) = phases.isEmpty || (phases contains phase) def line = f"$prefix%-30s: ${this}" val children = new mutable.ListBuffer[Quantity] } trait SubQuantity extends Quantity { protected def underlying: Quantity underlying.children += this } class Counter(val prefix: String, val phases: Seq[String]) extends Quantity with Ordered[Counter] { var value: Int = 0 def compare(that: Counter): Int = if (this.value < that.value) -1 else if (this.value > that.value) 1 else 0 override def equals(that: Any): Boolean = that match { case that: Counter => (this compare that) == 0 case _ => false } override def hashCode = value override def toString = value.toString } class View(val prefix: String, val phases: Seq[String], quant: => Any) extends Quantity { override def toString = quant.toString } private class RelCounter(prefix: String, override val underlying: Counter) extends Counter(prefix, underlying.phases) with SubQuantity { override def toString = if (value == 0) "0" else { assert(underlying.value != 0, prefix+"/"+underlying.line) f"${value.toFloat / underlying.value}%2.1f" } } class SubCounter(prefix: String, override val underlying: Counter) extends Counter(prefix, underlying.phases) with SubQuantity { def start() = (value, underlying.value) def stop(prev: (Int, Int)) { val (value0, uvalue0) = prev value = value0 + underlying.value - uvalue0 } override def toString = value + showPercent(value.toLong, underlying.value.toLong) } class Timer(val prefix: String, val phases: Seq[String]) extends Quantity { var nanos: Long = 0 var timings = 0 def start() = { (nanos, System.nanoTime()) } def stop(prev: TimerSnapshot) { val (nanos0, start) = prev nanos = nanos0 + System.nanoTime() - start timings += 1 } protected def show(ns: Long) = s"${ns/1000000}ms" override def toString = s"$timings spans, ${show(nanos)}" } class SubTimer(prefix: String, override val underlying: Timer) extends Timer(prefix, underlying.phases) with SubQuantity { override protected def show(ns: Long) = super.show(ns) + showPercent(ns, underlying.nanos) } class StackableTimer(prefix: String, underlying: Timer) extends SubTimer(prefix, underlying) with Ordered[StackableTimer] { var specificNanos: Long = 0 def compare(that: StackableTimer): Int = if (this.specificNanos < that.specificNanos) -1 else if (this.specificNanos > that.specificNanos) 1 else 0 override def equals(that: Any): Boolean = that match { case that: StackableTimer => (this compare that) == 0 case _ => false } override def hashCode = specificNanos.## override def toString = s"${super.toString} aggregate, ${show(specificNanos)} specific" } /** A mutable map quantity where missing elements are automatically inserted * on access by executing `initValue`. */ class QuantMap[K, V <% Ordered[V]](val prefix: String, val phases: Seq[String], initValue: => V) extends mutable.HashMap[K, V] with mutable.SynchronizedMap[K, V] with Quantity { override def default(key: K) = { val elem = initValue this(key) = elem elem } override def toString = this.toSeq.sortWith(_._2 > _._2).map { case (cls: Class[_], elem) => s"${cls.toString.substring(cls.toString.lastIndexOf("$") + 1)}: $elem" case (key, elem) => s"$key: $elem" }.mkString(", ") } /** A stack of timers, all active, where a timer's specific "clock" * is stopped as long as it is buried by some other timer in the stack, but * its aggregate clock keeps on ticking. */ class TimerStack { private var elems: List[(StackableTimer, Long)] = Nil /** Start given timer and push it onto the stack */ def push(t: StackableTimer): TimerSnapshot = { elems = (t, 0L) :: elems t.start() } /** Stop and pop top timer in stack */ def pop(prev: TimerSnapshot) = { val (nanos0, start) = prev val duration = System.nanoTime() - start val (topTimer, nestedNanos) :: rest = elems topTimer.nanos = nanos0 + duration topTimer.specificNanos += duration - nestedNanos topTimer.timings += 1 elems = rest match { case (outerTimer, outerNested) :: elems1 => (outerTimer, outerNested + duration) :: elems1 case Nil => Nil } } } private val qs = new mutable.HashMap[String, Quantity] private[scala] var areColdStatsLocallyEnabled: Boolean = false private[scala] var areHotStatsLocallyEnabled: Boolean = false /** Represents whether normal statistics can or cannot be enabled. */ @inline final def enabled: Boolean = areColdStatsLocallyEnabled def enabled_=(cond: Boolean) = { if (cond && !enabled) { StatisticsStatics.enableColdStats() areColdStatsLocallyEnabled = true } } /** Represents whether hot statistics can or cannot be enabled. */ @inline final def hotEnabled: Boolean = enabled && areHotStatsLocallyEnabled def hotEnabled_=(cond: Boolean) = { if (cond && enabled && !areHotStatsLocallyEnabled) { StatisticsStatics.enableHotStats() areHotStatsLocallyEnabled = true } } /** Tells whether statistics should be definitely reported to the user for this `Global` instance. */ @inline final def areStatisticsLocallyEnabled: Boolean = areColdStatsLocallyEnabled import scala.reflect.internal.Reporter /** Reports the overhead of measuring statistics via the nanoseconds variation. */ final def reportStatisticsOverhead(reporter: Reporter): Unit = { val start = System.nanoTime() var total = 0L for (i <- 1 to 10000) { val time = System.nanoTime() total += System.nanoTime() - time } val total2 = System.nanoTime() - start val variation = s"${total/10000.0}ns to ${total2/10000.0}ns" reporter.echo(NoPosition, s"Enabling statistics, measuring overhead = $variation per timer") } /** Helper for measuring the overhead of a concrete thunk `body`. */ @inline final def timed[T](timer: Timer)(body: => T): T = { val start = startTimer(timer) try body finally stopTimer(timer, start) } }
#!/bin/bash current_time=$(date +"%T") current_date=$(date +"%D") echo "Current Time: $current_time" echo "Current Date: $current_date"
#!/bin/sh # Install libdb4.8 (Berkeley DB). export LC_ALL=C set -e if [ -z "${1}" ]; then echo "Usage: $0 <base-dir> [<extra-bdb-configure-flag> ...]" echo echo "Must specify a single argument: the directory in which db4 will be built." echo "This is probably \`pwd\` if you're at the root of the defcoin repository." exit 1 fi expand_path() { echo "$(cd "${1}" && pwd -P)" } BDB_PREFIX="$(expand_path ${1})/db4"; shift; BDB_VERSION='db-4.8.30.NC' BDB_HASH='12edc0df75bf9abd7f82f821795bcee50f42cb2e5f76a6a281b85732798364ef' BDB_URL="https://download.oracle.com/berkeley-db/${BDB_VERSION}.tar.gz" check_exists() { which "$1" >/dev/null 2>&1 } sha256_check() { # Args: <sha256_hash> <filename> # if check_exists sha256sum; then echo "${1} ${2}" | sha256sum -c elif check_exists sha256; then if [ "$(uname)" = "FreeBSD" ]; then sha256 -c "${1}" "${2}" else echo "${1} ${2}" | sha256 -c fi else echo "${1} ${2}" | shasum -a 256 -c fi } http_get() { # Args: <url> <filename> <sha256_hash> # # It's acceptable that we don't require SSL here because we manually verify # content hashes below. # if [ -f "${2}" ]; then echo "File ${2} already exists; not downloading again" elif check_exists curl; then curl --insecure --retry 5 "${1}" -o "${2}" else wget --no-check-certificate "${1}" -O "${2}" fi sha256_check "${3}" "${2}" } mkdir -p "${BDB_PREFIX}" http_get "${BDB_URL}" "${BDB_VERSION}.tar.gz" "${BDB_HASH}" tar -xzvf ${BDB_VERSION}.tar.gz -C "$BDB_PREFIX" cd "${BDB_PREFIX}/${BDB_VERSION}/" # Apply a patch necessary when building with clang and c++11 (see https://community.oracle.com/thread/3952592) CLANG_CXX11_PATCH_URL='https://gist.githubusercontent.com/LnL7/5153b251fd525fe15de69b67e63a6075/raw/7778e9364679093a32dec2908656738e16b6bdcb/clang.patch' CLANG_CXX11_PATCH_HASH='7a9a47b03fd5fb93a16ef42235fa9512db9b0829cfc3bdf90edd3ec1f44d637c' http_get "${CLANG_CXX11_PATCH_URL}" clang.patch "${CLANG_CXX11_PATCH_HASH}" patch -p2 < clang.patch cd build_unix/ "${BDB_PREFIX}/${BDB_VERSION}/dist/configure" \ --enable-cxx --disable-shared --disable-replication --with-pic --prefix="${BDB_PREFIX}" \ "${@}" make install echo echo "db4 build complete." echo echo 'When compiling defcoind, run `./configure` in the following way:' echo echo " export BDB_PREFIX='${BDB_PREFIX}'" echo ' ./configure BDB_LIBS="-L${BDB_PREFIX}/lib -ldb_cxx-4.8" BDB_CFLAGS="-I${BDB_PREFIX}/include" ...'
import React, { useState, useEffect } from 'react'; import { Form, Input, Button } from 'antd'; const AddressForm = () => { const [name, setName] = useState(''); const [street, setStreet] = useState(''); const [city, setCity] = useState(''); const [state, setState] = useState(''); const [zip, setZip] = useState(''); const isValid = () => street.length > 0 && city.length > 0 && state.length > 0 && zip.length > 0; return ( <Form> <Form.Item label="Name"> <Input value={name} onChange={e => setName(e.target.value)} placeholder="Enter name" /> </Form.Item> <Form.Item label="Street"> <Input value={street} onChange={e => setStreet(e.target.value)} placeholder="Enter street address" /> </Form.Item> <Form.Item label="City"> <Input value={city} onChange={e => setCity(e.target.value)} placeholder="Enter city" /> </Form.Item> <Form.Item label="State"> <Input value={state} onChange={e => setState(e.target.value)} placeholder="Enter state" /> </Form.Item> <Form.Item label="Zip Code"> <Input value={zip} onChange={e => setZip(e.target.value)} placeholder="Enter zip code" /> </Form.Item> <Button type="primary" disabled={!isValid()}>Submit</Button> </Form> ) }
module.exports = (Bluebird) => { // think: super.catch const super_catch = Promise.prototype.catch; Bluebird.prototype.catch = Bluebird.prototype.caught = function catchFn(fn) { if (arguments.length > 1) { const filters = Array.prototype.slice.call(arguments, 0, -1); fn = arguments[arguments.length - 1]; return super_catch.call(this, filterCatch(filters, fn)); } else { return super_catch.call(this, fn); } }; function filterCatch(filters, fn) { return (error) => { for (const filter of filters) { if (testFilter(filter, error)) { return fn(error); //TODO: deal with Bluebird.bind() here? } } return Bluebird.reject(error); }; } }; const FILTER_CONFIGS = [ { // Error contructor filterTest: (t, error) => t && (t === Error || t.prototype instanceof Error), predicate: (t, error) => error instanceof t }, { // function filterTest: (t, error) => typeof t === 'function', predicate: (fn, error) => fn(error) }, { // else: Object shallow compare w/ // note: we test the thrown error, not the filter argument as in previous filterTest()s. This is what bluebird does. filterTest: (o, error) => typeof error === 'function' || (typeof error === 'object' && error !== null), // To match Bluebird's behavior, uses ==, not === intentionally predicate: (filter, error) => !Object.keys(filter).some(key => filter[key] != error[key]) } ]; function testFilter(filterArgument, error) { // get the right predicate function for the type of filter the user supplied. const filterConfig = FILTER_CONFIGS.find(filterConfig => filterConfig.filterTest(filterArgument, error)); const { predicate } = filterConfig || {}; // If not filters are valid, we jist return false. It's not an exception return predicate && predicate(filterArgument, error); }
<filename>examples/r2d2_atari_breakout.py import gym from keras.optimizers import Adam import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '../')) from src.r2d2 import R2D2, Actor from src.r2d2_callbacks import * from src.processor import AtariProcessor from src.image_model import DQNImageModel from src.memory import * from src.policy import * from src.common import InputType, LstmType, DuelingNetwork, seed_everything, LoggerType from src.callbacks import ConvLayerView, MovieLogger seed_everything(42) ENV_NAME = "BreakoutDeterministic-v4" class MyActor(Actor): def getPolicy(self, actor_index, actor_num): return EpsilonGreedy(0.1) def fit(self, index, agent): env = gym.make(ENV_NAME) agent.fit(env, visualize=False, verbose=0) env.close() class MyActor1(MyActor): def getPolicy(self, actor_index, actor_num): return EpsilonGreedy(0.01) class MyActor2(MyActor): def getPolicy(self, actor_index, actor_num): return EpsilonGreedy(0.1) #----------------------------------------------------------- # main #----------------------------------------------------------- def main(mode): env = gym.make(ENV_NAME) processor = AtariProcessor(is_clip=False, max_steps=1000) enable_rescaling = True kwargs = { "input_shape": processor.image_shape, "input_type": InputType.GRAY_2ch, "nb_actions": env.action_space.n, "optimizer": Adam(lr=0.0001), "metrics": [], "image_model": DQNImageModel(), "input_sequence": 4, # 入力フレーム数 "dense_units_num": 256, # Dense層のユニット数 "enable_dueling_network": True, # dueling_network有効フラグ "dueling_network_type": DuelingNetwork.AVERAGE, # dueling_networkのアルゴリズム "lstm_type": LstmType.STATELESS, # LSTMのアルゴリズム "lstm_units_num": 128, # LSTM層のユニット数 "lstm_ful_input_length": 1, # ステートフルLSTMの入力数 # train/action関係 "remote_memory_warmup_size": 50_000, # 初期のメモリー確保用step数(学習しない) "target_model_update": 10_000, # target networkのupdate間隔 "action_interval": 1, # アクションを実行する間隔 "batch_size": 16, "gamma": 0.997, # Q学習の割引率 "enable_double_dqn": True, # DDQN有効フラグ "enable_rescaling": enable_rescaling, # rescalingを有効にするか(priotrity) "rescaling_epsilon": 0.001, # rescalingの定数 "priority_exponent": 0.9, # priority優先度 "burnin_length": 2, # burn-in期間 "reward_multisteps": 3, # multistep reward # その他 "processor": processor, "actors": [MyActor1, MyActor2], "remote_memory": PERRankBaseMemory( capacity= 50_000, alpha=0.9, # PERの確率反映率 beta_initial=0.0, # IS反映率の初期値 beta_steps=1_000_000, # IS反映率の上昇step数 enable_is=True, # ISを有効にするかどうか ), # actor 関係 "actor_model_sync_interval": 200, # learner から model を同期する間隔 } #--- R2D2 manager = R2D2(**kwargs) test_env = gym.make(ENV_NAME) log = Logger2Stage( interval1=10, interval2=60*10, change_count=5, savedir="tmp", test_actor=MyActor, test_env=test_env, test_episodes=1, # 乱数なし ) if mode == "train": print("--- start ---") print("'Ctrl + C' is stop.") save_manager = SaveManager( save_dirpath="tmp", is_load=False, save_memory=True, checkpoint=True, checkpoint_interval=100_000, verbose=0 ) manager.train(nb_trains=1_750_000, callbacks=[save_manager, log]) # plot log.drawGraph() # 訓練結果を見る agent = manager.createTestAgent(MyActor, "tmp/last/learner.dat") agent.test(env, nb_episodes=1, visualize=True, verbose=1) # 動画保存用 movie = MovieLogger() conv = ConvLayerView(agent) agent.test(env, nb_episodes=1, visualize=False, callbacks=[movie, conv]) movie.save(gifname="tmp/breakout1.gif", fps=30) conv.save(grad_cam_layers=["conv_1", "conv_2", "conv_3"], add_adv_layer=True, add_val_layer=True, end_frame=200, gifname="tmp/breakout2.gif", fps=10) env.close() if __name__ == '__main__': main(mode="train") #main(mode="test")
<reponame>sdsmnc221/nexus-tests-rn<filename>src/sharedUI/Header/EmailInboxHeader.js import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import HeaderSearchBar from './components/HeaderSearchBar'; const Wrapper = styled.View` position: relative; z-index: 999; ${({ theme }) => theme.styles.flex('flex-start', null, null, true)} background-color: ${({ theme }) => theme.colors.ghostWhite}; `; const Title = styled.Text` width: 100%; padding: 16px 20px; background-color: ${({ theme }) => theme.colors.persianRed}; color: ${({ theme }) => theme.colors.ghostWhite}; font-family: ${({ theme }) => theme.fonts.cairo.semiBold}; font-size: 17px; letter-spacing: 0.34px; text-transform: lowercase; `; const EmailInboxHeader = ({ title }) => ( <Wrapper> <HeaderSearchBar /> <Title>{title}</Title> </Wrapper> ); EmailInboxHeader.propTypes = { title: PropTypes.string, }; EmailInboxHeader.defaultProps = { title: null, }; export default EmailInboxHeader;
import { GetUser, GetUserByEmail, SendEmail } from 'components/Api' import { useConfig, useLogAction, useProponents } from 'components/Hooks' import { useCallback, useEffect, useMemo, useState } from 'react' export const useEmail = () => { const [contactEmail, setContactEmail] = useState() const [contactEmailLogin, setContactEmailLogin] = useState() const config = useConfig() const { get: getProponent, allUserLoginNames } = useProponents() const logAction = useLogAction() useEffect(() => { getContactEmail() }, []) const getContactEmail = async () => { const emailAddress = config.itemFilter('contactEmail').TextValue setContactEmail(emailAddress) const user = await GetUserByEmail({ email: emailAddress }) setContactEmailLogin(user[0].LoginName) } const replacementPairs = useMemo(() => { return [ { searchvalue: /\n/g, newvalue: '<br>' }, // eslint-disable-next-line no-undef { searchvalue: /\[Title\]/g, newvalue: _spPageContextInfo.webTitle }, { searchvalue: /\[SiteLink\]/g, // eslint-disable-next-line no-undef newvalue: `<a href='${_spPageContextInfo.webAbsoluteUrl}'>${_spPageContextInfo.webTitle}</a>`, }, { searchvalue: /\[ContactEmail\]/g, newvalue: contactEmail, }, ] }, [contactEmail]) const replaceText = useCallback( (text, options = {}) => { const { additionalPairValues = [] } = options let newText = text const replacements = [...replacementPairs, ...additionalPairValues] for (let i = 0; i < replacements.length; i++) { newText = newText.replace( replacements[i].searchvalue, replacements[i].newvalue ) } return newText }, [replacementPairs] ) const sendEmailToCurrentProponentMembers = useCallback( async (type, options = {}) => { if (!config.itemFilter(type).YesNoValue) return const { currentUser } = options const proponentUsers = getProponent(currentUser.proponent).Users let emailContents = [] switch (type) { case 'addQuestionEmail': emailContents = proponentUsers.map((user) => { const subject = config.itemFilter(type).TextValue const body = config.itemFilter(type).MultiTextValue const additionalPairValues = [ { searchvalue: /\[AddresseeName\]/g, newvalue: user.Title, }, { searchvalue: /\[UserName\]/g, newvalue: currentUser.name, }, { searchvalue: /\[Proponent\]/g, newvalue: currentUser.proponent, }, ] const newBody = replaceText(body, { additionalPairValues }) const newSubject = replaceText(subject, { additionalPairValues }) return [ { to: user.LoginName, subject: newSubject, body: newBody, }, user.Title, ] }) break case 'proponentDocumentEmail': emailContents = proponentUsers.map((user) => { const subject = config.itemFilter(type).TextValue const body = config.itemFilter(type).MultiTextValue const additionalPairValues = [ { searchvalue: /\[UserName\]/g, newvalue: currentUser.name, }, ] const newBody = replaceText(body, { additionalPairValues }) const newSubject = replaceText(subject, { additionalPairValues }) return [ { to: user.LoginName, subject: newSubject, body: newBody, }, user.Title, ] }) break case 'withdrawQuestionEmail': emailContents = proponentUsers.map((user) => { const subject = config.itemFilter(type).TextValue const body = config.itemFilter(type).MultiTextValue const additionalPairValues = [ { searchvalue: /\[AddresseeName\]/g, newvalue: user.Title, }, { searchvalue: /\[UserName\]/g, newvalue: currentUser.name, }, ] const newBody = replaceText(body, { additionalPairValues }) const newSubject = replaceText(subject, { additionalPairValues }) return [ { to: user.LoginName, subject: newSubject, body: newBody, }, user.Title, ] }) break case 'ProponentDeleteDocumentEmail': emailContents = proponentUsers.map((user) => { const subject = config.itemFilter(type).TextValue const body = config.itemFilter(type).MultiTextValue const additionalPairValues = [ { searchvalue: /\[AddresseeName\]/g, newvalue: user.Title, }, { searchvalue: /\[UserName\]/g, newvalue: currentUser.name, }, ] const newBody = replaceText(body, { additionalPairValues }) const newSubject = replaceText(subject, { additionalPairValues }) return [ { to: user.LoginName, subject: newSubject, body: newBody, }, user.Title, ] }) break default: console.error( `sendEmailToCurrentProponentMembers type '${type}' is invalid` ) return } try { for (let i = 0; i < emailContents.length; i++) { await SendEmail(emailContents[i][0]) logAction(`sent ${type} to ${emailContents[i][1]}`, { snackbar: false, }) } } catch (error) { logAction( `Error: sendEmailToCurrentProponentMembers - ${type} - ${error}`, { variant: 'error', snackbar: false, } ) } return }, [config.items, getProponent, logAction, replaceText] ) const sendEmailToAllProponents = useCallback( async (type, options = {}) => { if (type !== 'publicDocumentEmail' && !config.itemFilter(type).YesNoValue) return let emailContents = [] switch (type) { case 'publicDocumentEmail': emailContents = allUserLoginNames.map((user) => { const subject = config.itemFilter(type).TextValue const body = config.itemFilter(type).MultiTextValue const newBody = replaceText(body) const newSubject = replaceText(subject) return { to: user, subject: newSubject, body: newBody, } }) break case 'newAnswerEmail': emailContents = allUserLoginNames.map((user) => { const subject = config.itemFilter(type).TextValue const body = config.itemFilter(type).MultiTextValue const newBody = replaceText(body) const newSubject = replaceText(subject) return { to: user, subject: newSubject, body: newBody, } }) break case 'updatedAnswerEmail': emailContents = allUserLoginNames.map((user) => { const subject = config.itemFilter(type).TextValue const body = config.itemFilter(type).MultiTextValue const newBody = replaceText(body) const newSubject = replaceText(subject) return { to: user, subject: newSubject, body: newBody, } }) break default: console.error(`sendEmailToAllProponents type '${type}' is invalid`) return } try { for (let i = 0; i < emailContents.length; i++) { await SendEmail(emailContents[i]) } logAction(`sent '${type}' to all proponent members`) } catch (error) { logAction(`Error: sendEmailToAllProponents - ${type} - ${error}`, { variant: 'error', snackbar: false, }) } return }, [allUserLoginNames, config.items, logAction, replaceText] ) const sendEmailToSiteContact = useCallback( async (type, options = {}) => { if (!config.itemFilter(type).YesNoValue) return const { userId, proponentName, proponentId } = options let subject = '', body = '', additionalPairValues = [] switch (type) { case 'removeUserEmail': const user = await GetUser(userId) additionalPairValues = [ { searchvalue: /\[UserName\]/g, newvalue: user.Title, }, { searchvalue: /\[Proponent\]/g, newvalue: proponentName, }, ] break case 'newQuestionEmail': additionalPairValues = [ { searchvalue: /\[Proponent\]/g, newvalue: getProponent(proponentId).Title, }, ] break case 'newDocumentEmail': additionalPairValues = [ { searchvalue: /\[Proponent\]/g, newvalue: getProponent(proponentId).Title, }, ] break default: console.error(`sendEmailToSiteContact type '${type}' is invalid`) return } subject = config.itemFilter(type).TextValue body = config.itemFilter(type).MultiTextValue const newBody = replaceText(body, { additionalPairValues }) const newSubject = replaceText(subject, { additionalPairValues }) try { await SendEmail({ to: contactEmailLogin, subject: newSubject, body: newBody, }) logAction(`sent ${type} to ${contactEmail}`, { snackbar: false }) } catch (error) { logAction(`Error: sendEmailToSiteContact - ${type} - ${error}`, { variant: 'error', snackbar: false, }) } return }, [config.items, contactEmail, contactEmailLogin, getProponent, logAction, replaceText] ) const sendEmailToNewMember = useCallback( async (options = {}) => { const type = 'addUserEmail' if (!config.itemFilter(type).YesNoValue) return const { member, proponentName } = options const subject = config.itemFilter(type).TextValue const body = config.itemFilter(type).MultiTextValue const additionalPairValues = [ { searchvalue: /\[AddresseeName\]/g, newvalue: member.DisplayText, }, { searchvalue: /\[Proponent\]/g, newvalue: proponentName, }, ] const newBody = replaceText(body, { additionalPairValues }) const newSubject = replaceText(subject, { additionalPairValues }) try { await SendEmail({ to: member.Key, subject: newSubject, body: newBody, }) logAction(`sent welcome email to ${member.DisplayText}`) } catch (error) { logAction(`Error: sendEmailToNewMember - ${error}`, { variant: 'error', snackbar: false, }) } return }, [config.items, logAction, replaceText] ) return { sendEmailToAllProponents, sendEmailToCurrentProponentMembers, sendEmailToSiteContact, sendEmailToNewMember, } }
<gh_stars>0 Rails.application.routes.draw do # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html resource :record, only: :show get '/search/:q', action: :search, controller: "search" end
echo "Starting pull notifications $SERVER" if [ "$SERVER" = "thrift" ]; then python thrift-server.py else python api.py fi
<filename>skill.js<gh_stars>0 const { Ability, events } = require('alexa-ability'); const { handleAbility } = require('alexa-ability-lambda-handler'); const { timeout, TimeoutError } = require('alexa-ability-timeout'); const { SQS } = require('aws-sdk'); const sqs = new SQS({ apiVersion: '2012-11-05' }); const app = new Ability({ applicationId: process.env.ALEXA_SKILL_ID, }); app.use(timeout(60000)); app.use((req, next) => { console.info('Handling:', req); next(); }); app.on(events.launch, (req) => { console.info('Launch', req); const speech = (` <speak> I'm ready. </speak> `); req.say('ssml', speech).send(); }); app.on(events.end, (req) => { console.info(`Session ended because: ${req.reason}`); const speech = (` <speak> Bye Bye <break time="50ms" /> Kainos </speak> `); req.say('ssml', speech).end(); }); app.on(events.help, (req) => { const speech = (` <speak> Please say <break time="50ms" /> Read question </speak> `); req.say('ssml', speech).send(); }); app.on(events.cancel, (req) => { if (req.timedOut) return; req.say('Cancelling!').end(); }); app.on(events.stop, (req) => { const speech = (` <speak> Bye Bye <break time="50ms" /> Kainos </speak> `); req.say('ssml', speech).end(); }); app.on('CustomHelpIntent', (req) => { const speech = (` <speak> Please say <break time="50ms" /> Read question </speak> `); req.say('ssml', speech).send(); }); app.on('TweetsReaderIntent', (req) => { console.info('Intent req', req); let message; const params = { AttributeNames: [ 'SentTimestamp', ], MaxNumberOfMessages: 1, MessageAttributeNames: [ 'All', ], QueueUrl: process.env.TWEETS_SQS_URL, }; sqs.receiveMessage(params, (err, data) => { if (err) { console.error('Receive Error', err); } else if (data.Messages) { console.info('SQS MSG:', data.Messages[0].MessageAttributes); message = { author: data.Messages[0].MessageAttributes.Author.StringValue, question: data.Messages[0].MessageAttributes.Message.StringValue, }; const deleteParams = { QueueUrl: process.env.TWEETS_SQS_URL, ReceiptHandle: data.Messages[0].ReceiptHandle, }; sqs.deleteMessage(deleteParams, (error) => { if (error) { console.error('Delete Error', err); } else { console.info('Message Deleted', data); } }); } let speech; if (message) { speech = (` <speak> ${message.author} said <break time="50ms" /> ${message.question} </speak> `); } else { speech = (` <speak> No questions to read <break time="100ms" /> Guys, Please send questions using Twitter <break time="100ms" /> <amazon:effect name="whispered">Don't be shy</amazon:effect> </speak> `); } req.say('ssml', speech).end(); }); }); app.on('IntroductionIntent', (req) => { const speech = (` <speak> Hello Kainos <break time="100ms" /> I am Alexa and I can read tweets tagged using <break time="50ms" /> #KainosKickoff18 <break time="50ms" /> and <break time="50ms" /> #AskAlexa <break time="100ms" /> Try me. Just send tweet with tags from the screen <break time="100ms" /> Good luck </speak> `); req.say('ssml', speech).send(); }); app.on('AMAZON.NextIntent', (req) => { const speech = (` <speak> Guys, Please send questions using Twitter <break time="100ms" /> <amazon:effect name="whispered">Don't be shy</amazon:effect> </speak> `); req.say('ssml', speech).send(); }); app.use((err, req) => { if (err instanceof TimeoutError) { req.say('Sorry, that took to long. Please try again.').send(); } }); app.use((req) => { req.say('I don\'t know what to say. Please try again or ask for help.').end(); }); exports.handler = handleAbility(app);
<filename>prog/main.c /* By Liyanboy74 https://github.com/liyanboy74 */ #include <mega16.h> #include <stdlib.h> #include <delay.h> #include <alcd.h> //KeyPad Lib #include "key.h" //Stepper motor StepAngel #define step_angle 0.8 #define STEPPER_PORT PORTA #define STEPPER_PIN PINA #define STEPPER_DDR DDRA //Step Codes const unsigned char StepCodes[]={0b0001,0b0011, 0b0010, 0b0110 ,0b0100 ,0b1100 ,0b1000 ,0b1001 }; //Buffer unsigned char lcd_b[32]; int angle=0,Step=0; //Run Pulse Generator void run_prog(int angle) { int i,temp; float temp2; if(angle>=0) temp=angle/(float)(step_angle/2.0); else temp=(-angle)/(float)(step_angle/2.0); temp2=temp*(step_angle/2.0); lcd_clear(); lcd_puts("Angle="); ftoa(temp2,1,lcd_b); if(angle>=0)lcd_putchar('+'); else lcd_putchar('-'); lcd_puts(lcd_b); lcd_puts("\xdf"); lcd_gotoxy(0,1); lcd_puts("Raning Prog.."); if(angle>=0) { for(i=0; i<temp; i++) { Step++; if(Step>7)Step=0; STEPPER_PORT = StepCodes[Step]; delay_ms(50); } } else { for(i=0; i<temp; i++) { Step--; if(Step<0)Step=7; STEPPER_PORT = StepCodes[Step]; delay_ms(50); } } lcd_gotoxy(0,1); lcd_puts("Prog Completed."); delay_ms(3000); return; } void main(void) { //KeyPad Buffer char ch; //GPIO Initial STEPPER_PORT=0b00000000; STEPPER_DDR= 0b00001111; //Startup Output State STEPPER_PORT=StepCodes[0]; // Alphanumeric LCD initialization // Connections are specified in the // Project|Configure|C Compiler|Libraries|Alphanumeric LCD menu: // Characters/line: 16 lcd_init(16); while(1) { lcd_clear(); lcd_puts("Motor Angle="); itoa(angle,lcd_b); lcd_gotoxy(0,1); if(angle>=0)lcd_putchar('+'); lcd_puts(lcd_b); lcd_puts("\xdf"); ch=getkey(); if(ch=='+'||ch=='-') { if(ch=='+') { if(angle<=0)angle=(-1)*angle; } else if(ch=='-') { if(angle>=0)angle=(-1)*angle; } } else if(ch=='='){run_prog(angle);} else if(ch=='c') { angle=0; } else { if(angle<100) angle=(angle*10)+(ch-48); } } }
package main import ( "fmt" "log" "net" "net/url" "os" "os/signal" "strings" "syscall" "time" "github.com/aler9/gortsplib/pkg/h264" "github.com/aler9/gortsplib/pkg/rtph264" "github.com/eyeson-team/eyeson-go" ghost "github.com/eyeson-team/ghost/v2" "github.com/notedit/rtmp/av" rtmph264 "github.com/notedit/rtmp/codec/h264" "github.com/notedit/rtmp/format/rtmp" "github.com/spf13/cobra" ) var ( apiEndpointFlag string userFlag string userIDFlag string roomIDFlag string rtmpListenAddrFlag string verboseFlag bool jitterQueueLenMSFlag int32 rootCommand = &cobra.Command{ Use: "rtmp-server [flags] $API_KEY|$GUEST_LINK", Short: "rtmp-server", Args: cobra.MinimumNArgs(1), PreRun: func(cmd *cobra.Command, args []string) { }, Run: func(cmd *cobra.Command, args []string) { rtmpServerExample(args[0], apiEndpointFlag, userFlag, roomIDFlag, rtmpListenAddrFlag, userIDFlag) }, } ) func main() { rootCommand.Flags().StringVarP(&apiEndpointFlag, "api-endpoint", "", "https://api.eyeson.team", "Set api-endpoint") rootCommand.Flags().StringVarP(&userFlag, "user", "", "rtmp-test", "User name to use") rootCommand.Flags().StringVarP(&userIDFlag, "user-id", "", "", "User id to use") rootCommand.Flags().StringVarP(&roomIDFlag, "room-id", "", "", "Room ID. If left empty, a new meeting will be created on each request") rootCommand.Flags().StringVarP(&rtmpListenAddrFlag, "rtmp-listen-addr", "", "rtmp://0.0.0.0:1935", "rtmp address this server shall listen to") rootCommand.Flags().BoolVarP(&verboseFlag, "verbose", "v", false, "verbose output") rootCommand.Flags().Int32VarP(&jitterQueueLenMSFlag, "delay", "", 150, "delay in ms") rootCommand.Execute() } // Get a room depending on the provided api-key or guestlink. func getRoom(apiKeyOrGuestlink, apiEndpoint, user, roomID, userID string) (*eyeson.UserService, error) { // determine if we have a guestlink if strings.HasPrefix(apiKeyOrGuestlink, "http") { // join as guest // guest-link: https://app.eyeson.team/?guest=h7IHRfwnV6Yuk3QtL2jbktuh guestPos := strings.LastIndex(apiKeyOrGuestlink, "guest=") if guestPos == -1 { return nil, fmt.Errorf("Invalid guest-link") } guestToken := apiKeyOrGuestlink[guestPos+len("guest="):] client := eyeson.NewClient("") baseURL, _ := url.Parse(apiEndpoint) client.BaseURL = baseURL return client.Rooms.GuestJoin(guestToken, userID, user, "") } else { // let's assume we have an apiKey, so fire up a new meeting client := eyeson.NewClient(apiKeyOrGuestlink) baseURL, _ := url.Parse(apiEndpoint) client.BaseURL = baseURL options := map[string]string{} if len(userID) > 0 { options["user[id]"] = userID } return client.Rooms.Join(roomID, user, options) } } func rtmpServerExample(apiKeyOrGuestlink, apiEndpoint, user, roomID, rtmpListenAddr, userID string) { room, err := getRoom(apiKeyOrGuestlink, apiEndpoint, user, roomID, userID) if err != nil { log.Println("Failed to get room") return } log.Println("Waiting for room to become ready") err = room.WaitReady() if err != nil { log.Fatalf("Failed: %s", err) } log.Println("Guest-link:", room.Data.Links.GuestJoin) log.Println("GUI-link:", room.Data.Links.Gui) eyesonClient, err := ghost.NewClient(room.Data, ghost.WithForceH264Codec(), ghost.WithSendOnly()) if err != nil { log.Fatalf("Failed to create eyeson-client %s", err) } defer eyesonClient.Destroy() eyesonClient.SetTerminatedHandler(func() { log.Println("Call terminated") os.Exit(0) }) if verboseFlag { eyesonClient.SetDataChannelHandler(func(data []byte) { log.Printf("DC message: %s\n", string(data)) }) } rtmpTerminatedCh := make(chan bool) eyesonClient.SetConnectedHandler(func(connected bool, localVideoTrack ghost.RTPWriter, localAudioTrack ghost.RTPWriter) { log.Println("Webrtc connected. Starting rtmp-server") setupRtmpServer(localVideoTrack, rtmpListenAddr, rtmpTerminatedCh) }) if err := eyesonClient.Call(); err != nil { log.Println("Failed to call:", err) return } // install signal-handler chStop := make(chan os.Signal, 1) signal.Notify(chStop, syscall.SIGINT, syscall.SIGTERM) // Block until rtmp-connection is done select { case <-chStop: break case <-rtmpTerminatedCh: break } log.Println("RTMP connection is done. So terminating this call") // terminate this call eyesonClient.TerminateCall() } func setupRtmpServer(videoTrack ghost.RTPWriter, listenAddr string, rtmpTerminated chan<- bool) { // // start rtmp-listener // go func() { rtmpServer := rtmp.NewServer() url, _ := url.Parse(listenAddr) host := rtmp.UrlGetHost(url) var err error var lis net.Listener if lis, err = net.Listen("tcp", host); err != nil { return } log.Println("RTMP server listening: ", listenAddr) // Init the rtph264-rtp-header-encoder only once, // and reuse if another rtmp-client connects. h264Encoder := rtph264.Encoder{ PayloadType: 96, PayloadMaxSize: 1200, } h264Encoder.Init() rtmpServer.HandleConn = func(c *rtmp.Conn, nc net.Conn) { log.Println("New rtmp-conn created") sps := []byte{} pps := []byte{} videoJB, err := NewVideoJitterBuffer(videoTrack, time.Duration(jitterQueueLenMSFlag)*time.Millisecond) if err != nil { log.Fatalf("Failed to setup vjb: %s", err) } defer videoJB.Close() for { packet, err := c.ReadPacket() if err != nil { log.Println("Failed to read packet:", err) //rtmpTerminated <- true return } switch packet.Type { case av.H264DecoderConfig: // read SPS and PPS and save them so those can be // prepended to each keyframe. // A different solution would be to signal the sprops via sdp. // But this would require to start the call _after_ the rtmp-client // is connected. codec, err := rtmph264.FromDecoderConfig(packet.Data) if err != nil { log.Fatalf("Failed to decode decoder-config:", err) } if len(codec.SPS) > 0 { sps = codec.SPS[0] } if len(codec.PPS) > 0 { pps = codec.PPS[0] } case av.H264: // rtmp h264 packet uses AVCC bit-stream // extract nalus from that bitstream nalus, err := h264.DecodeAVCC(packet.Data) if err != nil { log.Fatalf("Failed to decode packet:", err) } // only prepend keyframes with sps and pps if packet.IsKeyFrame { nalus = append(nalus, sps) nalus = append(nalus, pps) } // convert nalus to rtp-packets pkts, err := h264Encoder.Encode(nalus, packet.Time) if err != nil { log.Fatalf("error while encoding H264: %v", err) } for _, pkt := range pkts { err = videoJB.WriteRTP(pkt) if err != nil { log.Printf("Failed to write h264 sample: %s", err) return } } } } } for { nc, err := lis.Accept() if err != nil { time.Sleep(time.Second) continue } log.Println("New Client connected") rtmpServer.HandleNetConn(nc) } }() }
set echo off set feedback off set linesize 512 prompt prompt All Snapshot Logs in Database prompt break on LOG_OWNER skip 1 SELECT LOG_OWNER, MASTER, LOG_TABLE, LOG_TRIGGER, ROWIDS, PRIMARY_KEY, FILTER_COLUMNS, CURRENT_SNAPSHOTS FROM DBA_SNAPSHOT_LOGS ORDER BY 1, 2;
<reponame>stoimen/algorithms const Node = require('./node') let n1, n2, n3 beforeEach(() => { n1 = new Node(10) n2 = new Node(20) n3 = new Node(30) }) // constructor describe('Node', () => { test('new without data', () => { let node = new Node() expect(node.next).toBeNull() expect(node.prev).toBeNull() expect(node.data).toBeNull() }) test('new with data', () => { let data = { val: 10 } let node = new Node(data) expect(node.data).toBe(data) }) }) test('setting data and reference neighbors to a node', () => { let n = new Node(10) let prev = new Node() let next = new Node() let data = { val: 10 } n.prev = prev n.next = next n.data = 'data as a string' n.next.data = data expect(next.data).toBe(data) })
def find_top_n_frequent_elements(arr, n): frequencies = {} for item in arr: if item in frequencies: frequencies[item] += 1 else: frequencies[item] = 1 result = list(frequencies.items()) result.sort(key=lambda x: x[1], reverse=True) return result[:n]
#! /bin/bash . "$(dirname "$0")/config.sh" PLUGIN_NAME="weave-ci-registry:5000/weaveworks/net-plugin" HOST1_IP=$($SSH $HOST1 getent ahosts $HOST1 | grep "RAW" | cut -d' ' -f1) SERVICE="weave-850-service" NETWORK="weave-850-network" setup_master() { # Setup Docker image registry on $HOST1 docker_on $HOST1 run -p 5000:5000 -d registry:2 # Build plugin-v2 on $HOST1, because Circle "CI" runs only ancient # version of Docker which does not support v2 plugins. build_plugin_img="buildpluginv2-ci" rsync -az -e "$SSH" "$(dirname $0)/../prog/net-plugin" $HOST1:~/ $SSH $HOST1<<EOF docker rmi $build_plugin_img 2>/dev/null docker plugin disable $PLUGIN_NAME >/dev/null docker plugin remove $PLUGIN_NAME 2>/dev/null WORK_DIR=$(mktemp -d) mkdir -p \${WORK_DIR}/rootfs docker create --name=$build_plugin_img weaveworks/weave true docker export $build_plugin_img | tar -x -C \${WORK_DIR}/rootfs cp \${HOME}/net-plugin/launch.sh \${WORK_DIR}/rootfs/home/weave/launch.sh cp \${HOME}/net-plugin/config.json \${WORK_DIR} docker plugin create $PLUGIN_NAME \${WORK_DIR} echo "$HOST1_IP weave-ci-registry" | sudo tee -a /etc/hosts docker plugin push $PLUGIN_NAME # Start Swarm Manager and enable the plugin docker swarm init --advertise-addr=$HOST1_IP [ -n "$COVERAGE" ] && docker plugin set $PLUGIN_NAME EXTRA_ARGS="-test.coverprofile=/home/weave/cover.prof --" #docker plugin set $PLUGIN_NAME WEAVE_PASSWORD="foobar" docker plugin enable $PLUGIN_NAME EOF } setup_worker() { $SSH $HOST2<<EOF echo "$HOST1_IP weave-ci-registry" | sudo tee -a /etc/hosts ping -nq -W 2 -c 1 weave-ci-registry docker swarm join --token "$1" "${HOST1_IP}:2377" docker plugin install --disable --grant-all-permissions $PLUGIN_NAME [ -n "$COVERAGE" ] && docker plugin set $PLUGIN_NAME EXTRA_ARGS="-test.coverprofile=/home/weave/cover.prof --" #docker plugin set $PLUGIN_NAME WEAVE_PASSWORD="foobar" docker plugin enable $PLUGIN_NAME EOF } cleanup() { for h in $@; do $SSH $h<<EOF sudo sed -i '/weave-ci-registry/d' /etc/hosts docker service rm $SERVICE || true docker swarm leave --force || true docker network rm $NETWORK || true docker plugin disable -f $PLUGIN_NAME || true docker plugin remove -f $PLUGIN_NAME || true EOF done } wait_for_network() { for i in $(seq 10); do if docker_on $1 network inspect $2 >/dev/null 2>&1; then return fi echo "Waiting for \"$2\" network" sleep 2 done echo "Failed to wait for \"$2\" network" >&2 return 1 } wait_for_service() { for i in $(seq 60); do replicas=$($SSH $1 docker service ls -f="name=$2" | awk '{print $4}' | grep -v REPLICAS) if [ "$replicas" == "$3/$3" ]; then return fi echo "Waiting for \"$2\" service" sleep 2 done echo "Failed to wait for \"$2\" service" >&2 return 1 } start_suite "Test Docker plugin-v2" #cleanup $HOST1 $HOST2 #exit 1 setup_master setup_worker $($SSH $HOST1 docker swarm join-token --quiet worker) echo "Creating network and service..." # Create network and service $SSH $HOST1<<EOF docker plugin ls docker network create --driver="${PLUGIN_NAME}:latest" $NETWORK || true # Otherwise no containers will be scheduled on host2 sleep 20 docker service create --name=$SERVICE --network=$NETWORK --replicas=2 weaveworks/network-tester:latest || true journalctl -r -u docker.service -n30 EOF wait_for_service $HOST1 $SERVICE 2 C1=$($SSH $HOST1 weave ps | grep -v weave:expose | awk '{print $1}') C2_IP=$($SSH $HOST2 weave ps | grep -v weave:expose | awk '{print $3}' | cut -d/ -f1) assert_raises "exec_on $HOST1 $C1 $PING $C2_IP" # We do not test "weave {status,launch}", because the weave script does not detect # plugin-v2 if its name is prefixed with a registry name. # Failing to cleanup will make the rest of the tests to fail cleanup $HOST1 $HOST2 end_suite
<reponame>zouzias/microgbt #include <metrics/logloss.h> #include <metrics/rmse.h> #include "gtest/gtest.h" using namespace microgbt; TEST(microgbt, RMSE) { RMSE rmse; ASSERT_NEAR(rmse.scoreToPrediction(10.1), 10.1, 1.0e-11); } TEST(microgbt, RMSEHessian) { RMSE rmse; Vector preds = Vector(10); Vector hessian = rmse.hessian(preds); ASSERT_EQ(hessian.size(), preds.size()); // Hessian is the constant 2 ASSERT_NEAR(hessian[0], 2.0, 1.0e-11); ASSERT_NEAR(hessian[9], 2.0, 1.0e-11); } TEST(microgbt, RMSEGradient) { RMSE rmse; Vector preds = Vector(10); Vector targets = Vector(10); std::fill(preds.begin(), preds.end(), 100.0); std::fill(targets.begin(), targets.end(), 99.0); Vector grads = rmse.gradients(preds, targets); ASSERT_EQ(grads.size(), preds.size()); ASSERT_NEAR(grads[0], 2 * (100.0 - 99), 1.0e-7); } TEST(microgbt, RMSELossAtMustBeZero) { RMSE rmse; Vector preds = Vector(10); Vector targets = Vector(10); std::fill(preds.begin(), preds.end(), 1.0); std::fill(targets.begin(), targets.end(), 1.0); double loss = rmse.lossAt(preds, targets); ASSERT_NEAR(loss, 0, 1.0e-7); }
<filename>test.js var nextTick = require('./nexttick') , test = require('tap').test test("simple", function (t) { t.plan(1) nextTick(function () { t.pass() }) }) test("specified loop length", function (t) { var i = 0 nextTick.loop(function () { ++i }, 50).then(function () { t.equal(50, i) t.end() }) }) test("infinite loop with exit clause", function (t) { var i = 0 nextTick.loop(function (exit) { ++i if (i === 100) exit() }).then(function () { t.equal(100, i) t.end() }) }) test("while loop", function (t) { var i = 0 nextTick.while(function () { return i < 100 }, function () { ++i }).then(function () { t.equal(100, i) t.end() }) }) test("while loop w/ exit", function (t) { var i = 0 nextTick.while(function () { return i < 100 }, function (exit) { ++i if (i === 50) exit() }).then(function () { t.equal(50, i) t.end() }) }) test("nextTick w/ arguments", function (t) { nextTick(function (a, b, c) { t.equal(1, a) t.equal(2, b) t.equal(3, c) }, 1, 2, 3).then(function () { t.end() }) }) test("forEach", function (t) { var arrayA = [ 1, 2, 3 ] , arrayB = [] , indexes = [] nextTick.forEach(arrayA, function (v, i, array) { arrayB.push(v) indexes.push(i) t.same(array, arrayA) }).then(function () { t.same([ 1, 2, 3 ], arrayB) t.same([ 0, 1, 2 ], indexes) t.end() }) }) test("forEach w/ exit", function (t) { var arrayA = [ 1, 2, 3 ] , arrayB = [] , indexes = [] nextTick.forEach(arrayA, function (v, i, array, exit) { arrayB.push(v) indexes.push(i) t.same(array, arrayA) if (i === 1) exit() }).then(function () { t.same([ 1, 2 ], arrayB) t.same([ 0, 1 ], indexes) t.end() }) }) test("slice", function (t) { var array = [ 1, 2, 3, 4, 5 ] t.plan(421) nextTick.slice(array).then(function (sliced) { t.same(sliced, array.slice()) }) for (var begin = -10; begin < 10; begin++) { ;(function (begin) { nextTick.slice(array, begin).then(function (sliced) { t.same(sliced, array.slice(begin)) }) }(begin)) } for (var begin = -10; begin < 10; begin++) { for (var end = -10; end < 10; end++) { ;(function (begin, end) { nextTick.slice(array, begin, end).then(function (sliced) { t.same(sliced, array.slice(begin, end)) }) }(begin, end)) } } }) test("in", function (t) { var hashA = { foo: 'bar', baz: 'zoo', lol: 'blah' } , hashB = {} nextTick.in(hashA, function (v, k, hash) { hashB[k] = v t.same(hash, hashA) }).then(function () { t.same(hashB, hashA) t.end() }) }) test("in w/ exit", function (t) { var hashA = { foo: 'bar', baz: 'zoo', lol: 'blah' } , hashB = {} nextTick.in(hashA, function (v, k, hash, exit) { hashB[k] = v t.same(hash, hashA) if (k === 'baz') exit() }).then(function () { t.same(hashB, { foo: 'bar', baz: 'zoo' }) t.end() }) }) test("arguments passing to callback", function (t) { nextTick.forEach([ 1, 2, 3 ], function (value, index, array, exit) { exit('whatever', 'works') }).then(function (a, b) { t.equal('whatever', a) t.equal('works', b) t.end() }) }) test("error handling", function (t) { nextTick.forEach([ 1, 2, 3 ], function (value, index, array, exit) { exit(new Error('Some error')) }).then(function (err) { t.equal('Some error', err.message) t.throws(function () { throw err }) t.end() }) })
<gh_stars>1-10 'use strict'; var mongoose = require('mongoose'); var Schema = mongoose.Schema; var GiftCardSchema = new Schema({ gift_card_number: String, merchant_id: { type: Schema.Types.ObjectId, ref: 'Merchant' }, client_id: { type: Schema.Types.ObjectId, ref: 'Client' }, branch_id: { type: Schema.Types.ObjectId, ref: 'Branch' }, number: Number, balance: Number, points: Number }, {timestamps: true}); module.exports = mongoose.model('GiftCard', GiftCardSchema);
#!/bin/bash # Define aws cli profile to use profile="venicegeo" function size_buckets { # Set default search string to null (meaning search all buckets) search_base=${1:null} # Get a list of all buckets buckets=$(aws s3api list-buckets --profile $profile | jq --raw-output '.Buckets[] | .Name') for bucket in $buckets do if [[ "$bucket" == *"$search_base"* ]] then size=$(aws s3 ls --profile $profile --summarize --human-readable --recursive s3://$bucket | grep "Total Size") echo "Bucket: $bucket $size" fi done } size_buckets "venicegeo-s3-logs"
set -eo nounset cd /mnt/lfs/sources rm -rf gawk-4.1.4 tar xf gawk-4.1.4.tar.xz pushd gawk-4.1.4 ./configure --prefix=/tools make #make check make install popd rm -rf gawk-4.1.4
<filename>elements/lisk-utils/src/objects/buffer_array.ts<gh_stars>100-1000 /* * Copyright © 2020 Lisk Foundation * * See the LICENSE file at the top-level directory of this distribution * for licensing information. * * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation, * no part of this software, including this file, may be copied, modified, * propagated, or distributed except according to the terms contained in the * LICENSE file. * * Removal or modification of this copyright notice is prohibited. */ import { BufferSet } from '../data_structures/buffer_set'; export const bufferArrayIncludes = (arr: Buffer[], val: Buffer): boolean => arr.find(a => a.equals(val)) !== undefined; export const bufferArrayContains = (arr1: Buffer[], arr2: Buffer[]): boolean => arr2.every(val => bufferArrayIncludes(arr1, val)); export const bufferArrayContainsSome = (arr1: Buffer[], arr2: Buffer[]): boolean => arr2.some(val => bufferArrayIncludes(arr1, val)); export const bufferArrayEqual = (arr1: Buffer[], arr2: Buffer[]): boolean => arr1.length === arr2.length && arr1.every((val, index) => val.equals(arr2[index])); export const bufferArraySubtract = (arr1: Buffer[], arr2: Buffer[]): Buffer[] => arr1.filter(a => !bufferArrayIncludes(arr2, a)); export const bufferArrayOrderByLex = (arr1: Buffer[]): boolean => { const sortedArray = [...arr1]; sortedArray.sort((a, b) => a.compare(b)); return bufferArrayEqual(arr1, sortedArray); }; export const bufferArrayUniqueItems = (arr1: Buffer[]): boolean => arr1.length === new BufferSet([...arr1]).size;
<reponame>Bernardinhouessou/Projets_Autres<filename>Java EE Projects (TPs-autres)/Projets Java EE-JDBC/IHM_Garage JDBC/P2PAPartie4-Vehicule-JDBC-Correction/src/fr/ocr/sql/MarqueDAO.java<gh_stars>0 package fr.ocr.sql; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import voiture.Marque; public class MarqueDAO extends DAO<Marque> { public MarqueDAO(Connection conn) { super(conn); } public boolean create(Marque obj) { return true; } public boolean delete(Marque obj) { return false; } public boolean update(Marque obj) { return true; } public Marque find(int id) { Marque marque = new Marque(); try(Statement state = this.connect.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) { ResultSet result = state.executeQuery( "SELECT * FROM marque WHERE id = " + id); if (result.first()) marque = new Marque(id, result.getString("nom")); } catch (SQLException e) { new DAOException("MarqueDAO : " + e.getMessage()); } return marque; } public List<Marque> findAll() { List<Marque> list = new ArrayList<>(); try(Statement state = this.connect.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) { ResultSet result = state.executeQuery( "SELECT * FROM marque ORDER BY nom"); while (result.next()) list.add(new Marque(result.getInt("id"), result .getString("nom"))); } catch (SQLException e) { new DAOException("MarqueDAO : " + e.getMessage()); } return list; } }
#! /usr/bin/env bash # vim: set ts=3 sw=3 noet ft=sh : bash SCRIPT="${0#./}" BASE_DIR="${SCRIPT%/*}" WORKDIR="$PWD" if [ "$BASE_DIR" = "$SCRIPT" ]; then BASE_DIR="$WORKDIR" else if [[ "$0" != /* ]]; then # Make the path absolute BASE_DIR="$WORKDIR/$BASE_DIR" fi fi platform=vita ${BASE_DIR}/libretro-build.sh $@
from common.tests.core import BaseLiveTestCase from allegation.factories import ( OfficerAllegationFactory, AllegationCategoryFactory) class DataToolCategoriesTabTestCase(BaseLiveTestCase): def setUp(self): self.allegation_category = AllegationCategoryFactory() self.officer_allegation = OfficerAllegationFactory( cat=self.allegation_category, final_finding='NS') def tearDown(self): super(DataToolCategoriesTabTestCase, self).tearDown() self.allegation_category.delete() if self.officer_allegation.officer: self.officer_allegation.officer.delete() else: self.officer_allegation.delete() # Helper methods def filter_complaint_type(self): self.visit_home() self.link("Categories").click() self.until_ajax_complete() def check_number_officer(self, num): self.until(lambda: self.number_of_officers().should.equal(num)) def number_of_active_subcategories(self): active_subcategories = self.find_all( '.child-rows .category-name.active') return len(active_subcategories) def number_of_officers(self): officers = self.find_all('.officer') return len(officers) # Tests def test_click_on_category_only_show_allegation_belong_to_it(self): other_category = AllegationCategoryFactory() OfficerAllegationFactory(cat=other_category) self.filter_complaint_type() self.check_number_officer(2) self.until( lambda: self.link(self.allegation_category.category).is_displayed()) self.link(self.allegation_category.category).click() self.check_number_officer(1) def test_click_on_officer_will_show_compliant(self): self.filter_complaint_type() self.check_number_officer(1) self.browser.refresh() self.find('.checkmark').click() self.until(lambda: self.element_exist('.complaint-list')) self.find('.complaint-row > .row').click() self.element_exist('.complaint_detail').should.equal(True) def test_all_subcategories_should_be_selected(self): category = self.allegation_category.category allegation_category = AllegationCategoryFactory(category=category) OfficerAllegationFactory(cat=allegation_category) # First, we click a category, we should see the arrow beside the category self.filter_complaint_type() with self.browser_no_wait(): self.element_exist('.row .arrow-container').should.equal(False) self.until( lambda: self.link(self.allegation_category.category).click()) # TODO: We should have another test to check which main category this arrow belong to? self.element_exist('.row .arrow-container').should.equal(True) # And it should have a an arrow on the category self.until( lambda: self.number_of_active_subcategories().should.equal(2)) self.until( lambda: self.should_see_text(self.allegation_category.allegation_name)) self.link(self.allegation_category.allegation_name).click() self.until( lambda: self.number_of_active_subcategories().should.equal(1)) def test_categories_replacement_logic(self): category = self.allegation_category.category other_category = AllegationCategoryFactory() sub_category = AllegationCategoryFactory(category=category) OfficerAllegationFactory(cat=other_category) OfficerAllegationFactory(cat=sub_category) self.filter_complaint_type() self.link(category).click() self.until_ajax_complete() self.element_by_classname_and_text('filter-name', category).should.be.ok self.link(sub_category.allegation_name).click() self.until_ajax_complete() self.element_by_classname_and_text('filter-name', sub_category.allegation_name).should.be.ok self.element_by_classname_and_text('filter-name', category).should.be.false self.link(other_category.category).click() self.until_ajax_complete() self.element_by_classname_and_text('filter-name', other_category.category).should.be.ok self.element_by_classname_and_text('filter-name', sub_category.allegation_name).should.be.false
# /bin/bash ./build.sh mkdir -p ../LoadAssembly/bin/Debug/net5.0/Assembly rm ../LoadAssembly/bin/Debug/net5.0/Assembly/*.dll cp ../Assembly2/bin/Debug/net5.0/Assembly2.dll ../LoadAssembly/bin/Debug/net5.0/Assembly/ cd ../LoadAssembly/bin/Debug/net5.0/ ./LoadAssembly cd -
// By KRT girl xiplus #include <bits/stdc++.h> #define endl '\n' using namespace std; bool nisp[46341]={false}; int p[10000]; int main(){ // ios::sync_with_stdio(false); // cin.tie(0); nisp[0]=nisp[1]=true; int i=2,j,k=0; while(i<46341){ if(!nisp[i]){ p[k++]=i; j=i*2; while(j<46341){ nisp[j]=true; j+=i; } } i++; } int n; while(cin>>n){ int ans=0; for(int q=0;q<k;q++){ while(n%p[q]==0){ ans+=p[q]; n/=p[q]; } } if(n!=1)ans+=n; cout<<ans<<endl; } }
<reponame>djeada/Nauka-programowania<filename>src/Python/01_Interakcja_z_konsola/Zad6.py if __name__ == "__main__": """ Pobierz wielkosc w kilogramach i wypisz ilu gramom odpowiada. """ print("podaj wielkosc w kilogramach:") kilogramy = int(input()) gramy = kilogramy * 1000 print(kilogramy, " kg to ", gramy, " g") """ Pobierz wielkosc w calach i wypisz ilu centymetrom odpowiada. """ print("podaj wielkosc w calach:") cal = int(input()) cm = cal / 2.54 print(cal, " cali to", cm, " cm") """ Pobierz ilosc sekund i przelicz na godziny. """ print("podaj ilosc sekund:") sekundy = int(input()) godziny = sekundy / 3600 print(sekundy, " sekund to ", godziny, " godzin") """ Pobierz liczbe w euro i wypisz ilu zlotowkom odpowiada. """ print("podaj liczbe w euro:") euro = input() zloty = euro * 4.40 print(euro, " euro to ", zloty, " zlotych") """ Pobierz miare kata w stopniach i wypisz ilu radianom odpowiada. """ print("podaj miare kata w stopniach:") kat_stopnie = int(input()) kat_rad = kat_stopnie * 0.0174532 print(kat_stopnie, " stopni to ", kat_rad, " radianow") """ Pobierz temperature w stopniach Farenheita i wypisz ilu stopniom Celsjusza oraz ilu stopniom Kelwina odpowiada. """ print("podaj temperature w Farenheitach:") temp_f = int(input()) temp_c = (temp_f - 32) * 5 / 9 temp_k = temp_c - 273 print(temp_f, " F to ", temp_c, " C", " i ", temp_k, " K")
#!/usr/bin/env bash set -e export ZABBIX_SERVER_HOST=${TCPREMOTEADDR%:*} export PMPY_RUN_ID=` cat /dev/urandom | base64 | \ tr -cd a-z0-9 | head -c8 ` : ${SCRIPTS_DIR:=$PMPY_SCRIPTS_DIR} \ ${SCRIPTS_DIR:?} : ${MODULES_DIR:=$PMPY_MODULES_DIR} \ ${MODULES_DIR:?} : ${MODULES_PARALLELISM:=$PMPY_MODULES_PARALLELISM} \ ${MODULES_PARALLELISM:=3} cd $MODULES_DIR find . -mindepth 1 -maxdepth 1 \ -type d -printf %P\\n | xargs -rn1 -P$MODULES_PARALLELISM \ $SCRIPTS_DIR/process_module.sh
<reponame>keinpyisi/Yukihime /// <reference types="node" /> export declare const freshRequire: NodeRequireFunction;
<reponame>yurugengo-supporters/discord-bot-sandbox import express from 'express'; // GAEがサーバーをリスンしていないとそもそもアプリとして認識してくれないので、ダミーのレスポンスを返すようにしておく export const createDummyServer = (port: number) => { const PORT = port; const app = express(); app.get('/', (_req, res) => { res.send('🤖Bot is running!!🤖'); }); app.listen(PORT, () => { console.log(`App listening on port ${PORT}`); }); };
-- insert data sailboats for MySQL -- Author wyh -- 说明:打开此.sql文件,执行一次即可将数据插入已经建好的 sailboats 数据库中 use sailboats; set names utf8; insert into sailors values('22','Dustin',7,45); insert into sailors values('29','Brutus',1,33); insert into sailors values('31','Lubber',8,55); insert into sailors values('32','Andy',8,25); insert into sailors values('58','Rusty',10,35); insert into sailors values('64','Horatio',7,35); insert into sailors values('71','Zorba',10,16); insert into sailors values('74','Jeff',9,35); insert into sailors values('85','Art',3,25); insert into sailors values('95','Bob',3,63); insert into boats values('101','Interlake','Blue'); insert into boats values('102','Interlake','Red'); insert into boats values('103','Clipper','Green'); insert into boats values('104','Marine','Red'); insert into reserves values('22','101','1998-10-10'); insert into reserves values('22','102','1998-10-10'); insert into reserves values('22','103','1998-10-8'); insert into reserves values('22','104','1998-10-7'); insert into reserves values('31','102','1998-11-10'); insert into reserves values('31','103','1998-11-6'); insert into reserves values('31','104','1998-11-12'); insert into reserves values('64','101','1998-9-5'); insert into reserves values('64','102','1998-9-5'); insert into reserves values('74','103','1998-9-8');
// https://codeforces.com/contest/1047/problem/C #include <bits/stdc++.h> using namespace std; const int N = 15000000; bool primes[N]; int p, ps[N],a[N], factors[N]; void f() { for (int i = 2; i < N; i++) primes[i] = true; for (int i = 2; i < N; i++) if (primes[i]) for (int j = 2*i; j < N; j+=i) primes[j]=false; for (int i = 0; i < N; i++) if (primes[i]) ps[p++] = i; } int main() { ios::sync_with_stdio(0); cin.tie(0); f(); int n, x, g; cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; if (!i) g = a[i]; else g = __gcd(g, a[i]); } for (int i = 0; i < n; i++) { x = a[i]/g; int j = 0; while (x > 1) { if (primes[x]) { factors[x]++; break; } if (!(x%ps[j])) { factors[ps[j]]++; while(!(x%ps[j])) x/=ps[j]; } j++; } } int m = 0; for (int i = 0; i < N; i++) if (factors[i] < n) m = max(factors[i], m); if (m) cout << (n - m) << endl; else cout << "-1\n"; }
package org.usfirst.frc5112.Robot2017V3.subsystems; import org.usfirst.frc5112.Robot2017V3.RobotMap; import org.usfirst.frc5112.Robot2017V3.commands.DrivetrainCommands.OperatorControl; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.command.Subsystem; /** * */ public class Drivetrain extends Subsystem { private final RobotDrive drivetrain = RobotMap.drivetrainDrivetrain; private boolean invertedRotating = false; private double throttle = 0.7; private double turningThrottle = 0.7; private final double INITIAL_THROTTLE = 0.7; private final double FINAL_THROTTLE = 1.0; public double switchYSign = -1; public void initDefaultCommand() { // Set the default command for a subsystem here. setDefaultCommand(new OperatorControl()); } /** * Moves the robot forward at a specific speed until the Drivetrain.stop() * method is called. * * @param speed * The specific speed to move the robot at. */ public void forward(double speed) { drivetrain.arcadeDrive(-speed * switchYSign, -0.03*RobotMap.gyro.getAngle(), false); } /** * Moves the robot backwards at a specific speed until the Drivetrain.stop() * method is called. * * @param speed * The specific speed to move the robot at. */ public void reverse(double speed) { drivetrain.arcadeDrive(speed * switchYSign, -0.03*RobotMap.gyro.getAngle(), false); } /** * Rotates the robot in the clockwise direction (to the right). * @param speed Specifies the speed to rotate the robot at. */ public void rotateClockwise(double speed) { drivetrain.arcadeDrive(0, speed); } /** * Rotates the robot in the counterclockwise direction (to the left). * @param speed Specifies the speed to rotate the robot at. */ public void rotateCounterclockwise(double speed) { drivetrain.arcadeDrive(0, -speed); } /** * Stops all ongoing movements from the drivetrain. */ public void stop() { drivetrain.drive(0, 0); } public void operatorControl(Joystick joystick) { if (joystick.getRawButton(1)) { throttle = FINAL_THROTTLE; } else { throttle = INITIAL_THROTTLE; } if (!invertedRotating) { if (joystick.getY() < -0.1 || joystick.getY() > 0.1) { if (joystick.getY() <= -0.1){ drivetrain.arcadeDrive(((joystick.getY() + 0.1) * 10 / 9 * throttle) * switchYSign, joystick.getZ() * turningThrottle); }else { drivetrain.arcadeDrive(((joystick.getY() - 0.1) * 10 / 9 * throttle) * switchYSign, joystick.getZ() * turningThrottle); } } else { drivetrain.arcadeDrive(0, joystick.getZ() * turningThrottle); } } else { if (joystick.getY() < -0.1 || joystick.getY() > 0.1) { if (joystick.getY() <= -0.1){ drivetrain.arcadeDrive(((joystick.getY() + 0.1) * 10 / 9 * throttle) * switchYSign, joystick.getZ()* -1 * turningThrottle); }else { drivetrain.arcadeDrive(((joystick.getY() - 0.1) * 10 / 9 * throttle) * switchYSign, joystick.getZ()* -1 * turningThrottle); } } else { drivetrain.arcadeDrive(0, joystick.getZ() * turningThrottle * -1); } } } public void invertMotors() { RobotMap.drivetrainLeft3.setInverted(false); RobotMap.drivetrainLeft2.setInverted(false); RobotMap.drivetrainLeft1.setInverted(false); RobotMap.drivetrainRight3.setInverted(false); RobotMap.drivetrainRight2.setInverted(false); RobotMap.drivetrainRight1.setInverted(false); invertedRotating = true; } public void resetMotorDirection(){ RobotMap.drivetrainLeft3.setInverted(true); RobotMap.drivetrainLeft2.setInverted(true); RobotMap.drivetrainLeft1.setInverted(true); RobotMap.drivetrainRight3.setInverted(true); RobotMap.drivetrainRight2.setInverted(true); RobotMap.drivetrainRight1.setInverted(true); invertedRotating = false; } public void swtichYValue() { if (switchYSign == 1) { switchYSign = -1; } else { switchYSign = 1; } } }
<reponame>malliina/staticweb<filename>content/src/main/scala/com/malliina/staticweb/content/Html.scala package com.malliina.staticweb.content import com.malliina.staticweb.Constants.HelloContainerId import com.malliina.staticweb.content.Html.defer import scalatags.Text.all._ object Html { val defer = attr("defer").empty def apply(css: Seq[String], js: Seq[String]): Html = new Html(css, js) } class Html(css: Seq[String], js: Seq[String]) { def index = template( div(id := HelloContainerId)( h1("Hi") ) ) def notFound = template(div(h1("Not found"))) def template(content: Modifier*) = TagPage( html( head( meta(charset := "UTF-8"), tag("title")("Scala.js website"), css.map { path => link(href := path, rel := "stylesheet") }, js.map { path => script(defer, src := path, `type` := "text/javascript") } ), body( content ) ) ) }
/* eslint-disable @typescript-eslint/no-empty-function */ /* eslint-disable @typescript-eslint/camelcase */ import { IsOptional } from 'class-validator'; import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { ApiError } from '../api/ApiResult'; import { ErrorCodes } from '../api/ResultCodes'; import { DefaultPaging } from '../constant'; //base request dto export class BaseReqDto { static validate(value: any): void {} static convert(value: any): any { return value; } } // base response dto export class BaseResDto { static bundleData(value: any): any { return value; } } //base Paging request Dto export class PagingReqDto extends BaseReqDto { @ApiPropertyOptional() @IsOptional() page_num?: number; @ApiPropertyOptional() @IsOptional() page_size?: number; @ApiPropertyOptional({ description: 'true/false' }) @IsOptional() use_count?: boolean; static validate(value: any): void { const patt = /^[1-9]\d*$/; if (value.pageNum && (!patt.test(value.pageNum) || value.pageNum < 1)) { throw new ApiError( ErrorCodes.InvalidParameter, 'The pageNum must be a positive integer greater than 0', ); } if (value.pageSize && (!patt.test(value.pageSize) || value.pageNum < 1)) { throw new ApiError( ErrorCodes.InvalidParameter, 'The pageSize must be a positive integer greater than 0', ); } } static convert(value: any): any { if (!value.pageNum) { value.pageNum = DefaultPaging.pageNum; } if (!value.pageSize) { value.pageSize = DefaultPaging.pageSize; } if (!value.use_count) { value.use_count = false; } else { if (value.use_count === 'true') { value.use_count = true; } else { value.use_count = false; } } value.pageNum = Number(value.pageNum); value.pageSize = Number(value.pageSize); return value; } }
<gh_stars>0 package com.yahoo.ycsb.generator; import java.util.UUID; import org.bson.types.ObjectId; /** * Unique ID Generator for Pi resources. * */ public class UniqueIdGenerator { /** * Generates an incrementing unique id string. * * @return A Unique ID incremented from the previous. */ public static String generateIncrementing() { return new ObjectId().toString(); } /** * Generate a randomly generated unique id string. Wraps a call to {@link UUID#randomUUID()} followed by a removal * of all "-" characters from the output string. * * @return A Unique ID randomly generated. */ public static String generateRandom() { String fullUUID = UUID.randomUUID().toString(); String trimUUID = fullUUID.replaceAll("-", ""); return trimUUID; } }
<reponame>golinski/webflux-graphql /* * This file is generated by jOOQ. */ package com.yg.gqlwfdl.dataaccess.db.tables.records; import com.yg.gqlwfdl.dataaccess.db.tables.Company; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Record1; import org.jooq.Record5; import org.jooq.Row5; import org.jooq.impl.UpdatableRecordImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.11.2" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class CompanyRecord extends UpdatableRecordImpl<CompanyRecord> implements Record5<Long, String, String, Long, Long> { private static final long serialVersionUID = 2060775230; /** * Setter for <code>public.company.id</code>. */ public void setId(Long value) { set(0, value); } /** * Getter for <code>public.company.id</code>. */ public Long getId() { return (Long) get(0); } /** * Setter for <code>public.company.name</code>. */ public void setName(String value) { set(1, value); } /** * Getter for <code>public.company.name</code>. */ public String getName() { return (String) get(1); } /** * Setter for <code>public.company.address</code>. */ public void setAddress(String value) { set(2, value); } /** * Getter for <code>public.company.address</code>. */ public String getAddress() { return (String) get(2); } /** * Setter for <code>public.company.primary_contact</code>. */ public void setPrimaryContact(Long value) { set(3, value); } /** * Getter for <code>public.company.primary_contact</code>. */ public Long getPrimaryContact() { return (Long) get(3); } /** * Setter for <code>public.company.pricing_details</code>. */ public void setPricingDetails(Long value) { set(4, value); } /** * Getter for <code>public.company.pricing_details</code>. */ public Long getPricingDetails() { return (Long) get(4); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record1<Long> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record5 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row5<Long, String, String, Long, Long> fieldsRow() { return (Row5) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row5<Long, String, String, Long, Long> valuesRow() { return (Row5) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<Long> field1() { return Company.COMPANY.ID; } /** * {@inheritDoc} */ @Override public Field<String> field2() { return Company.COMPANY.NAME; } /** * {@inheritDoc} */ @Override public Field<String> field3() { return Company.COMPANY.ADDRESS; } /** * {@inheritDoc} */ @Override public Field<Long> field4() { return Company.COMPANY.PRIMARY_CONTACT; } /** * {@inheritDoc} */ @Override public Field<Long> field5() { return Company.COMPANY.PRICING_DETAILS; } /** * {@inheritDoc} */ @Override public Long component1() { return getId(); } /** * {@inheritDoc} */ @Override public String component2() { return getName(); } /** * {@inheritDoc} */ @Override public String component3() { return getAddress(); } /** * {@inheritDoc} */ @Override public Long component4() { return getPrimaryContact(); } /** * {@inheritDoc} */ @Override public Long component5() { return getPricingDetails(); } /** * {@inheritDoc} */ @Override public Long value1() { return getId(); } /** * {@inheritDoc} */ @Override public String value2() { return getName(); } /** * {@inheritDoc} */ @Override public String value3() { return getAddress(); } /** * {@inheritDoc} */ @Override public Long value4() { return getPrimaryContact(); } /** * {@inheritDoc} */ @Override public Long value5() { return getPricingDetails(); } /** * {@inheritDoc} */ @Override public CompanyRecord value1(Long value) { setId(value); return this; } /** * {@inheritDoc} */ @Override public CompanyRecord value2(String value) { setName(value); return this; } /** * {@inheritDoc} */ @Override public CompanyRecord value3(String value) { setAddress(value); return this; } /** * {@inheritDoc} */ @Override public CompanyRecord value4(Long value) { setPrimaryContact(value); return this; } /** * {@inheritDoc} */ @Override public CompanyRecord value5(Long value) { setPricingDetails(value); return this; } /** * {@inheritDoc} */ @Override public CompanyRecord values(Long value1, String value2, String value3, Long value4, Long value5) { value1(value1); value2(value2); value3(value3); value4(value4); value5(value5); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached CompanyRecord */ public CompanyRecord() { super(Company.COMPANY); } /** * Create a detached, initialised CompanyRecord */ public CompanyRecord(Long id, String name, String address, Long primaryContact, Long pricingDetails) { super(Company.COMPANY); set(0, id); set(1, name); set(2, address); set(3, primaryContact); set(4, pricingDetails); } }
#!/bin/bash export DEPS="/deps" export TARGET="/target" export PATH="$PATH:/target/bin" # versions of dependencies export VERSION_ZLIB=1.2.11 export VERSION_XML2=2.9.4 export VERSION_FFI=3.2.1 export VERSION_GETTEXT=0.19.8.1 export VERSION_GLIB=2.40.2 export VERSION_VIPS=8.6.1 export VERSION_EXIF=0.6.21 export VERSION_JPEG=1.5.1 export VERSION_LCMS2=2.8 # NOTE: libpng puts old releases in a subfolder older-releases export VERSION_PNG16=1.6.34 export VERSION_TIFF=4.0.7 export VERSION_ORC=0.4.26 export VERSION_FFTW=3.3.6-pl1 export VERSION_NASM=2.12.02 export VERSION_FFMPEG=3.3.5 export CC="gcc-5" export CXX="g++-5" export PKG_CONFIG_PATH="${TARGET}/lib/pkgconfig" export BASE_FLAGS="-s -fvisibility=hidden -I${TARGET}/include" export CFLAGS="${BASE_FLAGS}" export CPPFLAGS="${BASE_FLAGS} -static-libstdc++" export CXXFLAGS="${BASE_FLAGS} -static-libstdc++" export STATICLIB_CFLAGS="-g -O2 -fvisibility=hidden" export LDFLAGS="-L${TARGET}/lib" export LD_LIBRARY_PATH="${TARGET}"
#!/bin/sh set -e echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" # Used as a return value for each invocation of `strip_invalid_archs` function. STRIP_BINARY_RETVAL=0 # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") # Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # Use filter instead of exclude so missing patterns don't throw errors. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Copies and strips a vendored dSYM install_dsym() { local source="$1" if [ -r "$source" ]; then # Copy the dSYM into a the targets temp dir. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" local basename basename="$(basename -s .framework.dSYM "$source")" binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then strip_invalid_archs "$binary" fi if [[ $STRIP_BINARY_RETVAL == 1 ]]; then # Move the stripped file into its final destination. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" else # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" fi fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current target binary binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" # Intersect them with the architectures we are building for intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" # If there are no archs supported by this binary then warn the user if [[ -z "$intersected_archs" ]]; then echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." STRIP_BINARY_RETVAL=0 return fi stripped="" for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi STRIP_BINARY_RETVAL=1 } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/ApplinsSDK/ApplinsSDK.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/ApplinsSDK/ApplinsSDK.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi
class Component: def __init__(self, component_id, component_type): self.id = component_id self.type = component_type class Netlist: def __init__(self): self.components = {} self.connections = set() def add_component(self, component): self.components[component.id] = component def connect_components(self, component1, component2): self.connections.add((component1.id, component2.id)) self.connections.add((component2.id, component1.id)) def is_component_present(self, component): return component.id in self.components def get_component_type(self, component): return self.components[component.id].type
<reponame>vamshop/vamshop-cakephp-skeleton-app<gh_stars>0 module.exports = function(grunt) { var settings = {}; var settingsPath = 'Config/settings.json'; if (!grunt.file.exists(settingsPath)) { settingsPath += '.install'; } /** * Config */ var initConfig = { pkg: grunt.file.readJSON('package.json'), settings: grunt.file.readJSON(settingsPath), rootPath: __dirname, shell: { options: { stdout: true }, cachePluginPaths: { command: './Console/cake vamshop cachePluginPaths' } } }; var buildTasks = [ 'shell:cachePluginPaths' ]; /** * Vamshop plugins config */ var pluginPaths = grunt.file.readJSON('tmp/plugin_paths.json'); for (var plugin in pluginPaths) { var pluginPath = pluginPaths[plugin]; gruntHookFile = pluginPath + '/Grunthookfile.js'; if (grunt.file.exists(gruntHookFile)) { var pluginConfig = require(gruntHookFile)(grunt, initConfig); for (var gruntPlugin in pluginConfig) { var pluginTargets = pluginConfig[gruntPlugin]; for (var target in pluginTargets) { var targetConfig = pluginTargets[target]; // Add plugin to InitConfig if (typeof initConfig[gruntPlugin] === 'undefined') { initConfig[gruntPlugin] = {}; } initConfig[gruntPlugin][target] = targetConfig; // Register in build tasks if (target.indexOf('build-') == 0) { buildTasks.push(gruntPlugin + ':' + target); } } } } } //console.log(JSON.stringify(initConfig, undefined, 2)); grunt.initConfig(initConfig); /** * Load tasks */ require('load-grunt-tasks')(grunt); /** * Register tasks */ grunt.registerTask('build', buildTasks); };
//Componentes html let imagen = document.getElementById('img-roulette'), overlay = document.getElementById('overlay'), botonAtras = document.getElementById('button-back'), botonAdelante = document.getElementById('button-forward'); //Rutas imagenes const rutaSmallImg = [ "img/food1_small.webp", "img/food2_small.webp", "img/food3_small.webp", "img/food4_small.webp"]; //Parametros const INTERVAL_TIME = 3000; //ms let intervalo = setInterval(playInterval, INTERVAL_TIME); let indexAction = 0; //Lleva el indice de las acciones //FUNCIONES //Simple Print en consola function print(text){ console.log(text); } //Cambia el indice con el tiempo del interval function playInterval(){ if(indexAction < rutaSmallImg.length-1){ indexAction ++; }else { indexAction = 0; } cambiarImg(); } //Cambia la imagen dependiendo del indice function cambiarImg(){ print("RUTA: "+rutaSmallImg[indexAction]+" INDICE:"+indexAction); imagen.src = rutaSmallImg[indexAction]; } //Acciones function avanzarImagen(){ if(indexAction < rutaSmallImg.length-1){ indexAction ++; }else { indexAction = 0; } cambiarImg(); } function retrocederImagen(){ if(indexAction < rutaSmallImg.length){ indexAction --; if (indexAction<0){ indexAction = rutaSmallImg.length-1; } } cambiarImg(); } function pausarIntervalo(){ clearInterval(intervalo); } function iniciarIntervalo(){ intervalo = setInterval(playInterval, INTERVAL_TIME); } //Eventos Mouse botonAdelante.addEventListener('click', avanzarImagen); botonAtras.addEventListener('click', retrocederImagen); overlay.addEventListener('mouseenter', pausarIntervalo); overlay.addEventListener('mouseleave', iniciarIntervalo);
// Kinect data let bodies = null; function startDemo() { // *************** // * Scene setup * // *************** let kinectJoints = []; let canvas = document.getElementById('renderCanvas'); let engine = new BABYLON.Engine(canvas, true); let scene = new BABYLON.Scene(engine); let mainCamera = new BABYLON.FreemainCamera("MainCamera", new BABYLON.Vector3(0, 2, -2), scene); mainCamera.setTarget(BABYLON.Vector3.Zero()); mainCamera.attachControl(canvas, true); let mainLight = new BABYLON.HemisphericmainLight("mainLight1", new BABYLON.Vector3(0, 1, 0), scene); mainLight.intensity = 0.7; // ******************** // * Creating objects * // ******************** let skybox = BABYLON.Mesh.CreateBox("skybox", 250, scene); skybox.material = new BABYLON.StandardMaterial("skyboxMaterial", scene); skybox.material.backFaceCulling = false; skybox.material.reflectionTexture = new BABYLON.CubeTexture("Assets/Textures/skybox/skybox", scene); skybox.material.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE; mainLight.excludedMeshes.push(skybox); let ground = BABYLON.Mesh.CreateGround("ground1", 6, 6, 2, scene); ground.material = new BABYLON.StandardMaterial("groundMat", scene); ground.material.diffuseTexture = new BABYLON.Texture("Assets/Textures/ground.png", scene); // ************************** // * Creating Kinect Avatar * // ************************** let jointParent = new BABYLON.Mesh("KinectAvatar", scene); jointParent.isVisible = false; jointParent.position.y += 1; let jointMaterial = new BABYLON.StandardMaterial("JointMaterial", scene); jointMaterial.diffuseTexture = new BABYLON.Texture("Assets/Textures/box.png", scene); for (let i = 0; i < 25; i++) { kinectJoints.push(BABYLON.Mesh.CreateSphere("sphere_" + i, 16, 0.25, scene)); kinectJoints[i].jointType = i; kinectJoints[i].position.y = i * 0.2; kinectJoints[i].scaling = new BABYLON.Vector3(0.4, 0.4, 0.4); kinectJoints[i].parent = jointParent; kinectJoints[i].material = jointMaterial; } // Start the engine engine.runRenderLoop(function() { if (bodies != null && bodies.length) { let body = bodies[0]; for (let i = 0; i < 25; i++) { let joint = body.kinectJoints[kinectJoints[i].jointType]; kinectJoints[i].position.copyFromFloats(joint.Position.x, joint.Position.y, joint.Position.z); } } scene.render(); }); window.addEventListener('resize', function() { engine.resize(); }); } window.onload = function (event) { // Connection to the Kinect Server. let ws = new WebSocket("ws://127.0.0.1:8181"); ws.onopen = (e) => console.log("Connected to server"); ws.onerror = (e) => console.log("Error detected"); ws.onmessage = (e) => { bodies = JSON.parse(e.data); }; // Start the demo. startDemo(); };
/* * Copyright (c) 2007, Novell Inc. * * This program is licensed under the BSD license, read LICENSE.BSD * for further information */ /* * deb2solv - create a solv file from one or multiple debs * */ #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include "util.h" #include "pool.h" #include "repo.h" #include "repo_deb.h" #include "repo_solv.h" #include "common_write.h" static char * fgets0(char *s, int size, FILE *stream) { char *p = s; int c; while (--size > 0) { c = getc(stream); if (c == EOF) { if (p == s) return 0; c = 0; } *p++ = c; if (!c) return s; } *p = 0; return s; } int main(int argc, char **argv) { const char **debs = 0; char *manifest = 0; int manifest0 = 0; int c, i, res, ndebs = 0; Pool *pool = pool_create(); Repo *repo; FILE *fp; char buf[4096], *p; const char *basefile = 0; int is_repo = 0; while ((c = getopt(argc, argv, "0b:m:r")) >= 0) { switch(c) { case 'b': basefile = optarg; break; case 'm': manifest = optarg; break; case 'r': is_repo = 1; break; case '0': manifest0 = 1; break; default: exit(1); } } if (manifest) { if (!strcmp(manifest, "-")) fp = stdin; else if ((fp = fopen(manifest, "r")) == 0) { perror(manifest); exit(1); } for (;;) { if (manifest0) { if (!fgets0(buf, sizeof(buf), fp)) break; } else { if (!fgets(buf, sizeof(buf), fp)) break; if ((p = strchr(buf, '\n')) != 0) *p = 0; } debs = solv_extend(debs, ndebs, 1, sizeof(char *), 15); debs[ndebs++] = strdup(buf); } if (fp != stdin) fclose(fp); } while (optind < argc) { debs = solv_extend(debs, ndebs, 1, sizeof(char *), 15); debs[ndebs++] = strdup(argv[optind++]); } repo = repo_create(pool, "deb2solv"); repo_add_repodata(repo, 0); res = 0; if (!ndebs && !manifest && is_repo) { if (repo_add_debpackages(repo, stdin, REPO_REUSE_REPODATA|REPO_NO_INTERNALIZE)) { fprintf(stderr, "deb2solv: %s\n", pool_errstr(pool)); res = 1; } } for (i = 0; i < ndebs; i++) { if (is_repo) { if ((fp = fopen(debs[i], "r")) == 0) { perror(debs[i]); res = 1; continue; } if (repo_add_debpackages(repo, fp, REPO_REUSE_REPODATA|REPO_NO_INTERNALIZE)) { fprintf(stderr, "deb2solv: %s\n", pool_errstr(pool)); res = 1; } fclose(fp); continue; } if (repo_add_deb(repo, debs[i], REPO_REUSE_REPODATA|REPO_NO_INTERNALIZE) == 0) { fprintf(stderr, "deb2solv: %s\n", pool_errstr(pool)); res = 1; } } repo_internalize(repo); tool_write(repo, basefile, 0); pool_free(pool); for (c = 0; c < ndebs; c++) free((char *)debs[c]); solv_free(debs); exit(res); }
if($id != null) { $conn->query("UPDATE users SET name = '$name' WHERE id = '$id'"); }
#!/bin/bash # ============================================================================= # Sources a list of functions passed into the script. Functions must have a # matching directory with *.sh files. # ============================================================================= functions="$@" echo "Sourcing functions: $functions" for func in $functions; do if [ ! -d $func ]; then echo "Function not found: $func" 1>&2 else for script in $func/*.sh; do . "$script" || echo "Sourcing script failed: $script" 1>&2 done echo "Sourced function: $func" fi done
python -m domainbed.scripts.sweep launch\ --data_dir=./domainbed/data/\ --output_dir=../result_domainbed/final/Digits_sub04/ver01\ --command_launcher select_gpu\ --dataset Digits\ --algorithm RandGen\ --n_trials 2\ --multiple_job 2\ --holdout_fraction 0.0\ --select_gpu_idx 0\ --combination_test_envs singleDG\ --skip_confirmation False\ --hparams={\"cam_method\":0} python -m domainbed.scripts.sweep launch\ --data_dir=./domainbed/data/\ --output_dir=../result_domainbed/final/Digits_sub04/ver02\ --command_launcher select_gpu\ --dataset Digits\ --algorithm RandGen\ --n_trials 2\ --multiple_job 2\ --holdout_fraction 0.0\ --select_gpu_idx 0\ --combination_test_envs singleDG\ --skip_confirmation False\ --hparams={\"cam_method\":2} python -m domainbed.scripts.sweep launch\ --data_dir=./domainbed/data/\ --output_dir=../result_domainbed/final/Digits_sub04/ver03\ --command_launcher select_gpu\ --dataset Digits\ --algorithm RandGen\ --n_trials 2\ --multiple_job 2\ --holdout_fraction 0.0\ --select_gpu_idx 0\ --combination_test_envs singleDG\ --skip_confirmation False\ --hparams={\"cam_method\":4} python -m domainbed.scripts.sweep launch\ --data_dir=./domainbed/data/\ --output_dir=../result_domainbed/final/Digits_sub04/ver04\ --command_launcher select_gpu\ --dataset Digits\ --algorithm RandGen\ --n_trials 2\ --multiple_job 2\ --holdout_fraction 0.0\ --select_gpu_idx 0\ --combination_test_envs singleDG\ --skip_confirmation False\ --hparams={\"cam_method\":5} python -m domainbed.scripts.sweep launch\ --data_dir=./domainbed/data/\ --output_dir=../result_domainbed/final/Digits_sub04/ver05\ --command_launcher select_gpu\ --dataset Digits\ --algorithm RandGen\ --n_trials 2\ --multiple_job 2\ --holdout_fraction 0.0\ --select_gpu_idx 0\ --combination_test_envs singleDG\ --skip_confirmation False\ --hparams={\"cam_method\":6} python -m domainbed.scripts.sweep launch\ --data_dir=./domainbed/data/\ --output_dir=../result_domainbed/final/Digits_sub04/ver06\ --command_launcher select_gpu\ --dataset Digits\ --algorithm RandGen\ --n_trials 2\ --multiple_job 2\ --holdout_fraction 0.0\ --select_gpu_idx 0\ --combination_test_envs singleDG\ --skip_confirmation False\ --hparams={\"cam_method\":7}
#!/bin/bash git filter-branch --tree-filter ' for f in $(git ls-files) do sed -i '"'"'s/^.*$/& /'"'"' "$f" done'
<filename>ciat-bim-rule/src/main/java/com/ciat/bim/rule/engine/rpc/TbSendRPCReplyNode.java /** * Copyright © 2016-2021 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ciat.bim.rule.engine.rpc; import com.ciat.bim.common.data.rule.ComponentType; import com.ciat.bim.msg.EntityType; import com.ciat.bim.msg.TbMsg; import com.ciat.bim.rule.*; import com.ciat.bim.rule.util.TbNodeUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.util.StringUtils; import java.util.UUID; @Slf4j @RuleNode( type = ComponentType.ACTION, name = "rpc call reply", configClazz = TbSendRpcReplyNodeConfiguration.class, nodeDescription = "Sends reply to RPC call from device", nodeDetails = "Expects messages with any message type. Will forward message body to the device.", uiResources = {"static/rulenode/rulenode-core-config.js"}, configDirective = "tbActionNodeRpcReplyConfig", icon = "call_merge" ) public class TbSendRPCReplyNode implements TbNode { private TbSendRpcReplyNodeConfiguration config; @Override public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { this.config = TbNodeUtils.convert(configuration, TbSendRpcReplyNodeConfiguration.class); } @Override public void onMsg(TbContext ctx, TbMsg msg) { String serviceIdStr = msg.getMetaData().getValue(config.getServiceIdMetaDataAttribute()); String sessionIdStr = msg.getMetaData().getValue(config.getSessionIdMetaDataAttribute()); String requestIdStr = msg.getMetaData().getValue(config.getRequestIdMetaDataAttribute()); if (msg.getOriginator().getEntityType() != EntityType.DEVICE) { ctx.tellFailure(msg, new RuntimeException("Message originator is not a device entity!")); } else if (StringUtils.isEmpty(requestIdStr)) { ctx.tellFailure(msg, new RuntimeException("Request id is not present in the metadata!")); } else if (StringUtils.isEmpty(serviceIdStr)) { ctx.tellFailure(msg, new RuntimeException("Service id is not present in the metadata!")); } else if (StringUtils.isEmpty(sessionIdStr)) { ctx.tellFailure(msg, new RuntimeException("Session id is not present in the metadata!")); } else if (StringUtils.isEmpty(msg.getData())) { ctx.tellFailure(msg, new RuntimeException("Request body is empty!")); } else { ctx.getRpcService().sendRpcReplyToDevice(serviceIdStr, UUID.fromString(sessionIdStr), Integer.parseInt(requestIdStr), msg.getData()); ctx.tellSuccess(msg); } } @Override public void destroy() { } }
#!/usr/bin/env bash set -euo pipefail GH_REPO="https://github.com/purescript/spago" fail() { echo -e "asdf-spago: $*" exit 1 } curl_opts=(-fsSL) if [ -n "${GITHUB_API_TOKEN:-}" ]; then curl_opts=("${curl_opts[@]}" -H "Authorization: token $GITHUB_API_TOKEN") fi sort_versions() { sed 'h; s/[+-]/./g; s/.p\([[:digit:]]\)/.z\1/; s/$/.z/; G; s/\n/ /' | LC_ALL=C sort -t. -k 1,1 -k 2,2n -k 3,3n -k 4,4n -k 5,5n | awk '{print $2}' } list_github_tags() { git ls-remote --tags --refs "$GH_REPO" | grep -o 'refs/tags/[0-9].*' | cut -d/ -f3- } list_all_versions() { list_github_tags } download_release() { local version filename bin url version="$1" filename="$2" if [[ "$OSTYPE" == "linux-gnu"* ]]; then bin="linux" elif [[ "$OSTYPE" == "darwin"* ]]; then bin="osx" else fail "unrecognized operating system $OSTYPE" fi url="$GH_REPO/releases/download/${version}/${bin}.tar.gz" echo "* Downloading spago release $version..." curl "${curl_opts[@]}" -o "$filename" -C - "$url" || fail "Could not download $url" } install_version() { local install_type="$1" local version="$2" local install_path="$3" if [ "$install_type" != "version" ]; then fail "asdf-spago supports release installs only" fi local release_file="$install_path/spago-$version.tar.gz" ( mkdir -p "$install_path/bin" download_release "$version" "$release_file" tar -xzf "$release_file" -C "$install_path" || fail "Could not extract $release_file" mv $install_path/spago $install_path/bin rm "$release_file" test -x "$install_path/bin/spago" || fail "Expected $install_path/bin/spago to be executable." echo "spago $version installation was successful!" ) || ( rm -rf "$install_path" fail "An error ocurred while installing spago $version." ) }
#!/bin/bash -e # Copyright 2016 The Rook Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ARGS="$@" if [ $# -eq 0 ]; then ARGS=/bin/bash fi BUILDER_USER=${BUILDER_USER:-rook} BUILDER_GROUP=${BUILDER_GROUP:-rook} BUILDER_UID=${BUILDER_UID:-1000} BUILDER_GID=${BUILDER_GID:-1000} groupadd -o -g $BUILDER_GID $BUILDER_GROUP 2> /dev/null useradd -o -m -g $BUILDER_GID -u $BUILDER_UID $BUILDER_USER 2> /dev/null echo "$BUILDER_USER ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers export HOME=/home/${BUILDER_USER} echo "127.0.0.1 $(cat /etc/hostname)" >> /etc/hosts [[ -S /var/run/docker.sock ]] && chmod 666 /var/run/docker.sock chown -R $BUILDER_UID:$BUILDER_GID $HOME exec chpst -u :$BUILDER_UID:$BUILDER_GID ${ARGS}
//Sort the elements in an array #include<iostream.h> #include<conio.h> int main() { int a[10],i,j,temp; cout<<"Enter the elements of array:"; for(i=1;i!=0;i++) { cin>>a[i]; } for(i=0;i<5;i++) { for(j=0;j<5;j++) { if(a[i]<a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } for(i=0;i<5;i++) cout<<a[i]<<endl; getch(); return 0; }
const Joi = require("joi"); exports.validateProfile = (opts) => { const { id, phone, address, state, city, zip, company, status, seller } = opts; return Joi.object({ id: Joi.number().required(), address: Joi.string().required(), phone: Joi.number().required(), state: Joi.string().required(), city: Joi.number().required(), zip: Joi.number().required(), company: Joi.string().required(), status: Joi.string(), seller: Joi.boolean(), }).validate({ id, phone, address, state, city, zip, company, status, seller, }); }
/** * We.js default controller prototype * * All controllers is instance of this Controller prototype and have all actions defined here */ const _ = require('lodash'); /** * Constructor */ function Controller (attrs) { for (let attr in attrs) { if (attrs[attr].bind) { this[attr] = attrs[attr].bind(this); } else { this[attr] = attrs[attr]; } } } Controller.prototype = { /** * Default find action * * @param {Object} req express.js request * @param {Object} res express.js response */ find(req, res) { return res.locals.Model .findAndCountAll(res.locals.query) .then(function afterFindAndCount (record) { res.locals.metadata.count = record.count; res.locals.data = record.rows; res.ok(); }) .catch(res.queryError); }, /** * Default count action * * Built for only send count as JSON * * @param {Object} req express.js request * @param {Object} res express.js response */ count(req, res) { return res.locals.Model .count(res.locals.query) .then( (count)=> { res.status(200).send({ count: count }); }) .catch(res.queryError); }, /** * Default findOne action * * Record is preloaded in context loader by default and is avaible as res.locals.data * * @param {Object} req express.js request * @param {Object} res express.js response */ findOne(req, res, next) { if (!res.locals.data) { return next(); } // by default record is preloaded in context load res.ok(); }, /** * Create and create page actions * * @param {Object} req express.js request * @param {Object} res express.js response */ create(req, res) { if (!res.locals.template) { res.locals.template = res.locals.model + '/' + 'create'; } if (!res.locals.data) { res.locals.data = {}; } if (req.method === 'POST') { if (req.isAuthenticated && req.isAuthenticated()) { req.body.creatorId = req.user.id; } _.merge(res.locals.data, req.body); return res.locals.Model .create(req.body) .then(function afterCreate (record) { res.locals.data = record; res.created(); }) .catch(res.queryError); } else { res.ok(); } }, /** * Edit, edit page and update action * * Record is preloaded in context loader by default and is avaible as res.locals.data * * @param {Object} req express.js request * @param {Object} res express.js response */ edit(req, res) { if (!res.locals.template) { res.locals.template = res.local.model + '/' + 'edit'; } let record = res.locals.data; if (req.we.config.updateMethods.indexOf(req.method) >-1) { if (!record) { return res.notFound(); } record.update(req.body) .then(function reloadAssocs(n) { return n.reload() .then(function() { return n; }); }) .then(function afterUpdate (newRecord) { res.locals.data = newRecord; res.updated(); }) .catch(res.queryError); } else { res.ok(); } }, /** * Delete and delete action * * @param {Object} req express.js request * @param {Object} res express.js response */ delete(req, res) { if (!res.locals.template) { res.locals.template = res.local.model + '/' + 'delete'; } let record = res.locals.data; if (!record) { return res.notFound(); } res.locals.deleteMsg = res.locals.model + '.delete.confirm.msg'; if (req.method === 'POST' || req.method === 'DELETE') { record .destroy() .then(function afterDestroy () { res.locals.deleted = true; res.deleted(); }) .catch(res.queryError); } else { res.ok(); } } }; module.exports = Controller;
#!/bin/bash #useMB="$1" #useExtended="$2" #isMC="$3" #if [ -z "$useExtended" ]; then # argument="$useMB" #else # if [ -z "$isMC" ]; then # argument="$useMB,$useExtended" # else # argument="$useMB,$useExtended,$isMC" # fi #fi # #. scripts/extract_signal.sh $argument root -l -b -q Spectra.cc+ root -l -b -q Systematics.cc+ root -l -b -q Systematics.cc+'(true)' root -l -b -q JoinSystematics.cc+ root -l -b -q Final.cc+ root -l -b -q BWFits.cc+ root -l -b -q BWFits.cc+'(true)' root -l -b -q Final.cc+ root -l -b -q Ratio.cc+
// // Created by <NAME> @imgntn on April 18, 2016. // Copyright 2016 High Fidelity, Inc. // // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // var SCRIPT_URL = "http://hifi-production.s3.amazonaws.com/tutorials/entity_scripts/pingPongGun.js"; var MODEL_URL = 'http://hifi-production.s3.amazonaws.com/tutorials/pingPongGun/Pingpong-Gun-New.fbx'; var COLLISION_HULL_URL = 'http://hifi-production.s3.amazonaws.com/tutorials/pingPongGun/Pingpong-Gun-New.obj'; var center = Vec3.sum(Vec3.sum(MyAvatar.position, { x: 0, y: 0.5, z: 0 }), Vec3.multiply(0.5, Quat.getForward(Camera.getOrientation()))); var pingPongGunProperties = { type: "Model", name: "Tutorial Ping Pong Gun", modelURL: MODEL_URL, shapeType: 'compound', compoundShapeURL: COLLISION_HULL_URL, script: SCRIPT_URL, position: center, dimensions: { x: 0.125, y: 0.3875, z: 0.9931 }, gravity: { x: 0, y: -5.0, z: 0 }, lifetime: 3600, dynamic: true, userData: JSON.stringify({ grabbableKey: { invertSolidWhileHeld: true }, wearable: { joints: { RightHand: [{ x: 0.1177130937576294, y: 0.12922893464565277, z: 0.08307232707738876 }, { x: 0.4934672713279724, y: 0.3605862259864807, z: 0.6394805908203125, w: -0.4664038419723511 }], LeftHand: [{ x: 0.09151676297187805, y: 0.13639454543590546, z: 0.09354984760284424 }, { x: -0.19628101587295532, y: 0.6418180465698242, z: 0.2830369472503662, w: 0.6851521730422974 }] } } }) } var pingPongGun = Entities.addEntity(pingPongGunProperties); Script.stop();
import React, { Component } from 'react'; import { base } from '../Firebase' class ClickableAuthor extends Component { constructor(props){ super(props) this.state={"userName": ""} } componentDidMount(){ this.fetchUserName() } //Duplicando codigo en 2018 lul fetchUserName(){ base.fetch('users/', { context: this, asArray: true, queries: { orderByChild: 'userEmail', equalTo: this.props.userEmail }, then(data){ this.setState({'userName': data[0].key}) } }); } render(){ return <a onClick={()=>this.props.history.push('/profile/'+this.state.userName)}> {this.state.userName} </a> } } export default ClickableAuthor;
import io.chrisdavenport.rediculous._ import cats.implicits._ import cats.effect._ import fs2.io.net._ import fs2._ import com.comcast.ip4s._ import scala.concurrent.duration._ import cats.effect.std._ // Mimics 150 req/s load with 4 operations per request. // Completes 1,000,000 redis operations // Completes in <5 s object BasicExample extends IOApp { def run(args: List[String]): IO[ExitCode] = { val r = for { // maxQueued: How many elements before new submissions semantically block. Tradeoff of memory to queue jobs. // Default 1000 is good for small servers. But can easily take 100,000. // workers: How many threads will process pipelined messages. connection <- RedisConnection.queued[IO].withHost(host"localhost").withPort(port"6379").withMaxQueued(10000).withWorkers(workers = 1).build } yield connection r.use {client => val x: Redis[IO, RedisProtocol.Status] = RedisCommands.ping[RedisIO] val r = ( x, RedisCommands.get[RedisIO]("foo"), RedisCommands.set[RedisIO]("foo", "value"), RedisCommands.get[RedisIO]("foo") ).parTupled val r2= List.fill(10)(r.run(client)).parSequence val now = IO(java.time.Instant.now) ( now, Stream(()).covary[IO].repeat.map(_ => Stream.evalSeq(r2)).parJoin(15).take(100000).compile.lastOrError.flatTap(Console[IO].println(_)), now ).mapN{ case (before, _, after) => (after.toEpochMilli() - before.toEpochMilli()).millis }.flatMap{ duration => IO(println(s"Operation took ${duration}")) } } >> IO.pure(ExitCode.Success) } }
<reponame>lananh265/social-network "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.knife = void 0; var knife = { "viewBox": "0 0 512 512", "children": [{ "name": "path", "attribs": { "d": "M285.7,32c-3.3,0-6,1.4-8,3.8C259,58.7,224,116.1,224,250.1c0,39.2,33,39.2,32,69.4c0,0.1,0,0.3,0,0.4\r\n\tc-2,47.1-14.9,111.1-16,130.3c-0.4,15.2,9.7,29.8,24.1,29.8c0.1,0,0.1,0,0.2,0c0,0,0.1,0,0.2,0c14.4,0,23.5-14.4,23.5-29.6V38.3\r\n\tC288,33.3,287.5,32,285.7,32z" }, "children": [] }] }; exports.knife = knife;
/* Copyright (c) 2012, <NAME> * 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. * * 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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. */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "bspwm.h" #include "desktop.h" #include "ewmh.h" #include "history.h" #include "monitor.h" #include "pointer.h" #include "query.h" #include "rule.h" #include "restore.h" #include "settings.h" #include "tree.h" #include "window.h" #include "common.h" #include "subscribe.h" #include "messages.h" int handle_message(char *msg, int msg_len, FILE *rsp) { int cap = INIT_CAP; int num = 0; char **args = malloc(cap * sizeof(char *)); if (args == NULL) return MSG_FAILURE; for (int i = 0, j = 0; i < msg_len; i++) { if (msg[i] == 0) { args[num++] = msg + j; j = i + 1; } if (num >= cap) { cap *= 2; char **new = realloc(args, cap * sizeof(char *)); if (new == NULL) { free(args); return MSG_FAILURE; } else { args = new; } } } if (num < 1) { free(args); return MSG_SYNTAX; } char **args_orig = args; int ret = process_message(args, num, rsp); free(args_orig); return ret; } int process_message(char **args, int num, FILE *rsp) { if (streq("window", *args)) { return cmd_window(++args, --num); } else if (streq("desktop", *args)) { return cmd_desktop(++args, --num); } else if (streq("monitor", *args)) { return cmd_monitor(++args, --num); } else if (streq("query", *args)) { return cmd_query(++args, --num, rsp); } else if (streq("restore", *args)) { return cmd_restore(++args, --num); } else if (streq("control", *args)) { return cmd_control(++args, --num, rsp); } else if (streq("rule", *args)) { return cmd_rule(++args, --num, rsp); } else if (streq("pointer", *args)) { return cmd_pointer(++args, --num); } else if (streq("config", *args)) { return cmd_config(++args, --num, rsp); } else if (streq("quit", *args)) { return cmd_quit(++args, --num); } return MSG_UNKNOWN; } int cmd_window(char **args, int num) { if (num < 1) return MSG_SYNTAX; coordinates_t ref = {mon, mon->desk, mon->desk->focus}; coordinates_t trg = ref; if ((*args)[0] != OPT_CHR) { if (node_from_desc(*args, &ref, &trg)) num--, args++; else return MSG_FAILURE; } if (trg.node == NULL) return MSG_FAILURE; bool dirty = false; while (num > 0) { if (streq("-f", *args) || streq("--focus", *args)) { coordinates_t dst = trg; if (num > 1 && *(args + 1)[0] != OPT_CHR) { num--, args++; if (!node_from_desc(*args, &trg, &dst)) return MSG_FAILURE; } focus_node(dst.monitor, dst.desktop, dst.node); } else if (streq("-d", *args) || streq("--to-desktop", *args)) { num--, args++; coordinates_t dst; if (desktop_from_desc(*args, &trg, &dst)) { if (transfer_node(trg.monitor, trg.desktop, trg.node, dst.monitor, dst.desktop, dst.desktop->focus)) { trg.monitor = dst.monitor; trg.desktop = dst.desktop; } } else { return MSG_FAILURE; } } else if (streq("-m", *args) || streq("--to-monitor", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; coordinates_t dst; if (monitor_from_desc(*args, &trg, &dst)) { if (transfer_node(trg.monitor, trg.desktop, trg.node, dst.monitor, dst.monitor->desk, dst.monitor->desk->focus)) { trg.monitor = dst.monitor; trg.desktop = dst.monitor->desk; } } else { return MSG_FAILURE; } } else if (streq("-w", *args) || streq("--to-window", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; coordinates_t dst; if (node_from_desc(*args, &trg, &dst)) { if (transfer_node(trg.monitor, trg.desktop, trg.node, dst.monitor, dst.desktop, dst.node)) { trg.monitor = dst.monitor; trg.desktop = dst.desktop; } } else { return MSG_FAILURE; } } else if (streq("-s", *args) || streq("--swap", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; coordinates_t dst; if (node_from_desc(*args, &trg, &dst)) { if (swap_nodes(trg.monitor, trg.desktop, trg.node, dst.monitor, dst.desktop, dst.node)) { if (trg.desktop != dst.desktop) arrange(trg.monitor, trg.desktop); trg.monitor = dst.monitor; trg.desktop = dst.desktop; dirty = true; } } else { return MSG_FAILURE; } } else if (streq("-t", *args) || streq("--toggle", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; char *key = strtok(*args, EQL_TOK); char *val = strtok(NULL, EQL_TOK); alter_state_t a; bool b; if (val == NULL) { a = ALTER_TOGGLE; } else { if (parse_bool(val, &b)) a = ALTER_SET; else return MSG_FAILURE; } if (streq("fullscreen", key)) { set_fullscreen(trg.node, (a == ALTER_SET ? b : !trg.node->client->fullscreen)); dirty = true; } else if (streq("pseudo_tiled", key)) { set_pseudo_tiled(trg.node, (a == ALTER_SET ? b : !trg.node->client->pseudo_tiled)); dirty = true; } else if (streq("floating", key)) { set_floating(trg.node, (a == ALTER_SET ? b : !trg.node->client->floating)); dirty = true; } else if (streq("locked", key)) { set_locked(trg.monitor, trg.desktop, trg.node, (a == ALTER_SET ? b : !trg.node->client->locked)); } else if (streq("sticky", key)) { set_sticky(trg.monitor, trg.desktop, trg.node, (a == ALTER_SET ? b : !trg.node->client->sticky)); } else if (streq("private", key)) { set_private(trg.monitor, trg.desktop, trg.node, (a == ALTER_SET ? b : !trg.node->client->private)); } else { return MSG_FAILURE; } } else if (streq("-p", *args) || streq("--presel", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; if (!is_tiled(trg.node->client) || trg.desktop->layout != LAYOUT_TILED) return MSG_FAILURE; if (streq("cancel", *args)) { reset_mode(&trg); } else { direction_t dir; if (parse_direction(*args, &dir)) { double rat = trg.node->split_ratio; if (num > 1 && *(args + 1)[0] != OPT_CHR) { num--, args++; if (sscanf(*args, "%lf", &rat) != 1 || rat <= 0 || rat >= 1) return MSG_FAILURE; } if (auto_cancel && trg.node->split_mode == MODE_MANUAL && dir == trg.node->split_dir && rat == trg.node->split_ratio) { reset_mode(&trg); } else { trg.node->split_mode = MODE_MANUAL; trg.node->split_dir = dir; trg.node->split_ratio = rat; } window_draw_border(trg.node, trg.desktop->focus == trg.node, mon == trg.monitor); } else { return MSG_FAILURE; } } } else if (streq("-e", *args) || streq("--edge", *args)) { num--, args++; if (num < 2) return MSG_SYNTAX; if (!is_tiled(trg.node->client)) return MSG_FAILURE; direction_t dir; if (!parse_direction(*args, &dir)) return MSG_FAILURE; node_t *n = find_fence(trg.node, dir); if (n == NULL) return MSG_FAILURE; num--, args++; if ((*args)[0] == '+' || (*args)[0] == '-') { int pix; if (sscanf(*args, "%i", &pix) == 1) { int max = (n->split_type == TYPE_HORIZONTAL ? n->rectangle.height : n->rectangle.width); double rat = ((max * n->split_ratio) + pix) / max; if (rat > 0 && rat < 1) n->split_ratio = rat; else return MSG_FAILURE; } else { return MSG_FAILURE; } } else { double rat; if (sscanf(*args, "%lf", &rat) == 1 && rat > 0 && rat < 1) n->split_ratio = rat; else return MSG_FAILURE; } dirty = true; } else if (streq("-r", *args) || streq("--ratio", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; double rat; if (sscanf(*args, "%lf", &rat) == 1 && rat > 0 && rat < 1) { trg.node->split_ratio = rat; window_draw_border(trg.node, trg.desktop->focus == trg.node, mon == trg.monitor); } else { return MSG_FAILURE; } } else if (streq("-R", *args) || streq("--rotate", *args)) { num--, args++; if (num < 2) return MSG_SYNTAX; direction_t dir; if (!parse_direction(*args, &dir)) return MSG_FAILURE; node_t *n = find_fence(trg.node, dir); if (n == NULL) return MSG_FAILURE; num--, args++; int deg; if (parse_degree(*args, &deg)) { rotate_tree(n, deg); dirty = true; } else { return MSG_FAILURE; } } else if (streq("-c", *args) || streq("--close", *args)) { if (num > 1) return MSG_SYNTAX; window_close(trg.node); } else if (streq("-k", *args) || streq("--kill", *args)) { if (num > 1) return MSG_SYNTAX; window_kill(trg.monitor, trg.desktop, trg.node); dirty = true; } else { return MSG_SYNTAX; } num--, args++; } if (dirty) arrange(trg.monitor, trg.desktop); return MSG_SUCCESS; } int cmd_desktop(char **args, int num) { if (num < 1) return MSG_SYNTAX; coordinates_t ref = {mon, mon->desk, NULL}; coordinates_t trg = ref; if ((*args)[0] != OPT_CHR) { if (desktop_from_desc(*args, &ref, &trg)) num--, args++; else return MSG_FAILURE; } bool dirty = false; while (num > 0) { if (streq("-f", *args) || streq("--focus", *args)) { coordinates_t dst = trg; if (num > 1 && *(args + 1)[0] != OPT_CHR) { num--, args++; if (!desktop_from_desc(*args, &trg, &dst)) return MSG_FAILURE; } if (auto_alternate && dst.desktop == mon->desk) { desktop_select_t sel = {DESKTOP_STATUS_ALL, false, false}; history_find_desktop(HISTORY_OLDER, &trg, &dst, sel); } focus_node(dst.monitor, dst.desktop, dst.desktop->focus); } else if (streq("-m", *args) || streq("--to-monitor", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; if (trg.monitor->desk_head == trg.monitor->desk_tail) return MSG_FAILURE; coordinates_t dst; if (monitor_from_desc(*args, &trg, &dst)) { transfer_desktop(trg.monitor, dst.monitor, trg.desktop); trg.monitor = dst.monitor; update_current(); } else { return MSG_FAILURE; } } else if (streq("-s", *args) || streq("--swap", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; coordinates_t dst; if (desktop_from_desc(*args, &trg, &dst)) swap_desktops(trg.monitor, trg.desktop, dst.monitor, dst.desktop); else return MSG_FAILURE; } else if (streq("-b", *args) || streq("--bubble", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; cycle_dir_t cyc; if (parse_cycle_direction(*args, &cyc)) { desktop_t *d = trg.desktop; if (cyc == CYCLE_PREV) { if (d->prev == NULL) { while (d->next != NULL) { swap_desktops(trg.monitor, d, trg.monitor, d->next); } } else { swap_desktops(trg.monitor, d, trg.monitor, d->prev); } } else { if (d->next == NULL) { while (d->prev != NULL) { swap_desktops(trg.monitor, d, trg.monitor, d->prev); } } else { swap_desktops(trg.monitor, d, trg.monitor, d->next); } } } else { return MSG_FAILURE; } } else if (streq("-l", *args) || streq("--layout", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; layout_t lyt; cycle_dir_t cyc; if (parse_cycle_direction(*args, &cyc)) change_layout(trg.monitor, trg.desktop, (trg.desktop->layout + 1) % 2); else if (parse_layout(*args, &lyt)) change_layout(trg.monitor, trg.desktop, lyt); else return MSG_FAILURE; } else if (streq("-n", *args) || streq("--rename", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; put_status(SBSC_MASK_DESKTOP_RENAME, "desktop_rename %s %s %s\n", trg.monitor->name, trg.desktop->name, *args); snprintf(trg.desktop->name, sizeof(trg.desktop->name), "%s", *args); ewmh_update_desktop_names(); put_status(SBSC_MASK_REPORT); } else if (streq("-r", *args) || streq("--remove", *args)) { if (trg.desktop->root == NULL && trg.monitor->desk_head != trg.monitor->desk_tail) { remove_desktop(trg.monitor, trg.desktop); show_desktop(trg.monitor->desk); update_current(); return MSG_SUCCESS; } else { return MSG_FAILURE; } } else if (streq("-c", *args) || streq("--cancel-presel", *args)) { reset_mode(&trg); } else if (streq("-F", *args) || streq("--flip", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; flip_t flp; if (parse_flip(*args, &flp)) { flip_tree(trg.desktop->root, flp); dirty = true; } else { return MSG_FAILURE; } } else if (streq("-R", *args) || streq("--rotate", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; int deg; if (parse_degree(*args, &deg)) { rotate_tree(trg.desktop->root, deg); dirty = true; } else { return MSG_FAILURE; } } else if (streq("-E", *args) || streq("--equalize", *args)) { equalize_tree(trg.desktop->root); dirty = true; } else if (streq("-B", *args) || streq("--balance", *args)) { balance_tree(trg.desktop->root); dirty = true; } else if (streq("-C", *args) || streq("--circulate", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; circulate_dir_t cir; if (parse_circulate_direction(*args, &cir)) { circulate_leaves(trg.monitor, trg.desktop, cir); dirty = true; } else { return MSG_FAILURE; } } else if (streq("-t", *args) || streq("--toggle", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; char *key = strtok(*args, EQL_TOK); char *val = strtok(NULL, EQL_TOK); alter_state_t a; bool b; if (val == NULL) { a = ALTER_TOGGLE; } else { if (parse_bool(val, &b)) a = ALTER_SET; else return MSG_FAILURE; } if (streq("floating", key)) trg.desktop->floating = (a == ALTER_SET ? b : !trg.desktop->floating); else return MSG_FAILURE; } else { return MSG_SYNTAX; } num--, args++; } if (dirty) arrange(trg.monitor, trg.desktop); return MSG_SUCCESS; } int cmd_monitor(char **args, int num) { if (num < 1) return MSG_SYNTAX; coordinates_t ref = {mon, NULL, NULL}; coordinates_t trg = ref; if ((*args)[0] != OPT_CHR) { if (monitor_from_desc(*args, &ref, &trg)) num--, args++; else return MSG_FAILURE; } while (num > 0) { if (streq("-f", *args) || streq("--focus", *args)) { coordinates_t dst = trg; if (num > 1 && *(args + 1)[0] != OPT_CHR) { num--, args++; if (!monitor_from_desc(*args, &trg, &dst)) return MSG_FAILURE; } if (auto_alternate && dst.monitor == mon) { desktop_select_t sel = {DESKTOP_STATUS_ALL, false, false}; history_find_monitor(HISTORY_OLDER, &trg, &dst, sel); } focus_node(dst.monitor, dst.monitor->desk, dst.monitor->desk->focus); } else if (streq("-d", *args) || streq("--reset-desktops", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; desktop_t *d = trg.monitor->desk_head; while (num > 0 && d != NULL) { put_status(SBSC_MASK_DESKTOP_RENAME, "desktop_rename %s %s %s\n", trg.monitor->name, d->name, *args); snprintf(d->name, sizeof(d->name), "%s", *args); initialize_desktop(d); arrange(trg.monitor, d); d = d->next; num--, args++; } put_status(SBSC_MASK_REPORT); while (num > 0) { add_desktop(trg.monitor, make_desktop(*args)); num--, args++; } while (d != NULL) { desktop_t *next = d->next; if (d == mon->desk) focus_node(trg.monitor, d->prev, d->prev->focus); merge_desktops(trg.monitor, d, mon, mon->desk); remove_desktop(trg.monitor, d); d = next; } } else if (streq("-a", *args) || streq("--add-desktops", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; while (num > 0) { add_desktop(trg.monitor, make_desktop(*args)); num--, args++; } } else if (streq("-r", *args) || streq("--remove-desktops", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; while (num > 0) { coordinates_t dst; if (locate_desktop(*args, &dst) && dst.monitor->desk_head != dst.monitor->desk_tail && dst.desktop->root == NULL) { remove_desktop(dst.monitor, dst.desktop); show_desktop(dst.monitor->desk); } num--, args++; } } else if (streq("-o", *args) || streq("--order-desktops", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; desktop_t *d = trg.monitor->desk_head; while (d != NULL && num > 0) { desktop_t *next = d->next; coordinates_t dst; if (locate_desktop(*args, &dst) && dst.monitor == trg.monitor) { swap_desktops(trg.monitor, d, dst.monitor, dst.desktop); if (next == dst.desktop) next = d; } d = next; num--, args++; } } else if (streq("-n", *args) || streq("--rename", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; put_status(SBSC_MASK_MONITOR_RENAME, "monitor_rename %s %s\n", trg.monitor->name, *args); snprintf(trg.monitor->name, sizeof(trg.monitor->name), "%s", *args); put_status(SBSC_MASK_REPORT); } else if (streq("-s", *args) || streq("--swap", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; coordinates_t dst; if (monitor_from_desc(*args, &trg, &dst)) swap_monitors(trg.monitor, dst.monitor); else return MSG_FAILURE; } else { return MSG_SYNTAX; } num--, args++; } return MSG_SUCCESS; } int cmd_query(char **args, int num, FILE *rsp) { coordinates_t ref = {mon, mon->desk, mon->desk->focus}; coordinates_t trg = {NULL, NULL, NULL}; domain_t dom = DOMAIN_TREE; int d = 0, t = 0; while (num > 0) { if (streq("-T", *args) || streq("--tree", *args)) { dom = DOMAIN_TREE, d++; } else if (streq("-M", *args) || streq("--monitors", *args)) { dom = DOMAIN_MONITOR, d++; } else if (streq("-D", *args) || streq("--desktops", *args)) { dom = DOMAIN_DESKTOP, d++; } else if (streq("-W", *args) || streq("--windows", *args)) { dom = DOMAIN_WINDOW, d++; } else if (streq("-H", *args) || streq("--history", *args)) { dom = DOMAIN_HISTORY, d++; } else if (streq("-S", *args) || streq("--stack", *args)) { dom = DOMAIN_STACK, d++; } else if (streq("-m", *args) || streq("--monitor", *args)) { trg.monitor = ref.monitor; if (num > 1 && *(args + 1)[0] != OPT_CHR) { num--, args++; if (!monitor_from_desc(*args, &ref, &trg)) return MSG_FAILURE; } t++; } else if (streq("-d", *args) || streq("--desktop", *args)) { trg.monitor = ref.monitor; trg.desktop = ref.desktop; if (num > 1 && *(args + 1)[0] != OPT_CHR) { num--, args++; if (!desktop_from_desc(*args, &ref, &trg)) return MSG_FAILURE; } t++; } else if (streq("-w", *args) || streq("--window", *args)) { trg = ref; if (num > 1 && *(args + 1)[0] != OPT_CHR) { num--, args++; if (!node_from_desc(*args, &ref, &trg)) return MSG_FAILURE; } t++; } else { return MSG_SYNTAX; } num--, args++; } if (d != 1 || t > 1) return MSG_SYNTAX; if (dom == DOMAIN_HISTORY) query_history(trg, rsp); else if (dom == DOMAIN_STACK) query_stack(rsp); else if (dom == DOMAIN_WINDOW) query_windows(trg, rsp); else query_monitors(trg, dom, rsp); return MSG_SUCCESS; } int cmd_rule(char **args, int num, FILE *rsp) { if (num < 1) return MSG_SYNTAX; while (num > 0) { if (streq("-a", *args) || streq("--add", *args)) { num--, args++; if (num < 2) return MSG_SYNTAX; rule_t *rule = make_rule(); snprintf(rule->cause, sizeof(rule->cause), "%s", *args); num--, args++; size_t i = 0; while (num > 0) { if (streq("-o", *args) || streq("--one-shot", *args)) { rule->one_shot = true; } else { for (size_t j = 0; i < sizeof(rule->effect) && j < strlen(*args); i++, j++) rule->effect[i] = (*args)[j]; if (num > 1 && i < sizeof(rule->effect)) rule->effect[i++] = ' '; } num--, args++; } rule->effect[MIN(i, sizeof(rule->effect) - 1)] = '\0'; add_rule(rule); } else if (streq("-r", *args) || streq("--remove", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; int idx; while (num > 0) { if (parse_index(*args, &idx)) remove_rule_by_index(idx - 1); else if (streq("tail", *args)) remove_rule(rule_tail); else if (streq("head", *args)) remove_rule(rule_head); else remove_rule_by_cause(*args); num--, args++; } } else if (streq("-l", *args) || streq("--list", *args)) { num--, args++; list_rules(num > 0 ? *args : NULL, rsp); } else { return MSG_SYNTAX; } num--, args++; } return MSG_SUCCESS; } int cmd_pointer(char **args, int num) { if (num < 1) return MSG_SYNTAX; while (num > 0) { if (streq("-t", *args) || streq("--track", *args)) { num--, args++; if (num < 2) return MSG_SYNTAX; int x, y; if (sscanf(*args, "%i", &x) == 1 && sscanf(*(args + 1), "%i", &y) == 1) track_pointer(x, y); else return MSG_FAILURE; num--, args++; } else if (streq("-g", *args) || streq("--grab", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; pointer_action_t pac; if (parse_pointer_action(*args, &pac)) grab_pointer(pac); else return MSG_FAILURE; } else if (streq("-u", *args) || streq("--ungrab", *args)) { ungrab_pointer(); } else { return MSG_SYNTAX; } num--, args++; } return MSG_SUCCESS; } int cmd_restore(char **args, int num) { if (num < 1) return MSG_SYNTAX; while (num > 0) { if (streq("-T", *args) || streq("--tree", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; restore_tree(*args); } else if (streq("-H", *args) || streq("--history", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; restore_history(*args); } else if (streq("-S", *args) || streq("--stack", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; restore_stack(*args); } else { return MSG_SYNTAX; } num--, args++; } return MSG_SUCCESS; } int cmd_control(char **args, int num, FILE *rsp) { if (num < 1) return MSG_SYNTAX; while (num > 0) { if (streq("--adopt-orphans", *args)) { adopt_orphans(); } else if (streq("--toggle-visibility", *args)) { toggle_visibility(); } else if (streq("--subscribe", *args)) { num--, args++; int field = 0; if (num < 1) { field = SBSC_MASK_REPORT; } else { subscriber_mask_t mask; while (num > 0) { if (parse_subscriber_mask(*args, &mask)) { field |= mask; } else { return MSG_SYNTAX; } num--, args++; } } add_subscriber(rsp, field); return MSG_SUBSCRIBE; } else if (streq("--get-status", *args)) { print_report(rsp); } else if (streq("--record-history", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; bool b; if (parse_bool(*args, &b)) record_history = b; else return MSG_SYNTAX; } else { return MSG_SYNTAX; } num--, args++; } return MSG_SUCCESS; } int cmd_config(char **args, int num, FILE *rsp) { if (num < 1) return MSG_SYNTAX; coordinates_t ref = {mon, mon->desk, mon->desk->focus}; coordinates_t trg = {NULL, NULL, NULL}; if ((*args)[0] == OPT_CHR) { if (streq("-m", *args) || streq("--monitor", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; if (!monitor_from_desc(*args, &ref, &trg)) return MSG_FAILURE; } else if (streq("-d", *args) || streq("--desktop", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; if (!desktop_from_desc(*args, &ref, &trg)) return MSG_FAILURE; } else if (streq("-w", *args) || streq("--window", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; if (!node_from_desc(*args, &ref, &trg)) return MSG_FAILURE; } else { return MSG_SYNTAX; } num--, args++; } if (num == 2) return set_setting(trg, *args, *(args + 1)); else if (num == 1) return get_setting(trg, *args, rsp); else return MSG_SYNTAX; } int cmd_quit(char **args, int num) { if (num > 0 && sscanf(*args, "%i", &exit_status) != 1) return MSG_FAILURE; running = false; return MSG_SUCCESS; } int set_setting(coordinates_t loc, char *name, char *value) { #define DESKWINDEFSET(k, v) \ if (loc.node != NULL) \ loc.node->client->k = v; \ else if (loc.desktop != NULL) \ loc.desktop->k = v; \ else if (loc.monitor != NULL) \ for (desktop_t *d = loc.monitor->desk_head; d != NULL; d = d->next) \ d->k = v; \ else \ k = v; if (streq("border_width", name)) { unsigned int bw; if (sscanf(value, "%u", &bw) != 1) return MSG_FAILURE; DESKWINDEFSET(border_width, bw) #undef DESKWINDEFSET #define DESKDEFSET(k, v) \ if (loc.desktop != NULL) \ loc.desktop->k = v; \ else if (loc.monitor != NULL) \ return MSG_SYNTAX; \ else \ k = v; } else if (streq("window_gap", name)) { int wg; if (sscanf(value, "%i", &wg) != 1) return MSG_FAILURE; DESKDEFSET(window_gap, wg) #undef DESKDEFSET #define MONDESKSET(k, v) \ if (loc.desktop != NULL) \ loc.desktop->k = v; \ else if (loc.monitor != NULL) \ loc.monitor->k = v; \ else \ for (monitor_t *m = mon_head; m != NULL; m = m->next) \ m->k = v; } else if (streq("top_padding", name)) { int tp; if (sscanf(value, "%i", &tp) != 1) return MSG_FAILURE; MONDESKSET(top_padding, tp) } else if (streq("right_padding", name)) { int rp; if (sscanf(value, "%i", &rp) != 1) return MSG_FAILURE; MONDESKSET(right_padding, rp) } else if (streq("bottom_padding", name)) { int bp; if (sscanf(value, "%i", &bp) != 1) return MSG_FAILURE; MONDESKSET(bottom_padding, bp) } else if (streq("left_padding", name)) { int lp; if (sscanf(value, "%i", &lp) != 1) return MSG_FAILURE; MONDESKSET(left_padding, lp) #undef MONDESKSET #define SETSTR(s) \ } else if (streq(#s, name)) { \ if (snprintf(s, sizeof(s), "%s", value) < 0) \ return MSG_FAILURE; SETSTR(external_rules_command) SETSTR(status_prefix) #undef SETSTR } else if (streq("split_ratio", name)) { double r; if (sscanf(value, "%lf", &r) == 1 && r > 0 && r < 1) split_ratio = r; else return MSG_FAILURE; return MSG_SUCCESS; #define SETCOLOR(s) \ } else if (streq(#s, name)) { \ snprintf(s, sizeof(s), "%s", value); SETCOLOR(focused_border_color) SETCOLOR(active_border_color) SETCOLOR(normal_border_color) SETCOLOR(presel_border_color) SETCOLOR(focused_locked_border_color) SETCOLOR(active_locked_border_color) SETCOLOR(normal_locked_border_color) SETCOLOR(focused_sticky_border_color) SETCOLOR(active_sticky_border_color) SETCOLOR(normal_sticky_border_color) SETCOLOR(focused_private_border_color) SETCOLOR(active_private_border_color) SETCOLOR(normal_private_border_color) SETCOLOR(urgent_border_color) #undef SETCOLOR } else if (streq("initial_polarity", name)) { child_polarity_t p; if (parse_child_polarity(value, &p)) { initial_polarity = p; } else { return MSG_FAILURE; } } else if (streq("focus_follows_pointer", name)) { bool b; if (parse_bool(value, &b) && b != focus_follows_pointer) { focus_follows_pointer = b; uint32_t values[] = {CLIENT_EVENT_MASK | (focus_follows_pointer ? XCB_EVENT_MASK_ENTER_WINDOW : 0)}; for (monitor_t *m = mon_head; m != NULL; m = m->next) { for (desktop_t *d = m->desk_head; d != NULL; d = d->next) { for (node_t *n = first_extrema(d->root); n != NULL; n = next_leaf(n, d->root)) { xcb_change_window_attributes(dpy, n->client->window, XCB_CW_EVENT_MASK, values); } } } if (focus_follows_pointer) { for (monitor_t *m = mon_head; m != NULL; m = m->next) { window_show(m->root); } } else { for (monitor_t *m = mon_head; m != NULL; m = m->next) { window_hide(m->root); } disable_motion_recorder(); } return MSG_SUCCESS; } else { return MSG_FAILURE; } #define SETBOOL(s) \ } else if (streq(#s, name)) { \ if (!parse_bool(value, &s)) \ return MSG_FAILURE; SETBOOL(borderless_monocle) SETBOOL(gapless_monocle) SETBOOL(leaf_monocle) SETBOOL(pointer_follows_focus) SETBOOL(pointer_follows_monitor) SETBOOL(apply_floating_atom) SETBOOL(auto_alternate) SETBOOL(auto_cancel) SETBOOL(history_aware_focus) SETBOOL(focus_by_distance) SETBOOL(ignore_ewmh_focus) SETBOOL(center_pseudo_tiled) #undef SETBOOL #define SETMONBOOL(s) \ } else if (streq(#s, name)) { \ if (!parse_bool(value, &s)) \ return MSG_FAILURE; \ if (s) \ update_monitors(); SETMONBOOL(remove_disabled_monitors) SETMONBOOL(remove_unplugged_monitors) SETMONBOOL(merge_overlapping_monitors) #undef SETMONBOOL } else { return MSG_FAILURE; } for (monitor_t *m = mon_head; m != NULL; m = m->next) for (desktop_t *d = m->desk_head; d != NULL; d = d->next) arrange(m, d); return MSG_SUCCESS; } int get_setting(coordinates_t loc, char *name, FILE* rsp) { if (streq("split_ratio", name)) fprintf(rsp, "%lf", split_ratio); else if (streq("window_gap", name)) if (loc.desktop != NULL) fprintf(rsp, "%i", loc.desktop->window_gap); else if (loc.monitor != NULL) return MSG_SYNTAX; else fprintf(rsp, "%i", window_gap); else if (streq("border_width", name)) if (loc.node != NULL) fprintf(rsp, "%u", loc.node->client->border_width); else if (loc.desktop != NULL) fprintf(rsp, "%u", loc.desktop->border_width); else fprintf(rsp, "%u", border_width); else if (streq("external_rules_command", name)) fprintf(rsp, "%s", external_rules_command); else if (streq("status_prefix", name)) fprintf(rsp, "%s", status_prefix); else if (streq("initial_polarity", name)) fprintf(rsp, "%s", initial_polarity == FIRST_CHILD ? "first_child" : "second_child"); #define MONDESKGET(k) \ else if (streq(#k, name)) \ if (loc.desktop != NULL) \ fprintf(rsp, "%i", loc.desktop->k); \ else if (loc.monitor != NULL) \ fprintf(rsp, "%i", loc.monitor->k); \ else \ return MSG_FAILURE; MONDESKGET(top_padding) MONDESKGET(right_padding) MONDESKGET(bottom_padding) MONDESKGET(left_padding) #undef DESKGET #define GETCOLOR(s) \ else if (streq(#s, name)) \ fprintf(rsp, "%s", s); GETCOLOR(focused_border_color) GETCOLOR(active_border_color) GETCOLOR(normal_border_color) GETCOLOR(presel_border_color) GETCOLOR(focused_locked_border_color) GETCOLOR(active_locked_border_color) GETCOLOR(normal_locked_border_color) GETCOLOR(focused_sticky_border_color) GETCOLOR(active_sticky_border_color) GETCOLOR(normal_sticky_border_color) GETCOLOR(urgent_border_color) #undef GETCOLOR #define GETBOOL(s) \ else if (streq(#s, name)) \ fprintf(rsp, "%s", BOOLSTR(s)); GETBOOL(borderless_monocle) GETBOOL(gapless_monocle) GETBOOL(leaf_monocle) GETBOOL(focus_follows_pointer) GETBOOL(pointer_follows_focus) GETBOOL(pointer_follows_monitor) GETBOOL(apply_floating_atom) GETBOOL(auto_alternate) GETBOOL(auto_cancel) GETBOOL(history_aware_focus) GETBOOL(focus_by_distance) GETBOOL(ignore_ewmh_focus) GETBOOL(center_pseudo_tiled) GETBOOL(remove_disabled_monitors) GETBOOL(remove_unplugged_monitors) GETBOOL(merge_overlapping_monitors) #undef GETBOOL else return MSG_FAILURE; fprintf(rsp, "\n"); return MSG_SUCCESS; } bool parse_subscriber_mask(char *s, subscriber_mask_t *mask) { if (streq("all", s)) { *mask = SBSC_MASK_ALL; } else if (streq("window", s)) { *mask = SBSC_MASK_WINDOW; } else if (streq("desktop", s)) { *mask = SBSC_MASK_DESKTOP; } else if (streq("monitor", s)) { *mask = SBSC_MASK_MONITOR; } else if (streq("window_manage", s)) { *mask = SBSC_MASK_WINDOW_MANAGE; } else if (streq("window_unmanage", s)) { *mask = SBSC_MASK_WINDOW_UNMANAGE; } else if (streq("window_swap", s)) { *mask = SBSC_MASK_WINDOW_SWAP; } else if (streq("window_transfer", s)) { *mask = SBSC_MASK_WINDOW_TRANSFER; } else if (streq("window_focus", s)) { *mask = SBSC_MASK_WINDOW_FOCUS; } else if (streq("window_resize", s)) { *mask = SBSC_MASK_WINDOW_RESIZE; } else if (streq("window_move", s)) { *mask = SBSC_MASK_WINDOW_MOVE; } else if (streq("window_state", s)) { *mask = SBSC_MASK_WINDOW_STATE; } else if (streq("desktop_add", s)) { *mask = SBSC_MASK_DESKTOP_ADD; } else if (streq("desktop_rename", s)) { *mask = SBSC_MASK_DESKTOP_RENAME; } else if (streq("desktop_remove", s)) { *mask = SBSC_MASK_DESKTOP_REMOVE; } else if (streq("desktop_swap", s)) { *mask = SBSC_MASK_DESKTOP_SWAP; } else if (streq("desktop_transfer", s)) { *mask = SBSC_MASK_DESKTOP_TRANSFER; } else if (streq("desktop_focus", s)) { *mask = SBSC_MASK_DESKTOP_FOCUS; } else if (streq("desktop_layout", s)) { *mask = SBSC_MASK_DESKTOP_LAYOUT; } else if (streq("desktop_state", s)) { *mask = SBSC_MASK_DESKTOP_STATE; } else if (streq("monitor_add", s)) { *mask = SBSC_MASK_MONITOR_ADD; } else if (streq("monitor_rename", s)) { *mask = SBSC_MASK_MONITOR_RENAME; } else if (streq("monitor_remove", s)) { *mask = SBSC_MASK_MONITOR_REMOVE; } else if (streq("monitor_focus", s)) { *mask = SBSC_MASK_MONITOR_FOCUS; } else if (streq("monitor_resize", s)) { *mask = SBSC_MASK_MONITOR_RESIZE; } else if (streq("report", s)) { *mask = SBSC_MASK_REPORT; } else { return false; } return true; } bool parse_bool(char *value, bool *b) { if (streq("true", value) || streq("on", value)) { *b = true; return true; } else if (streq("false", value) || streq("off", value)) { *b = false; return true; } return false; } bool parse_layout(char *s, layout_t *l) { if (streq("monocle", s)) { *l = LAYOUT_MONOCLE; return true; } else if (streq("tiled", s)) { *l = LAYOUT_TILED; return true; } return false; } bool parse_direction(char *s, direction_t *d) { if (streq("right", s)) { *d = DIR_RIGHT; return true; } else if (streq("down", s)) { *d = DIR_DOWN; return true; } else if (streq("left", s)) { *d = DIR_LEFT; return true; } else if (streq("up", s)) { *d = DIR_UP; return true; } return false; } bool parse_cycle_direction(char *s, cycle_dir_t *d) { if (streq("next", s)) { *d = CYCLE_NEXT; return true; } else if (streq("prev", s)) { *d = CYCLE_PREV; return true; } return false; } bool parse_circulate_direction(char *s, circulate_dir_t *d) { if (streq("forward", s)) { *d = CIRCULATE_FORWARD; return true; } else if (streq("backward", s)) { *d = CIRCULATE_BACKWARD; return true; } return false; } bool parse_history_direction(char *s, history_dir_t *d) { if (streq("older", s)) { *d = HISTORY_OLDER; return true; } else if (streq("newer", s)) { *d = HISTORY_NEWER; return true; } return false; } bool parse_flip(char *s, flip_t *f) { if (streq("horizontal", s)) { *f = FLIP_HORIZONTAL; return true; } else if (streq("vertical", s)) { *f = FLIP_VERTICAL; return true; } return false; } bool parse_pointer_action(char *s, pointer_action_t *a) { if (streq("move", s)) { *a = ACTION_MOVE; return true; } else if (streq("resize_corner", s)) { *a = ACTION_RESIZE_CORNER; return true; } else if (streq("resize_side", s)) { *a = ACTION_RESIZE_SIDE; return true; } else if (streq("focus", s)) { *a = ACTION_FOCUS; return true; } return false; } bool parse_child_polarity(char *s, child_polarity_t *p) { if (streq("first_child", s)) { *p = FIRST_CHILD; return true; } else if (streq("second_child", s)) { *p = SECOND_CHILD; return true; } return false; } bool parse_degree(char *s, int *d) { int i = atoi(s); while (i < 0) i += 360; while (i > 359) i -= 360; if ((i % 90) != 0) { return false; } else { *d = i; return true; } } bool parse_window_id(char *s, long int *i) { char *end; errno = 0; long int ret = strtol(s, &end, 0); if (errno != 0 || *end != '\0') return false; else *i = ret; return true; } bool parse_bool_declaration(char *s, char **key, bool *value, alter_state_t *state) { *key = strtok(s, EQL_TOK); char *v = strtok(NULL, EQL_TOK); if (v == NULL) { *state = ALTER_TOGGLE; return true; } else { if (parse_bool(v, value)) { *state = ALTER_SET; return true; } else { return false; } } return false; } bool parse_index(char *s, int *i) { int idx; if (sscanf(s, "^%i", &idx) != 1 || idx < 1) return false; *i = idx; return true; }