text
stringlengths
1
1.05M
x = 1; for (i = 0; i < 20; i++) { x = x * 2; console.log(x); }
<reponame>domenic/mojo<gh_stars>10-100 # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'targets': [ { 'target_name': 'multiple_proguards_test_apk', 'type': 'none', 'variables': { 'app_manifest_version_name%': '<(android_app_version_name)', 'java_in_dir': '.', 'proguard_enabled': 'true', 'proguard_flags_paths': [ # Both these proguard?.flags files need to be part of the build to # remove both warnings from the src/dummy/DummyActivity.java file, else the # build will fail. 'proguard1.flags', 'proguard2.flags', ], 'R_package': 'dummy', 'R_package_relpath': 'dummy', 'apk_name': 'MultipleProguards', # This is a build-only test. There's nothing to install. 'gyp_managed_install': 0, # The Java code produces warnings, so force the build to not show them. 'chromium_code': 0, }, 'includes': [ '../../../../build/java_apk.gypi' ], }, ], }
from sklearn import tree import pandas as pd # Read the dataset data = pd.read_csv('data.csv') # Split the data into features (X) and target (Y) X = data[['age', 'gender', 'income']] Y = data['label'] # Train the decision tree model clf = tree.DecisionTreeClassifier() clf = clf.fit(X, Y)
// $(document).ready(function () { // setTimeout(function () { // $('.alert').fadeOut('slow'); // }, 2000) // }); // const _location = document.location.pathname; let navBars = document.getElementsByClassName('btn btn-success m-1'); for (let nav in navBars){ if (navBars[nav].href.includes( _location)){ console.log(navBars[nav].href.includes( _location)); navBars[nav].classList.add('btn-warning'); break; } }
# frozen_string_literal: true module PickyGuard module Generators class InstallGenerator < Rails::Generators::Base source_root File.expand_path('templates', __dir__) def generate_install copy_file 'ability.rb', 'app/models/ability.rb' copy_file 'role_policies.rb', 'app/picky_guard/role_policies.rb' copy_file 'resource_actions.rb', 'app/picky_guard/resource_actions.rb' copy_file 'user_role_checker.rb', 'app/picky_guard/user_role_checker.rb' end end end end
<reponame>smagill/opensphere-desktop package io.opensphere.core.util.swing; import java.awt.event.MouseAdapter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * The Class GhostDropAdapter. */ public class GhostDropAdapter extends MouseAdapter { /** The action. */ private final String myAction; /** The glass pane. */ private final GhostGlassPane myGlassPane; /** The listeners. */ private final List<GhostDropListener> myListeners; /** * Instantiates a new ghost drop adapter. * * @param glassPane the glass pane * @param action the action */ public GhostDropAdapter(GhostGlassPane glassPane, String action) { myGlassPane = glassPane; myAction = action; myListeners = new ArrayList<>(); } /** * Adds the ghost drop listener. * * @param listener the listener */ public void addGhostDropListener(GhostDropListener listener) { if (listener != null) { myListeners.add(listener); } } /** * Gets the action. * * @return the action */ public String getAction() { return myAction; } /** * Gets the glass pane. * * @return the glass pane */ public GhostGlassPane getGlassPane() { return myGlassPane; } /** * Removes the ghost drop listener. * * @param listener the listener */ public void removeGhostDropListener(GhostDropListener listener) { if (listener != null) { myListeners.remove(listener); } } /** * Fire ghost drop event. * * @param evt the evt */ protected void fireGhostDropEvent(GhostDropEvent evt) { Iterator<GhostDropListener> it = myListeners.iterator(); while (it.hasNext()) { it.next().ghostDropped(evt); } } }
<filename>test/getAndroidDeepLink.js<gh_stars>1-10 import { getAndroidDeepLink } from "../lib"; describe("getAndroidDeepLink()", () => { describe("when called with a non supported app name", () => { it("should return undefined", () => { const deeplink = getAndroidDeepLink("https://www.habak.com"); expect(deeplink).to.equal(undefined); }); }); describe("when called with a supported app name", () => { it("should act as wrapper for apps scripts", () => { let href = "https://www.twitter.com/enzo_ferey"; let deeplink = getAndroidDeepLink(href); let deeplinkScript = apps.twitter(href, ANDROID_TARGET); expect(deeplink).to.equal(deeplinkScript); href = "https://www.instagram.com/enzo_ferey"; deeplink = getAndroidDeepLink(href); deeplinkScript = apps.instagram(href, ANDROID_TARGET); expect(deeplink).to.equal(deeplinkScript); }); }); });
class BaGPipeEnvironment(Superclass): def _setUp(self): self.temp_dir = self.useFixture(fixtures.TempDir()).path # Create the central_data_bridge and central_external_bridge self.central_data_bridge = self.useFixture( net_helpers.OVSBridgeFixture('cnt-data')).bridge self.central_external_bridge = self.useFixture( net_helpers.OVSBridgeFixture('cnt-ex')).bridge
from pyln.client import LightningRpc import pandas import networkx as nx import matplotlib.pyplot as plt l1 = LightningRpc(".lightning/bitcoin/lightning-rpc") info = l1.getinfo() channels = l1.listchannels() channels.keys() dfc = pandas.DataFrame(channels["channels"]) nodes = l1.listnodes() nodes.keys() dfn = pandas.DataFrame(nodes["nodes"]) # Create empty graph g = nx.Graph() # Add edges and edge attributes for i, elrow in dfc.iterrows(): g.add_edge(elrow[0], elrow[1], attr_dict=elrow[2:].to_dict()) # Add node attributes for i, nlrow in dfn.iterrows(): g.add_node[nlrow['nodeid']] = nlrow[1:].to_dict() print('# of edges: {}'.format(g.number_of_edges())) print('# of nodes: {}'.format(g.number_of_nodes())) # Calculate list of nodes with odd degree nodes_odd_degree = [v for v, d in g.degree_iter() if d % 2 == 1]
source ~/.cache/wal/colors.sh echo '<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>author</key> <string>Template: Chris Kempson, Scheme: Louie Helm</string> <key>name</key> <string>Base16</string> <key>semanticClass</key> <string>theme.base16.wal</string> <key>colorSpaceName</key> <string>sRGB</string> <key>gutterSettings</key> <dict> <key>background</key> <string>'$color1'</string> <key>divider</key> <string>'$color1'</string> <key>foreground</key> <string>'$color3'</string> <key>selectionBackground</key> <string>'$color2'</string> <key>selectionForeground</key> <string>'$color4'</string> </dict> <key>settings</key> <array> <dict> <key>settings</key> <dict> <key>background</key> <string>'$color0'</string> <key>caret</key> <string>'$color5'</string> <key>foreground</key> <string>'$color5'</string> <key>invisibles</key> <string>'$color3'</string> <key>lineHighlight</key> <string>'$color3'55</string> <key>selection</key> <string>'$color2'</string> </dict> </dict> <dict> <key>name</key> <string>Text</string> <key>scope</key> <string>variable.parameter.function</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color5'</string> </dict> </dict> <dict> <key>name</key> <string>Comments</string> <key>scope</key> <string>comment, punctuation.definition.comment</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color3'</string> </dict> </dict> <dict> <key>name</key> <string>Punctuation</string> <key>scope</key> <string>punctuation.definition.string, punctuation.definition.variable, punctuation.definition.string, punctuation.definition.parameters, punctuation.definition.string, punctuation.definition.array</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color5'</string> </dict> </dict> <dict> <key>name</key> <string>Delimiters</string> <key>scope</key> <string>none</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color5'</string> </dict> </dict> <dict> <key>name</key> <string>Operators</string> <key>scope</key> <string>keyword.operator</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color5'</string> </dict> </dict> <dict> <key>name</key> <string>Keywords</string> <key>scope</key> <string>keyword</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color14'</string> </dict> </dict> <dict> <key>name</key> <string>Variables</string> <key>scope</key> <string>variable</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color8'</string> </dict> </dict> <dict> <key>name</key> <string>Functions</string> <key>scope</key> <string>entity.name.function, meta.require, support.function.any-method</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color13'</string> </dict> </dict> <dict> <key>name</key> <string>Classes</string> <key>scope</key> <string>support.class, entity.name.class, entity.name.type.class</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color10'</string> </dict> </dict> <dict> <key>name</key> <string>Classes</string> <key>scope</key> <string>meta.class</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color7'</string> </dict> </dict> <dict> <key>name</key> <string>Methods</string> <key>scope</key> <string>keyword.other.special-method</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color13'</string> </dict> </dict> <dict> <key>name</key> <string>Storage</string> <key>scope</key> <string>storage</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color14'</string> </dict> </dict> <dict> <key>name</key> <string>Support</string> <key>scope</key> <string>support.function</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color12'</string> </dict> </dict> <dict> <key>name</key> <string>Strings, Inherited Class</string> <key>scope</key> <string>string, constant.other.symbol, entity.other.inherited-class</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color11'</string> </dict> </dict> <dict> <key>name</key> <string>Integers</string> <key>scope</key> <string>constant.numeric</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color9'</string> </dict> </dict> <dict> <key>name</key> <string>Floats</string> <key>scope</key> <string>none</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color9'</string> </dict> </dict> <dict> <key>name</key> <string>Boolean</string> <key>scope</key> <string>none</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color9'</string> </dict> </dict> <dict> <key>name</key> <string>Constants</string> <key>scope</key> <string>constant</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color9'</string> </dict> </dict> <dict> <key>name</key> <string>Tags</string> <key>scope</key> <string>entity.name.tag</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color8'</string> </dict> </dict> <dict> <key>name</key> <string>Attributes</string> <key>scope</key> <string>entity.other.attribute-name</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color9'</string> </dict> </dict> <dict> <key>name</key> <string>Attribute IDs</string> <key>scope</key> <string>entity.other.attribute-name.id, punctuation.definition.entity</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color13'</string> </dict> </dict> <dict> <key>name</key> <string>Selector</string> <key>scope</key> <string>meta.selector</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color14'</string> </dict> </dict> <dict> <key>name</key> <string>Values</string> <key>scope</key> <string>none</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color9'</string> </dict> </dict> <dict> <key>name</key> <string>Headings</string> <key>scope</key> <string>markup.heading punctuation.definition.heading, entity.name.section</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>'$color13'</string> </dict> </dict> <dict> <key>name</key> <string>Units</string> <key>scope</key> <string>keyword.other.unit</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color9'</string> </dict> </dict> <dict> <key>name</key> <string>Bold</string> <key>scope</key> <string>markup.bold, punctuation.definition.bold</string> <key>settings</key> <dict> <key>fontStyle</key> <string>bold</string> <key>foreground</key> <string>'$color10'</string> </dict> </dict> <dict> <key>name</key> <string>Italic</string> <key>scope</key> <string>markup.italic, punctuation.definition.italic</string> <key>settings</key> <dict> <key>fontStyle</key> <string>italic</string> <key>foreground</key> <string>'$color14'</string> </dict> </dict> <dict> <key>name</key> <string>Code</string> <key>scope</key> <string>markup.raw.inline</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color11'</string> </dict> </dict> <dict> <key>name</key> <string>Link Text</string> <key>scope</key> <string>string.other.link, punctuation.definition.string.end.markdown</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color8'</string> </dict> </dict> <dict> <key>name</key> <string>Link Url</string> <key>scope</key> <string>meta.link</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color9'</string> </dict> </dict> <dict> <key>name</key> <string>Lists</string> <key>scope</key> <string>markup.list</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color8'</string> </dict> </dict> <dict> <key>name</key> <string>Quotes</string> <key>scope</key> <string>markup.quote</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color9'</string> </dict> </dict> <dict> <key>name</key> <string>Separator</string> <key>scope</key> <string>meta.separator</string> <key>settings</key> <dict> <key>background</key> <string>'$color2'</string> <key>foreground</key> <string>'$color5'</string> </dict> </dict> <dict> <key>name</key> <string>Inserted</string> <key>scope</key> <string>markup.inserted</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color11'</string> </dict> </dict> <dict> <key>name</key> <string>Deleted</string> <key>scope</key> <string>markup.deleted</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color8'</string> </dict> </dict> <dict> <key>name</key> <string>Changed</string> <key>scope</key> <string>markup.changed</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color14'</string> </dict> </dict> <dict> <key>name</key> <string>Colors</string> <key>scope</key> <string>constant.other.color</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color12'</string> </dict> </dict> <dict> <key>name</key> <string>Regular Expressions</string> <key>scope</key> <string>string.regexp</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color12'</string> </dict> </dict> <dict> <key>name</key> <string>Escape Characters</string> <key>scope</key> <string>constant.character.escape</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color12'</string> </dict> </dict> <dict> <key>name</key> <string>Embedded</string> <key>scope</key> <string>punctuation.section.embedded, variable.interpolation</string> <key>settings</key> <dict> <key>foreground</key> <string>'$color14'</string> </dict> </dict> <dict> <key>name</key> <string>Illegal</string> <key>scope</key> <string>invalid.illegal</string> <key>settings</key> <dict> <key>background</key> <string>'$color8'</string> <key>foreground</key> <string>'$color7'</string> </dict> </dict> <dict> <key>name</key> <string>Broken</string> <key>scope</key> <string>invalid.broken</string> <key>settings</key> <dict> <key>background</key> <string>'$color9'</string> <key>foreground</key> <string>'$color0'</string> </dict> </dict> <dict> <key>name</key> <string>Deprecated</string> <key>scope</key> <string>invalid.deprecated</string> <key>settings</key> <dict> <key>background</key> <string>'$color15'</string> <key>foreground</key> <string>'$color7'</string> </dict> </dict> <dict> <key>name</key> <string>Unimplemented</string> <key>scope</key> <string>invalid.unimplemented</string> <key>settings</key> <dict> <key>background</key> <string>'$color3'</string> <key>foreground</key> <string>'$color7'</string> </dict> </dict> </array> <key>uuid</key> <string>uuid</string> </dict> </plist>'
#!/bin/bash dieharder -d 201 -g 51 -S 1935197833
#!/usr/bin/env bash ################################################################################ # Abstract cli integration for ansible projects or collections # # Copyright: (C) 2021 TechDivision GmbH - All Rights Reserved # Author: Johann Zelger <j.zelger@techdivision.com> # Author: Florian Schmid <f.schmid@techdivision.com> ################################################################################ # Set a global trap for e.g. ctrl+c to run shutdown routine trap shutdown SIGINT # track start time APPLICATION_START_TIME=$(date +%s); # define application to be auto startet in case of testing purpose for example : "${APPLICATION_AUTOSTART:=1}" # define default spinner enabled : "${SPINNER_ENABLED:=1}" # define application return codes APPLICATION_RETURN_CODE_ERROR=255 APPLICATION_RETURN_CODE_SUCCESS=0 # set default return code 0 APPLICATION_RETURN_CODE=$APPLICATION_RETURN_CODE_SUCCESS # define default setting for debug info output APPLICATION_DEBUG_INFO_ENABLED=0; # define default help behaviour output APPLICATION_HELP_INFO_ENABLED=0; # define default force behaviour APPLICATION_FORCE_INFO_ENABLED=0; # define variables APPLICATION_NAME="valet.sh" # define default git relevant variables APPLICATION_GIT_NAMESPACE="valet-sh" APPLICATION_GIT_REPOSITORY="valet-sh" APPLICATION_GIT_URL="https://github.com/${APPLICATION_GIT_NAMESPACE}/${APPLICATION_GIT_REPOSITORY}" APPLICATION_INCLUDE_URL="https://raw.githubusercontent.com/${APPLICATION_GIT_NAMESPACE}/install/master/include.sh" # define default playbook dir ANSIBLE_PLAYBOOKS_DIR="playbooks" # define application prefix path APPLICATION_PREFIX_PATH="/usr/local" # define default install directory APPLICATION_REPO_DIR="${APPLICATION_PREFIX_PATH}/${APPLICATION_GIT_NAMESPACE}/${APPLICATION_GIT_REPOSITORY}" # define default venv directory APPLICATION_VENV_DIR="${APPLICATION_PREFIX_PATH}/${APPLICATION_GIT_NAMESPACE}/venv" # use current bash source script dir as base_dir BASE_DIR=${BASE_DIR:=${APPLICATION_REPO_DIR}} # check if git dir is available in base dir if [ -d "${BASE_DIR}/.git" ]; then # get the current version from git repository in base dir APPLICATION_VERSION=$(git --git-dir="${BASE_DIR}/.git" --work-tree="${BASE_DIR}" describe --tags) fi ############################################################################## # Logs messages in given type ############################################################################## function out() { case "${1--h}" in error) printf "\\033[1;31m✘ %s\\033[0m\\n" "$2";; warning) printf "\\033[1;33m⚠ %s\\033[0m\\n" "$2";; success) printf "\\033[1;32m✔ %s\\033[0m\\n" "$2";; task) printf "▸ %s\\n" "$2";; *) printf "%s\\n" "$*";; esac } ####################################### # Validates version against semver # Globals: # None # Arguments: # Version # Returns: # None ####################################### function version_validate() { local version=$1 if [[ "$version" =~ ${SEMVER_REGEX} ]]; then if [ "$#" -eq "2" ]; then local major=${BASH_REMATCH[1]} local minor=${BASH_REMATCH[2]} local patch=${BASH_REMATCH[3]} local prere=${BASH_REMATCH[4]} local build=${BASH_REMATCH[5]} eval "$2=(\"$major\" \"$minor\" \"$patch\" \"$prere\" \"$build\")" else echo "$version" fi else out error "Version $version does not match the semver scheme 'X.Y.Z(-PRERELEASE)(+BUILD)'. See help for more information." error fi } ############################################################################## # Compares versions ############################################################################## function version_compare() { version_validate "$1" V version_validate "$2" V_ for i in 0 1 2; do local diff=$((${V[$i]} - ${V_[$i]})) if [[ $diff -lt 0 ]]; then echo -1; return 0 elif [[ $diff -gt 0 ]]; then echo 1; return 0 fi done if [[ -z "${V[3]}" ]] && [[ -n "${V_[3]}" ]]; then echo -1; return 0; elif [[ -n "${V[3]}" ]] && [[ -z "${V_[3]}" ]]; then echo 1; return 0; elif [[ -n "${V[3]}" ]] && [[ -n "${V_[3]}" ]]; then if [[ "${V[3]}" > "${V_[3]}" ]]; then echo 1; return 0; elif [[ "${V[3]}" < "${V_[3]}" ]]; then echo -1; return 0; fi fi echo 0 } ############################################################################## # Prepares application by installing dependencies and itself ############################################################################## function prepare() { # check if root user is acting if [[ ${EUID:-$(id -u)} -eq 0 ]]; then error "Please do not run ${APPLICATION_NAME} as root"; fi # set cwd to base dir cd "${BASE_DIR}" || error "Unable to set cwd to ${BASE_DIR}" } ############################################################################## # Upgrade meachanism of applications itself ############################################################################## function self_upgrade() { # exit immediately if a command exits with a non-zero status set -e # include external vars and functions source /dev/stdin <<< "$( curl -sS ${APPLICATION_INCLUDE_URL} )" # trigger sudo password check sudo true # create version map to extract major, minor and build parts later on version_validate "${APPLICATION_VERSION}" APPLICATION_VERSION_MAP # define default git tag filter based on major version GIT_TAG_FILTER="^${APPLICATION_VERSION_MAP[0]}.*"; # if major 1 than check if old darwin tags are filtered for macos if [[ "${APPLICATION_VERSION_MAP[0]}" = "1" ]] && [[ "${OSTYPE}" = "darwin"* ]]; then GIT_TAG_FILTER="${GIT_TAG_FILTER}${OSTYPE}" fi # check if force self_upgrade was triggered if [ $APPLICATION_FORCE_INFO_ENABLED = 1 ]; then out warning "CAUTION! This will trigger a major version update if it's available." read -r -p "Are You Sure? [Y/n] " input echo ""; case $input in [yY][eE][sS]|[yY]) GIT_TAG_FILTER=".*" ;; [nN][oO]|[nN]) exit 1 ;; *) out error "Invalid input '$input'" shutdown ;; esac fi # trigger install_upgrade process GIT_TAG=$(install_upgrade "${APPLICATION_GIT_URL}" "${APPLICATION_REPO_DIR}" "${GIT_TAG_FILTER}") # process specific upgrade strategy if [ "$(version_compare "${APPLICATION_VERSION}" "${GIT_TAG}")" = "-1" ] || [ $APPLICATION_FORCE_INFO_ENABLED = 1 ]; then # (re)install dependencies and venv install_dependencies "${APPLICATION_VENV_DIR}" "${APPLICATION_REPO_DIR}" # (re)link app install_link "${APPLICATION_VENV_DIR}" "${APPLICATION_NAME}" # (re)set system-wide symlink to be in path out success "Successfully upgraded from ${APPLICATION_VERSION} to latest version ${GIT_TAG}" else out success "Already on the latest version $GIT_TAG" fi } ############################################################################## # Prints the console tool header ############################################################################## function print_header() { echo -e "\\033[1m$APPLICATION_NAME\\033[0m \\033[34m$APPLICATION_VERSION\\033[0m" printf "\\n" } ############################################################################## # Prints the console tool header ############################################################################## function print_footer() { LC_NUMERIC="en_US.UTF-8" APPLICATION_END_TIME=$(date +%s) APPLICATION_EXECUTION_TIME=$(echo "$APPLICATION_END_TIME - $APPLICATION_START_TIME" | bc); if [ $APPLICATION_DEBUG_INFO_ENABLED = 1 ]; then printf "\\n" printf "\\e[34m" printf "\\e[1mDebug information:\\033[0m" printf "\\e[34m" printf "\\n" printf " Version: \\e[1m%s\\033[0m\\n" "$APPLICATION_VERSION" printf "\\e[34m" printf " Execution time: \\e[1m%f sec.\\033[0m\\n" "$APPLICATION_EXECUTION_TIME" printf "\\e[34m" printf " Exitcode: \\e[1m%s\\033[0m\\n" "$APPLICATION_RETURN_CODE" printf "\\e[34m\\033[0m" printf "\\n" fi } ############################################################################## # Print usage help and command list ############################################################################## function print_usage() { local cmd_output_space=' ' local cmd_name="-x" # show general help if no specific command was given if [[ -z "$1" ]]; then printf "\\e[33mUsage:\\e[39m\\n" printf " command [options] [command] [arguments]\\n" printf "\\n" printf "\\e[33mOptions:\\e[39m\\n" printf "\\e[32m -h %s \\e[39mDisplay this help message\\n" "${cmd_output_space:${#cmd_name}}" printf "\\e[32m -v %s \\e[39mDisplay this application version\\n" "${cmd_output_space:${#cmd_name}}" printf "\\e[32m -d %s \\e[39mDisplay debug information\\n" "${cmd_output_space:${#cmd_name}}" printf "\\n" printf "\\e[33mCommands:\\e[39m\\n" local cmd_name="self-upgrade" local cmd_description="Upgrade to latest version." printf " \\e[32m%s %s \\e[39m${cmd_description}\\n" "${cmd_name}" "${cmd_output_space:${#cmd_name}}" if [ -d "$BASE_DIR/playbooks" ]; then for file in ./playbooks/**.yml; do local cmd_name cmd_name="$(basename "${file}" .yml)" local cmd_description cmd_description=$(grep '^\#[[:space:]]@description:' -m 1 "${file}" | awk -F'"' '{ print $2}'); if [ -n "${cmd_description}" ]; then printf " \\e[32m%s %s \\e[39m${cmd_description}\\n" "${cmd_name}" "${cmd_output_space:${#cmd_name}}" fi done fi printf "\\n" else # parse command specific playbook if command was given cmd_file="$BASE_DIR/playbooks/$1.yml" cmd_type="" cmd_help="" # check if requested playbook yml exist and execute it if [ ! -f "$cmd_file" ]; then out error "Command '$1' not available" shutdown fi # parse playbook file for comment header informations while read -r line; do if [[ ${line} == "---" ]] ; then break fi if [[ ${line} = "# @command:"* ]] ; then cmd_type="command" cmd_name=$(echo "${line}" | grep '^\#[[:space:]]@command:' -m 1 | awk -F'"' '{ print $2}'); continue fi if [[ ${line} = "# @description:"* ]] ; then cmd_type="description" cmd_description=$(echo "${line}" | grep '^\#[[:space:]]@description:' -m 1 | awk -F'"' '{ print $2}'); continue fi if [[ ${line} = "# @usage:"* ]] ; then cmd_usage=$(echo "${line}" | grep '^\#[[:space:]]@usage:' -m 1 | awk -F'"' '{ print $2}'); cmd_type="usage" continue fi if [[ ${line} = "# @help:"* ]] ; then cmd_type="help" continue fi if [[ ${cmd_type} == "help" ]] ; then cmd_help+=" " cmd_help+=$(echo "${line}" | awk -F'# ' '{ print $2}'); cmd_help+=$'\n' fi done < "${cmd_file}" printf "\\e[33mCommand:\\e[39m\\e[32m %s\\e[39m\\n" "${cmd_name}" printf " %s\\n" "${cmd_description}" printf "\\n" printf "\\e[33mUsage:\\e[39m\\n" printf " %s\\n" "${cmd_usage}" printf "\\n" printf "\\e[33mHelp:\\e[39m\\n" printf "%s\\n" "${cmd_help}" fi } ############################################################################## # Executes command via ansible playbook ############################################################################## function execute_ansible_playbook() { local command=$1 local ansible_playbook_file="$ANSIBLE_PLAYBOOKS_DIR/$command.yml" local ansible_options="" local parsed_args=$2 local parsed_opts=$3 # define complete extra vars object read -r -d '' ansible_extra_vars << EOM { "cli": { "name": "${APPLICATION_NAME}", "version": "${APPLICATION_VERSION}", "args": [${parsed_args}], "opts": [${parsed_opts}] } } EOM ansible_extra_vars=("--extra-vars" "${ansible_extra_vars}") # check if requested playbook yml exist and execute it if [ -f "$ansible_playbook_file" ]; then # parse playbook file to check for header information while read -r line; do if [[ ${line} == "---" ]] ; then break fi if [[ ${line} = "# @sudo:"* ]] ; then # shutdown valet.sh when user sudo command was not successful if ! sudo true; then shutdown fi fi done < "${ansible_playbook_file}" # check if debug was enabled and set correct ansible optionsy if [ "$APPLICATION_DEBUG_INFO_ENABLED" = 1 ]; then ansible_options="-v" fi # activate application venv if available if [ -f "${APPLICATION_VENV_DIR}/bin/activate" ]; then source "${APPLICATION_VENV_DIR}/bin/activate" fi # execute ansible-playbook ansible-playbook ${ansible_options} "${ansible_playbook_file}" "${ansible_extra_vars[@]}" || APPLICATION_RETURN_CODE=$? # deactivate venv if available deactivate 2>/dev/null || true else out error "Command '$command' not available" fi } ############################################################################## # Error handling and abort function with log message ############################################################################## function error() { # check if error message is given if [ -z "$*" ]; then echo "no error message given" shutdown $APPLICATION_RETURN_CODE_ERROR fi # output error message to user out error "$*" # trigger immediate shutdown shutdown $APPLICATION_RETURN_CODE_ERROR } ############################################################################## # Shutdown cli client script ############################################################################## function shutdown() { # kill spinner by pid if [[ -n "${SPINNER_PID}" && "${SPINNER_PID}" -gt 0 ]]; then kill -9 "${SPINNER_PID}" &> /dev/null wait "$!" 2>/dev/null fi # deactivate application venv deactivate 2>/dev/null || true # exit if [ "$1" ]; then APPLICATION_RETURN_CODE=$1 fi exit "${APPLICATION_RETURN_CODE}" } ############################################################################## # Process all bash args given from shell ############################################################################## function process_args() { local parsed_command="" local parsed_args="" local parsed_opts="" # check if no arguments were given if [ $# -eq 0 ]; then # just display usage in case of zero arguments print_usage else # parse options first and handle it for i in "$@"; do # parse double dash options (ansible) if [[ ${i:0:2} == "--" ]]; then if [ ${#parsed_opts} -gt 0 ]; then parsed_opts+=,; fi parsed_opts+="\"${i}\""; shift continue fi # parse single dash options (cli) if [[ ${i:0:1} == "-" ]]; then if [ ${#parsed_opts} -gt 0 ]; then parsed_opts+=,; fi parsed_opts+="\"${i}\""; case ${i} in -d) # enable debug info export APPLICATION_DEBUG_INFO_ENABLED=1 shift ;; -v) # immediate shutdown to display version only shutdown shift ;; -h) # print usage for help then shutdown export APPLICATION_HELP_INFO_ENABLED=1 shift ;; -f) # enable force info export APPLICATION_FORCE_INFO_ENABLED=1 shift ;; -*) shift # error in this case error "Invalid option: ${i}" esac # parse command and given args else if [ ${#parsed_command} -gt 0 ]; then if [ ${#parsed_args} -gt 0 ]; then parsed_args+=,; fi parsed_args+="\"${i}\"" else parsed_command=$1; fi fi done; # if help info was enabled by "-h" output help if [ "$APPLICATION_HELP_INFO_ENABLED" = 1 ]; then print_usage "${parsed_command}" shutdown fi # handle remaining args if given if [ -n "$*" ]; then case "${1--h}" in self-upgrade) self_upgrade;; # try to execute playbook based on command # ansible will throw an error if specific playbook does not exist *) execute_ansible_playbook "$parsed_command" "$parsed_args" "$parsed_opts";; esac else print_usage fi fi } ############################################################################## # Main ############################################################################## function main() { prepare print_header process_args "$@" print_footer shutdown } # start cli with given command line args if autostart is enabled if [ "${APPLICATION_AUTOSTART}" = "1" ]; then main "$@"; fi
package presentation.components; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import javax.swing.JComponent; import javax.swing.SwingUtilities; import presentation.PlayGameController; import utils.Position; public class BoardBox extends JComponent implements MouseListener { protected static int width = 18; protected static int height = 18; protected Position position; protected boolean flag; protected boolean hidden; protected BufferedImage image; protected Graphics painter; protected Color color; public BoardBox (Position p) { super(); enableInputMethods(true); addMouseListener(this); this.position = p; this.flag = false; this.hidden = true; this.color = new Color(224,224,224); } @Override public Dimension getPreferredSize() { return ( new Dimension(width, height) ); } @Override public Dimension getMinimumSize() { return this.getPreferredSize(); } @Override public Dimension getMaximumSize() { return this.getPreferredSize(); } @Override public void paintComponent(Graphics g) { painter = g; } public Position getPosition() { return position; } @Override public void mouseClicked(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { this.hidden = false; this.flag = true; PlayGameController.getInstance().prDiscoverBox(position); } else if (SwingUtilities.isRightMouseButton(e)) { PlayGameController.getInstance().prFlagBox(position); this.toggleFlag(); } } public void discover() {} protected void toggleFlag() { if (flag == true) { flag = false; this.setForeground( Color.BLACK ); } else { flag = true; this.setForeground( Color.RED ); } } @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} }
/* Copyright (c) 2012-2017 <NAME> <<EMAIL>> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "Global.h" #include "GLXFrameGrabber.h" #include "ShmStructs.h" #include <GL/gl.h> #include <GL/glu.h> #include <GL/glext.h> #include <X11/extensions/Xfixes.h> #define CGLE(code) \ code; \ if(m_debug) CheckGLError(#code); static unsigned int g_glx_frame_grabber_counter = 0; // Print the last OpenGL error if there was one. static void CheckGLError(const char* at) { GLenum error = glGetError(); if(error != GL_NO_ERROR) { GLINJECT_PRINT("Warning: OpenGL error in " << at << ": " << gluErrorString(error)); } } // Returns the OpenGL version as (major * 1000 + minor). So OpenGL 2.1 would be '2001'. static unsigned int GetGLVersion() { // get version string const char *str = (const char*) glGetString(GL_VERSION); if(str == NULL) { GLINJECT_PRINT("Error: Could not get OpenGL version, version string is NULL!"); exit(1); } // read major version unsigned int dot1 = strspn(str, "0123456789"); if(str[dot1] != '.') { GLINJECT_PRINT("Error: Could not get OpenGL version, version string is '" << str << "'!"); exit(1); } unsigned int major = atoi(str); // read minor version unsigned int dot2 = strspn(str + dot1 + 1, "0123456789") + dot1 + 1; if(str[dot2] != '.' && str[dot2] != ' ' && str[dot2] != '\0') { GLINJECT_PRINT("Error: Could not get OpenGL version, version string is '" << str << "'!"); exit(1); } unsigned int minor = atoi(str + dot1 + 1); GLINJECT_PRINT("OpenGL version = " << major << "." << minor << " (" << str << ")."); return major * 1000 + minor; } static void GLImageDrawCursor(Display* dpy, uint8_t* image_data, size_t image_stride, int image_width, int image_height, int recording_area_x, int recording_area_y) { // get the cursor XFixesCursorImage *xcim = XFixesGetCursorImage(dpy); if(xcim == NULL) return; // calculate the position of the cursor int x = xcim->x - xcim->xhot - recording_area_x; int y = xcim->y - xcim->yhot - recording_area_y; // calculate the part of the cursor that's visible int cursor_left = std::max(0, -x), cursor_right = std::min((int) xcim->width, image_width - x); int cursor_top = std::max(0, -y), cursor_bottom = std::min((int) xcim->height, image_height - y); // draw the cursor // XFixesCursorImage uses 'long' instead of 'int' to store the cursor images, which is a bit weird since // 'long' is 64-bit on 64-bit systems and only 32 bits are actually used. The image uses premultiplied alpha. for(int j = cursor_top; j < cursor_bottom; ++j) { unsigned long *cursor_row = xcim->pixels + xcim->width * j; uint8_t *image_row = image_data + image_stride * (image_height - 1 - y - j); for(int i = cursor_left; i < cursor_right; ++i) { unsigned long cursor_pixel = cursor_row[i]; uint8_t *image_pixel = image_row + 4 * (x + i); int cursor_a = (uint8_t) (cursor_pixel >> 24); int cursor_r = (uint8_t) (cursor_pixel >> 16); int cursor_g = (uint8_t) (cursor_pixel >> 8); int cursor_b = (uint8_t) (cursor_pixel >> 0); if(cursor_a == 255) { image_pixel[2] = cursor_r; image_pixel[1] = cursor_g; image_pixel[0] = cursor_b; } else { image_pixel[2] = (image_pixel[2] * (255 - cursor_a) + 127) / 255 + cursor_r; image_pixel[1] = (image_pixel[1] * (255 - cursor_a) + 127) / 255 + cursor_g; image_pixel[0] = (image_pixel[0] * (255 - cursor_a) + 127) / 255 + cursor_b; } } } // free the cursor XFree(xcim); } GLXFrameGrabber::GLXFrameGrabber(Display* display, Window window, GLXDrawable drawable) { m_id = ++g_glx_frame_grabber_counter; m_x11_display = display; m_x11_window = window; m_glx_drawable = drawable; m_gl_version = (unsigned int) -1; // get it later, when the OpenGL context has been selected m_warn_too_small = true; m_warn_too_large = true; m_stream_writer = NULL; try { Init(); } catch(...) { Free(); throw; } } GLXFrameGrabber::~GLXFrameGrabber() { Free(); } void GLXFrameGrabber::Init() { GLINJECT_PRINT("[GLXFrameGrabber " << m_id << "] Created GLX frame grabber."); // enable debugging? { const char *ssr_glx_debug = getenv("SSR_GLX_DEBUG"); if(ssr_glx_debug != NULL && atoi(ssr_glx_debug) > 0) { GLINJECT_PRINT("[GLXFrameGrabber " << m_id << "] GLX debugging enabled."); m_debug = true; } else { m_debug = false; } } // showing the cursor requires XFixes (which should be supported on any modern X server, but let's check it anyway) { int event, error; if(XFixesQueryExtension(m_x11_display, &event, &error)) { m_has_xfixes = true; } else { GLINJECT_PRINT("[GLXFrameGrabber " << m_id << "] Warning: XFixes is not supported by server, the cursor will not be recorded."); m_has_xfixes = false; } } // create stream writer { std::string channel; const char *ssr_channel = getenv("SSR_CHANNEL"); if(ssr_channel != NULL) channel = ssr_channel; std::ostringstream source; source << "glx" << std::setw(4) << std::setfill('0') << m_id; m_stream_writer = new SSRVideoStreamWriter(channel, source.str()); } } void GLXFrameGrabber::Free() { // destroy stream writer if(m_stream_writer != NULL) { delete m_stream_writer; m_stream_writer = NULL; } GLINJECT_PRINT("[GLXFrameGrabber " << m_id << "] Destroyed GLX frame grabber."); } void GLXFrameGrabber::GrabFrame() { // get the OpenGL version if(m_gl_version == (unsigned int) -1) m_gl_version = GetGLVersion(); // get the size of the window // glXQueryDrawable is buggy, use XGetGeometry instead unsigned int width, height, stride; { Window unused_window; int unused; XGetGeometry(m_x11_display, m_x11_window, &unused_window, &unused, &unused, &width, &height, (unsigned int*) &unused, (unsigned int*) &unused); stride = grow_align16(width * 4); m_stream_writer->UpdateSize(width, height, -(int) stride); } // ignore frames that are too small or too large if(width < 2 || height < 2) { if(m_warn_too_small) { m_warn_too_small = false; GLINJECT_PRINT("[GLXFrameGrabber " << m_id << "] Error: Frame is too small!"); } return; } if(width > 10000 || height > 10000) { if(m_warn_too_large) { m_warn_too_large = false; GLINJECT_PRINT("[GLXFrameGrabber " << m_id << "] Error: Frame is too large!"); } return; } // should we capture this frame? unsigned int flags; void *image_data = m_stream_writer->NewFrame(&flags); if(image_data == NULL) return; // detect errors in external code so it won't look like it's my fault :) if(m_debug) CheckGLError("<external code>"); // save settings CGLE(glPushAttrib(GL_PIXEL_MODE_BIT)); CGLE(glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT)); int old_pbo, old_fbo_draw, old_fbo_read; CGLE(glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &old_pbo)); CGLE(glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &old_fbo_draw)); CGLE(glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &old_fbo_read)); // change settings CGLE(glBindBuffer(GL_PIXEL_PACK_BUFFER, 0)); CGLE(glBindFramebuffer(GL_FRAMEBUFFER, 0)); CGLE(glPixelStorei(GL_PACK_SWAP_BYTES, 0)); CGLE(glPixelStorei(GL_PACK_ROW_LENGTH, stride / 4)); CGLE(glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0)); CGLE(glPixelStorei(GL_PACK_SKIP_PIXELS, 0)); CGLE(glPixelStorei(GL_PACK_SKIP_ROWS, 0)); CGLE(glPixelStorei(GL_PACK_SKIP_IMAGES, 0)); CGLE(glPixelStorei(GL_PACK_ALIGNMENT, 8)); CGLE(glReadBuffer(GL_BACK)); // capture the frame CGLE(glReadPixels(0, 0, width, height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, image_data)); // draw the cursor if((flags & GLINJECT_FLAG_RECORD_CURSOR) && m_has_xfixes) { int inner_x, inner_y; Window unused_window; if(XTranslateCoordinates(m_x11_display, m_x11_window, DefaultRootWindow(m_x11_display), 0, 0, &inner_x, &inner_y, &unused_window)) { GLImageDrawCursor(m_x11_display, (uint8_t*) image_data, stride, width, height, inner_x, inner_y); } } // write the frame m_stream_writer->NextFrame(); // restore settings CGLE(glBindBuffer(GL_PIXEL_PACK_BUFFER, old_pbo)); CGLE(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, old_fbo_draw)); CGLE(glBindFramebuffer(GL_READ_FRAMEBUFFER, old_fbo_read)); CGLE(glPopClientAttrib()); CGLE(glPopAttrib()); }
<filename>src/shapeFu/index.js var regl = require('regl')() const {frame} = regl import mat4 from 'gl-mat4' import most from 'most' import { params as cameraDefaults } from '../common/controls/orbitControls' import camera from '../common/camera' import { sceneData } from '../common/data' import {controlsLoop as controlsLoop} from '../common/controls/controlsLoop' import { interactionsFromEvents, pointerGestures } from '../common/interactions/pointerGestures' import drawFrame from './drawFrame' // data const settings = { toggleSoftShadows: false, toggleAO: false, bgColor: [1, 1, 1, 1], rayMarch: { uRM_maxIterations: 400, uRM_stop_threshold: 0.0001, uRM_grad_step: 0.01, uRM_clip_far: 100.0 } } const container = document.querySelectorAll('canvas')[1] const fullData = Object.assign({}, {scene: sceneData}, settings) // main render function: data in, rendered frame out function render (data) { let _data = data let viewMat = data.camera.view _data.view = mat4.invert(viewMat, viewMat) drawFrame(_data) } // dynamic drawing /*frame((props, context) => { render(fullData) })*/ // render one frame //render(fullData) // render multiple, with controls //controlsLoop(cameraDefaults, render, fullData) // interactions : camera controls const baseInteractions$ = interactionsFromEvents(container) const gestures = pointerGestures(baseInteractions$) const camMoves$ = controlsLoop({gestures}, {settings: cameraDefaults, camera}, fullData) const heartBeat$ = most.periodic(16) // merge all the things that should trigger a re-render most.merge( camMoves$, heartBeat$.map(x => fullData) ) .forEach(render)
big = little.upper() little = big.lower()
<filename>app-dialog/src/main/java/com/king/app/dialog/AppDialog.java package com.king.app.dialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.support.annotation.NonNull; import android.support.annotation.StyleRes; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import com.king.app.dialog.fragment.AppDialogFragment; /** * @author Jenly <a href="mailto:<EMAIL>">Jenly</a> */ public enum AppDialog { INSTANCE; private final float DEFAULT_WIDTH_RATIO = 0.85f; private Dialog mDialog; private String mTag; //------------------------------------------- /** * 通过{@link AppDialogConfig} 创建一个视图 * @param context * @param config 弹框配置 {@link AppDialogConfig} * @return */ public View createAppDialogView(@NonNull Context context,@NonNull AppDialogConfig config){ View view = config.getView(context); TextView tvDialogTitle = view.findViewById(config.getTitleId()); setText(tvDialogTitle,config.getTitle()); tvDialogTitle.setVisibility(config.isHideTitle() ? View.GONE : View.VISIBLE); TextView tvDialogContent = view.findViewById(config.getContentId()); setText(tvDialogContent,config.getContent()); Button btnDialogCancel = view.findViewById(config.getCancelId()); setText(btnDialogCancel,config.getCancel()); btnDialogCancel.setOnClickListener(config.getOnClickCancel() != null ? config.getOnClickCancel() : mOnClickDismissDialog); btnDialogCancel.setVisibility(config.isHideCancel() ? View.GONE : View.VISIBLE); try{ //不强制要求要有中间的线 View line = view.findViewById(R.id.line); if(line != null){ line.setVisibility(config.isHideCancel() ? View.GONE : View.VISIBLE); } }catch (Exception e){ } Button btnDialogOK = view.findViewById(config.getOkId()); setText(btnDialogOK,config.getOk()); btnDialogOK.setOnClickListener(config.getOnClickOk() != null ? config.getOnClickOk() : mOnClickDismissDialog); return view; } //------------------------------------------- private View.OnClickListener mOnClickDismissDialog = new View.OnClickListener() { @Override public void onClick(View v) { dismissDialog(); } }; private void setText(TextView tv,CharSequence text){ if(!TextUtils.isEmpty(text)){ tv.setText(text); } } //------------------------------------------- public void dismissDialogFragment(FragmentManager fragmentManager){ dismissDialogFragment(fragmentManager,mTag); mTag = null; } public void dismissDialogFragment(FragmentManager fragmentManager,String tag){ if(tag!=null){ DialogFragment dialogFragment = (DialogFragment) fragmentManager.findFragmentByTag(tag); dismissDialogFragment(dialogFragment); } } public void dismissDialogFragment(DialogFragment dialogFragment){ if(dialogFragment!=null){ dialogFragment.dismiss(); } } //------------------------------------------- /** * 显示DialogFragment * @param fragmentManager * @return */ public String showDialogFragment(FragmentManager fragmentManager,AppDialogConfig config){ AppDialogFragment dialogFragment = AppDialogFragment.newInstance(config); String tag = dialogFragment.getTag() !=null ? dialogFragment.getTag() : dialogFragment.getClass().getSimpleName(); showDialogFragment(fragmentManager,dialogFragment,tag); mTag = tag; return tag; } /** * 显示DialogFragment * @param fragmentManager * @param dialogFragment * @return */ public String showDialogFragment(FragmentManager fragmentManager,DialogFragment dialogFragment){ String tag = dialogFragment.getTag() !=null ? dialogFragment.getTag() : dialogFragment.getClass().getSimpleName(); showDialogFragment(fragmentManager,dialogFragment,tag); mTag = tag; return tag; } /** * 显示DialogFragment * @param fragmentManager * @param dialogFragment * @param tag * @return */ public String showDialogFragment(FragmentManager fragmentManager,DialogFragment dialogFragment, String tag) { dismissDialogFragment(fragmentManager); dialogFragment.show(fragmentManager,tag); mTag = tag; return tag; } //------------------------------------------- /** * 显示弹框 * @param context * @param config 弹框配置 {@link AppDialogConfig} */ public void showDialog(Context context,AppDialogConfig config){ showDialog(context,config,true); } /** * 显示弹框 * @param context * @param config 弹框配置 {@link AppDialogConfig} * @param isCancel 是否可取消(默认为true,false则拦截back键) */ public void showDialog(Context context,AppDialogConfig config,boolean isCancel){ showDialog(context,createAppDialogView(context,config),R.style.app_dialog,DEFAULT_WIDTH_RATIO,isCancel); } /** * 显示弹框 * @param context * @param contentView 弹框内容视图 */ public void showDialog(Context context,View contentView){ showDialog(context,contentView,DEFAULT_WIDTH_RATIO); } /** * 显示弹框 * @param context * @param contentView 弹框内容视图 * @param isCancel 是否可取消(默认为true,false则拦截back键) */ public void showDialog(Context context,View contentView,boolean isCancel){ showDialog(context,contentView,R.style.app_dialog,DEFAULT_WIDTH_RATIO,isCancel); } /** * 显示弹框 * @param context * @param contentView 弹框内容视图 * @param widthRatio 宽度比例,根据屏幕宽度计算得来 */ public void showDialog(Context context,View contentView,float widthRatio){ showDialog(context,contentView,widthRatio,true); } /** * 显示弹框 * @param context * @param contentView 弹框内容视图 * @param widthRatio 宽度比例,根据屏幕宽度计算得来 * @param isCancel 是否可取消(默认为true,false则拦截back键) */ public void showDialog(Context context,View contentView,float widthRatio,boolean isCancel){ showDialog(context,contentView,R.style.app_dialog,widthRatio,isCancel); } /** * 显示弹框 * @param context * @param contentView 弹框内容视图 * @param resId Dialog样式 * @param widthRatio 宽度比例,根据屏幕宽度计算得来 */ public void showDialog(Context context, View contentView, @StyleRes int resId, float widthRatio){ showDialog(context,contentView,resId,widthRatio,true); } /** * 显示弹框 * @param context * @param contentView 弹框内容视图 * @param resId Dialog样式 * @param widthRatio 宽度比例,根据屏幕宽度计算得来 * @param isCancel 是否可取消(默认为true,false则拦截back键) */ public void showDialog(Context context, View contentView, @StyleRes int resId, float widthRatio,final boolean isCancel){ dismissDialog(); mDialog = new Dialog(context,resId); mDialog.setContentView(contentView); mDialog.setCanceledOnTouchOutside(false); mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ if(isCancel){ dismissDialog(); } return true; } return false; } }); setDialogWindow(context,mDialog,widthRatio); mDialog.show(); } private void setDialogWindow(Context context,Dialog dialog,float widthRatio){ Window window = dialog.getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); lp.width = (int)(context.getResources().getDisplayMetrics().widthPixels * widthRatio); window.setAttributes(lp); } public void dismissDialog(){ dismissDialog(mDialog); } private void dismissDialog(Dialog dialog){ if(dialog!=null){ dialog.dismiss(); } } //------------------------------------------- }
<filename>client/src/components/Buttons/index.js import React from "react"; import { useHistory } from "react-router-dom"; import "./style.css"; import Row from "react-bootstrap/Row"; import Col from "react-bootstrap/Col"; import Button from "react-bootstrap/Button"; const Buttons = () => { const history = useHistory(); return ( <Row className="p-5 justify-content-center"> <Col md="4"> <Button block variant="none" className="mb-3 big-button" onClick={() => history.push("/create-post")} >Give Something</Button> </Col> <Col md="4"> <Button block variant="none" className="mb-3 big-button" onClick={() => history.push("/create-post")} >Ask for Something</Button> </Col> </Row> ) } export default Buttons
<filename>src/main/java/com/apeelingtech/worldcraft/entity/mob/BasicMob.java package com.apeelingtech.worldcraft.entity.mob; import com.apeelingtech.worldcraft.graphics.Sprite; import com.apeelingtech.worldcraft.level.Level; public class BasicMob extends Mob { public BasicMob(double spawnX, double spawnY, Level level) { super(Sprite.mobBasic, spawnX, spawnY, Sprite.mobBasic.getWidth(), Sprite.mobBasic.getHeight(), level); } }
<reponame>sagarc-contrail/contrail-controller # # Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. # """ This file contains implementation of inetconf interface for physical router configuration manager """ from ncclient import manager import copy import time import datetime from cStringIO import StringIO from dm_utils import DMUtils from device_api.juniper_common_xsd import * class PushConfigState(object): PUSH_STATE_INIT = 0 PUSH_STATE_SUCCESS = 1 PUSH_STATE_RETRY = 2 REPUSH_INTERVAL = 15 REPUSH_MAX_INTERVAL = 300 PUSH_DELAY_PER_KB = 0.01 PUSH_DELAY_MAX = 100 PUSH_DELAY_ENABLE = True @classmethod def set_repush_interval(cls, value): cls.REPUSH_INTERVAL = value # end set_repush_interval @classmethod def set_repush_max_interval(cls, value): cls.REPUSH_MAX_INTERVAL = value # end set_repush_max_interval @classmethod def set_push_delay_per_kb(cls, value): cls.PUSH_DELAY_PER_KB = value # end set_push_delay_per_kb @classmethod def set_push_delay_max(cls, value): cls.PUSH_DELAY_MAX = value # end set_push_delay_max @classmethod def set_push_delay_enable(cls, value): cls.PUSH_DELAY_ENABLE = value # end set_push_delay_enable @classmethod def get_repush_interval(cls): return cls.REPUSH_INTERVAL # end set_repush_interval @classmethod def get_repush_max_interval(cls): return cls.REPUSH_MAX_INTERVAL # end get_repush_max_interval @classmethod def get_push_delay_per_kb(cls): return cls.PUSH_DELAY_PER_KB # end get_push_delay_per_kb @classmethod def get_push_delay_max(cls): return cls.PUSH_DELAY_MAX # end get_push_delay_max @classmethod def get_push_delay_enable(cls): return cls.PUSH_DELAY_ENABLE # end get_push_delay_enable # end PushConfigState class PhysicalRouterConfig(object): # mapping from contrail family names to junos _FAMILY_MAP = { 'route-target': '', 'inet-vpn': FamilyInetVpn(unicast=''), 'inet6-vpn': FamilyInet6Vpn(unicast=''), 'e-vpn': FamilyEvpn(signaling='') } def __init__(self, management_ip, user_creds, vendor, product, logger=None): self.management_ip = management_ip self.user_creds = user_creds self.vendor = vendor self.product = product self.reset_bgp_config() self._logger = logger self.push_config_state = PushConfigState.PUSH_STATE_INIT self.commit_stats = { 'last_commit_time': '', 'last_commit_duration': '', 'commit_status_message': '', 'total_commits_sent_since_up': 0, } # end __init__ def update(self, management_ip, user_creds, vendor, product): self.management_ip = management_ip self.user_creds = user_creds self.vendor = vendor self.product = product # end update def get_commit_stats(self): return self.commit_stats # end get_commit_stats def retry(self): if self.push_config_state == PushConfigState.PUSH_STATE_RETRY: return True return False # end retry def get_xml_data(self, config): xml_data = StringIO() config.export(xml_data, 1) xml_str = xml_data.getvalue() return xml_str.replace("comment>", "junos:comment>", -1) # end get_xml_data def build_netconf_config(self, groups, operation='replace'): groups.set_name("__contrail__") configuraion = Configuration(groups=groups) groups.set_operation(operation) apply_groups = ApplyGroups(name="__contrail__") configuraion.set_apply_groups(apply_groups) if operation == "delete": apply_groups.set_operation(operation) conf = config(configuration=configuraion) return conf def send_netconf(self, new_config, default_operation="merge", operation="replace"): self.push_config_state = PushConfigState.PUSH_STATE_INIT start_time = None config_size = 0 try: with manager.connect(host=self.management_ip, port=22, username=self.user_creds['username'], password=self.user_creds['password'], unknown_host_cb=lambda x, y: True) as m: new_config = self.build_netconf_config(new_config, operation) config_str = self.get_xml_data(new_config) self._logger.info("\nsend netconf message: %s\n" % config_str) config_size = len(config_str) m.edit_config( target='candidate', config=config_str, test_option='test-then-set', default_operation=default_operation) self.commit_stats['total_commits_sent_since_up'] += 1 start_time = time.time() m.commit() end_time = time.time() self.commit_stats['commit_status_message'] = 'success' self.commit_stats['last_commit_time'] = \ datetime.datetime.fromtimestamp( end_time).strftime('%Y-%m-%d %H:%M:%S') self.commit_stats['last_commit_duration'] = str( end_time - start_time) self.push_config_state = PushConfigState.PUSH_STATE_SUCCESS except Exception as e: if self._logger: self._logger.error("Router %s: %s" % (self.management_ip, e.message)) self.commit_stats[ 'commit_status_message'] = 'failed to apply config,\ router response: ' + e.message if start_time is not None: self.commit_stats['last_commit_time'] = \ datetime.datetime.fromtimestamp( start_time).strftime('%Y-%m-%d %H:%M:%S') self.commit_stats['last_commit_duration'] = str( time.time() - start_time) self.push_config_state = PushConfigState.PUSH_STATE_RETRY return config_size # end send_config def add_pnf_logical_interface(self, junos_interface): if not self.interfaces_config: self.interfaces_config = Interfaces(comment=DMUtils.interfaces_comment()) family = Family(inet=FamilyInet([Address(name=junos_interface.ip)])) unit = Unit(name=junos_interface.unit, vlan_id=junos_interface.vlan_tag, family=family) interface = Interface(name=junos_interface.ifd_name, unit=unit) self.interfaces_config.add_interface(interface) # end add_pnf_logical_interface def add_lo0_unit_0_interface(self): if not self.bgp_params or not self.bgp_params.get('address'): return if not self.interfaces_config: self.interfaces_config = Interfaces(comment=DMUtils.interfaces_comment()) lo_intf = Interface(name="lo0") self.interfaces_config.add_interface(lo_intf) fam_inet = FamilyInet(address=[Address(name=self.bgp_params['address'] + "/32", primary='', preferred='')]) intf_unit = Unit(name="0", family=Family(inet=fam_inet), comment=DMUtils.lo0_unit_0_comment()) lo_intf.add_unit(intf_unit) # end add_lo0_unit_0_interface def add_static_routes(self, parent, static_routes): static_config = parent.get_static() if not static_config: static_config = Static() parent.set_static(static_config) for dest, next_hops in static_routes.items(): route_config = Route(name=dest) for next_hop in next_hops: next_hop_str = next_hop.get("next-hop") preference = next_hop.get("preference") if not next_hop_str: continue if preference: route_config.set_qualified_next_hop(QualifiedNextHop( name=next_hop_str, preference=str(preference))) else: route_config.set_next_hop(next_hop_str) static_config.add_route(route_config) # end add_static_routes def add_dynamic_tunnels(self, tunnel_source_ip, ip_fabric_nets, bgp_router_ips): dynamic_tunnel = DynamicTunnel(name=DMUtils.dynamic_tunnel_name(self.get_asn()), source_address=tunnel_source_ip, gre='') if ip_fabric_nets is not None: for subnet in ip_fabric_nets.get("subnet", []): dest_net = subnet['ip_prefix'] + '/' + str(subnet['ip_prefix_len']) dynamic_tunnel.add_destination_networks( DestinationNetworks(name=dest_net, comment=DMUtils.ip_fabric_subnet_comment())) for r_name, bgp_router_ip in bgp_router_ips.items(): dynamic_tunnel.add_destination_networks( DestinationNetworks(name=bgp_router_ip + '/32', comment=DMUtils.bgp_router_subnet_comment(r_name))) dynamic_tunnels = DynamicTunnels() dynamic_tunnels.add_dynamic_tunnel(dynamic_tunnel) if self.global_routing_options_config is None: self.global_routing_options_config = RoutingOptions(comment=DMUtils.routing_options_comment()) self.global_routing_options_config.set_dynamic_tunnels(dynamic_tunnels) # end add_dynamic_tunnels def add_inet_public_vrf_filter(self, forwarding_options_config, firewall_config, inet_type): fo = Family() inet_filter = InetFilter(input=DMUtils.make_public_vrf_filter_name(inet_type)) if inet_type == 'inet6': fo.set_inet6(FamilyInet6(filter=inet_filter)) else: fo.set_inet(FamilyInet(filter=inet_filter)) forwarding_options_config.add_family(fo) f = FirewallFilter(name=DMUtils.make_public_vrf_filter_name(inet_type)) f.set_comment(DMUtils.public_vrf_filter_comment()) ff = firewall_config.get_family() if not ff: ff = FirewallFamily() firewall_config.set_family(ff) if inet_type == 'inet6': inet6 = ff.get_inet6() if not inet6: inet6 = FirewallInet() ff.set_inet6(inet6) inet6.add_filter(f) else: inet = ff.get_inet() if not inet: inet = FirewallInet() ff.set_inet(inet) inet.add_filter(f) term = Term(name="default-term", then=Then(accept='')) f.add_term(term) return f # end add_inet_public_vrf_filter def add_inet_filter_term(self, ri_name, prefixes, inet_type): if inet_type == 'inet6': prefixes = DMUtils.get_ipv6_prefixes(prefixes) else: prefixes = DMUtils.get_ipv4_prefixes(prefixes) from_ = From() for prefix in prefixes: from_.add_destination_address(prefix) then_ = Then() then_.add_routing_instance(ri_name) return Term(name=DMUtils.make_vrf_term_name(ri_name), fromxx=from_, then=then_) # end add_inet_filter_term ''' ri_name: routing instance name to be configured on mx is_l2: a flag used to indicate routing instance type, i.e : l2 or l3 is_l2_l3: VN forwarding mode is of type 'l2_l3' or not import/export targets: routing instance import, export targets prefixes: for l3 vrf static routes and for public vrf filter terms gateways: for l2 evpn, bug#1395944 router_external: this indicates the routing instance configured is for the public network interfaces: logical interfaces to be part of vrf fip_map: contrail instance ip to floating-ip map, used for snat & floating ip support network_id : this is used for configuraing irb interfaces static_routes: this is used for add PNF vrf static routes no_vrf_table_label: if this is set to True will not generate vrf table label knob restrict_proxy_arp: proxy-arp restriction config is generated for irb interfaces only if vn is external and has fip map highest_enapsulation_priority: highest encapsulation configured ''' def add_routing_instance(self, ri_conf): ri_name = ri_conf.get("ri_name") vn = ri_conf.get("vn") is_l2 = ri_conf.get("is_l2", False) is_l2_l3 = ri_conf.get("is_l2_l3", False) import_targets = ri_conf.get("import_targets", set()) export_targets = ri_conf.get("export_targets", set()) prefixes = ri_conf.get("prefixes", []) gateways = ri_conf.get("gateways", []) router_external = ri_conf.get("router_external", False) interfaces = ri_conf.get("interfaces", []) vni = ri_conf.get("vni", None) fip_map = ri_conf.get("fip_map", None) network_id = ri_conf.get("network_id", None) static_routes = ri_conf.get("static_routes", {}) no_vrf_table_label = ri_conf.get("no_vrf_table_label", False) restrict_proxy_arp = ri_conf.get("restrict_proxy_arp", False) highest_enapsulation_priority = \ ri_conf.get("highest_enapsulation_priority") or "MPLSoGRE" self.routing_instances[ri_name] = ri_conf ri_config = self.ri_config or RoutingInstances(comment=DMUtils.routing_instances_comment()) policy_config = self.policy_config or PolicyOptions(comment=DMUtils.policy_options_comment()) ri = Instance(name=ri_name) if vn: is_nat = True if fip_map else False ri.set_comment(DMUtils.vn_ri_comment(vn, is_l2, is_l2_l3, is_nat)) ri_config.add_instance(ri) ri_opt = None if router_external and is_l2 == False: ri_opt = RoutingInstanceRoutingOptions( static=Static(route=[Route(name="0.0.0.0/0", next_table="inet.0", comment=DMUtils.public_vrf_route_comment())])) ri.set_routing_options(ri_opt) # for both l2 and l3 ri.set_vrf_import(DMUtils.make_import_name(ri_name)) ri.set_vrf_export(DMUtils.make_export_name(ri_name)) has_ipv6_prefixes = DMUtils.has_ipv6_prefixes(prefixes) has_ipv4_prefixes = DMUtils.has_ipv4_prefixes(prefixes) if not is_l2: if ri_opt is None: ri_opt = RoutingInstanceRoutingOptions() ri.set_routing_options(ri_opt) if prefixes and fip_map is None: static_config = ri_opt.get_static() if not static_config: static_config = Static() ri_opt.set_static(static_config) rib_config_v6 = None static_config_v6 = None for prefix in prefixes: if ':' in prefix and not rib_config_v6: static_config_v6 = Static() rib_config_v6 = RIB(name=ri_name + ".inet6.0") rib_config_v6.set_static(static_config_v6) ri_opt.set_rib(rib_config_v6) if ':' in prefix: static_config_v6.add_route(Route(name=prefix, discard='')) else: static_config.add_route(Route(name=prefix, discard='')) if router_external: self.add_to_global_ri_opts(prefix) ri.set_instance_type("vrf") if not no_vrf_table_label: ri.set_vrf_table_label('') # only for l3 if fip_map is None: for interface in interfaces: ri.add_interface(Interface(name=interface.name)) if static_routes: self.add_static_routes(ri_opt, static_routes) if has_ipv4_prefixes: ri_opt.set_auto_export(AutoExport(family=Family(inet=FamilyInet(unicast='')))) if has_ipv6_prefixes: ri_opt.set_auto_export(AutoExport(family=Family(inet6=FamilyInet6(unicast='')))) else: if highest_enapsulation_priority == "VXLAN": ri.set_instance_type("virtual-switch") elif highest_enapsulation_priority in ["MPLSoGRE", "MPLSoUDP"]: ri.set_instance_type("evpn") if fip_map is not None: if ri_opt is None: ri_opt = RoutingInstanceRoutingOptions() ri.set_routing_options(ri_opt) static_config = ri_opt.get_static() if not static_config: static_config = Static() ri_opt.set_static(static_config) static_config.add_route(Route(name="0.0.0.0/0", next_hop=interfaces[0].name, comment=DMUtils.fip_ingress_comment())) ri.add_interface(Interface(name=interfaces[0].name)) public_vrf_ips = {} for pip in fip_map.values(): if pip["vrf_name"] not in public_vrf_ips: public_vrf_ips[pip["vrf_name"]] = set() public_vrf_ips[pip["vrf_name"]].add(pip["floating_ip"]) for public_vrf, fips in public_vrf_ips.items(): ri_public = Instance(name=public_vrf) ri_config.add_instance(ri_public) ri_public.add_interface(Interface(name=interfaces[1].name)) ri_opt = RoutingInstanceRoutingOptions() ri_public.set_routing_options(ri_opt) static_config = Static() ri_opt.set_static(static_config) for fip in fips: static_config.add_route(Route(name=fip + "/32", next_hop=interfaces[1].name, comment=DMUtils.fip_egress_comment())) # add policies for export route targets ps = PolicyStatement(name=DMUtils.make_export_name(ri_name)) ps.set_comment(DMUtils.vn_ps_comment(vn, "Export")) then = Then() ps.set_term(Term(name="t1", then=then)) for route_target in export_targets: comm = Community(add='', community_name=DMUtils.make_community_name(route_target)) then.add_community(comm) if fip_map is not None: # for nat instance then.set_reject('') else: then.set_accept('') policy_config.add_policy_statement(ps) # add policies for import route targets ps = PolicyStatement(name=DMUtils.make_import_name(ri_name)) ps.set_comment(DMUtils.vn_ps_comment(vn, "Import")) from_ = From() term = Term(name="t1", fromxx=from_) ps.set_term(term) for route_target in import_targets: from_.add_community(DMUtils.make_community_name(route_target)) term.set_then(Then(accept='')) ps.set_then(Then(reject='')) policy_config.add_policy_statement(ps) # add firewall config for public VRF forwarding_options_config = self.forwarding_options_config firewall_config = self.firewall_config if router_external and is_l2 == False: forwarding_options_config = (self.forwarding_options_config or ForwardingOptions(DMUtils.forwarding_options_comment())) firewall_config = self.firewall_config or Firewall(DMUtils.firewall_comment()) if has_ipv4_prefixes and not self.inet4_forwarding_filter: #create single instance inet4 filter self.inet4_forwarding_filter = self.add_inet_public_vrf_filter( forwarding_options_config, firewall_config, "inet") if has_ipv6_prefixes and not self.inet6_forwarding_filter: #create single instance inet6 filter self.inet6_forwarding_filter = self.add_inet_public_vrf_filter( forwarding_options_config, firewall_config, "inet6") if has_ipv4_prefixes: #add terms to inet4 filter term = self.add_inet_filter_term(ri_name, prefixes, "inet4") # insert before the last term terms = self.inet4_forwarding_filter.get_term() terms = [term] + (terms or []) self.inet4_forwarding_filter.set_term(terms) if has_ipv6_prefixes: #add terms to inet6 filter term = self.add_inet_filter_term(ri_name, prefixes, "inet6") # insert before the last term terms = self.inet6_forwarding_filter.get_term() terms = [term] + (terms or []) self.inet6_forwarding_filter.set_term(terms) if fip_map is not None: firewall_config = firewall_config or Firewall(DMUtils.firewall_comment()) f = FirewallFilter(name=DMUtils.make_private_vrf_filter_name(ri_name)) f.set_comment(DMUtils.vn_firewall_comment(vn, "private")) ff = firewall_config.get_family() if not ff: ff = FirewallFamily() firewall_config.set_family(ff) inet = ff.get_inet() if not inet: inet = FirewallInet() ff.set_inet(inet) inet.add_filter(f) term = Term(name=DMUtils.make_vrf_term_name(ri_name)) from_ = From() for fip_user_ip in fip_map.keys(): from_.add_source_address(fip_user_ip) term.set_from(from_) term.set_then(Then(routing_instance=[ri_name])) f.add_term(term) term = Term(name="default-term", then=Then(accept='')) f.add_term(term) interfaces_config = self.interfaces_config or Interfaces(comment=DMUtils.interfaces_comment()) irb_intf = Interface(name="irb") interfaces_config.add_interface(irb_intf) intf_unit = Unit(name=str(network_id), comment=DMUtils.vn_irb_fip_inet_comment(vn)) if restrict_proxy_arp: intf_unit.set_proxy_arp(ProxyArp(restricted='')) inet = FamilyInet() inet.set_filter(InetFilter(input=DMUtils.make_private_vrf_filter_name(ri_name))) intf_unit.set_family(Family(inet=inet)) irb_intf.add_unit(intf_unit) # add L2 EVPN and BD config bd_config = None interfaces_config = self.interfaces_config proto_config = self.proto_config if (is_l2 and vni is not None and self.is_family_configured(self.bgp_params, "e-vpn")): ri.set_vtep_source_interface("lo0.0") if highest_enapsulation_priority == "VXLAN": bd_config = BridgeDomains() ri.set_bridge_domains(bd_config) bd = Domain(name=DMUtils.make_bridge_name(vni), vlan_id='none', vxlan=VXLan(vni=vni)) bd.set_comment(DMUtils.vn_bd_comment(vn, "VXLAN")) bd_config.add_domain(bd) for interface in interfaces: bd.add_interface(Interface(name=interface.name)) if is_l2_l3: # network_id is unique, hence irb bd.set_routing_interface("irb." + str(network_id)) ri.set_protocols(RoutingInstanceProtocols( evpn=Evpn(encapsulation='vxlan', extended_vni_list='all'))) elif highest_enapsulation_priority in ["MPLSoGRE", "MPLSoUDP"]: ri.set_vlan_id('none') if is_l2_l3: # network_id is unique, hence irb ri.set_routing_interface("irb." + str(network_id)) evpn = Evpn() evpn.set_comment(DMUtils.vn_evpn_comment(vn, highest_enapsulation_priority)) for interface in interfaces: evpn.add_interface(Interface(name=interface.name)) ri.set_protocols(RoutingInstanceProtocols(evpn=evpn)) interfaces_config = self.interfaces_config or Interfaces(comment=DMUtils.interfaces_comment()) if is_l2_l3: irb_intf = Interface(name='irb', gratuitous_arp_reply='') interfaces_config.add_interface(irb_intf) if gateways is not None: intf_unit = Unit(name=str(network_id), comment=DMUtils.vn_irb_comment(vn, False, is_l2_l3)) irb_intf.add_unit(intf_unit) family = Family() intf_unit.set_family(family) inet = None inet6 = None for (irb_ip, gateway) in gateways: if ':' in irb_ip: if not inet6: inet6 = FamilyInet6() family.set_inet6(inet6) addr = Address() inet6.add_address(addr) else: if not inet: inet = FamilyInet() family.set_inet(inet) addr = Address() inet.add_address(addr) addr.set_name(irb_ip) addr.set_comment(DMUtils.irb_ip_comment(irb_ip)) if len(gateway) and gateway != '0.0.0.0': addr.set_virtual_gateway_address(gateway) self.build_l2_evpn_interface_config(interfaces_config, interfaces, vn) if (not is_l2 and not is_l2_l3 and gateways): interfaces_config = self.interfaces_config or Interfaces(comment=DMUtils.interfaces_comment()) ifl_num = str(1000 + int(network_id)) lo_intf = Interface(name="lo0") interfaces_config.add_interface(lo_intf) intf_unit = Unit(name=ifl_num, comment=DMUtils.l3_lo_intf_comment(vn)) lo_intf.add_unit(intf_unit) family = Family() intf_unit.set_family(family) inet = None inet6 = None for (lo_ip, _) in gateways: (ip, _) = lo_ip.split('/') if ':' in lo_ip: if not inet6: inet6 = FamilyInet6() family.set_inet6(inet6) addr = Address() inet6.add_address(addr) lo_ip = ip + '/' + '128' else: if not inet: inet = FamilyInet() family.set_inet(inet) addr = Address() inet.add_address(addr) lo_ip = ip + '/' + '32' addr.set_name(lo_ip) addr.set_comment(DMUtils.lo0_ip_comment(lo0_ip)) ri.add_interface(Interface(name="lo0." + ifl_num, comment=DMUtils.lo0_ri_intf_comment(vn))) # fip services config services_config = self.services_config if fip_map is not None: services_config = self.services_config or Services() services_config.set_comment(DMUtils.services_comment()) service_name = DMUtils.make_services_set_name(ri_name) service_set = ServiceSet(name=service_name) service_set.set_comment(DMUtils.service_set_comment(vn)) services_config.add_service_set(service_set) nat_rule = NATRules(name=service_name + "-sn-rule") service_set.add_nat_rules(NATRules(name=DMUtils.make_snat_rule_name(ri_name), comment=DMUtils.service_set_nat_rule_comment(vn, "SNAT"))) service_set.add_nat_rules(NATRules(name=DMUtils.make_dnat_rule_name(ri_name), comment=DMUtils.service_set_nat_rule_comment(vn, "DNAT"))) next_hop_service = NextHopService(inside_service_interface = interfaces[0].name, outside_service_interface = interfaces[1].name) service_set.set_next_hop_service(next_hop_service) nat = NAT(allow_overlapping_nat_pools='') nat.set_comment(DMUtils.nat_comment()) services_config.add_nat(nat) snat_rule = Rule(name=DMUtils.make_snat_rule_name(ri_name), match_direction="input") snat_rule.set_comment(DMUtils.snat_rule_comment()) nat.add_rule(snat_rule) dnat_rule = Rule(name=DMUtils.make_dnat_rule_name(ri_name), match_direction="output") dnat_rule.set_comment(DMUtils.dnat_rule_comment()) nat.add_rule(dnat_rule) for pip, fip_vn in fip_map.items(): fip = fip_vn["floating_ip"] term = Term(name=DMUtils.make_ip_term_name(pip)) snat_rule.set_term(term) # private ip from_ = From(source_address=[pip + "/32"]) term.set_from(from_) # public ip then_ = Then() term.set_then(then_) translated = Translated(source_prefix=fip + "/32", translation_type=TranslationType(basic_nat44='')) then_.set_translated(translated) term = Term(name=DMUtils.make_ip_term_name(fip)) dnat_rule.set_term(term) # public ip from_ = From(destination_address=[fip + "/32"]) term.set_from(from_) # private ip then_ = Then() term.set_then(then_) translated = Translated(destination_prefix=pip + "/32", translation_type=TranslationType(dnat_44='')) then_.set_translated(translated) interfaces_config = self.interfaces_config or Interfaces(comment=DMUtils.interfaces_comment()) si_intf = Interface(name=interfaces[0].ifd_name, comment=DMUtils.service_ifd_comment()) interfaces_config.add_interface(si_intf) intf_unit = Unit(name=interfaces[0].unit, comment=DMUtils.service_intf_comment("Ingress")) si_intf.add_unit(intf_unit) family = Family(inet=FamilyInet()) intf_unit.set_family(family) intf_unit.set_service_domain("inside") intf_unit = Unit(name=interfaces[1].unit, comment=DMUtils.service_intf_comment("Egress")) si_intf.add_unit(intf_unit) family = Family(inet=FamilyInet()) intf_unit.set_family(family) intf_unit.set_service_domain("outside") self.forwarding_options_config = forwarding_options_config self.firewall_config = firewall_config self.policy_config = policy_config self.proto_config = proto_config self.interfaces_config = interfaces_config self.services_config = services_config self.route_targets |= import_targets | export_targets self.ri_config = ri_config # end add_routing_instance def build_l2_evpn_interface_config(self, interfaces_config, interfaces, vn=None): ifd_map = {} for interface in interfaces: ifd_map.setdefault(interface.ifd_name, []).append(interface) for ifd_name, interface_list in ifd_map.items(): intf = Interface(name=ifd_name) interfaces_config.add_interface(intf) if interface_list[0].is_untagged(): if (len(interface_list) > 1): self._logger.error( "invalid logical interfaces config for ifd %s" % ( ifd_name)) continue intf.set_encapsulation("ethernet-bridge") intf.add_unit(Unit(name=interface_list[0].unit, comment=DMUtils.l2_evpn_intf_unit_comment(vn, False), family=Family(bridge=''))) else: intf.set_flexible_vlan_tagging('') intf.set_encapsulation("flexible-ethernet-services") for interface in interface_list: intf.add_unit(Unit(name=interface.unit, comment=DMUtils.l2_evpn_intf_unit_comment(vn, True, interface.vlan_tag), encapsulation='vlan-bridge', vlan_id=str(interface.vlan_tag))) # end build_l2_evpn_interface_config def set_global_routing_options(self, bgp_params): if bgp_params['address'] is not None: if not self.global_routing_options_config: self.global_routing_options_config = RoutingOptions(comment=DMUtils.routing_options_comment()) self.global_routing_options_config.set_router_id(bgp_params['address']) # end set_global_routing_options def add_to_global_ri_opts(self, prefix): if not prefix: return if self.global_routing_options_config is None: self.global_routing_options_config = RoutingOptions(comment=DMUtils.routing_options_comment()) static_config = Static() if ':' in prefix: rib_config_v6 = RIB(name='inet6.0') rib_config_v6.set_static(static_config) self.global_routing_options_config.add_rib(rib_config_v6) else: self.global_routing_options_config.add_static(static_config) static_config.add_route(Route(name=prefix, discard='')) # end add_to_global_ri_opts def is_family_configured(self, params, family_name): if params is None or params.get('address_families') is None: return False families = params['address_families'].get('family', []) if family_name in families: return True return False def add_families(self, parent, params): if params.get('address_families') is None: return families = params['address_families'].get('family', []) if not families: return family_etree = Family() parent.set_family(family_etree) for family in families: fam = family.replace('-', '_') if family in ['e-vpn', 'e_vpn']: fam = 'evpn' if family in self._FAMILY_MAP: getattr(family_etree, "set_" + fam)(self._FAMILY_MAP[family]) else: getattr(family_etree, "set_" + fam)('') # end add_families def add_bgp_auth_config(self, bgp_config, bgp_params): if bgp_params.get('auth_data') is None: return keys = bgp_params['auth_data'].get('key_items', []) if len(keys) > 0: bgp_config.set_authentication_key(keys[0].get('key')) def add_bgp_hold_time_config(self, bgp_config, bgp_params): if bgp_params.get('hold_time') is None: return bgp_config.set_hold_time(bgp_params.get('hold_time')) def set_bgp_config(self, params, bgp_obj): self.bgp_params = params self.bgp_obj = bgp_obj # end set_bgp_config def _get_bgp_config_xml(self, external=False): if self.bgp_params is None: return None bgp_group = BgpGroup() bgp_group.set_comment(DMUtils.bgp_group_comment(self.bgp_obj)) if external: bgp_group.set_name(DMUtils.make_bgp_group_name(self.get_asn(), True)) bgp_group.set_type('external') bgp_group.set_multihop('') else: bgp_group.set_name(DMUtils.make_bgp_group_name(self.get_asn(), False)) bgp_group.set_type('internal') bgp_group.set_local_address(self.bgp_params['address']) self.add_families(bgp_group, self.bgp_params) self.add_bgp_auth_config(bgp_group, self.bgp_params) self.add_bgp_hold_time_config(bgp_group, self.bgp_params) return bgp_group # end _get_bgp_config_xml def reset_bgp_config(self): self.routing_instances = {} self.bgp_params = None self.bgp_obj = None self.ri_config = None self.interfaces_config = None self.services_config = None self.policy_config = None self.firewall_config = None self.inet4_forwarding_filter = None self.inet6_forwarding_filter = None self.forwarding_options_config = None self.global_routing_options_config = None self.proto_config = None self.route_targets = set() self.bgp_peers = {} self.external_peers = {} # ene reset_bgp_config def delete_bgp_config(self): self.reset_bgp_config() self.send_netconf(Groups(), default_operation="none", operation="delete") # end delete_config def add_bgp_peer(self, router, params, attr, external, peer): peer_data = {} peer_data['params'] = params peer_data['attr'] = attr peer_data['obj'] = peer if external: self.external_peers[router] = peer_data else: self.bgp_peers[router] = peer_data # end add_peer def _get_neighbor_config_xml(self, bgp_config, peers): for peer, peer_data in peers.items(): obj = peer_data.get('obj') params = peer_data.get('params', {}) attr = peer_data.get('attr', {}) nbr = BgpGroup(name=peer) nbr.set_comment(DMUtils.bgp_group_comment(obj)) bgp_config.add_neighbor(nbr) bgp_sessions = attr.get('session') if bgp_sessions: # for now assume only one session session_attrs = bgp_sessions[0].get('attributes', []) for session_attr in session_attrs: # For not, only consider the attribute if bgp-router is # not specified if session_attr.get('bgp_router') is None: self.add_families(nbr, session_attr) self.add_bgp_auth_config(nbr, session_attr) break peer_as = params.get('local_autonomous_system') or params.get('autonomous_system') nbr.set_peer_as(peer_as) # end _get_neighbor_config_xml def get_asn(self): return self.bgp_params.get('local_autonomous_system') or self.bgp_params.get('autonomous_system') def set_as_config(self): if self.global_routing_options_config is None: self.global_routing_options_config = RoutingOptions(comment=DMUtils.routing_options_comment()) self.global_routing_options_config.set_route_distinguisher_id(self.bgp_params['identifier']) self.global_routing_options_config.set_autonomous_system(str(self.get_asn())) # end set_as_config def set_route_targets_config(self): if self.policy_config is None: self.policy_config = PolicyOptions(comment=DMUtils.policy_options_comment()) for route_target in self.route_targets: comm = CommunityType(name=DMUtils.make_community_name(route_target), members=route_target) self.policy_config.add_community(comm) # end set_route_targets_config def set_bgp_group_config(self): bgp_config = self._get_bgp_config_xml() if bgp_config is None: return False if self.proto_config is None: self.proto_config = Protocols(comment=DMUtils.protocols_comment()) bgp = Bgp() self.proto_config.set_bgp(bgp) bgp.add_group(bgp_config) self._get_neighbor_config_xml(bgp_config, self.bgp_peers) if self.external_peers is not None: ext_grp_config = self._get_bgp_config_xml(True) bgp.add_group(ext_grp_config) self._get_neighbor_config_xml(ext_grp_config, self.external_peers) return True # end set_bgp_group_config def send_bgp_config(self): if not self.set_bgp_group_config(): return 0 self.set_as_config() self.set_route_targets_config() groups = Groups() groups.set_comment(DMUtils.groups_comment()) groups.set_routing_instances(self.ri_config) groups.set_interfaces(self.interfaces_config) groups.set_services(self.services_config) groups.set_policy_options(self.policy_config) groups.set_firewall(self.firewall_config) groups.set_forwarding_options(self.forwarding_options_config) groups.set_routing_options(self.global_routing_options_config) groups.set_protocols(self.proto_config) return self.send_netconf(groups) # end send_bgp_config # end PhycalRouterConfig class JunosInterface(object): def __init__(self, if_name, if_type, if_vlan_tag=0, if_ip=None): self.name = if_name self.if_type = if_type self.vlan_tag = if_vlan_tag ifparts = if_name.split('.') self.ifd_name = ifparts[0] self.unit = ifparts[1] self.ip = if_ip # end __init__ def is_untagged(self): if not self.vlan_tag: return True return False # end is_untagged # end JunosInterface
<gh_stars>100-1000 'use strict'; const path = require('path'); const packageJson = require(path.join(process.cwd(), 'package.json')); module.exports = { 'Smoketest'(browser) { browser .url(`${browser.launchUrl}/`) .waitForElementVisible('body', 1000) .assert.containsText('body', packageJson.name) .end(); } };
#!/bin/bash fw_depends resin leiningen
import sys import global_config import logging def __execute(args): # Configure logging global_config.config_logging('../log/app.log') # Perform action based on command-line arguments if len(args) < 1: print("No command-line arguments provided") else: action = args[0] if action == "action1": # Perform action 1 logging.info("Executing action 1") elif action == "action2": # Perform action 2 logging.info("Executing action 2") else: logging.error("Invalid action specified") if __name__ == "__main__": '''Program entrance.''' __execute(sys.argv[1:])
""" A program to convert a decimal number to a binary number """ def decimal_to_bin(decimal): """ Convert a decimal number to a binary number """ binary = [] while(decimal > 0): binary.append(decimal % 2) decimal = decimal // 2 binary.reverse() return binary if __name__ == '__main__': decimal = 74 print(decimal_to_bin(decimal))
#!/usr/bin/env bash machine_list=$1 what=$2 where=$3 for machine in `cat $machine_list` do scp $what $machine:$where done
using System; using System.Collections.Generic; namespace CommonAlgo.CrackingTheCodingInterview { public class AnimalQueue { private readonly List<Cat> _cats = new List<Cat>(); private readonly List<Dog> _dogs = new List<Dog>(); private int _order; public int Count { get { return _dogs.Count + _cats.Count; } } public void Enqueue(Animal animal) { animal.Order = _order++; if (animal is Cat) { _cats.Add((Cat)animal); } else if (animal is Dog) { _dogs.Add((Dog)animal); } else { throw new ArgumentException("Invalid animal type"); } } public Animal DequeueAny() { if (_dogs.Count == 0 && _cats.Count == 0) { throw new InvalidOperationException("No animals in the queue"); } if (_dogs.Count == 0) { return DequeueCat(); } else if (_cats.Count == 0) { return DequeueDog(); } if (_dogs[0].Order < _cats[0].Order) { return DequeueDog(); } else { return DequeueCat(); } } public Cat DequeueCat() { if (_cats.Count == 0) { throw new InvalidOperationException("No cats in the queue"); } Cat cat = _cats[0]; _cats.RemoveAt(0); return cat; } public Dog DequeueDog() { if (_dogs.Count == 0) { throw new InvalidOperationException("No dogs in the queue"); } Dog dog = _dogs[0]; _dogs.RemoveAt(0); return dog; } } public class Animal { public int Order { get; set; } } public class Cat : Animal { // Cat-specific properties and methods can be added here } public class Dog : Animal { // Dog-specific properties and methods can be added here } }
#!/bin/sh for i in $(cat ~/dotfiles/.lists/extensions.list) do code --install-extension $i done
import Faker from 'faker' import { v4 as uuid } from 'uuid' import { isPeerError } from '../peer/errors' import { Peer } from '../peer/model' import { CreateOptions, HttpOptions, PeerService } from '../peer/service' import { randomAsset } from './asset' type BuildOptions = Omit<Partial<CreateOptions>, 'http'> & { http?: Partial<HttpOptions> } export class PeerFactory { public constructor(private peers: PeerService) {} public async build(options: BuildOptions = {}): Promise<Peer> { const peerOptions: CreateOptions = { asset: options.asset || randomAsset(), http: { outgoing: options.http?.outgoing || { authToken: <PASSWORD>.string(32), endpoint: Faker.internet.url() } }, staticIlpAddress: options.staticIlpAddress || 'test.' + uuid() } if (options.http?.incoming) { peerOptions.http.incoming = options.http.incoming } if (options.maxPacketAmount) { peerOptions.maxPacketAmount = options.maxPacketAmount } const peer = await this.peers.create(peerOptions) if (isPeerError(peer)) { throw new Error('unable to create peer, err=' + peer) } return peer } }
config() { NEW="$1" OLD="$(dirname $NEW)/$(basename $NEW .new)" # If there's no config file by that name, mv it over: if [ ! -r $OLD ]; then mv $NEW $OLD elif [ "$(cat $OLD | md5sum)" = "$(cat $NEW | md5sum)" ]; then # toss the redundant copy rm $NEW fi # Otherwise, we leave the .new copy for the admin to consider... } config etc/ftpcloudfs.conf.new
#!/bin/sh # Copyright 2017 The Nuclio 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. # @nuclio.configure # # function.yaml: # metadata: # name: parser # spec: # runtime: shell # handler: parser.sh:main # build: # commands: # - apk --update --no-cache add jq # # triggers: # incrementor_http: # maxWorkers: 4 # kind: "http" # `jq .return_this`: '{"return_this": "aaaa", "foo": 123}' -> "aaaa"\n (with parenthesis and newline) # tr -d \"\\n: "aaaa"\n -> aaaa jq .return_this | tr -d \"\\n
/** * @module */ /** * Extrait le titre d'une vidéo Vimeo. * * @param {string} videoId L'identifiant de la vidéo Vimeo. * @param {string|undefined} hash L'éventuel <em>hash</em> pour accéder à une * vidéo non-listée. * @returns {Promise<string>} Une promesse contenant le titre. */ export const extract = async function (videoId, hash) { const response = await fetch(`https://vimeo.com/${videoId}` + (undefined === hash ? "" : `/${hash}`)); const text = await response.text(); const doc = new DOMParser().parseFromString(text, "text/html"); return doc.querySelector(`meta[property="og:title"]`).content; };
#! /bin/bash cd $(dirname "$0") running="$(forever list | grep bot_commands.js)" echo $running if [ "$running" != "" ] then echo "bot is running." else echo "bot is not running, starting.." if [ "$1" == "production" ] then echo "running production bot" # forever start bot_commands.js npm run foreverproductionbot else # forever start bot_commands.js npm run foreverbot fi echo "done! Bot is running now!" fi # you can check that is bot running and if not this script will restart it. (remove test at the end for production) # by adding this to crontab (restarts bot on sundays 12:00 if it's down.): # 00 12 * * 0 cd ~/git/telegrambot/ && ./check_bot_is_running test
#! /usr/bin/env bash set -e # exit on first error # Copy over basic configuration files cp /home/user/skynet-webportal/setup-scripts/support/tmux.conf /home/user/.tmux.conf cp /home/user/skynet-webportal/setup-scripts/support/bashrc /home/user/.bashrc source /home/user/.bashrc # Add SSH keys and set SSH configs sudo cp /home/user/skynet-webportal/setup-scripts/support/ssh_config /etc/ssh/ssh_config mkdir -p /home/user/.ssh # cat /home/user/skynet-webportal/setup-scripts/support/authorized_keys >> /home/user/.ssh/authorized_keys # Install apt packages sudo apt-get update sudo apt-get -y install ufw tmux ranger htop nload gcc g++ make git vim unzip curl awscli # Setup GIT credentials (so commands like git stash would work) git config --global user.email "devs@nebulous.tech" git config --global user.name "Sia Dev" # Setup firewall sudo ufw --force enable # --force to make it non-interactive sudo ufw logging low # enable logging for debugging purpose: tail -f /var/log/ufw.log sudo ufw allow ssh # allow ssh connection to server sudo ufw allow 80,443/tcp # allow http and https ports # OPTIONAL: terminfo for alacritty terminal via ssh # If you don't use the alacritty terminal you can remove this step. wget -c https://raw.githubusercontent.com/alacritty/alacritty/master/extra/alacritty.info sudo tic -xe alacritty,alacritty-direct alacritty.info rm alacritty.info # Set up file limits - siad uses a lot so we need to adjust so it doesn't choke up sudo cp /home/user/skynet-webportal/setup-scripts/support/limits.conf /etc/security/limits.conf # Set UTC timezone so all of the servers report the same time sudo timedatectl set-timezone UTC
const express = require('express'); const cors = require('cors'); const { appPort } = require('./config/config'); const { addLog } = require('./services/store/logService'); const writeLogs = require('./middleware/writeLogs'); const usersRoutes = require('./routes/users'); const postsRoutes = require('./routes/posts'); const commentsRoutes = require('./routes/comments'); const app = express(); app.use(express.json()); app.use(cors()); app.use(writeLogs(addLog)); app.use('/users', usersRoutes); app.use('/posts', postsRoutes); app.use('/comments', commentsRoutes); app.use((err, req, res, next) => { if (res.headersSent) { return next(err); } return res.status(500).send('Something broke!'); }); app.use((req, res) => { res.status(404); res.send('Page not found'); }); app.listen(appPort, () => {});
import random def generate_password(length): password_str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+" password = "".join(random.sample(password_str,length )) return password # Driver Code length = 20 print(generate_password(length))
def find_index(item, lst): for i, x in enumerate(lst): if x == item: return i return -1 output = find_index('c', list) print(output)
<filename>checkout/src/environments/environment.prod.ts export const environment = { production: true, clientKey: "YOUR_CLIENT_KEY" };
# The Book of Ruby - http://www.sapphiresteel.com def mymethod( somearg ) print( "I say: " << somearg ) end this_is_a_method_name = method(:mymethod) puts( this_is_a_method_name ) puts( "#{this_is_a_method_name.class}" ) this_is_a_method_name.call( "hello world" )
'use strict' // ---------------------------------------------------------------------------------------- // Copyright 2020 <NAME>, All rights reserved // Library for solar-related visualizations // ---------------------------------------------------------------------------------------- var debug = false; // Convenience function that creates an SVG element from type, value and text strings function svgen(n, v, t) { n = document.createElementNS("http://www.w3.org/2000/svg", n); for (var p in v) if(p == "xlink:href") { n.setAttributeNS("http://www.w3.org/1999/xlink", p, v[p]); } else if(p == "xmlns:xlink") { n.setAttributeNS("http://www.w3.org/2000/xmlns/", p, v[p]); } else if(p == "xmlns") { n.setAttributeNS("http://www.w3.org/2000/xmlns/", p, v[p]); } else if(p == "xml:space") { n.setAttributeNS("http://www.w3.org/XML/1998/namespace", p, v[p]); } else { n.setAttributeNS(null, p, v[p]); } if(t) n.innerHTML = t; return n } // Math utility functions function circleX(centerx, angle, distance) { return(distance * Math.cos(-1 * angle / (180/Math.PI)) + centerx); } function circleY(centery, angle, distance) { return(distance * Math.sin(-1 * angle / (180/Math.PI)) + centery); } function tanX(centerx, angle, distance, tandist) { return(distance * Math.cos(-1 * angle / (180/Math.PI)) + centerx + tandist * Math.cos(-1 * (angle - 90) / (180/Math.PI))); } function tanY(centery, angle, distance, tandist) { return(distance * Math.sin(-1 * angle / (180/Math.PI)) + centery + tandist * Math.sin(-1 * (angle - 90) / (180/Math.PI))); } // ---------------------------------------------------------------------------------------- // Solar Power Flow Visualization // ---------------------------------------------------------------------------------------- function solar_draw(svg, day, cloudy, sol_watts, grid_connected, grid_watts, load_watts, bat_watts = null, bat_soc = null, background_color = "#FFFFFF") { if(bat_watts == null) { bat_soc = null; } if(grid_connected == null) { grid_watts = 0; } svg.appendChild(svgen('ellipse', { cx: 300, cy: 300, rx: 128, ry: 128, "stroke-width": 40, stroke:'#22220A', "fill": 'none' })); if(grid_connected != null) { flow_draw(svg, 180, 90, 40, 0, 0, 0, '#22220A', false, false); flow_draw(svg, 90, 0, 40, 0, 0, 0, '#22220A', false, false); } if(bat_watts != null) { flow_draw(svg, 0, 270, 40, 0, 0, 0, '#22220A', false, false); flow_draw(svg, 270, 180, 40, 0, 0, 0, '#22220A', false, false); } // Debug gridlines (Set debug to true at top of file to enable) if(debug) { svg.appendChild(svgen('path', { d: "M300,0 l0,600", stroke:'#444444', "stroke-width": 1 })) } if(debug) { svg.appendChild(svgen('path', { d: "M0,300 l600,0", stroke:'#444444', "stroke-width": 1 })) } var panels = svgen('g', {transform:"translate(0 245)" }); panels_draw(panels, day, cloudy); svg.appendChild(panels) var house = svgen('g', {transform:"translate(500 245)" }); house_draw(house); svg.appendChild(house) if(grid_connected != null) { var grid = svgen('g', {transform:"translate(253 10)" }); grid_draw(grid, grid_connected); svg.appendChild(grid) } if(bat_watts != null) { var battery = svgen('g', {transform:"translate(252 470)" }); battery_draw(battery, bat_soc); svg.appendChild(battery) } if(bat_watts == null) { bat_watts = 0; } // ------------------------------------- if(grid_watts == 0 && bat_watts == 0 && sol_watts > 0 && load_watts > 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "01" )) } flow_draw(svg, 180, 0, 40, 0, 0, 0, '#FFCC99',); } if(grid_watts == 0 && bat_watts < 0 && sol_watts > 0 && load_watts == 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "02" )) } flow_draw(svg, 270, 180, 40, 0, 0, 0, '#FFCC99', true); } if(grid_watts < 0 && bat_watts == 0 && sol_watts > 0 && load_watts == 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "03" )) } flow_draw(svg, 180, 90, 40, 0, 0, 0, '#FFCC99'); } if(grid_watts == 0 && bat_watts > 0 && sol_watts == 0 && load_watts > 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "04" )) } flow_draw(svg, 0, 270, 40, 0, 0, 0, '#9999CC', true); } if(grid_watts < 0 && bat_watts > 0 && sol_watts == 0 && load_watts == 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "05" )) } flow_draw(svg, 90, 270, 40, 0, 0, 0, '#9999CC', true); } if(grid_watts > 0 && bat_watts == 0 && sol_watts == 0 && load_watts > 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "06" )) } flow_draw(svg, 90, 0, 40, 0, 0, 0, '#CC6666'); } if(grid_watts > 0 && bat_watts < 0 && sol_watts == 0 && load_watts == 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "07" )) } flow_draw(svg, 90, 270, 40, 0, 0, 0, '#CC6666'); } // ------------------------------------- if(grid_watts < 0 && bat_watts == 0 && sol_watts > 0 && load_watts > 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "11" )) } flow_draw(svg, 180, 90, 40 * ((grid_watts * -1) / sol_watts), 20 * (load_watts / sol_watts), 0, 20 * (load_watts / sol_watts), '#FFCC99', false, true, 40); flow_draw(svg, 180, 0, 40 * (load_watts / sol_watts), -20 * ((grid_watts * -1) / sol_watts), 0, -20 * ((grid_watts * -1) / sol_watts), '#FFCC99', false, true, 0); } if(grid_watts == 0 && bat_watts < 0 && sol_watts > 0 && load_watts > 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "12" )) } flow_draw(svg, 180, 0, 40 * (load_watts / sol_watts), 20 * ((bat_watts * -1) / sol_watts), 0, 0, '#FFCC99', false, true, 40); flow_draw(svg, 270, 180, 40 * ((bat_watts * -1) / sol_watts), 0, -20 * (load_watts / sol_watts), 0, '#FFCC99', true, true, 0); } if(grid_watts < 0 && bat_watts < 0 && sol_watts > 0 && load_watts == 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "13" )) } flow_draw(svg, 180, 90, 40 * ((grid_watts * -1) / sol_watts), 20 * ((bat_watts * -1) / sol_watts), 0, 0, '#FFCC99', false, true, 40); flow_draw(svg, 270, 180, 40 * ((bat_watts * -1) / sol_watts), 0, -20 * ((grid_watts * -1) / sol_watts), 0, '#FFCC99', true, true, 0); } if(bat_watts > 0 && sol_watts == 0 && load_watts > 0 && grid_watts < 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "14" )) } flow_draw(svg, 0, 270, 40 * (load_watts / bat_watts), 0, -20 * ((grid_watts * -1) / bat_watts), 20 * ((grid_watts * -1) / bat_watts), '#9999CC', true, true, 40); flow_draw(svg, 90, 270, 40 * ((grid_watts * -1) / bat_watts), 0, 20 * (load_watts / bat_watts), -20 * (load_watts / bat_watts), '#9999CC', true, true, 0); } if(grid_watts > 0 && (bat_watts * -1) > 0 && sol_watts == 0 && load_watts > 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "15" )) } flow_draw(svg, 90, 0, 40 * (load_watts/grid_watts), 20 * ((bat_watts * -1) / grid_watts), 0, 20 * ((bat_watts * -1) / grid_watts), '#CC6666', false, true, 40); flow_draw(svg, 90, 270, 40 * ((bat_watts * -1) / grid_watts), -20 * (load_watts/grid_watts), 0, -20 * (load_watts/grid_watts), '#CC6666', false, true, 0); } if(grid_watts > 0 && bat_watts == 0 && sol_watts > 0 && load_watts > 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "16" )) } flow_draw(svg, 180, 0, 40 * (sol_watts / load_watts), 0, 20 * (grid_watts / load_watts), -20 * (grid_watts / load_watts), '#FFCC99'); flow_draw(svg, 90, 0, 40 * (grid_watts / load_watts), 0, -20 * (sol_watts / load_watts), 20 * (sol_watts / load_watts), '#CC6666'); } if(grid_watts > 0 && bat_watts < 0 && sol_watts > 0 && load_watts == 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "17" )) } flow_draw(svg, 270, 180, 40 * (sol_watts / (bat_watts * -1)), 20 * (grid_watts / (bat_watts * -1)), 0, 0, '#FFCC99', true); flow_draw(svg, 90, 270, 40 * (grid_watts / (bat_watts * -1)), 0, -20 * (sol_watts / (bat_watts * -1)), 0, '#CC6666'); } if(grid_watts > 0 && bat_watts > 0 && sol_watts == 0 && load_watts > 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "18" )) } flow_draw(svg, 90, 0, 40 * (grid_watts / load_watts), 0, -20 * (bat_watts / load_watts), 0, '#CC6666'); flow_draw(svg, 0, 270, 40 * (bat_watts / load_watts), 20 * (grid_watts / load_watts), 0, 0, '#9999CC', true); } if(grid_watts == 0 && bat_watts > 0 && sol_watts > 0 && load_watts > 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "19" )) } flow_draw(svg, 180, 0, 40 * (sol_watts / load_watts), 0, -20 * (bat_watts / load_watts), 0, '#FFCC99'); flow_draw(svg, 0, 270, 40 * (bat_watts / load_watts), 20 * (sol_watts / load_watts), 0, 0, '#9999CC', true); } // ------------------------------------- if(grid_watts < 0 && bat_watts < 0 && sol_watts > 0 && load_watts > 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "21" )) } var grid_width = 40 * ((grid_watts * -1) / (load_watts + (grid_watts * -1) + (bat_watts * -1))); var load_width = 40 * (load_watts / (load_watts + (grid_watts * -1) + (bat_watts * -1))); var bat_width = 40 * ((bat_watts * -1) / (load_watts + (grid_watts * -1) + (bat_watts * -1))); var sol_grid_offset = ((grid_width + load_width) / 2) - (grid_width / 2); var sol_load_offset = -1 * ((grid_width + load_width) / 2) + (load_width / 2); flow_draw(svg, 180, 90, grid_width, 20 * ((load_watts + (bat_watts * -1)) / sol_watts), 0, sol_grid_offset, '#FFCC99', false, true, 40); flow_draw(svg, 180, 0, load_width, -20 * ((grid_watts * -1) / sol_watts) + bat_width / 2, 0, sol_load_offset, '#FFCC99', false, true, 0); flow_draw(svg, 270, 180, bat_width, 0, -20 * ((load_watts + (grid_watts * -1)) / sol_watts), 0, '#FFCC99', true, true, 0); } if((bat_watts * -1) + load_watts == sol_watts + grid_watts && (bat_watts * -1) < sol_watts && grid_watts < load_watts && sol_watts > 0 && load_watts > 0 && grid_watts > 0 && bat_watts < 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "22" )) } var grid_load_width = 40 * (grid_watts / (load_watts + (bat_watts * -1))); var sol_load_width = 40 * ((sol_watts - (bat_watts * -1)) / (load_watts + (bat_watts * -1))); var sol_bat_width = 40 * ((bat_watts * -1) / (load_watts + (bat_watts * -1))); var sol_total_width = sol_load_width + sol_bat_width; var load_total_width = sol_load_width + grid_load_width; var sol_load_offset = -1 * (load_total_width / 2) + (sol_load_width / 2); var grid_load_offset = (load_total_width / 2) - (grid_load_width / 2); flow_draw(svg, 90, 0, grid_load_width, 0, -1 * grid_load_offset, grid_load_offset, '#CC6666'); flow_draw(svg, 180, 0, sol_load_width, 20 * ((bat_watts * -1) / sol_watts) - (grid_load_width / 2), -1 * sol_load_offset, sol_load_offset, '#FFCC99'); flow_draw(svg, 270, 180, sol_bat_width, 0, -20 * ((load_watts - grid_watts) / sol_watts), 0, '#FFCC99', true); } if((bat_watts * -1) + load_watts == sol_watts + grid_watts && (bat_watts * -1) > sol_watts && grid_watts > load_watts && sol_watts > 0 && load_watts > 0 && grid_watts > 0 && bat_watts < 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "23" )) } var grid_width = 40 * (grid_watts) / (load_watts + (bat_watts * -1)); var grid_load_width = 40 * ((grid_watts - (bat_watts * -1 - sol_watts)) / (load_watts + (bat_watts * -1))); var grid_bat_width = 40 * ((grid_watts - load_watts) / (load_watts + (bat_watts * -1))); var sol_bat_width = 40 * (sol_watts / (load_watts + (bat_watts * -1))); var sol_bat_offset = (grid_bat_width / 2); var grid_bat_offset = -1 * (sol_bat_width / 2); var grid_load_offset = (grid_width / 2) - (grid_load_width / 2); flow_draw(svg, 90, 0, grid_load_width, grid_load_offset, 0, grid_load_offset, '#CC6666', false, true, grid_width); flow_draw(svg, 90, 270, grid_bat_width, -20 * (load_watts / (grid_watts + sol_watts)), grid_bat_offset, -20 * (load_watts / (grid_watts + sol_watts)), '#CC6666', false, true, 0); flow_draw(svg, 270, 180, sol_bat_width, sol_bat_offset, 0, 0, '#FFCC99', true); } if(sol_watts > 0 && load_watts > 0 && grid_watts > 0 && bat_watts > 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "24" )) } var grid_width = 40 * (grid_watts / (sol_watts + grid_watts + bat_watts)); var sol_width = 40 * (sol_watts / (sol_watts + grid_watts + bat_watts)); var total_width = grid_width + sol_width; var grid_offset = (total_width / 2) - (grid_width / 2); var sol_offset = -1 * (total_width / 2) + (sol_width / 2); flow_draw(svg, 90, 0, grid_width, 0, -20 * ((bat_watts + sol_watts) / (load_watts)), grid_offset, '#CC6666'); flow_draw(svg, 180, 0, sol_width, 0, 20 * ((grid_watts) / (load_watts)) - 20 * ((bat_watts) / (load_watts)), sol_offset, '#FFCC99'); flow_draw(svg, 0, 270, 40 * (bat_watts / (sol_watts + grid_watts + bat_watts)), 20 * ((grid_watts + sol_watts) / (sol_watts + grid_watts + bat_watts)), 0, 0, '#9999CC', true); } if(grid_watts == load_watts && sol_watts == (bat_watts * -1) && sol_watts != 0 && grid_watts != 0 && load_watts >= 0) { if(debug) { svg.appendChild(svgen('text', { x: 10, y: 40, "text-anchor":"start", "fill":"#CCCCCC", "font-size":32, "font-family":"Arial"}, "25" )) } flow_draw(svg, 90, 0, 40 * (grid_watts / (sol_watts + grid_watts)), 0, 0, 0, '#CC6666'); flow_draw(svg, 270, 180, 40 * (sol_watts / (sol_watts + grid_watts)), 0, 0, 0, '#FFCC99', true); } } // Draw individual flows function flow_draw(svg, startAngle, endAngle, width, startoffset, endoffset, inneroffset, color, reverse = false, arrow = true, startarrowwidth = null) { var centerx = 300; var centery = 300; var inner = 0; if(startoffset < 0 && endoffset > 0 && inneroffset > 0) inner = 1; svg.appendChild(svgen('path', { d: "M" + tanX(centerx, startAngle, 172, startoffset) + "," + tanY(centery, startAngle, 172, startoffset) + " " + "L" + tanX(centerx, startAngle, 156 + inneroffset, startoffset) + "," + tanY(centery, startAngle, 156 + inneroffset, startoffset) + " " + "A28,28 0 0,0 " + circleX(centerx, startAngle - (10 - inneroffset/4) - startoffset/2, 128 + inneroffset) + "," + circleY(centery, startAngle - (10 - inneroffset/4) - startoffset/2, 128 + inneroffset) + " " + "A" + (128 + inneroffset) + "," + (128 + inneroffset) + " 0 " + inner + "1 " + circleX(centerx, endAngle + (10 - inneroffset/4) - endoffset/2, 128+ inneroffset) + "," + circleY(centery, endAngle + (10 - inneroffset/4) - endoffset/2, 128 + inneroffset) + " " + "A28,28 0 0,0 " + tanX(centerx, endAngle, 156 + inneroffset, endoffset) + "," + tanY(centery, endAngle, 156 + inneroffset, endoffset) + " " + "L" + tanX(centerx, endAngle, 172, endoffset) + "," + tanY(centery, endAngle, 172, endoffset) , fill:'none', stroke: color, 'stroke-width': width })); if(arrow) { if(!reverse) { [startAngle, endAngle] = [endAngle, startAngle]; [startoffset, endoffset] = [endoffset, startoffset]; } svg.appendChild(svgen('path', { d: "M" + tanX(centerx, startAngle, 172, startoffset + width/2) + "," + tanY(centery, startAngle, 172, startoffset + width/2) + " " + "L" + tanX(centerx, startAngle, 172 + width/4, startoffset) + "," + tanY(centery, startAngle, 172 + width/4, startoffset) + " " + "L" + tanX(centerx, startAngle, 172, startoffset - width/2) + "," + tanY(centery, startAngle, 172, startoffset - width/2) , fill: color })); [startAngle, endAngle] = [endAngle, startAngle]; [startoffset, endoffset] = [endoffset, startoffset]; if(startarrowwidth != null && startarrowwidth > 0) { width = startarrowwidth; startoffset = 0; } if(startarrowwidth == null || startarrowwidth > 0) { svg.appendChild(svgen('path', { d: "M" + tanX(centerx, startAngle, 172, startoffset + width/2) + "," + tanY(centery, startAngle, 172, startoffset + width/2) + " " + "L" + tanX(centerx, startAngle, 172 + width/4, startoffset + width/2) + "," + tanY(centery, startAngle, 172 + width/4, startoffset + width/2) + " " + "L" + tanX(centerx, startAngle, 172, startoffset) + "," + tanY(centery, startAngle, 172, startoffset) + " " + "L" + tanX(centerx, startAngle, 172 + width/4, startoffset - width/2) + "," + tanY(centery, startAngle, 172 + width/4, startoffset - width/2) + " " + "L" + tanX(centerx, startAngle, 172, startoffset - width/2) + "," + tanY(centery, startAngle, 172, startoffset - width/2), fill: color })); } } } // ---------------------------------------------------------------------------------------- // Icons // ---------------------------------------------------------------------------------------- function panels_draw(svg, is_day, cloudcover) { var panelFill = "#6666FF"; var sunStroke = "#FFCC22"; // Uncomment to show bounding rect //svg.appendChild(svgen('rect', { x: 0, y: 0, width: 100, height: 100, stroke:'#FF0000', "stroke-width": 5 })); if(cloudcover >= 75) { sunStroke = "#FFCC22"; } if(is_day == true) { svg.appendChild(svgen('path', { d: "M30,56 A28,28 0 0,1 86,56 Z", "stroke-linejoin": "round", fill: sunStroke })); svg.appendChild(svgen('path', { d: "M" + circleX(58, 5, 34) + "," + circleY(56, 5, 34) + " L" + circleX(58, 5, 44) + "," + circleY(56, 5, 44), "stroke-linecap": "round", "stroke-width": 5, stroke: sunStroke })); svg.appendChild(svgen('path', { d: "M" + circleX(58, 33, 34) + "," + circleY(56, 33, 34) + " L" + circleX(58, 33, 44) + "," + circleY(56, 33, 44), "stroke-linecap": "round", "stroke-width": 5, stroke: sunStroke })); svg.appendChild(svgen('path', { d: "M" + circleX(58, 61, 34) + "," + circleY(56, 61, 34) + " L" + circleX(58, 61, 44) + "," + circleY(56, 61, 44), "stroke-linecap": "round", "stroke-width": 5, stroke: sunStroke })); svg.appendChild(svgen('path', { d: "M" + circleX(58, 90, 34) + "," + circleY(56, 90, 34) + " L" + circleX(58, 90, 44) + "," + circleY(56, 90, 44), "stroke-linecap": "round", "stroke-width": 5, stroke: sunStroke })); svg.appendChild(svgen('path', { d: "M" + circleX(58, 118, 34) + "," + circleY(56, 118, 34) + " L" + circleX(58, 118, 44) + "," + circleY(56, 118, 44), "stroke-linecap": "round", "stroke-width": 5, stroke: sunStroke })); svg.appendChild(svgen('path', { d: "M" + circleX(58, 146, 34) + "," + circleY(56, 146, 34) + " L" + circleX(58, 146, 44) + "," + circleY(56, 146, 44), "stroke-linecap": "round", "stroke-width": 5, stroke: sunStroke })); svg.appendChild(svgen('path', { d: "M" + circleX(58, 175, 34) + "," + circleY(56, 175, 34) + " L" + circleX(58, 175, 44) + "," + circleY(56, 175, 44), "stroke-linecap": "round", "stroke-width": 5, stroke: sunStroke })); } else { panelFill = "#333399"; svg.appendChild(svgen('path', { d: "M30,56 A28,28 0 0,1 86,56 Z", "stroke-linejoin": "round", fill: "#DDDDDD" })); svg.appendChild(svgen('ellipse', { cx: 44, cy: 42, rx: 6, ry: 6, "fill": '#AAAAAA' })); svg.appendChild(svgen('ellipse', { cx: 49, cy: 49, rx: 5, ry: 5, "fill": '#999999' })); svg.appendChild(svgen('ellipse', { cx: 64, cy: 46, rx: 5, ry: 5, "fill": '#BBBBBB' })); } if(cloudcover >= 50) { svg.appendChild(svgen('ellipse', { cx: 30, cy: 36, rx: 10, ry: 10, "fill": '#FFFFFF', stroke:'#EEEEEE', "stroke-width": 1 })); svg.appendChild(svgen('ellipse', { cx: 45, cy: 31, rx: 12, ry: 12, "fill": '#FFFFFF', stroke:'#EEEEEE', "stroke-width": 1 })); svg.appendChild(svgen('ellipse', { cx: 58, cy: 38, rx: 7.5, ry: 7.5, "fill": '#FFFFFF', stroke:'#EEEEEE', "stroke-width": 1 })); svg.appendChild(svgen('ellipse', { cx: 66, cy: 42, rx: 4, ry: 4, "fill": '#FFFFFF', stroke:'#EEEEEE', "stroke-width": 1 })); svg.appendChild(svgen('rect', { x: 30, y: 33, width: 15, height: 10, fill:'#FFFFFF'})); svg.appendChild(svgen('rect', { x: 30, y: 41, width: 36, height: 5, fill:'#FFFFFF'})); svg.appendChild(svgen('path', { d: "M30,46 l36,0", stroke:'#EEEEEE', "stroke-width": 1 })); } if(cloudcover >= 75) { svg.appendChild(svgen('ellipse', { cx: 60, cy: 46, rx: 10, ry: 10, "fill": '#FFFFFF', stroke:'#EEEEEE', "stroke-width": 1 })); svg.appendChild(svgen('ellipse', { cx: 75, cy: 41, rx: 12, ry: 12, "fill": '#FFFFFF', stroke:'#EEEEEE', "stroke-width": 1 })); svg.appendChild(svgen('ellipse', { cx: 88, cy: 48, rx: 7.5, ry: 7.5, "fill": '#FFFFFF', stroke:'#EEEEEE', "stroke-width": 1 })); svg.appendChild(svgen('ellipse', { cx: 96, cy: 52, rx: 4, ry: 4, "fill": '#FFFFFF', stroke:'#EEEEEE', "stroke-width": 1 })); svg.appendChild(svgen('rect', { x: 60, y: 43, width: 15, height: 10, fill:'#FFFFFF'})); svg.appendChild(svgen('rect', { x: 60, y: 51, width: 36, height: 5, fill:'#FFFFFF'})); svg.appendChild(svgen('path', { d: "M60,56 l36,0", stroke:'#EEEEEE', "stroke-width": 1 })); } svg.appendChild(svgen('path', { d: "M0,90 l20,0 l20,-30 l-20,0 l-20,30 Z", "stroke-linejoin": "round", fill: panelFill })); svg.appendChild(svgen('path', { d: "M28,90 l20,0 l20,-30 l-20,0 l-20,30 Z", "stroke-linejoin": "round", fill: panelFill })); svg.appendChild(svgen('path', { d: "M56,90 l20,0 l20,-30 l-20,0 l-20,30 Z", "stroke-linejoin": "round", fill: panelFill })); } function battery_draw(svg, percent) { var width = (percent / 100) * 72; var color = "#99CC99"; if(percent <= 70) color = "#FFFF66"; if(percent <= 50) color = "#CC6666"; // Uncomment to show bounding rect // svg.appendChild(svgen('rect', { x: 0, y: 0, width: 100, height: 100, stroke:'#FF0000', "stroke-width": 5 })); svg.appendChild(svgen('path', { d: "M10,35 l" + width + ",0 l0,30 l-" + width + ",0 Z", "stroke-linejoin": "round", fill: color })); svg.appendChild(svgen('path', { d: "M10,35 l73,0 l0,9 l7,0 l0,14 l-7,0 l0,9 l-73,0 Z", "stroke-linejoin": "round", "stroke-width": 5, stroke: "#9999CC", fill: "none" })); } function house_draw(svg) { // Uncomment to show bounding rect // svg.appendChild(svgen('rect', { x: 0, y: 0, width: 100, height: 100, stroke:'#FF0000', "stroke-width": 5 })); svg.appendChild(svgen('path', { d: "M20,86 l20,0 l0,-30 l20,0 l0,30 l20,0 l0,-50 l-30,-10 l-30,10 Z", "stroke-linejoin": "round", fill: "#CC99CC" })); svg.appendChild(svgen('path', { d: "M50,15 l-40,14 l2,5 L50,21 L50,15 l40,14 l-2,5 L50,21 Z", "stroke-linejoin": "round", "stroke-width": 5, fill: "#CC99CC" })); svg.appendChild(svgen('path', { d: "M80,15 l-10,0 l0,10 l10,4 Z", "stroke-linejoin": "round", "stroke-width": 5, fill: "#CC99CC" })); } function grid_draw(svg, energized) { // Uncomment to show bounding rect // svg.appendChild(svgen('rect', { x: 0, y: 0, width: 100, height: 100, stroke:'#FF0000', "stroke-width": 5 })); svg.appendChild(svgen('path', { d: "M27,90 l15,-50", "stroke-linejoin": "round", "stroke-linecap": "round", "stroke-width": 3, stroke: "#AAAAAA", fill: "none" })); svg.appendChild(svgen('path', { d: "M67,90 l-15,-50", "stroke-linejoin": "round", "stroke-linecap": "round", "stroke-width": 3, stroke: "#AAAAAA", fill: "none" })); svg.appendChild(svgen('path', { d: "M27,90 l32,-25 l-24,0 l32,25", "stroke-linejoin": "round", "stroke-linecap": "round", "stroke-width": 3, stroke: "#AAAAAA", fill: "none" })); svg.appendChild(svgen('path', { d: "M41,40 l16,25", "stroke-linejoin": "round", "stroke-linecap": "round", "stroke-width": 3, stroke: "#AAAAAA", fill: "none" })); svg.appendChild(svgen('path', { d: "M53,40 l-16,25", "stroke-linejoin": "round", "stroke-linecap": "round", "stroke-width": 3, stroke: "#AAAAAA", fill: "none" })); svg.appendChild(svgen('path', { d: "M27,40 l40,0 l-20,-10 Z", "stroke-linejoin": "round", "stroke-linecap": "round", "stroke-width": 3, stroke: "#AAAAAA", fill: "none" })); svg.appendChild(svgen('path', { d: "M27,20 l40,0 l-20,-10 Z", "stroke-linejoin": "round", "stroke-linecap": "round", "stroke-width": 3, stroke: "#AAAAAA", fill: "none" })); svg.appendChild(svgen('path', { d: "M41,40 l0,-25", "stroke-linejoin": "round", "stroke-linecap": "round", "stroke-width": 3, stroke: "#AAAAAA", fill: "none" })); svg.appendChild(svgen('path', { d: "M53,40 l0,-25", "stroke-linejoin": "round", "stroke-linecap": "round", "stroke-width": 3, stroke: "#AAAAAA", fill: "none" })); svg.appendChild(svgen('path', { d: "M33,40 l0,5", "stroke-linejoin": "round", "stroke-linecap": "round", "stroke-width": 3, stroke: "#AAAAAA", fill: "none" })); svg.appendChild(svgen('path', { d: "M61,40 l0,5", "stroke-linejoin": "round", "stroke-linecap": "round", "stroke-width": 3, stroke: "#AAAAAA", fill: "none" })); svg.appendChild(svgen('path', { d: "M33,20 l0,5", "stroke-linejoin": "round", "stroke-linecap": "round", "stroke-width": 3, stroke: "#AAAAAA", fill: "none" })); svg.appendChild(svgen('path', { d: "M61,20 l0,5", "stroke-linejoin": "round", "stroke-linecap": "round", "stroke-width": 3, stroke: "#AAAAAA", fill: "none" })); if(energized) { svg.appendChild(svgen('path', { d: "M75,20 l0,5 l5,0 l-5,10 l0,-5 l-5,0 l5,-10 Z", fill: "#FFFF66" })); svg.appendChild(svgen('path', { d: "M25,50 l0,5 l5,0 l-5,10 l0,-5 l-5,0 l5,-10 Z", fill: "#FFFF66" })); } else { svg.appendChild(svgen('path', { d: "M75,20 l0,5 l5,0 l-5,10 l0,-5 l-5,0 l5,-10 Z", "stroke-width": 1, stroke: "#AAAAAA" })); svg.appendChild(svgen('path', { d: "M25,50 l0,5 l5,0 l-5,10 l0,-5 l-5,0 l5,-10 Z", "stroke-width": 1, stroke: "#AAAAAA" })); } }
#!/usr/bin/env bash rm -rf $(which kymsu) rm -rf ~/.kymsu echo "KYMSU has been uninstalled."
import { ArrayObservable } from '../observable/ArrayObservable'; import { ScalarObservable } from '../observable/ScalarObservable'; import { EmptyObservable } from '../observable/EmptyObservable'; import { concatStatic } from './concat'; import { isScheduler } from '../util/isScheduler'; /** * Returns an Observable that emits the items in a specified Iterable before it begins to emit items emitted by the * source Observable. * * <img src="./img/startWith.png" width="100%"> * * emitted by the source Observable. * @owner Observable * @this {?} * @param {...?} array * @return {?} */ export function startWith(...array) { let /** @type {?} */ scheduler = (array[array.length - 1]); if (isScheduler(scheduler)) { array.pop(); } else { scheduler = null; } const /** @type {?} */ len = array.length; if (len === 1) { return concatStatic(new ScalarObservable(/** @type {?} */ (array[0]), scheduler), /** @type {?} */ (this)); } else if (len > 1) { return concatStatic(new ArrayObservable(/** @type {?} */ (array), scheduler), /** @type {?} */ (this)); } else { return concatStatic(new EmptyObservable(scheduler), /** @type {?} */ (this)); } }
<reponame>rexcorp01/bet6<filename>pick6-frontend/src/actions/pickSheetFormTeams.js export const updatePickSheetFormTeams = team => { return { type: "UPDATE_PICK_SHEET_FORM_TEAMS", team } } export const removeTeamFromPickSheetForm = team => { return { type: "REMOVE_TEAM_FROM_FORM", team } }
/* https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/create-a-method-on-an-object Using the dog object, give it a method called sayLegs. The method should return the sentence "This dog has 4 legs." (1) dog.sayLegs() should be a function. (2) dog.sayLegs() should return the given string - note that punctuation and spacing matter. */ let dog = { name: "Spot", numLegs: 4, sayLegs: () => { return `This dog has ${dog.numLegs} legs.` } }; console.log(dog.sayLegs());
mkdir week10 mkdir week01 cd week01 nano file.txt cd .. cd week10 link ../week01/file.txt _ex2.txt cd .. inode=$(stat -c '%i' ./week01/file.txt) echo "${inode}" find ./ -inum $inode >> ex2.txt find ./week01/file.txt -inum $inode -exec rm {} \; >> ex2.txt ls -i ./week01/file.txt
package com.qiwen.interview.thread; import java.io.Serializable; /** * 第二种实现方式, 实现 Runnable 接口 * @author liqiwen * @version 1.2 * @since 1.2 */ public class ThreadDemo2 implements Runnable { @Override public void run() { System.out.println("第二种方式实现线程:" + Thread.currentThread().getName()); } }
#!/usr/bin/env bash # Copyright 2018 The Oppia 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. set -e source $(dirname $0)/setup.sh || exit 1 # Checking if pip is installed. If you are having # trouble, please ensure that you have pip installed (see "Installing Oppia" # on the Oppia developers' wiki page). echo Checking if pip is installed on the local machine if ! type pip > /dev/null 2>&1 ; then echo "" echo " Pip is required to install Oppia dependencies, but pip wasn't found" echo " on your local machine." echo "" echo " Please see \"Installing Oppia\" on the Oppia developers' wiki page:" if [ "${OS}" == "Darwin" ] ; then echo " https://github.com/oppia/oppia/wiki/Installing-Oppia-%28Mac-OS%29" else echo " https://github.com/oppia/oppia/wiki/Installing-Oppia-%28Linux%29" fi # If pip is not installed, quit. exit 1 fi echo Checking if webtest is installed in third_party if [ ! -d "$TOOLS_DIR/webtest-1.4.2" ]; then echo Installing webtest framework # Note that the github URL redirects, so we pass in -L to tell curl to follow the redirect. curl -o webtest-download.zip -L https://github.com/Pylons/webtest/archive/1.4.2.zip unzip webtest-download.zip -d $TOOLS_DIR rm webtest-download.zip fi
<filename>packages/core/src/icons/components/RadioEmpty.js import React from 'react'; export default function SvgRadioEmpty(props) { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="-1980 -5001 32 32" width="1em" height="1em" {...props} > <path data-name="\u9577\u65B9\u5F62 7898" fill="transparent" d="M-1980-5001h32v32h-32z" /> <path data-name="\u524D\u9762\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u578B\u629C\u304D 9" d="M-1958-4975h-12a4.005 4.005 0 01-4-4v-12a4 4 0 014-4h12a4 4 0 014 4v12a4 4 0 01-4 4zm-12-18a2 2 0 00-2 2v12a2 2 0 002 2h12a2 2 0 002-2v-12a2 2 0 00-2-2z" /> </svg> ); }
import json import requests class zaif_last_price: def __init__(self, currency_pair): self.url = 'https://api.zaif.jp/api/1/last_price/'+currency_pair response = requests.get(self.url) if response.status_code != 200: raise Exception('return status code is {}'.format(response.status_code)) self.response = json.loads(response.text) def get_price(self): return self.response['last_price'] ''' { "last": 135875.0, "high": 136000.0, "low": 131570.0, "vwap": 133301.7489, "volume": 6889.215, "bid": 135875.0, "ask": 135920.0 } キー 詳細 型 last 終値 float high 過去24時間の高値 float low 過去24時間の安値 float vwap 過去24時間の加重平均 float volume 過去24時間の出来高 float bid 買気配値 float ask 売気配値 float 補足 ''' class zaif_ticker: def __init__(self, currency_pair): self.url = 'https://api.zaif.jp/api/1/ticker/'+currency_pair response = requests.get(self.url) if response.status_code != 200: raise Exception('return status code is {}'.format(response.status_code)) self.response = json.loads(response.text) def get_last(self): return self.response['last'] def get_high(self): return self.response['high'] def get_low(self): return self.response['low'] def get_vwap(self): return self.response['vwap'] def get_volume(self): return self.response['volume'] def get_bid(self): return self.response['bid'] def get_ask(self): return self.response['ask']
#include <OpenGL/gl.h> typedef struct { // Texture data structure // Include necessary fields for texture data } Texture; void renderTextureOnCube(Texture* texture) { // Set up the rendering mode based on the defined macro #ifdef GT_Rendering_TextureCube_OpenGL21 // Set up OpenGL 2.1 specific rendering mode for cube texture // Example: glEnable(GL_TEXTURE_2D); #endif // Bind the texture glBindTexture(GL_TEXTURE_2D, texture->id); // Assuming texture id is available in the Texture struct // Render the texture on the cube // Example: glBegin(GL_QUADS); ... glEnd(); // Clean up after rendering // Example: glDisable(GL_TEXTURE_2D); }
#!/bin/bash -e # This script is used to build, test and squash the OpenShift Docker images. # # Name of resulting image will be: 'NAMESPACE/BASE_IMAGE_NAME-VERSION-OS'. # # BASE_IMAGE_NAME - Usually name of the main component within container. # OS - Specifies distribution - "rhel7" or "centos7" # VERSION - Specifies the image version - (must match with subdirectory in repo) # TEST_MODE - If set, build a candidate image and test it # TAG_ON_SUCCESS - If set, tested image will be re-tagged as a non-candidate # image, if the tests pass. # VERSIONS - Must be set to a list with possible versions (subdirectories) # OPENSHIFT_NAMESPACES - Which of available versions (subdirectories) should be # put into openshift/ namespace. OS=${1-$OS} VERSION=${2-$VERSION} DOCKERFILE_PATH="" test -z "$BASE_IMAGE_NAME" && { BASE_DIR_NAME=$(echo $(basename `pwd`) | sed -e 's/-[0-9]*$//g') BASE_IMAGE_NAME="${BASE_DIR_NAME#sti-}" } NAMESPACE="rhmap/" # Cleanup the temporary Dockerfile created by docker build with version trap "rm -f ${DOCKERFILE_PATH}.version" SIGINT SIGQUIT EXIT # Perform docker build but append the LABEL with GIT commit id at the end function docker_build_with_version { local dockerfile="$1" # Use perl here to make this compatible with OSX DOCKERFILE_PATH=$(perl -MCwd -e 'print Cwd::abs_path shift' $dockerfile) cp ${DOCKERFILE_PATH} "${DOCKERFILE_PATH}.version" git_version=$(git rev-parse --short HEAD) echo "LABEL io.openshift.builder-version=\"${git_version}\"" >> "${dockerfile}.version" docker build -t ${IMAGE_NAME} -f "${dockerfile}.version" . if [[ "${SKIP_SQUASH}" != "1" ]]; then squash "${dockerfile}.version" fi rm -f "${DOCKERFILE_PATH}.version" } # Install the docker squashing tool[1] and squash the result image # [1] https://github.com/goldmann/docker-scripts function squash { # FIXME: We have to use the exact versions here to avoid Docker client # compatibility issues easy_install -q --user docker_py==1.6.0 docker-scripts==0.4.4 base=$(awk '/^FROM/{print $2}' $1) ${HOME}/.local/bin/docker-scripts squash -f $base ${IMAGE_NAME} } # Versions are stored in subdirectories. You can specify VERSION variable # to build just one single version. By default we build all versions dirs=${VERSION:-$VERSIONS} for dir in ${dirs}; do case " $OPENSHIFT_NAMESPACES " in *\ ${dir}\ *) ;; *) if [ "${OS}" == "centos7" ]; then NAMESPACE="centos/" else # we don't test rhel versions of SCL owned images if [[ "${SKIP_RHEL_SCL}" == "1" ]]; then echo "Skipping rhel scl image ${BASE_IMAGE_NAME}-${dir//./}-{$OS}" continue fi NAMESPACE="rhscl/" fi esac IMAGE_NAME="${NAMESPACE}${BASE_IMAGE_NAME}-${dir//./}-${OS}" if [[ -v TEST_MODE ]]; then IMAGE_NAME+="-candidate" fi echo "-> Building ${IMAGE_NAME} ..." pushd ${dir} > /dev/null if [ "$OS" == "rhel7" -o "$OS" == "rhel7-candidate" ]; then docker_build_with_version Dockerfile.rhel7 else docker_build_with_version Dockerfile fi if [[ -v TEST_MODE ]]; then IMAGE_NAME=${IMAGE_NAME} test/run if [[ $? -eq 0 ]] && [[ "${TAG_ON_SUCCESS}" == "true" ]]; then echo "-> Re-tagging ${IMAGE_NAME} image to ${IMAGE_NAME%"-candidate"}" docker tag -f $IMAGE_NAME ${IMAGE_NAME%"-candidate"} echo "-> Tag successful" fi fi popd > /dev/null done
extension JRSDKSearchInfo { func typeRepresentation() -> String { switch JRSDKModelUtils.searchInfoType(self) { case .oneWayType: return "Oneway" case .directReturnType: return "Return" // ... handle other cases if necessary } } }
<html> <head> <title>Prime Numbers Up To 50</title> <style> table { font-family: arial, sans-serif; border: 1px solid black; width: 100%; } tr { border: 1px solid black; } th, td { text-align: center; padding: 8px; } </style> </head> <body> <h1>Prime Numbers Up To 50</h1> <table> <tr> <th>Number</th> </tr> <tr> <td>2</td> </tr> <tr> <td>3</td> </tr> <tr> <td>5</td> </tr> <tr> <td>7</td> </tr> <tr> <td>11</td> </tr> <tr> <td>13</td> </tr> <tr> <td>17</td> </tr> <tr> <td>19</td> </tr> <tr> <td>23</td> </tr> <tr> <td>29</td> </tr> <tr> <td>31</td> </tr> <tr> <td>37</td> </tr> <tr> <td>41</td> </tr> <tr> <td>43</td> </tr> <tr> <td>47</td> </tr> <tr> <td>49</td> </tr> </table> </body> </html>
<reponame>DanHunt27/Music-Website from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): artist_name = models.CharField(max_length=100) song_name = models.CharField(max_length=100) description = models.TextField(max_length=280, blank=True, default='') link = models.URLField(max_length=1000) user = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.artist_name + " - " + self.song_name def get_absolute_url(self): return reverse('index') class Comment(models.Model): post = models.ForeignKey('main.Post', on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.text
octave --eval "test sumOfTwo"
<reponame>devosoft/empirical-prefab-demo #pragma once #include <string> #include "emp/math/Random.hpp" #include "emp/prefab/Card.hpp" #include "emp/prefab/CodeBlock.hpp" #include "emp/prefab/ReadoutPanel.hpp" #include "emp/web/Button.hpp" #include "emp/web/Document.hpp" int counter = 0; void readout_panel_example( emp::web::Document& doc ) { // ------ Readout Panel Example ------ emp::prefab::Card readout_panel_ex("INIT_CLOSED"); doc << readout_panel_ex; readout_panel_ex.AddHeaderContent("<h3>Readout Panel</h3>"); readout_panel_ex << "<h3>Live Demo:</h3><hr>"; // Refresh values every 100 milliseconds emp::prefab::ReadoutPanel values("Readout Values", 100); // A random number generator std::function<std::string()> random_number = [](){ static emp::Random rand; return emp::to_string(rand.GetUInt()); }; values.AddValues( "Random", "A randomly generated number", random_number, "Counter", "How many times you've clicked the button", counter ); readout_panel_ex << values; emp::web::Button adder([](){ ++counter; }, "Add one to counter"); adder.SetAttr("class", "btn btn-primary"); readout_panel_ex << adder; readout_panel_ex << "<br><br><h3>Code:</h3><hr>"; const std::string readout_panel_code = R"( #include "emp/math/Random.hpp" #include "emp/prefab/Card.hpp" #include "emp/prefab/ReadoutPanel.hpp" #include "emp/web/web.hpp" #include "emp/web/Button.hpp" emp::web::Document doc("emp_base"); int counter = 0; int main() { // Refresh values every 100 milliseconds emp::prefab::ReadoutPanel values("Readout Values", 100); std::function<std::string()> random_number = [](){ static emp::Random rand; return emp::to_string(rand.GetUInt()); }; values.AddValues( "Random", "A randomly generated number", random_number, "Counter", "How many times you've clicked the button", counter ); doc << values; emp::web::Button adder([](){ ++counter; }, "Add one to counter") adder.SetAttr("class", "btn"); doc << adder; } )"; emp::prefab::CodeBlock readout_panel_code_block(readout_panel_code, "c++"); readout_panel_ex << readout_panel_code_block; }
public static string CalculateVelocity(double x1, double y1, double x2, double y2, double t1, double t2) { double velocity = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)) / (t2 - t1); if (velocity > 3185) { return "Velocity exceeds threshold"; } return velocity.ToString(); }
<reponame>bookmansoft/gamegold-wechat-server<gh_stars>1-10 let facade = require('gamecloud') let {EntityType, InviteType, NotifyType, ResType,ActivityType,em_Condition_Type,em_Condition_Checkmode, ReturnCode} = facade.const function handle(event){ /** * @type {UserEntity} */ let $user = this.GetObject(EntityType.User, event.dst); /** * @type {AllyObject} */ let $ao = this.GetObject(EntityType.Ally, event.aid); if(!!$user && !!$ao){ if($ao.ReqAllowAccepted(event.src, $user) == ReturnCode.Success){ $user.getInviteMgr().Clear(InviteType.AllyReq, 0); $user.getInviteMgr().Clear(InviteType.AllyInvite, 0); } $user.getInviteMgr().Clear(InviteType.AllyReq, event.aid); $user.getInviteMgr().Clear(InviteType.AllyInvite, event.aid); } } module.exports.handle = handle;
#!/bin/bash # A script that is meant to be used with the Nomad cluster examples to: # # 1. Wait for the Nomad server cluster to come up. # 2. Print out the IP addresses of the Nomad servers. # 3. Print out some example commands you can run against your Nomad servers. set -e readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" readonly SCRIPT_NAME="$(basename "$0")" readonly MAX_RETRIES=30 readonly SLEEP_BETWEEN_RETRIES_SEC=10 function log { local readonly level="$1" local readonly message="$2" local readonly timestamp=$(date +"%Y-%m-%d %H:%M:%S") >&2 echo -e "${timestamp} [${level}] [$SCRIPT_NAME] ${message}" } function log_info { local readonly message="$1" log "INFO" "$message" } function log_warn { local readonly message="$1" log "WARN" "$message" } function log_error { local readonly message="$1" log "ERROR" "$message" } function assert_is_installed { local readonly name="$1" if [[ ! $(command -v ${name}) ]]; then log_error "The binary '$name' is required by this script but is not installed or in the system's PATH." exit 1 fi } function get_required_terraform_output { local readonly output_name="$1" local output_value output_value=$(terraform output -no-color "$output_name") if [[ -z "$output_value" ]]; then log_error "Unable to find a value for Terraform output $output_name" exit 1 fi echo "$output_value" } # # Usage: join SEPARATOR ARRAY # # Joins the elements of ARRAY with the SEPARATOR character between them. # # Examples: # # join ", " ("A" "B" "C") # Returns: "A, B, C" # function join { local readonly separator="$1" shift local readonly values=("$@") printf "%s$separator" "${values[@]}" | sed "s/$separator$//" } function get_all_nomad_server_property_values { local server_property_name="$1" local gcp_project local gcp_zone local cluster_tag_name local expected_num_servers gcp_project=$(get_required_terraform_output "gcp_project") gcp_zone=$(get_required_terraform_output "gcp_zone") cluster_tag_name=$(get_required_terraform_output "nomad_server_cluster_tag_name") expected_num_servers=$(get_required_terraform_output "nomad_server_cluster_size") log_info "Looking up $server_property_name for $expected_num_servers Nomad server Compute Instances." local vals local i for (( i=1; i<="$MAX_RETRIES"; i++ )); do vals=($(get_nomad_server_property_values "$gcp_project" "$gcp_zone" "$cluster_tag_name" "$server_property_name")) if [[ "${#vals[@]}" -eq "$expected_num_servers" ]]; then log_info "Found $server_property_name for all $expected_num_servers expected Nomad servers!" echo "${vals[@]}" return else log_warn "Found $server_property_name for ${#vals[@]} of $expected_num_servers Nomad servers. Will sleep for $SLEEP_BETWEEN_RETRIES_SEC seconds and try again." sleep "$SLEEP_BETWEEN_RETRIES_SEC" fi done log_error "Failed to find the $server_property_name for $expected_num_servers Nomad server Compute Instances after $MAX_RETRIES retries." exit 1 } function wait_for_all_nomad_servers_to_register { local readonly server_ips=($@) local readonly server_ip="${server_ips[0]}" local expected_num_nomad_servers expected_num_nomad_servers=$(get_required_terraform_output "nomad_server_cluster_size") log_info "Waiting for $expected_num_nomad_servers Nomad servers to register in the cluster" for (( i=1; i<="$MAX_RETRIES"; i++ )); do log_info "Running 'nomad server-members' command against server at IP address $server_ip" # Intentionally use local and readonly here so that this script doesn't exit if the nomad server-members or grep # commands exit with an error. local readonly members=$(nomad server-members -address="http://$server_ip:4646") local readonly alive_members=$(echo "$members" | grep "alive") local readonly num_nomad_servers=$(echo "$alive_members" | wc -l | tr -d ' ') if [[ "$num_nomad_servers" -eq "$expected_num_nomad_servers" ]]; then log_info "All $expected_num_nomad_servers Nomad servers have registered in the cluster!" return else log_info "$num_nomad_servers out of $expected_num_nomad_servers Nomad servers have registered in the cluster." log_info "Sleeping for $SLEEP_BETWEEN_RETRIES_SEC seconds and will check again." sleep "$SLEEP_BETWEEN_RETRIES_SEC" fi done log_error "Did not find $expected_num_nomad_servers Nomad servers registered after $MAX_RETRIES retries." exit 1 } function get_nomad_server_property_values { local readonly gcp_project="$1" local readonly gcp_zone="$2" local readonly cluster_tag_name="$3" local readonly property_name="$4" local instances cluster_tag_name=$(get_required_terraform_output "nomad_server_cluster_tag_name") log_info "Fetching external IP addresses for Consul Server Compute Instances with tag \"$cluster_tag_name\"" instances=$(gcloud compute instances list \ --project "$gcp_project"\ --filter "zone : $gcp_zone" \ --filter "tags.items~^$cluster_tag_name\$" \ --format "value($property_name)") echo "$instances" } function get_nomad_server_ips { get_all_nomad_server_property_values "EXTERNAL_IP" } function print_instructions { local readonly server_ips=($@) local readonly server_ip="${server_ips[0]}" local instructions=() instructions+=("\nYour Nomad servers are running at the following IP addresses:\n\n${server_ips[@]/#/ }\n") instructions+=("Some commands for you to try:\n") instructions+=(" nomad server-members -address=http://$server_ip:4646") instructions+=(" nomad node-status -address=http://$server_ip:4646") instructions+=(" nomad run -address=http://$server_ip:4646 $SCRIPT_DIR/example.nomad") instructions+=(" nomad status -address=http://$server_ip:4646 example\n") local instructions_str instructions_str=$(join "\n" "${instructions[@]}") echo -e "$instructions_str" } function run { assert_is_installed "terraform" assert_is_installed "nomad" local server_ips server_ips=$(get_nomad_server_ips) wait_for_all_nomad_servers_to_register "$server_ips" print_instructions "$server_ips" } run
### Windows Subsystem for Linux is_wsl || return 1 # allow browser links to be opened in default browser if command -v wslview >/dev/null 2>&1; then export BROWSER="wslview" export DISPLAY=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2}'):0 fi export FIGNORE=".dll:.DLL:.mof:.rll"
export * from './HashSet'; export * from './iterate';
<reponame>ministryofjustice/prison-visits-2 class AlterVisitsAddEmailOverrides < ActiveRecord::Migration[4.2] def change add_column :visits, :override_email_checks, :boolean, default: false add_column :visits, :email_override, :string end end
var API_URL = 'https://alansyue-api.dev.newideas.com.tw/api' export { API_URL };
<filename>src/cli/list/list.definition.ts /* * This program and the accompanying materials are made available under the terms of the * Eclipse Public License v2.0 which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-v20.html * * SPDX-License-Identifier: EPL-2.0 * * Copyright Contributors to the Zowe Project. * */ import { ICommandDefinition } from "@zowe/imperative"; import {CommonOptions} from "../common-options"; import { ListReviewsDefinition } from "./reviews/list-reviews.definition"; /** * This object defines the top level command group for zosfiles. This is not * something that is intended to be used outside of this npm package. * * @private */ const definition: ICommandDefinition = { name: "list", aliases: ["ls"], type: "group", summary: "List different details about your studies", description: "List different details about your studies", children: [ ListReviewsDefinition ], passOn: [ { property: "options", value: [ CommonOptions.TOKEN_OPTION ], ignoreNodes: [{ type: 'group' // don't put the token option on commands that only have children }] } ] }; export = definition;
#!/usr/bin/env bash DIR=$(cd $(dirname $0);pwd) cd ${DIR}/../docs/sequence-diagram MMDC_CMD=$DIR/../node_modules/.bin/mmdc mmd_list=( "authentication-by-EIP712-signature" ) for i in "${mmd_list[@]}" do filename="${i}" ${MMDC_CMD} -i ${filename}.mmd -o ${filename}.svg done
#!/usr/bin/env bash ## system/kill-my-procs-by-name.sh # Kill current user's processes by name. usage="Usage: $0 'regex matching command name and/or args' [...] Kills invoking user's processes by name and arguments, as a more-general and more-dangerous variant of the idea behind the standard 'killall' command. In particular so scripts can kill scripts. See 'Example' below for how this differs from the standard 'killall' command. Also see 'Warning' below that for how this could cause unexpected damage. Example: If you run 'update-grub', then the actual command arguments might be '/bin/sh -e /usr/sbin/update-grub'. This would be caused by the 'update-grub' command being found under '/usr/sbin/' and starting with the \"shebang\" line '#!/bin/sh -e'. This would cause 'killall update-grub' to fail due to the actual process name being 'sh'. Furthermore, because there could be several other scripts running under the 'sh' interpreter, running 'killall sh' would kill too much. However, because 'update-grub' is in the arguments passed to 'sh' when it's ran, searching by command name + args with 'sh.*update-grub' may yield the desired result. Warning: Even though this is more accurate than 'killall' for killing interpreted scripts by invoked name, this can easily kill too much if you happen to be running, e.g., a text editor that's editing the script you're killing the processes of. This problem can be reduced by including the interpretor's name, but such a solution is then fragile against program updates changing their interpretors. " if [ -z "$1" ]; then echo -e "$usage" exit 1 fi IFS=$'\n' for name in "$@"; do # TODO: Why doesn't $BASHPID work directly?!‽ ## 'pgrep' is no substitute for grepping thru ps output for args # shellcheck disable=SC2009 for line in $(bp=$BASHPID; ps xo pid=,args= | grep -E "$name" | grep -v "grep $name" | grep -Ev " *($bp|$$) "); do pid="$(echo "$line" | sed -r 's/\s*([0-9]+) .*/\1/g')" kill "$pid" done done
#!/bin/bash # usage: dump-foundobs.sh zchecker.db new.db if [[ -z "$1" || -z "$2" ]] then echo "Usage: dump-ztf-i-foundobs.sh zchecker.db new.db"; exit 1; fi sqlite3 $1 <<EOF ATTACH DATABASE "${2}" AS zb; CREATE TABLE IF NOT EXISTS zb.ztf_found( foundid INTEGER PRIMARY KEY, objid INTEGER KEY, obsid INTEGER KEY, desg TEXT, nightid INTEGER KEY, obsdate TEXT, ra FLOAT, dec FLOAT, dra FLOAT, ddec FLOAT, ra3sig FLOAT, dec3sig FLOAT, vmag FLOAT, rh FLOAT, rdot FLOAT, delta FLOAT, phase FLOAT, sangle FLOAT, trueanomaly FLOAT, tmtp FLOAT, infobits INTEGER, filtercode TEXT, filefracday INTEGER, field INTEGER, ccdid INTEGER, qid INTEGER, airmass FLOAT, seeing FLOAT, maglimit FLOAT, programid INTEGER, stackid INTEGER KEY, dx FLOAT, dy FLOAT, bgap INTEGER, bg FLOAT, bg_area INTEGER, bg_stdev FLOAT, flux BLOB, m BLOB, merr BLOB, flag INTEGER, m5 FLOAT, ostat FLOAT, archivefile TEXT ); CREATE UNIQUE INDEX IF NOT EXISTS zb.ztf_found_objid_obsid ON ztf_found(obsid,objid); INSERT OR IGNORE INTO zb.ztf_found SELECT foundid,objid,obsid,desg,nightid,obsdate,ra,dec,dra,ddec,ra3sig,dec3sig, vmag,rh,rdot,delta,phase,sangle,trueanomaly,tmtp,infobits,filtercode,filefracday,field, ccdid,qid,airmass,seeing,maglimit,programid,stackid,dx,dy,bgap,bg,bg_area,bg_stdev,flux, m,merr,flag,m5,ostat,archivefile FROM ztf_found LEFT JOIN ztf_cutouts USING (foundid) LEFT JOIN obj USING (objid) LEFT JOIN ztf_stacks USING (stackid) LEFT JOIN ztf_phot USING (foundid); CREATE TABLE IF NOT EXISTS zb.obj(objid INTEGER PRIMARY KEY, desg); INSERT OR IGNORE INTO zb.obj SELECT objid,desg FROM obj; CREATE TABLE IF NOT EXISTS zb.ztf_nights( nightid INTEGER PRIMARY KEY, date TEXT, exposures INTEGER, quads INTEGER ); INSERT OR IGNORE INTO zb.ztf_nights SELECT nightid,date,exposures,quads FROM ztf_nights; CREATE TABLE IF NOT EXISTS zb.obj_summary( objid INTEGER PRIMARY KEY, desg TEXT, nobs INTEGER, nnights INTEGER, last_night TEXT, vmag FLOAT, rh FLOAT, m FLOAT, merr FLOAT, ostat FLOAT, ng INTEGER, nr INTEGER, ni INTEGER ); INSERT OR REPLACE INTO zb.obj_summary SELECT objid,desg,nobs,nnights,SUBSTR(last_night,1,10),last_vmag,last_rh,last_m,last_merr,last_ostat,ng,nr,ni FROM zb.ztf_found JOIN ( SELECT t1.objid, last_night, t1.vmag as last_vmag, t1.rh as last_rh, t1.m as last_m, t1.merr as last_merr, t1.ostat as last_ostat, nobs,nnights,ng,nr,ni FROM zb.ztf_found t1 JOIN ( SELECT objid,MAX(obsdate) AS last_night, COUNT() AS nobs,COUNT(DISTINCT nightid) AS nnights, SUM(filtercode = 'zg') AS ng, SUM(filtercode = 'zr') AS nr, SUM(filtercode = 'zi') AS ni FROM zb.ztf_found WHERE m NOT NULL GROUP BY objid) t2 ON t1.objid = t2.objid AND t1.obsdate = t2.last_night ) USING (objid) GROUP BY objid; CREATE TABLE IF NOT EXISTS zb.ztf_stacks( stackid INTEGER PRIMARY KEY, stackfile TEXT ); INSERT OR IGNORE INTO zb.ztf_stacks SELECT stackid,stackfile FROM ztf_stacks; CREATE TABLE IF NOT EXISTS zb.outbursts( foundid INTEGER PRIMARY KEY, objid INTEGER, COMMENT TEXT ); CREATE INDEX IF NOT EXISTS zb.outbursts_objid_index ON outbursts(objid); EOF
#!/usr/bin/env bash # Variables # ------------------------------------------------------------------------------ readonly PACKAGE_VERSION="v$(node -p -e "require('./package.json').release")" readonly AWS_S3_BUCKET="sdk.10darts.com" readonly CLOUDFRONT_DISTRIBUTION_ID="EJQDLWYC89E1C" # Buld and upload # ------------------------------------------------------------------------------ npm run build aws --profile 10darts s3 cp dist/10dartsSDK.js s3://${AWS_S3_BUCKET}/${PACKAGE_VERSION}/ --acl public-read aws --profile 10darts s3 cp dist/10dartsServiceWorker.js s3://${AWS_S3_BUCKET}/${PACKAGE_VERSION}/ --acl public-read aws --profile 10darts cloudfront create-invalidation --distribution-id ${CLOUDFRONT_DISTRIBUTION_ID} --paths /${PACKAGE_VERSION}/*
<filename>spec/models/concerns/contact_list_matcher_behaviour_spec.rb require "rails_helper" RSpec.describe ContactListMatcherBehaviour do subject do described_module = described_class unless defined?(TestMatcher) stub_const("TestMatcher", Class.new do include described_module end) end TestMatcher.new end describe '#category' do it 'returns the model name humanized' do expect(subject.category).to eq('Test matcher') end end describe '#add' do let(:contacts) { 'Bob' } context 'when adding a single contact' do it 'adds the contact to contact list' do expect{ subject.add(1, contacts) }.to change(subject, :contacts).from([]).to(['Bob']) end end context 'when adding a several contacts' do context 'with the same score' do let(:contacts) { %w[Bob Alice] } it 'adds contacts to contact list' do expect{ subject.add(1, contacts) }.to change(subject, :contacts).from([]).to(%w[Bob Alice]) end end context 'with different scores' do let(:contacts_one) { %w[Mark Jez] } let(:contacts_half_one) { ['<NAME>'] } it 'adds contacts to contact list' do expect{ subject.add(1, contacts_one) subject.add(0.5, contacts_half_one) }.to change(subject, :contacts).from([]).to(['Mark', 'Jez', '<NAME>']) end end end end describe '#any?' do context 'with no contacts' do it { is_expected.not_to be_any } end context 'with a contact' do before { subject.add 1, 'Jez' } it { is_expected.to be_any } end end end
<gh_stars>1-10 package au.org.noojee.irrigation.widgets.client.timerLabel; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.ui.Widget; import com.vaadin.client.communication.RpcProxy; import com.vaadin.client.communication.StateChangeEvent; import com.vaadin.client.ui.AbstractComponentConnector; import com.vaadin.shared.ui.Connect; @Connect(au.org.noojee.irrigation.widgets.timerLabel.TimerLabelComponent.class) // NO_UCD public class TimerLabelConnector extends AbstractComponentConnector { private static final long serialVersionUID = 3279348308010471050L; TimerLabelServerRpc rpc = RpcProxy.create(TimerLabelServerRpc.class, this); public TimerLabelConnector() { registerRpc(TimerLabelClientRpc.class, new TimerLabelClientRpc() { private static final long serialVersionUID = -4175656221548699772L; @Override public void start() { getWidget().start(); } @Override public void stop() { getWidget().stop(); } @Override public void setInitialValue(TimeThreshold[] thresholds) { getWidget().setInitialValue(thresholds); } }); } @Override protected Widget createWidget() { TimerLabelWidget widget = GWT.create(TimerLabelWidget.class); widget.setRpc(rpc); return widget; } @Override public TimerLabelWidget getWidget() { return (TimerLabelWidget) super.getWidget(); } @Override public TimerLabelState getState() { return (TimerLabelState) super.getState(); } @Override public void onStateChanged(StateChangeEvent stateChangeEvent) { super.onStateChanged(stateChangeEvent); getWidget().restoreState(getState()); } }
<gh_stars>10-100 import React, { Component } from 'react'; import PropTypes from 'prop-types'; import AccessTimeIcon from 'react-icons/lib/md/access-time'; import VolumeOffIcon from 'react-icons/lib/md/volume-off'; import VolumeUpIcon from 'react-icons/lib/md/volume-up'; import CloseIcon from 'react-icons/lib/md/close'; import SendIcon from 'react-icons/lib/md/send'; import axios from 'axios'; import moment from 'moment'; import { connect } from 'react-redux'; import { compose } from 'redux'; import { addSong } from 'Redux/api/currentStation/actions'; import { setPreviewVideo, muteVideoRequest } from 'Redux/page/station/actions'; import Autosuggest from 'react-autosuggest'; import match from 'autosuggest-highlight/match'; import parse from 'autosuggest-highlight/parse'; import Grid from 'material-ui/Grid'; import Tooltip from 'material-ui/Tooltip'; import Button from 'material-ui/Button'; import Icon from 'material-ui/Icon'; import IconButton from 'material-ui/IconButton'; import Card from 'material-ui/Card'; import TextField from 'material-ui/TextField'; import Paper from 'material-ui/Paper'; import Typography from 'material-ui/Typography'; import { withStyles } from 'material-ui/styles'; import withRouter from 'react-router-dom/withRouter'; import { MenuItem } from 'material-ui/Menu'; import { Player } from 'Component'; import { withNotification } from 'Component/Notification'; import { Images } from 'Theme'; import { transformText, transformNumber } from 'Transformer'; import classNames from 'classnames'; import styles from './styles'; /* eslint-disable no-shadow */ class AddLink extends Component { constructor(props) { super(props); this.state = { videoId: '', searchText: '', songMessage: '', suggestions: [], notFoundSearchResults: false, isDisableButton: true, isAddLinkProgress: false, muted: true, userDid: false, }; this._onChange = this._onChange.bind(this); this._onAddClick = this._onAddClick.bind(this); this._onSuggestionsFetchRequested = this._onSuggestionsFetchRequested.bind( this, ); this._onSuggestionsClearRequested = this._onSuggestionsClearRequested.bind( this, ); this._onSuggestionSelected = this._onSuggestionSelected.bind(this); this._renderLinkBoxSection = this._renderLinkBoxSection.bind(this); this._renderPreviewSection = this._renderPreviewSection.bind(this); this._renderSuggestion = this._renderSuggestion.bind(this); this._renderInput = this._renderInput.bind(this); this._onVolumeClick = this._onVolumeClick.bind(this); this._clearSearchInput = this._clearSearchInput.bind(this); this._onSongMessageChange = this._onSongMessageChange.bind(this); } componentWillUnmount() { this.props.setPreviewVideo(); } componentWillReceiveProps(nextProps) { const { mutePreview, muteNowPlaying, userDid, currentStation } = nextProps; this.setState({ muted: mutePreview }); // Save volume status into local storage for reloading the page const volumeStatus = { muteNowPlaying, mutePreview, userDid, }; localStorage.setItem('volumeStatus', JSON.stringify(volumeStatus)); // Reset add link box when navigating to another station if ( (this.props.currentStation && this.props.currentStation.station_id) !== (currentStation && currentStation.station_id) ) { this.setState({ searchText: '' }); } } /* Get info of a video or list of videos based on ids from search results */ _getVideoUrl(video) { return `${process.env.REACT_APP_YOUTUBE_URL + video.id}&t=0s`; } async _getVideoInfo(id) { const { data: { items }, } = await axios.get(`${process.env.REACT_APP_YOUTUBE_API_URL}/videos`, { params: { key: process.env.REACT_APP_YOUTUBE_API_KEY, part: 'id,snippet,contentDetails,status', id, }, }); return items; } /* Get search results */ async _getSearchResults(value) { const { data: { items }, } = await axios.get(`${process.env.REACT_APP_YOUTUBE_API_URL}/search`, { params: { key: process.env.REACT_APP_YOUTUBE_API_KEY, q: value, part: 'snippet', safeSearch: 'strict', // regionCode: 'VN', // STAMEQ type: 'video', videoEmbeddable: 'true', // videoSyndicated: 'true', maxResults: 5, videoDefinition: 'any', relevanceLanguage: 'en', }, }); // Get all video ids from search results that used to get info of those (contains more params like containDetails, status,...) let videoIds = ''; items.forEach(item => { videoIds += `${item.id.videoId},`; }); const result = await this._getVideoInfo(videoIds); return result; } /** AutoComplete Search */ _renderInput(inputProps) { const { classes, value, ref, ...other } = inputProps; return [ <TextField key={1} autoComplete="search-input" id="search-input" name="search-input" className={classes.textField} value={value} inputRef={ref} InputProps={{ classes: { input: classes.input, }, ...other, }} />, <IconButton key={2} color="default" onClick={this._clearSearchInput} className={classes.closeIcon} > <CloseIcon /> </IconButton>, ]; } _renderSuggestion(suggestion, { query, isHighlighted }) { const { classes } = this.props; const matches = match(suggestion.snippet.title, query); const parts = parse(suggestion.snippet.title, matches); return ( <MenuItem selected={isHighlighted} component="div"> <img src={suggestion.snippet.thumbnails.default.url} className={classes.searchItemImg} /> <span> {parts.map((part, index) => <span key={index}>{part.text}</span>)} </span> </MenuItem> ); } static _renderSuggestionsContainer(options) { const { containerProps, children } = options; return ( <Paper {...containerProps} square> {children} </Paper> ); } static _getSuggestionValue(suggestion) { return suggestion.snippet.title; } _timeoutSearchFunc; _onSuggestionsFetchRequested({ value }) { const { setPreviewVideo, notification } = this.props; try { clearTimeout(this._timeoutSearchFunc); this._timeoutSearchFunc = setTimeout(async () => { // Display preview if result is a youtube link without search if (transformText.checkValidYoutubeUrl(value)) { // skip the other params of youtube link // just get the main part: https://www.youtube.com/watch?v={video_id} const input = `${value.split('&')[0]}&t=0s`; const videoId = transformText.checkValidYoutubeUrl(input); const data = await this._getVideoInfo(videoId); // if the video is deleted from youtube if (data.length === 0) { this.setState({ notFoundSearchResults: true, }); } else { const embeddableVideo = data[0].status.embeddable; setPreviewVideo(data[0]); // The "Add" button will be depended on that the video is embeddable onto your website or not this.setState({ isDisableButton: !embeddableVideo, }); if (!embeddableVideo) { notification.app.warning({ message: 'Your video cannot be added because of copyright issue or it is blocked from the owner.', duration: 10000, }); } } } // Search by keyword if value is not a youtube link if (!transformText.checkValidYoutubeUrl(value)) { const data = await this._getSearchResults(value); this.setState( { videoId: '', suggestions: data, }, () => { if (this.state.suggestions.length === 0) { this.setState({ notFoundSearchResults: true }); } }, ); } else { this.setState({ suggestions: [], }); } }, 300); } catch (error) { console.log(error); } } _onSuggestionsClearRequested() { this.setState({ suggestions: [], }); } _onSuggestionSelected(e, { suggestion }) { const { nowPlaying, setPreviewVideo } = this.props; if (!nowPlaying.url) { this.setState({ isMute: true }); } setPreviewVideo(suggestion); this.previewVideo = suggestion; this.setState({ isDisableButton: false, searchText: suggestion.snippet.title, videoId: suggestion.videoId, }); } /** End of autoComplete search */ /* Handle add link events */ _clearSearchInput() { const { setPreviewVideo } = this.props; this.setState({ searchText: '', notFoundSearchResults: false, }); setPreviewVideo(); } _onChange(e) { const result = e.target.value; const { setPreviewVideo } = this.props; this.setState({ searchText: result }); if (result === '') { setPreviewVideo(); this.setState({ isDisableButton: true, videoId: '', notFoundSearchResults: false, }); } } _onSongMessageChange(e) { this.setState({ songMessage: e.target.value, }); } _onAddClick() { const { preview, addSong, setPreviewVideo, muteVideoRequest, muteNowPlaying, userDid, match: { params: { stationId }, }, user: { userId, username, name, avatar_url }, notification, } = this.props; // If authenticated setPreviewVideo(); muteVideoRequest({ muteNowPlaying: userDid ? muteNowPlaying : false, userDid, }); addSong({ songUrl: this._getVideoUrl(preview), title: preview.snippet.title, thumbnail: preview.snippet.thumbnails.default.url, stationId, userId, songMessage: this.state.songMessage, creator: { username, name, avatar_url }, duration: moment .duration(preview.contentDetails.duration) .asMilliseconds(), localstations: localStorage.getItem('local-stations'), }); this.setState({ searchText: '', songMessage: '', isDisableButton: true, isMute: true, }); } /* End of handle add link events */ /* Handle preview volume */ _onVolumeClick() { const { muteVideoRequest, userDid, muteNowPlaying, mutePreview, } = this.props; muteVideoRequest({ muteNowPlaying: userDid && muteNowPlaying ? muteNowPlaying : mutePreview, mutePreview: !mutePreview, userDid: !!(userDid && muteNowPlaying), }); } /* Render icon if there is not preview content */ _renderEmptyComponent() { const { classes } = this.props; const { notFoundSearchResults } = this.state; return ( <Grid container className={classes.emptyCollection} justify="center" alignItems="center" > {notFoundSearchResults ? ( <img src={Images.notFound} className={classes.notFound} /> ) : ( <img src={Images.loadingSong} className={classes.emptyImg} /> )} </Grid> ); } _renderLinkBoxSection() { const { classes } = this.props; return ( <Grid item md={4} xs={12} className={classes.addLinkBoxLeft}> <Grid container className={classes.gridContainer} direction="column" justify="space-between" > <Grid item xs={12}> <Autosuggest theme={{ container: classes.autoSearchContainer, suggestionsContainerOpen: classes.suggestionsContainerOpen, suggestionsList: classes.suggestionsList, suggestion: classes.suggestion, }} alwaysRenderSuggestions={false} renderInputComponent={this._renderInput} suggestions={this.state.suggestions} onSuggestionsFetchRequested={this._onSuggestionsFetchRequested} onSuggestionsClearRequested={this._onSuggestionsClearRequested} onSuggestionSelected={this._onSuggestionSelected} renderSuggestionsContainer={AddLink._renderSuggestionsContainer} getSuggestionValue={AddLink._getSuggestionValue} renderSuggestion={this._renderSuggestion} inputProps={{ classes, placeholder: 'Type the video name. e.g. Shape of you,...', value: this.state.searchText, onChange: this._onChange, }} /> </Grid> </Grid> </Grid> ); } _renderPreviewSection() { const { classes, preview } = this.props; const { isDisableButton, muted } = this.state; let view = null; if (preview === null) { view = this._renderEmptyComponent(); } else { const videoDuration = moment.duration(preview.contentDetails.duration); view = ( <Grid container className={classes.content}> <Grid item xs={12} sm={4} className={classes.previewImg}> <Player url={this._getVideoUrl(preview)} showProgressbar={false} muted={muted} playing={true} enablePointerEvent={'all'} /> </Grid> <Grid item sm={8} xs={12} className={classes.previewRightContainer}> <p className={classes.previewTitle}>{preview.snippet.title}</p> {preview && ( <div className={classes.durationContainer}> <AccessTimeIcon color={'rgba(0, 0, 0, 0.54)'} /> {videoDuration >= 300000 ? ( <Tooltip placement={'bottom-start'} title="This video has long duration." > <p className={classNames( classes.durationText, classes.warningText, )} > {transformNumber.millisecondsToTime(videoDuration)} </p> </Tooltip> ) : ( <p className={classNames( classes.durationText, classes.secondaryText, )} > {transformNumber.millisecondsToTime(videoDuration)} </p> )} <p className={classNames( classes.secondaryText, classes.channelName, )} > Channel: {preview.snippet.channelTitle} </p> </div> )} <TextField fullWidth multiline rowsMax={1} placeholder="Do you want to say something about this video?" value={this.state.songMessage} onChange={this._onSongMessageChange} className={classes.messageInput} /> <IconButton onClick={this._onVolumeClick} className={classes.volume} color="default" > {muted ? <VolumeOffIcon /> : <VolumeUpIcon />} </IconButton> <Button className={classes.sendBtn} raised color="primary" disabled={isDisableButton} mini={true} onClick={this._onAddClick} > Add{' '} <Icon className={classes.sendIcon}> <SendIcon /> </Icon> </Button> </Grid> </Grid> ); } return ( <Grid item xs={12} md={8} className={classes.addLinkBoxRight}> {view} </Grid> ); } render() { const { classes } = this.props; return ( <Grid container className={classes.addLinkContainer}> <Grid item xs={12} className={classes.linkTitle}> <div> <Typography type={'display1'} className={classes.primaryText}> Add song </Typography> <span className={classes.secondaryText} /> </div> </Grid> <Card className={classes.addLinkBox}> <Grid item xs={12}> <Grid container className={classes.gridContainer}> {this._renderLinkBoxSection()} {this._renderPreviewSection()} </Grid> </Grid> </Card> </Grid> ); } } AddLink.propTypes = { classes: PropTypes.object.isRequired, addSong: PropTypes.func, setPreviewVideo: PropTypes.func, preview: PropTypes.object, nowPlaying: PropTypes.object, match: PropTypes.any, user: PropTypes.any, muteVideoRequest: PropTypes.func, mutePreview: PropTypes.bool, muteNowPlaying: PropTypes.bool, userDid: PropTypes.bool, isAuthenticated: PropTypes.bool, joinedStation: PropTypes.bool, notification: PropTypes.object, currentStation: PropTypes.object, }; const mapStateToProps = ({ page, api }) => ({ preview: page.station.preview, mutePreview: page.station.mutePreview, muteNowPlaying: page.station.muteNowPlaying, userDid: page.station.userDid, user: api.user.data, nowPlaying: api.currentStation.nowPlaying, isAuthenticated: api.user.isAuthenticated, joinedStation: page.station.joinedStation, currentStation: api.currentStation.station, }); const mapDispatchToProps = dispatch => ({ addSong: option => dispatch(addSong(option)), setPreviewVideo: video => dispatch(setPreviewVideo(video)), muteVideoRequest: ({ muteNowPlaying, mutePreview, userDid }) => dispatch(muteVideoRequest({ muteNowPlaying, mutePreview, userDid })), }); export default compose( withStyles(styles), connect( mapStateToProps, mapDispatchToProps, ), withRouter, withNotification, )(AddLink);
import * as PIXI from 'pixi.js'; export const utils = PIXI.utils, Application = PIXI.Application, Container = PIXI.Container, loader = PIXI.Loader, resources = PIXI.resources, TextureCache = PIXI.utils.TextureCache, Sprite = PIXI.Sprite, Rectangle = PIXI.Rectangle;
<filename>app/controllers/producers_controller.rb class ProducersController < ApplicationController before_action :set_producer, only: %i[ show edit update destroy ] # GET /producers or /producers.json def index @producers = Producer.all end # GET /producers/1 or /producers/1.json def show end # GET /producers/new def new @producer = Producer.new end # GET /producers/1/edit def edit end # POST /producers or /producers.json def create @producer = Producer.new(producer_params) respond_to do |format| if @producer.save format.html { redirect_to producer_url(@producer), notice: "Producer was successfully created." } format.json { render :show, status: :created, location: @producer } else format.html { render :new, status: :unprocessable_entity } format.json { render json: @producer.errors, status: :unprocessable_entity } end end end # PATCH/PUT /producers/1 or /producers/1.json def update respond_to do |format| if @producer.update(producer_params) format.html { redirect_to producer_url(@producer), notice: "Producer was successfully updated." } format.json { render :show, status: :ok, location: @producer } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @producer.errors, status: :unprocessable_entity } end end end # DELETE /producers/1 or /producers/1.json def destroy @producer.destroy respond_to do |format| format.html { redirect_to producers_url, notice: "Producer was successfully destroyed." } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_producer @producer = Producer.find(params[:id]) end # Only allow a list of trusted parameters through. def producer_params params.require(:producer).permit(:name) end end
#!/bin/bash if [[ "$@" == "bash" ]]; then exec $@ fi if [[ -z $RUNNER_NAME ]]; then echo "RUNNER_NAME environment variable is not set, using '${HOSTNAME}'." export RUNNER_NAME=${HOSTNAME} fi if [[ -z $RUNNER_WORK_DIRECTORY ]]; then echo "RUNNER_WORK_DIRECTORY environment variable is not set, using '_work'." export RUNNER_WORK_DIRECTORY="_work" fi if [[ -z $RUNNER_TOKEN && -z $GITHUB_ACCESS_TOKEN ]]; then echo "Error : You need to set RUNNER_TOKEN (or GITHUB_ACCESS_TOKEN) environment variable." exit 1 fi if [[ -z $RUNNER_REPOSITORY_URL && -z $RUNNER_ORGANIZATION_URL ]]; then echo "Error : You need to set the RUNNER_REPOSITORY_URL (or RUNNER_ORGANIZATION_URL) environment variable." exit 1 fi if [[ -z $RUNNER_REPLACE_EXISTING ]]; then export RUNNER_REPLACE_EXISTING="true" fi CONFIG_OPTS="" if [ "$(echo $RUNNER_REPLACE_EXISTING | tr '[:upper:]' '[:lower:]')" == "true" ]; then CONFIG_OPTS="--replace" fi if [[ -n $RUNNER_LABELS ]]; then CONFIG_OPTS="${CONFIG_OPTS} --labels ${RUNNER_LABELS}" fi if [[ -f ".runner" ]]; then echo "Runner already configured. Skipping config." else if [[ ! -z $RUNNER_ORGANIZATION_URL ]]; then SCOPE="orgs" RUNNER_URL="${RUNNER_ORGANIZATION_URL}" else SCOPE="repos" RUNNER_URL="${RUNNER_REPOSITORY_URL}" fi if [[ -n $GITHUB_ACCESS_TOKEN ]]; then echo "Exchanging the GitHub Access Token with a Runner Token (scope: ${SCOPE})..." _PROTO="$(echo "${RUNNER_URL}" | grep :// | sed -e's,^\(.*://\).*,\1,g')" _URL="$(echo "${RUNNER_URL/${_PROTO}/}")" _PATH="$(echo "${_URL}" | grep / | cut -d/ -f2-)" RUNNER_TOKEN="$(curl -XPOST -fsSL \ -H "Authorization: token ${GITHUB_ACCESS_TOKEN}" \ -H "Accept: application/vnd.github.v3+json" \ "https://api.github.com/${SCOPE}/${_PATH}/actions/runners/registration-token" \ | jq -r '.token')" fi ./config.sh \ --url $RUNNER_URL \ --token $RUNNER_TOKEN \ --name $RUNNER_NAME \ --work $RUNNER_WORK_DIRECTORY \ $CONFIG_OPTS \ --unattended fi exec "$@"
mvn clean source:jar install -Dmaven.test.skip
import nltk from nltk.tokenize import sent_tokenize from nltk.sentiment.vader import SentimentIntensityAnalyzer sentence = "This movie was extremely disappointing." sid = SentimentIntensityAnalyzer() sentiment = sid.polarity_scores(sentence) if sentiment['compound'] >= 0.05: sentiment_label = "positive" elif sentiment['compound'] <= - 0.05: sentiment_label = "negative" else: sentiment_label = "neutral" print(sentiment_label) # prints "negative"
let getZoneTime = function (date, timezone) { let offset = date.getTimezoneOffset() * 60 * 1000 // 单位为分钟的时间差 return new Date(date + offset + timezone * 60 * 60 * 1000) } let getZoneDate = function (date = new Date(), timezone = 8) { let offset = date.getTimezoneOffset() * 60 * 1000 return new Date(date.getTime() + offset + timezone * 60 * 60 * 1000) } let formatTime = function (date, fmt) { // meizz let o = { "M+": date.getMonth() + 1, //月份 "d+": date.getDate(), //日 "h+": date.getHours(), //小时 "m+": date.getMinutes(), //分 "s+": date.getSeconds(), //秒 "q+": Math.floor((date.getMonth() + 3) / 3), //季度 "S": date.getMilliseconds() //毫秒 } if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)) for (let k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))) return fmt } module.exports = { /** * 解析URL参数 * @param {URL} url * @param {String} name * @return URL.params[name] */ getParameterByName (url, name) { if (!url || !name) return "" name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]") let reg = new RegExp("[\\?&]" + name + "=([^&#]*)"), result = reg.exec(url) return result === null ? "" : decodeURIComponent(result[1]) }, /** * 获取当前时区时间(默认东八区) * @param {Number} timezone 时区 * @return {Date} 指定时区时间 */ getZoneTime (date, timezone = 8) { return getZoneTime(date, timezone) }, getZoneDate () { return getZoneDate(new Date(), 8) }, /** * 格式化控制台输出时间 * @param {Date} date 时间 * @param {Number} zonetime 时区 */ formatTime (date, fmt = 'yyyy-MM-dd hh:mm:ss', zonetime = 8) { let now = getZoneTime(date, zonetime) return formatTime(date, fmt) }, /** * 获取两个日期的时间差 * @param {Date} day1 * @param {Date} day2 * @return day2 - day1 得到的天数差距(精确到day) */ getDateGap (day1, day2) { let gap = day2.getTime() - day1.getTime() return parseInt(gap / (1000 * 60 * 60 * 24)) }, }
package dendromica_core; import net.minecraft.entity.EntityType; import net.minecraft.entity.SpawnGroup; import net.minecraft.util.Identifier; import net.minecraft.world.biome.Biome; import net.minecraft.world.gen.feature.*; import net.minecraft.world.gen.surfacebuilder.SurfaceBuilder; public class EurenitePlains extends Biome { public EurenitePlains(){ super(new Biome.Settings() .configureSurfaceBuilder(SurfaceBuilder.DEFAULT, SurfaceBuilder.GRASS_CONFIG) .precipitation(Biome.Precipitation.RAIN) .category(Biome.Category.PLAINS) .depth(0.24f) .scale(0.2f) .temperature(0.6f) .downfall(0.7f) .parent((String)null)); this.addStructureFeature(StructureFeature.MINESHAFT.configure(new MineshaftFeatureConfig(0.004000000189989805D, net.minecraft.world.gen.feature.MineshaftFeature.Type.NORMAL))); this.addStructureFeature(StructureFeature.STRONGHOLD.configure(FeatureConfig.DEFAULT)); this.addStructureFeature(StructureFeature.VILLAGE.configure(new StructurePoolFeatureConfig(new Identifier("village/plains/town_centers"), 6))); DefaultBiomeFeatures.addLandCarvers(this); DefaultBiomeFeatures.addDefaultLakes(this); DefaultBiomeFeatures.addDungeons(this); DefaultBiomeFeatures.addDefaultFlowers(this); DefaultBiomeFeatures.addDefaultGrass(this); DefaultBiomeFeatures.addMineables(this); DefaultBiomeFeatures.addDefaultOres(this); DefaultBiomeFeatures.addDefaultDisks(this); DefaultBiomeFeatures.addDefaultVegetation(this); DefaultBiomeFeatures.addSprings(this); this.addSpawn(SpawnGroup.CREATURE, new Biome.SpawnEntry(EntityType.SHEEP, 12, 4, 4)); this.addSpawn(SpawnGroup.CREATURE, new Biome.SpawnEntry(EntityType.PIG, 10, 4, 4)); this.addSpawn(SpawnGroup.CREATURE, new Biome.SpawnEntry(EntityType.CHICKEN, 10, 4, 4)); this.addSpawn(SpawnGroup.CREATURE, new Biome.SpawnEntry(EntityType.COW, 8, 4, 4)); this.addSpawn(SpawnGroup.MONSTER, new Biome.SpawnEntry(EntityType.SPIDER, 100, 4, 4)); this.addSpawn(SpawnGroup.MONSTER, new Biome.SpawnEntry(EntityType.ZOMBIE, 95, 4, 4)); this.addSpawn(SpawnGroup.MONSTER, new Biome.SpawnEntry(EntityType.ZOMBIE_VILLAGER, 5, 1, 1)); this.addSpawn(SpawnGroup.MONSTER, new Biome.SpawnEntry(EntityType.SKELETON, 100, 4, 4)); this.addSpawn(SpawnGroup.MONSTER, new Biome.SpawnEntry(EntityType.CREEPER, 100, 4, 4)); this.addSpawn(SpawnGroup.MONSTER, new Biome.SpawnEntry(EntityType.SLIME, 100, 4, 4)); this.addSpawn(SpawnGroup.MONSTER, new Biome.SpawnEntry(EntityType.ENDERMAN, 10, 1, 4)); } }
<filename>jhiRoot/plantsMS/src/main/java/fr/syncrase/ecosyst/web/rest/SolResource.java package fr.syncrase.ecosyst.web.rest; import fr.syncrase.ecosyst.domain.Sol; import fr.syncrase.ecosyst.repository.SolRepository; import fr.syncrase.ecosyst.service.SolQueryService; import fr.syncrase.ecosyst.service.SolService; import fr.syncrase.ecosyst.service.criteria.SolCriteria; import fr.syncrase.ecosyst.web.rest.errors.BadRequestAlertException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Objects; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import tech.jhipster.web.util.HeaderUtil; import tech.jhipster.web.util.PaginationUtil; import tech.jhipster.web.util.ResponseUtil; /** * REST controller for managing {@link fr.syncrase.ecosyst.domain.Sol}. */ @RestController @RequestMapping("/api") public class SolResource { private final Logger log = LoggerFactory.getLogger(SolResource.class); private static final String ENTITY_NAME = "plantsMsSol"; @Value("${jhipster.clientApp.name}") private String applicationName; private final SolService solService; private final SolRepository solRepository; private final SolQueryService solQueryService; public SolResource(SolService solService, SolRepository solRepository, SolQueryService solQueryService) { this.solService = solService; this.solRepository = solRepository; this.solQueryService = solQueryService; } /** * {@code POST /sols} : Create a new sol. * * @param sol the sol to create. * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new sol, or with status {@code 400 (Bad Request)} if the sol has already an ID. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PostMapping("/sols") public ResponseEntity<Sol> createSol(@RequestBody Sol sol) throws URISyntaxException { log.debug("REST request to save Sol : {}", sol); if (sol.getId() != null) { throw new BadRequestAlertException("A new sol cannot already have an ID", ENTITY_NAME, "idexists"); } Sol result = solService.save(sol); return ResponseEntity .created(new URI("/api/sols/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) .body(result); } /** * {@code PUT /sols/:id} : Updates an existing sol. * * @param id the id of the sol to save. * @param sol the sol to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated sol, * or with status {@code 400 (Bad Request)} if the sol is not valid, * or with status {@code 500 (Internal Server Error)} if the sol couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PutMapping("/sols/{id}") public ResponseEntity<Sol> updateSol(@PathVariable(value = "id", required = false) final Long id, @RequestBody Sol sol) throws URISyntaxException { log.debug("REST request to update Sol : {}, {}", id, sol); if (sol.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } if (!Objects.equals(id, sol.getId())) { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } if (!solRepository.existsById(id)) { throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); } Sol result = solService.save(sol); return ResponseEntity .ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, sol.getId().toString())) .body(result); } /** * {@code PATCH /sols/:id} : Partial updates given fields of an existing sol, field will ignore if it is null * * @param id the id of the sol to save. * @param sol the sol to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated sol, * or with status {@code 400 (Bad Request)} if the sol is not valid, * or with status {@code 404 (Not Found)} if the sol is not found, * or with status {@code 500 (Internal Server Error)} if the sol couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PatchMapping(value = "/sols/{id}", consumes = { "application/json", "application/merge-patch+json" }) public ResponseEntity<Sol> partialUpdateSol(@PathVariable(value = "id", required = false) final Long id, @RequestBody Sol sol) throws URISyntaxException { log.debug("REST request to partial update Sol partially : {}, {}", id, sol); if (sol.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } if (!Objects.equals(id, sol.getId())) { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } if (!solRepository.existsById(id)) { throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); } Optional<Sol> result = solService.partialUpdate(sol); return ResponseUtil.wrapOrNotFound( result, HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, sol.getId().toString()) ); } /** * {@code GET /sols} : get all the sols. * * @param pageable the pagination information. * @param criteria the criteria which the requested entities should match. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of sols in body. */ @GetMapping("/sols") public ResponseEntity<List<Sol>> getAllSols(SolCriteria criteria, Pageable pageable) { log.debug("REST request to get Sols by criteria: {}", criteria); Page<Sol> page = solQueryService.findByCriteria(criteria, pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); return ResponseEntity.ok().headers(headers).body(page.getContent()); } /** * {@code GET /sols/count} : count all the sols. * * @param criteria the criteria which the requested entities should match. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the count in body. */ @GetMapping("/sols/count") public ResponseEntity<Long> countSols(SolCriteria criteria) { log.debug("REST request to count Sols by criteria: {}", criteria); return ResponseEntity.ok().body(solQueryService.countByCriteria(criteria)); } /** * {@code GET /sols/:id} : get the "id" sol. * * @param id the id of the sol to retrieve. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the sol, or with status {@code 404 (Not Found)}. */ @GetMapping("/sols/{id}") public ResponseEntity<Sol> getSol(@PathVariable Long id) { log.debug("REST request to get Sol : {}", id); Optional<Sol> sol = solService.findOne(id); return ResponseUtil.wrapOrNotFound(sol); } /** * {@code DELETE /sols/:id} : delete the "id" sol. * * @param id the id of the sol to delete. * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/sols/{id}") public ResponseEntity<Void> deleteSol(@PathVariable Long id) { log.debug("REST request to delete Sol : {}", id); solService.delete(id); return ResponseEntity .noContent() .headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())) .build(); } }
# port 1 untag vlan 100, 200 # port 2~3 tag vlan 100 # port 4~5 tag vlan 200 # table_add portmap set_unassigned 1 => # table_add portmap set_tagged 2 => # table_add portmap set_tagged 3 => # table_add portmap set_tagged 4 => # table_add portmap set_tagged 5 => # table_add portmap_egress set_unassigned 1 => # table_add portmap_egress vlan_tagged 2 => # table_add portmap_egress vlan_tagged 3 => # table_add portmap_egress vlan_tagged 4 => # table_add portmap_egress vlan_tagged 5 => # tagged # mc_node_create 65000 2 3 4 # mc_node_create 65000 5 6 # mc_node_create 65000 2 3 4 # mc_node_create 65000 5 6 # untagged # mc_node_create 65001 1 # mc_node_create 65001 1 # mc_mgrp_create 100 # mc_mgrp_create 200 # mc_node_associate 100 0 # mc_node_associate 100 1 # mc_node_associate 100 4 # mc_node_associate 200 2 # mc_node_associate 200 3 # mc_node_associate 200 5 table_add dmac dmac_hit 0x020304050601 => 1 table_add dmac dmac_hit 0x020304050611 => 2 table_add dmac dmac_hit 0x020304050622 => 2 # table_add dmac dmac_hit 0x020304050612 100 => 3 # table_add dmac dmac_hit 0x020304050621 200 => 4 # table_add dmac dmac_hit 0x020304050622 200 => 5
# Create fresh dependency package directory rm -rf ./gatech-covid-data-lambda mkdir gatech-covid-data-lambda #mkdir gatech-covid-data-lambda/package # Install dependencies pip3 install --target ./gatech-covid-data-lambda -r requirements.txt # Zip dependencies #cd gatech-covid-data-lambda/package #zip -r9 ../function.zip . #cd .. #rm -rf ./package # Add scripts to lambda folder cp ./lambda_function.py ./gatech-covid-data-lambda/lambda_function.py cp ./scrape_covid_data.py ./gatech-covid-data-lambda/scrape_covid_data.py # Zip the lambda folder rm gatech-covid-data-lambda.zip cd gatech-covid-data-lambda zip -r9 ../gatech-covid-data-lambda.zip .
// This file is part of the casycom project // // Copyright (c) 2015 by <NAME> <<EMAIL>> // This file is free software, distributed under the ISC license. #pragma once #include "main.h" #include <sys/poll.h> #ifdef __cplusplus extern "C" { #endif //---------------------------------------------------------------------- // Timer protocol constants enum ETimerWatchCmd { WATCH_STOP = 0, WATCH_READ = POLLIN, WATCH_WRITE = POLLOUT, WATCH_RDWR = WATCH_READ| WATCH_WRITE, WATCH_TIMER = POLLMSG, WATCH_READ_TIMER = WATCH_READ| WATCH_TIMER, WATCH_WRITE_TIMER = WATCH_WRITE| WATCH_TIMER, WATCH_RDWR_TIMER = WATCH_RDWR| WATCH_TIMER }; typedef uint64_t casytimer_t; enum { TIMER_MAX = INT64_MAX, TIMER_NONE = UINT64_MAX }; //---------------------------------------------------------------------- // PTimer typedef void (*MFN_Timer_watch)(void* vo, enum ETimerWatchCmd cmd, int fd, casytimer_t timer); typedef struct _DTimer { iid_t interface; MFN_Timer_watch Timer_watch; } DTimer; extern const Interface i_Timer; //---------------------------------------------------------------------- void PTimer_watch (const Proxy* pp, enum ETimerWatchCmd cmd, int fd, casytimer_t timeoutms); //---------------------------------------------------------------------- // PTimerR typedef void (*MFN_TimerR_timer)(void* vo, int fd, const Msg* msg); typedef struct _DTimerR { iid_t interface; MFN_TimerR_timer TimerR_timer; } DTimerR; extern const Interface i_TimerR; //---------------------------------------------------------------------- void PTimerR_timer (const Proxy* pp, int fd); //---------------------------------------------------------------------- extern const Factory f_Timer; bool Timer_run_timer (int toWait) noexcept; casytimer_t Timer_now (void) noexcept; size_t Timer_watch_list_size (void) noexcept; size_t Timer_watch_list_for_poll (struct pollfd* fds, size_t fdslen, int* timeout) noexcept NONNULL(1); //---------------------------------------------------------------------- // PTimer inlines #ifdef __cplusplus namespace { #endif static inline void PTimer_stop (const Proxy* pp) { PTimer_watch (pp, WATCH_STOP, -1, TIMER_NONE); } static inline void PTimer_timer (const Proxy* pp, casytimer_t timeoutms) { PTimer_watch (pp, WATCH_TIMER, -1, timeoutms); } static inline void PTimer_wait_read (const Proxy* pp, int fd) { PTimer_watch (pp, WATCH_READ, fd, TIMER_NONE); } static inline void PTimer_wait_write (const Proxy* pp, int fd) { PTimer_watch (pp, WATCH_WRITE, fd, TIMER_NONE); } static inline void PTimer_wait_rdwr (const Proxy* pp, int fd) { PTimer_watch (pp, WATCH_RDWR, fd, TIMER_NONE); } static inline void PTimer_wait_read_with_timeout (const Proxy* pp, int fd, casytimer_t timeoutms) { PTimer_watch (pp, WATCH_READ_TIMER, fd, timeoutms); } static inline void PTimer_wait_write_with_timeout (const Proxy* pp, int fd, casytimer_t timeoutms) { PTimer_watch (pp, WATCH_WRITE_TIMER, fd, timeoutms); } static inline void PTimer_wait_rdwr_with_timeout (const Proxy* pp, int fd, casytimer_t timeoutms) { PTimer_watch (pp, WATCH_RDWR_TIMER, fd, timeoutms); } #ifdef __cplusplus } // namespace } // extern "C" #endif
<reponame>jjasonclark/version_monitor package main import ( "fmt" "net/http" "net/url" ) type monitor struct { past map[string]checkResult slackURL string } // NewMonitor creates a monitor func NewMonitor(slackURL string) monitor { return monitor{make(map[string]checkResult), slackURL} } func (m *monitor) postSlack(msg string) error { data := url.Values{} data.Set("payload", msg) r, err := http.PostForm(m.slackURL, data) if err != nil { return err } r.Body.Close() return nil } func (m *monitor) compareVersions(last, r checkResult) { if last.sameAs(r) { fmt.Printf("%s: Same version as last time %s\n", r.Name, fmt.Sprintf(r.Verify, r.Result)) } else { m.formatMessage(r) } } func (m *monitor) formatMessage(r checkResult) { msg, err := r.output() if err != nil { fmt.Printf("Error creating Slack message: %s\n", err) } else { m.reportToSlack(msg) } } func (m *monitor) reportToSlack(msg string) { fmt.Printf("Slack message: %s\n", msg) if e := m.postSlack(msg); e != nil { fmt.Printf("Failed to post Slack message: %s\n", e) } } func (m *monitor) processResults(results <-chan checkResult, quit <-chan bool) { for { select { case <-quit: return case r := <-results: if r.Err != nil { fmt.Printf("%s: Error: %s\n", r.Name, r.Err) } else { last, ok := m.past[r.Name] m.past[r.Name] = r if ok { m.compareVersions(last, r) } else { fmt.Printf("%s: Initial version %s\n", r.Name, fmt.Sprintf(r.Verify, r.Result)) } } } } }
$(document).ready(function(){ $(".owl-carousel").owlCarousel({ loop:true, margin:10, nav:true, center: true, navText: [ "<i class='testimonial-arrow'><svg xmlns='http://www.w3.org/2000/svg' width='40' height='40' fill='currentColor' class='bi bi-arrow-left-circle-fill' viewBox='0 0 16 16'><path d='M8 0a8 8 0 1 0 0 16A8 8 0 0 0 8 0zm3.5 7.5a.5.5 0 0 1 0 1H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 7.5H11.5z'/></svg></i>", "<i class='testimonial-arrow'><svg xmlns='http://www.w3.org/2000/svg' width='40' height='40' fill='currentColor' class='bi bi-arrow-right-circle-fill' viewBox='0 0 16 16'><path d='M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0zM4.5 7.5a.5.5 0 0 0 0 1h5.793l-2.147 2.146a.5.5 0 0 0 .708.708l3-3a.5.5 0 0 0 0-.708l-3-3a.5.5 0 1 0-.708.708L10.293 7.5H4.5z'/></svg></i>" ], responsive:{ 0:{ items:1 }, 600:{ items:1 }, 1000:{ items:3 } } }); });
package weixin.lottery.controller; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.jeecgframework.core.common.controller.BaseController; import org.jeecgframework.core.common.exception.BusinessException; import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery; import org.jeecgframework.core.common.hibernate.qbc.HqlQuery; import org.jeecgframework.core.common.hibernate.qbc.PageList; import org.jeecgframework.core.common.model.json.AjaxJson; import org.jeecgframework.core.common.model.json.DataGrid; import org.jeecgframework.core.constant.Globals; import org.jeecgframework.core.util.BrowserUtils; import org.jeecgframework.core.util.ExceptionUtil; import org.jeecgframework.core.util.MyBeanUtils; import org.jeecgframework.core.util.ResourceUtil; import org.jeecgframework.core.util.StringUtil; import org.jeecgframework.poi.excel.ExcelExportUtil; import org.jeecgframework.poi.excel.ExcelImportUtil; import org.jeecgframework.poi.excel.entity.ExcelTitle; import org.jeecgframework.poi.excel.entity.ImportParams; import org.jeecgframework.tag.core.easyui.TagUtil; import org.jeecgframework.web.system.service.SystemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import weixin.lottery.entity.WeixinDrawDetailEntity; import weixin.lottery.entity.WeixinDrawrecordParam; import weixin.lottery.service.WeixinDrawDetailServiceI; /** * @Title: Controller * @Description: 抽奖记录表 * @author onlineGenerator * @date 2015-02-07 11:20:39 * @version V1.0 * */ @Scope("prototype") @Controller @RequestMapping("/weixinDrawDetailController") public class WeixinDrawDetailController extends BaseController { /** * Logger for this class */ private static final Logger logger = Logger .getLogger(WeixinDrawDetailController.class); @Autowired private WeixinDrawDetailServiceI weixinDrawDetailService; @Autowired private SystemService systemService; private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @RequestMapping(params = "hdRecord") public ModelAndView hdRecord(HttpServletRequest request) { String hdId = request.getParameter("hdId"); request.setAttribute("hdId", hdId); return new ModelAndView("weixin/lottery/weixinDrawrecordList"); } @RequestMapping(params = "datagridBySql") public void datagridBySql(WeixinDrawrecordParam weixinDrawrecord,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { String hdid = request.getParameter("hdid"); request.setAttribute("hdid", hdid); StringBuffer sql=new StringBuffer(); sql.append("SELECT COUNT(1) counts,hdid , opendid , accountid FROM weixin_draw_detail t where 1=1 " ); if(hdid!=null&&!"".equals(hdid)){ sql.append(" and t.hdid=").append("'").append(hdid).append("'"); } sql.append(" and t.accountid=").append("'").append(ResourceUtil.getWeiXinAccountId()).append("'"); sql.append(" GROUP BY t.hdid ,t.opendid,t.accountid"); HqlQuery hqlQuery=new HqlQuery(WeixinDrawrecordParam.class,sql.toString(),dataGrid); PageList pageList=this.weixinDrawDetailService.getPageListBySql(hqlQuery, false); List<Object[]> list= pageList.getResultList(); List<WeixinDrawrecordParam> param=new ArrayList<WeixinDrawrecordParam>(); int i=0; for (Object[] objects : list) { WeixinDrawrecordParam wd=new WeixinDrawrecordParam(); Object counts=objects[0]; if(counts!=null){ wd.setCounts(Integer.valueOf(counts.toString())); } Object hdi=objects[1]; if(hdi!=null){ wd.setHdid(hdi.toString()); } Object opendid=objects[2]; if(opendid!=null){ wd.setOpendid(opendid.toString()); } Object accountid=objects[3]; if(accountid!=null){ wd.setAccountid(accountid.toString()); } wd.setId(i+""); i++; param.add(wd); } dataGrid.setResults(param); dataGrid.setTotal(pageList.getCount()); dataGrid.setPage(pageList.getCurPageNO()); dataGrid.setRows(pageList.getOffset()); TagUtil.datagrid(response, dataGrid); } /** * 抽奖记录表列表 页面跳转 * * @return */ @RequestMapping(params = "weixinDrawDetail") public ModelAndView weixinDrawDetail(HttpServletRequest request) { request.setAttribute("hdid", request.getParameter("hdid")); request.setAttribute("opendid", request.getParameter("opendid")); return new ModelAndView("weixin/lottery/weixinDrawDetailList"); } /** * easyui AJAX请求数据 * * @param request * @param response * @param dataGrid * @param user */ @RequestMapping(params = "datagrid") public void datagrid(WeixinDrawDetailEntity weixinDrawDetail, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { CriteriaQuery cq = new CriteriaQuery(WeixinDrawDetailEntity.class, dataGrid); // 查询条件组装器 org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, weixinDrawDetail, request.getParameterMap()); try { // 自定义追加查询条件 } catch (Exception e) { throw new BusinessException(e.getMessage()); } cq.add(); this.weixinDrawDetailService.getDataGridReturn(cq, true); TagUtil.datagrid(response, dataGrid); } /** * 删除抽奖记录表 * * @return */ @RequestMapping(params = "doDel") @ResponseBody public AjaxJson doDel(WeixinDrawDetailEntity weixinDrawDetail, HttpServletRequest request) { AjaxJson j = new AjaxJson(); weixinDrawDetail = systemService.getEntity( WeixinDrawDetailEntity.class, weixinDrawDetail.getId()); message = "抽奖记录表删除成功"; try { weixinDrawDetailService.delete(weixinDrawDetail); systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO); } catch (Exception e) { e.printStackTrace(); message = "抽奖记录表删除失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 批量删除抽奖记录表 * * @return */ @RequestMapping(params = "doBatchDel") @ResponseBody public AjaxJson doBatchDel(String ids, HttpServletRequest request) { AjaxJson j = new AjaxJson(); message = "抽奖记录表删除成功"; try { for (String id : ids.split(",")) { WeixinDrawDetailEntity weixinDrawDetail = systemService .getEntity(WeixinDrawDetailEntity.class, id); weixinDrawDetailService.delete(weixinDrawDetail); systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO); } } catch (Exception e) { e.printStackTrace(); message = "抽奖记录表删除失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 添加抽奖记录表 * * @param ids * @return */ @RequestMapping(params = "doAdd") @ResponseBody public AjaxJson doAdd(WeixinDrawDetailEntity weixinDrawDetail, HttpServletRequest request) { AjaxJson j = new AjaxJson(); message = "抽奖记录表添加成功"; try { weixinDrawDetailService.save(weixinDrawDetail); systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO); } catch (Exception e) { e.printStackTrace(); message = "抽奖记录表添加失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 更新抽奖记录表 * * @param ids * @return */ @RequestMapping(params = "doUpdate") @ResponseBody public AjaxJson doUpdate(WeixinDrawDetailEntity weixinDrawDetail, HttpServletRequest request) { AjaxJson j = new AjaxJson(); message = "抽奖记录表更新成功"; WeixinDrawDetailEntity t = weixinDrawDetailService.get( WeixinDrawDetailEntity.class, weixinDrawDetail.getId()); try { MyBeanUtils.copyBeanNotNull2Bean(weixinDrawDetail, t); weixinDrawDetailService.saveOrUpdate(t); systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO); } catch (Exception e) { e.printStackTrace(); message = "抽奖记录表更新失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 抽奖记录表新增页面跳转 * * @return */ @RequestMapping(params = "goAdd") public ModelAndView goAdd(WeixinDrawDetailEntity weixinDrawDetail, HttpServletRequest req) { if (StringUtil.isNotEmpty(weixinDrawDetail.getId())) { weixinDrawDetail = weixinDrawDetailService.getEntity( WeixinDrawDetailEntity.class, weixinDrawDetail.getId()); req.setAttribute("weixinDrawDetailPage", weixinDrawDetail); } return new ModelAndView("weixin/lottery/weixinDrawDetail-add"); } /** * 抽奖记录表编辑页面跳转 * * @return */ @RequestMapping(params = "goUpdate") public ModelAndView goUpdate(WeixinDrawDetailEntity weixinDrawDetail, HttpServletRequest req) { if (StringUtil.isNotEmpty(weixinDrawDetail.getId())) { weixinDrawDetail = weixinDrawDetailService.getEntity( WeixinDrawDetailEntity.class, weixinDrawDetail.getId()); req.setAttribute("weixinDrawDetailPage", weixinDrawDetail); } return new ModelAndView("weixin/lottery/weixinDrawDetail-update"); } /** * 导入功能跳转 * * @return */ @RequestMapping(params = "upload") public ModelAndView upload(HttpServletRequest req) { return new ModelAndView("weixin/lottery/weixinDrawDetailUpload"); } /** * 导出excel * * @param request * @param response */ @RequestMapping(params = "exportXls") public void exportXls(WeixinDrawDetailEntity weixinDrawDetail, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { response.setContentType("application/vnd.ms-excel"); String codedFileName = null; OutputStream fOut = null; try { codedFileName = "抽奖记录表"; // 根据浏览器进行转码,使其支持中文文件名 if (BrowserUtils.isIE(request)) { response.setHeader( "content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(codedFileName, "UTF-8") + ".xls"); } else { String newtitle = new String(codedFileName.getBytes("UTF-8"), "ISO8859-1"); response.setHeader("content-disposition", "attachment;filename=" + newtitle + ".xls"); } // 产生工作簿对象 HSSFWorkbook workbook = null; CriteriaQuery cq = new CriteriaQuery(WeixinDrawDetailEntity.class, dataGrid); org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil .installHql(cq, weixinDrawDetail, request.getParameterMap()); List<WeixinDrawDetailEntity> weixinDrawDetails = this.weixinDrawDetailService .getListByCriteriaQuery(cq, false); workbook = ExcelExportUtil.exportExcel(new ExcelTitle("抽奖记录表列表", "导出人:" + ResourceUtil.getSessionUserName().getRealName(), "导出信息"), WeixinDrawDetailEntity.class, weixinDrawDetails); fOut = response.getOutputStream(); workbook.write(fOut); } catch (Exception e) { } finally { try { fOut.flush(); fOut.close(); } catch (IOException e) { } } } /** * 导出excel 使模板 * * @param request * @param response */ @RequestMapping(params = "exportXlsByT") public void exportXlsByT(WeixinDrawDetailEntity weixinDrawDetail, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { response.setContentType("application/vnd.ms-excel"); String codedFileName = null; OutputStream fOut = null; try { codedFileName = "抽奖记录表"; // 根据浏览器进行转码,使其支持中文文件名 if (BrowserUtils.isIE(request)) { response.setHeader( "content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(codedFileName, "UTF-8") + ".xls"); } else { String newtitle = new String(codedFileName.getBytes("UTF-8"), "ISO8859-1"); response.setHeader("content-disposition", "attachment;filename=" + newtitle + ".xls"); } // 产生工作簿对象 HSSFWorkbook workbook = null; workbook = ExcelExportUtil.exportExcel(new ExcelTitle("抽奖记录表列表", "导出人:" + ResourceUtil.getSessionUserName().getRealName(), "导出信息"), WeixinDrawDetailEntity.class, null); fOut = response.getOutputStream(); workbook.write(fOut); } catch (Exception e) { } finally { try { fOut.flush(); fOut.close(); } catch (IOException e) { } } } @SuppressWarnings("unchecked") @RequestMapping(params = "importExcel", method = RequestMethod.POST) @ResponseBody public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) { AjaxJson j = new AjaxJson(); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { MultipartFile file = entity.getValue();// 获取上传文件对象 ImportParams params = new ImportParams(); params.setTitleRows(2); params.setSecondTitleRows(1); params.setNeedSave(true); try { List<WeixinDrawDetailEntity> listWeixinDrawDetailEntitys = (List<WeixinDrawDetailEntity>) ExcelImportUtil .importExcelByIs(file.getInputStream(), WeixinDrawDetailEntity.class, params); for (WeixinDrawDetailEntity weixinDrawDetail : listWeixinDrawDetailEntitys) { weixinDrawDetailService.save(weixinDrawDetail); } j.setMsg("文件导入成功!"); } catch (Exception e) { j.setMsg("文件导入失败!"); logger.error(ExceptionUtil.getExceptionMessage(e)); } finally { try { file.getInputStream().close(); } catch (IOException e) { e.printStackTrace(); } } } return j; } }
#!/bin/bash # ============================================= # === generate the environment file that systemd will use # ============================================= # env var export PEER_NAME=$(hostname) export PRIVATE_IP=$(ip addr show eth0 | grep -Po 'inet \K[\d.]+') touch /etc/etcd.env echo "PEER_NAME=$PEER_NAME" >> /etc/etcd.env echo "PRIVATE_IP=$PRIVATE_IP" >> /etc/etcd.env # ============================================= # === copy the systemd unit file # ============================================= # hostnames etcd0="master0" etcd1="master1" etcd2="master2" # IP address etcd0ip="10.0.0.4" etcd1ip="10.0.0.5" etcd2ip="10.0.0.6" cat >/etc/systemd/system/etcd.service <<EOF [Unit] Description=etcd Documentation=https://github.com/coreos/etcd Conflicts=etcd.service Conflicts=etcd2.service [Service] EnvironmentFile=/etc/etcd.env Type=notify Restart=always RestartSec=5s LimitNOFILE=40000 TimeoutStartSec=0 ExecStart=/usr/local/bin/etcd --name ${PEER_NAME} \ --data-dir /var/lib/etcd \ --listen-client-urls https://${PRIVATE_IP}:2379 \ --advertise-client-urls https://${PRIVATE_IP}:2379 \ --listen-peer-urls https://${PRIVATE_IP}:2380 \ --initial-advertise-peer-urls https://${PRIVATE_IP}:2380 \ --cert-file=/etc/kubernetes/pki/etcd/server.pem \ --key-file=/etc/kubernetes/pki/etcd/server-key.pem \ --client-cert-auth \ --trusted-ca-file=/etc/kubernetes/pki/etcd/ca.pem \ --peer-cert-file=/etc/kubernetes/pki/etcd/peer.pem \ --peer-key-file=/etc/kubernetes/pki/etcd/peer-key.pem \ --peer-client-cert-auth \ --peer-trusted-ca-file=/etc/kubernetes/pki/etcd/ca.pem \ --initial-cluster $etcd0=https://$etcd0ip:2380,$etcd1=https://$etcd1ip:2380,$etcd2=https://$etcd2ip:2380 \ --initial-cluster-token my-etcd-token \ --initial-cluster-state new [Install] WantedBy=multi-user.target EOF # launch etcd systemctl daemon-reload systemctl start etcd # check if launched successfully systemctl status etcd
<filename>Algorithm/src/test/java/com/leetcode/Solution_395Test.java package com.leetcode; import org.testng.annotations.Test; public class Solution_395Test { @Test public void testLongestSubstring() { Solution_395 solution_395 = new Solution_395(); System.out.println(solution_395.longestSubstring("bbaaacbd", 3)); } }
from flask import Flask, render_template, request, redirect, session, flash from mysqlconnection import MySQLConnector app = Flask(__name__) app.secret_key = 'secretsquirrel' mysql = MySQLConnector(app, 'friendsdb') @app.route('/') def index(): showQuery = 'SELECT * FROM friends' friends = mysql.query_db(showQuery) return render_template('index.html', all_friends = friends) @app.route('/friends/<friend_id>/edit') def edit(friend_id): friend_id = friend_id return render_template('edit.html', friend_id = friend_id) @app.route('/friends/<friend_id>', methods=['POST']) def update(friend_id): data = { 'first_name' : request.form['first_name'], 'last_name' : request.form['last_name'], 'occupation' : request.form['occupation'], 'id' : friend_id } updateQuery = "UPDATE friends SET first_name = :first_name, last_name = :last_name, occupation = :occupation WHERE id = :id" mysql.query_db(updateQuery, data) return redirect('/') @app.route('/friends', methods=['POST']) def create(): data = { 'first_name' : request.form['first_name'], 'last_name' : request.form['last_name'], 'occupation' : request.form['occupation'] } createQuery = 'INSERT INTO friends (first_name, last_name, occupation, created_at, updated_at) VALUES (:first_name, :last_name, :occupation, NOW(), NOW())' mysql.query_db(createQuery, data) return redirect('/') @app.route('/friends/<friend_id>/confirm') def confirm(friend_id): data = { 'id' : friend_id } friend_id = friend_id singleFriendQuery = 'SELECT * FROM friends WHERE id = :id' oneFriend = mysql.query_db(singleFriendQuery, data) return render_template('delete.html', friend_id = friend_id, oneFriend = oneFriend) @app.route('/friends/<friend_id>/delete', methods=['POST']) def destroy(friend_id): data = {'id' : friend_id} deleteQuery = 'DELETE FROM friends WHERE id = :id' mysql.query_db(deleteQuery, data) return redirect('/') app.run(debug=True)
#!/bin/bash set -e cd fontconfig autoreconf -fiv pip install lxml pip install six $CONFIGURE --enable-libxml2 --enable-static=yes --disable-shared $FONTCONFIG_OPTIONS CFLAGS="$FLAGS" $CROSS_COMPILE_FLAGS $MAKE install
import numpy as np import matplotlib.pyplot as plt # FUNCTION: simdarts # PURPOSE: Simulates throwing darts and estimates the value of π # INPUTS: num - Number of darts to be thrown # OUTPUT: Dictionary containing the estimated value of π def simdarts(num): # Generate random coordinates for the darts within the unit square x = np.random.rand(num) y = np.random.rand(num) # Count the number of darts that fall within the unit circle inside_circle = (x**2 + y**2) <= 1 num_inside_circle = np.sum(inside_circle) # Estimate the value of π est_pi = 4 * num_inside_circle / num return {'estpi': est_pi} # FUNCTION: histdarts # PURPOSE: Plot a histogram of the estimated π value of several dart simulations # INPUTS: Number of histogram points; number of darts per simulation def histdarts(numdarts, numsims): estpis = np.zeros(numsims) for c in range(numsims): estpis[c] = simdarts(num=numdarts)['estpi'] # Plot a histogram of the estimated π values plt.hist(estpis, bins=30, edgecolor='black') plt.title('Histogram of Estimated π Values') plt.xlabel('Estimated π Value') plt.ylabel('Frequency') plt.show() # Example usage histdarts(1000, 100)
<reponame>paulholden2/springcm<filename>lib/springcm-sdk/client.rb require "faraday" require "json" require "springcm-sdk/account" require "springcm-sdk/folder" require "springcm-sdk/document" require "springcm-sdk/group" require "springcm-sdk/middleware" module Springcm class Client # Default API client options DEFAULT_OPTIONS = { # If true, the client will use a simple retry mechanism when connection # to the API server fails due to e.g. temporary Internet service outage. # The connection is re-attempted up to five times, delaying 2 ** n # seconds between attempts, where n is the number of previous attempts. retry_connection_failed: true }.freeze attr_reader :access_token # @param data_center [String] Data center name, e.g. uatna11 # @param client_id [String] Your API client ID # @param client_secret [String] Your API client secret # @parma options [Hash] API client options def initialize(data_center, client_id, client_secret, options=DEFAULT_OPTIONS) if !["na11", "uatna11", "eu11", "eu21", "na21", "us11"].include?(data_center) raise Springcm::ConnectionInfoError.new("Invalid data center '#{data_center.to_s}'") end @options = options @data_center = data_center @client_id = client_id @client_secret = client_secret @api_version = "201411" @auth_version = "201606" @access_token end # Connect to the configured SpringCM API service # @param safe If truthy, connection failure does not raise an exception # @return [Boolean] Whether connection was successful def connect(safe=true) conn = Faraday.new(url: auth_url) do |conn| conn.request :retry, retry_statuses: [429], exceptions: [Springcm::RateLimitExceededError] conn.use Springcm::Middleware::RateLimit conn.use Springcm::Middleware::RetryConnectionFailed if @options[:retry_connection_failed] conn.adapter :net_http end res = conn.post do |req| req.headers['Content-Type'] = 'application/json' req.body = { client_id: @client_id, client_secret: @client_secret }.to_json end if res.success? data = JSON.parse(res.body) @access_token = data.fetch("access_token") @expiry = Time.now + data.fetch("expires_in") - 300 else @access_token = nil @expiry = nil raise Springcm::InvalidClientIdOrSecretError.new if !safe return false end end def get_account_info conn = authorized_connection(url: object_api_url) res = conn.get do |req| req.headers["Content-Type"] = "application/json" req.url "accounts/current" end if res.success? data = JSON.parse(res.body) @account = Springcm::Account.new(data, self) true else false end end def account if @account.nil? get_account_info end @account end # Shorthand for connecting unsafely def connect! connect(false) end # Retrieve the root folder in SpringCM # @return [Springcm::Folder] The root folder object. def root_folder conn = authorized_connection(url: object_api_url) res = conn.get do |req| req.url "folders" req.params["systemfolder"] = "root" end if res.success? data = JSON.parse(res.body) return Folder.new(data, self) else nil end end def folder(path: nil, uid: nil) if (path.nil? && uid.nil?) || (!path.nil? && !uid.nil?) raise ArgumentError.new("Specify exactly one of: path, uid") end if path == "/" return root_folder end conn = authorized_connection(url: object_api_url) res = conn.get do |req| if !path.nil? req.url "folders" req.params["path"] = path elsif !uid.nil? req.url "folders/#{uid}" end Folder.resource_params.each { |key, value| req.params[key] = value } end if res.success? data = JSON.parse(res.body) return Folder.new(data, self) else nil end end def document(path: nil, uid: nil) if (path.nil? && uid.nil?) || (!path.nil? && !uid.nil?) raise ArgumentError.new("Specify exactly one of: path, uid") end conn = authorized_connection(url: object_api_url) res = conn.get do |req| if !path.nil? req.url "documents" req.params["path"] = path elsif !uid.nil? req.url "documents/#{uid}" end Document.resource_params.each { |key, value| req.params[key] = value } end if res.success? data = JSON.parse(res.body) return Document.new(data, self) else nil end end def groups(offset: 0, limit: 20) Helpers.validate_offset_limit!(offset, limit) conn = authorized_connection(url: object_api_url) res = conn.get do |req| req.url "groups" req.params["offset"] = offset req.params["limit"] = limit end if res.success? data = JSON.parse(res.body) ResourceList.new(data, self, Group, self) else nil end end def users(offset: 0, limit: 20) Helpers.validate_offset_limit!(offset, limit) conn = authorized_connection(url: object_api_url) res = conn.get do |req| req.url "users" req.params["offset"] = offset req.params["limit"] = limit end if res.success? data = JSON.parse(res.body) ResourceList.new(data, self, User, self) else nil end end # Check if client is successfully authenticated # @return [Boolean] Whether a valid, unexpired access token is held. def authenticated? !!@access_token && @expiry > Time.now end # Get the URL for object API requests def object_api_url "https://api#{@data_center}.springcm.com/v#{@api_version}" end # Get the URL for content upload API requests def upload_api_url "https://apiupload#{@data_center}.springcm.com/v#{@api_version}" end # Get the URL for content download requests def download_api_url "https://apidownload#{@data_center}.springcm.com/v#{@api_version}" end # Get the URL for authentication requests def auth_url "https://auth#{auth_subdomain_suffix}.springcm.com/api/v#{@auth_version}/apiuser" end def authorized_connection(*options) if !authenticated? connect! end Faraday.new(*options) do |conn| options = [{ max: 10, interval: 1, interval_randomness: 0.5, backoff_factor: 2, retry_statuses: [401, 429], exceptions: [Springcm::AuthExpiredError, Springcm::RateLimitExceededError], retry_block: -> (env, options, retries, exception) { if exception.class == Springcm::AuthExpiredError connect! env.request_headers['Authorization'] = "bearer #{@access_token}" end } }] conn.request :retry, *options conn.use Springcm::Middleware::RateLimit conn.use Springcm::Middleware::AuthExpire conn.use Springcm::Middleware::RetryConnectionFailed if @options[:retry_connection_failed] conn.adapter :net_http conn.authorization('bearer', @access_token) end end private def auth_subdomain_suffix if @data_center.start_with?("uat") "uat" else "" end end end end
def ascii_value(c): # convert character to ascii code code = ord(c) return code print(ascii_value('z'))
#!/bin/bash set -e log_level() { case "$1" in -e) echo "$(date) [Err] : " ${@:2} ;; -w) echo "$(date) [Warn]: " ${@:2} ;; -i) echo "$(date) [Info] : " ${@:2} ;; *) echo "$(date) [Debug]: " ${@:2} ;; esac } function printUsage { echo "" echo "Usage:" echo " $0 -i id_rsa -d 192.168.102.34 -u azureuser --file aks_file --tenant-Id tenant-id --subscription-id subscription-id --disable-host-key-checking" echo "" echo "Options:" echo " -u, --user User name associated to the identifity-file" echo " -i, --identity-file RSA private key tied to the public key used to create the Kubernetes cluster (usually named 'id_rsa')" echo " -d, --vmd-host The DVM's public IP or FQDN (host name starts with 'vmd-')" echo " -t, --tenant-id The Tenant ID used by aks engine" echo " -s, --subscription-id The Subscription ID used by aks engine" echo " -f, --file Aks Engine Scale or Upgrade script to run on dvm" echo " -p, --parameter For scale node_count should be passed and for upgrade version should be passed" echo " -h, --help Print the command usage" exit 1 } function download_scripts { ARTIFACTSURL=$1 script=$2 echo "[$(date +%Y%m%d%H%M%S)][INFO] Pulling aks script from this repo: $ARTIFACTSURL" curl -fs $ARTIFACTSURL -o $SCRIPTSFOLDER/$script if [ ! -f $SCRIPTSFOLDER/$script ]; then echo "[$(date +%Y%m%d%H%M%S)][ERROR] Required script not available. URL: $ARTIFACTSURL" exit 1 fi } if [ "$#" -eq 0 ] then printUsage fi # Handle named parameters while [[ "$#" -gt 0 ]] do case $1 in -i|--identity-file) IDENTITYFILE="$2" shift 2 ;; -m|--master-host) MASTER_HOST="$2" shift 2 ;; -d|--vmd-host) DVM_HOST="$2" shift 2 ;; -u|--user) USER="$2" shift 2 ;; -t|--tenant-id) TENANT_ID="$2" shift 2 ;; -s|--subscription-id) SUBSCRIPTION_ID="$2" shift 2 ;; -f|--file) FILE="$2" shift 2 ;; -p|--parameter) PARAMETER="$2" shift 2 ;; -o|--operation) OPERATION="$2" shift 2 ;; -h|--help) printUsage ;; *) log_level -e "Incorrect option $1" printUsage ;; esac done # Validate input if [ -z "$USER" ] then log_level -e "--user is required" printUsage fi if [ -z "$IDENTITYFILE" ] then log_level -e "--identity-file is required" printUsage fi if [ -z "$DVM_HOST" ] then log_level -e "--vmd-host should be provided" printUsage fi if [ -z "$PARAMETER" ] then log_level -e "--parameter should be provided" printusuage fi if [ -z "$OPERATION" ] then log_level -e "--operation should be provided" printusuage fi if [ ! -f $IDENTITYFILE ] then log_level -e "identity-file not found at $IDENTITYFILE" printUsage exit 1 else cat $IDENTITYFILE | grep -q "BEGIN \(RSA\|OPENSSH\) PRIVATE KEY" \ || { echo "The identity file $IDENTITYFILE is not a RSA Private Key file."; echo "A RSA private key file starts with '-----BEGIN [RSA|OPENSSH] PRIVATE KEY-----''"; exit 1; } fi # Print user input log_level -i "" log_level -i "user: $USER" log_level -i "identity-file: $IDENTITYFILE" log_level -i "vmd-host: $DVM_HOST" log_level -i "tenant-id: $TENANT_ID" log_level -i "subscription-id: $SUBSCRIPTION_ID" log_level -i "file: $FILE" log_level -i "parameter: $PARAMETER" log_level -i "operation: $OPERATION" log_level -i "" NOW=`date +%Y%m%d%H%M%S` SCRIPTSFOLDER="./AksEngineScripts/scripts" if [ ! -d $SCRIPTSFOLDER ]; then mkdir -p $SCRIPTSFOLDER fi log_level -i "script folder: $SCRIPTSFOLDER" AZURE_USER=$USER IDENTITY_FILE_BACKUP_PATH="/home/$AZURE_USER/IDENTITY_FILEBACKUP" echo "Backing up identity files at ($IDENTITY_FILE_BACKUP_PATH)" ssh -t -i $IDENTITYFILE $USER@$DVM_HOST "if [ -f /home/$AZURE_USER/.ssh/id_rsa ]; then mkdir -p $IDENTITY_FILE_BACKUP_PATH; sudo mv /home/$AZURE_USER/.ssh/id_rsa $IDENTITY_FILE_BACKUP_PATH; fi;" echo -i "Copying over new identity file" scp -i $IDENTITYFILE $IDENTITYFILE $USER@$DVM_HOST:/home/$AZURE_USER/.ssh/id_rsa ROOT_PATH=/home/$AZURE_USER FILENAME=$(basename $FILE) download_scripts $FILE $FILENAME scp -q -i $IDENTITYFILE $SCRIPTSFOLDER/*.sh $USER@$DVM_HOST:$ROOT_PATH if [ $OPERATION == "scale" ] ; then ssh -t -i $IDENTITYFILE $USER@$DVM_HOST "./$FILENAME --tenant-id $TENANT_ID --subscription-id $SUBSCRIPTION_ID --node-count $PARAMETER --user $AZURE_USER" fi if [ $OPERATION == "upgrade" ] ; then ssh -t -i $IDENTITYFILE $USER@$DVM_HOST "./$FILENAME --tenant-id $TENANT_ID --subscription-id $SUBSCRIPTION_ID --upgrade-version $PARAMETER --user $AZURE_USER ;" fi
#!/bin/bash #/* # * This file is part of TangoMan Provisions package. # * # * Copyright (c) 2021 "Matthias Morin" <mat@tangoman.io> # * # * This source file is subject to the MIT license that is bundled # * with this source code in the file LICENSE. # */ #/** # * PHP CS Fixer # * # * @link https://cs.symfony.com # * @category dev # */ CURDIR=$(dirname "$(realpath "${BASH_SOURCE[0]}")") # shellcheck source=/dev/null . "${CURDIR}/../tools/src/colors/colors.sh" VERSION=3 alert_primary 'Install php-cs-fixer' if [ ! -x "$(command -v wget)" ]; then echo_error "\"$(basename "${0}")\" requires wget, try: 'sudo apt-get install -y wget'" exit 1 fi # download with wget echo_info "wget -q https://cs.symfony.com/download/php-cs-fixer-v${VERSION}.phar" wget -q https://cs.symfony.com/download/php-cs-fixer-v${VERSION}.phar # install php-cs-fixer globally echo_info "sudo mv -fv php-cs-fixer-v${VERSION}.phar /usr/local/bin/php-cs-fixer" sudo mv -fv php-cs-fixer-v${VERSION}.phar /usr/local/bin/php-cs-fixer # fix permissions echo_info 'sudo chmod uga+x /usr/local/bin/php-cs-fixer' sudo chmod uga+x /usr/local/bin/php-cs-fixer echo_info 'sync' sync
<gh_stars>100-1000 import {OpCall} from '../nodeTypes' import { TRUE_VALUE, FALSE_VALUE, NULL_VALUE, fromNumber, Value, fromString, fromJS, fromDateTime, StreamValue, } from '../values' import {isEqual} from './equality' import {partialCompare} from './ordering' import {gatherText, Token, Pattern, matchText, matchTokenize, matchAnalyzePattern} from './matching' type GroqOperatorFn = (left: Value, right: Value) => Value | PromiseLike<Value> export const operators: {[key in OpCall]: GroqOperatorFn} = { '==': function eq(left, right) { return isEqual(left, right) ? TRUE_VALUE : FALSE_VALUE }, '!=': function neq(left, right) { return isEqual(left, right) ? FALSE_VALUE : TRUE_VALUE }, '>': function gt(left, right) { if (left.type === 'stream' || right.type === 'stream') return NULL_VALUE const result = partialCompare(left.data, right.data) if (result === null) { return NULL_VALUE } return result > 0 ? TRUE_VALUE : FALSE_VALUE }, '>=': function gte(left, right) { if (left.type === 'stream' || right.type === 'stream') return NULL_VALUE const result = partialCompare(left.data, right.data) if (result === null) { return NULL_VALUE } return result >= 0 ? TRUE_VALUE : FALSE_VALUE }, '<': function lt(left, right) { if (left.type === 'stream' || right.type === 'stream') return NULL_VALUE const result = partialCompare(left.data, right.data) if (result === null) { return NULL_VALUE } return result < 0 ? TRUE_VALUE : FALSE_VALUE }, '<=': function lte(left, right) { if (left.type === 'stream' || right.type === 'stream') return NULL_VALUE const result = partialCompare(left.data, right.data) if (result === null) { return NULL_VALUE } return result <= 0 ? TRUE_VALUE : FALSE_VALUE }, // eslint-disable-next-line func-name-matching in: async function inop(left, right) { if (right.type === 'path') { if (left.type !== 'string') { return NULL_VALUE } return right.data.matches(left.data) ? TRUE_VALUE : FALSE_VALUE } if (right.isArray()) { for await (const b of right) { if (isEqual(left, b)) { return TRUE_VALUE } } return FALSE_VALUE } return NULL_VALUE }, match: async function match(left, right) { let tokens: Token[] = [] let patterns: Pattern[] = [] await gatherText(left, (part) => { tokens = tokens.concat(matchTokenize(part)) }) const didSucceed = await gatherText(right, (part) => { patterns = patterns.concat(matchAnalyzePattern(part)) }) if (!didSucceed) { return FALSE_VALUE } const matched = matchText(tokens, patterns) return matched ? TRUE_VALUE : FALSE_VALUE }, '+': function plus(left, right) { if (left.type === 'datetime' && right.type === 'number') { return fromDateTime(left.data.add(right.data)) } if (left.type === 'number' && right.type === 'number') { return fromNumber(left.data + right.data) } if (left.type === 'string' && right.type === 'string') { return fromString(left.data + right.data) } if (left.type === 'object' && right.type === 'object') { return fromJS({...left.data, ...right.data}) } if (left.type === 'array' && right.type === 'array') { return fromJS(left.data.concat(right.data)) } if (left.isArray() && right.isArray()) { return new StreamValue(async function* () { for await (const val of left) { yield val } for await (const val of right) { yield val } }) } return NULL_VALUE }, '-': function minus(left, right) { if (left.type === 'datetime' && right.type === 'number') { return fromDateTime(left.data.add(-right.data)) } if (left.type === 'datetime' && right.type === 'datetime') { return fromNumber(left.data.difference(right.data)) } if (left.type === 'number' && right.type === 'number') { return fromNumber(left.data - right.data) } return NULL_VALUE }, '*': numericOperator((a, b) => a * b), '/': numericOperator((a, b) => a / b), '%': numericOperator((a, b) => a % b), '**': numericOperator((a, b) => Math.pow(a, b)), } function numericOperator(impl: (a: number, b: number) => number): GroqOperatorFn { return function (left, right) { if (left.type === 'number' && right.type === 'number') { const result = impl(left.data, right.data) return fromNumber(result) } return NULL_VALUE } }
<filename>src/com/source/excenv/model/bots/bot.java<gh_stars>0 package com.source.excenv.model.bots; import com.source.excenv.model.player.sideway_player; public abstract class bot extends sideway_player { //the update is where the bot do its calculations public abstract void update(); public abstract void updateRect(); //moveMent, same as player @Override public abstract void moveLeft(); @Override public abstract void moveRight(); @Override public abstract void jump(); }
<reponame>Kardzhaliyski/Java-OOP<gh_stars>0 package cardswithpower; enum CardSuit { CLUBS(0), DIAMONDS(13), HEARTS(26), SPADES(39); private final int power; CardSuit(int power) { this.power = power; } public int getPower() { return power; } }
<filename>java/ReflectionExample.java import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class ReflectionExample { public static void main(String[] args) throws Exception { Class<?> c = Class.forName("Horse"); Constructor<?> ctor = c.getConstructor(String.class); Animal h = Animal.class.cast(ctor.newInstance("CJ")); Method m = h.getClass().getMethod("speak"); assert m.invoke(h).equals("CJ says neigh"); } }
SELECT Course FROM Course_Students GROUP BY Course HAVING COUNT(*) >= 3;
package mage.deck; import mage.cards.ExpansionSet; import mage.cards.Sets; import mage.cards.decks.Constructed; import mage.sets.HistoricAnthology; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * @author mikalinn777 * * Historic is a Magic The Gathering Arena format. https://mtg.gamepedia.com/Historic_(format) */ public class Historic extends Constructed { public Historic() { super("Constructed - Historic"); Date cutoff = new GregorianCalendar(2017, Calendar.SEPTEMBER, 29).getTime(); // XLN release date for (ExpansionSet set : Sets.getInstance().values()) { if (set.getSetType().isStandardLegal() && (set.getReleaseDate().after(cutoff) || set.getReleaseDate().equals(cutoff))) { setCodes.add(set.getCode()); setCodes.add(mage.sets.HistoricAnthology.getInstance().getCode()); } } banned.add("Oko, Thief of Crowns"); banned.add("Once Upon a Time"); banned.add("Veil of Summer"); banned.add("Nexus of Fate"); banned.add("Winota, Joiner of Forces"); banned.add("Fires of Invention"); banned.add("Agent of Treachery"); } }
package com.dabe.skyapp.model.api.interfaces; import com.dabe.skyapp.model.data.dto.response.Response; import rx.Observable; /** * Created by <NAME> on 25.01.2017 20:55. * Project: SkyApp; Skype: pandamoni1 */ public interface ISkyApi { /** * Запрос на код без пароля * * @param email - <NAME> * @return возвращает AuthTokenDTO */ Observable<Response> easyLogin(String email); /** * Запрос на логин с паролем * * @param email - мыло * @param password - <PASSWORD> * @return возвращает AppTokenDTO */ Observable<Response> hardLogin(String email, String password); /** * Проверка пина по authToken, который получили при запросе кода * @param code - введенный код * @param authToken - временный токен авторизации * @return возвращает AppTokenDTO */ Observable<Response> verifyCode(String code, String authToken); /** * Синхронизация данных с сервером * @param appToken - токен приложения * @return какае-нибудь данные */ Observable<Response> syncData(String appToken); }