text
stringlengths
1
1.05M
<reponame>dprince/smokestack<gh_stars>1-10 require 'test_helper' class ConfigTemplateTest < ActiveSupport::TestCase fixtures :config_templates test "create valid config template" do config_template=ConfigTemplate.create( :name => "Libvirt MySQL", :description => "Libvirt QEMU w/ MySQL", :cookbook_repo_url => "http://a.b.c/blah", :environment => "", :server_group_json => "{}" ) assert_equal("Libvirt MySQL", config_template.name) assert_equal("Libvirt QEMU w/ MySQL", config_template.description) assert_equal("http://a.b.c/blah", config_template.cookbook_repo_url) assert_equal("{}", config_template.server_group_json) end test "config template fails with invalid environment" do config_template=ConfigTemplate.new( :name => "Libvirt MySQL", :description => "Libvirt QEMU w/ MySQL", :cookbook_repo_url => "http://a.b.c/blah", :environment => %{foo\nbar}, :server_group_json => "{}" ) assert_equal(false, config_template.valid?) end end
#!/bin/sh ## Usage: ## . ./export-env.sh ; $COMMAND ## . ./export-env.sh ; echo ${MINIENTREGA_FECHALIMITE} ## https://stackoverflow.com/a/20909045/1513580 unamestr=$(uname) if [ "$unamestr" = 'Linux' ]; then export $(grep -v '^#' .env | xargs -d '\n') elif [ "$unamestr" = 'FreeBSD' ]; then export $(grep -v '^#' .env | xargs -0) fi
<reponame>Banuba/beauty-android-java<filename>app/src/main/assets/bnb-resources/effects/Makeup/modules/hair/avg-color/accumulate/copy.vert.js<gh_stars>0 'use strict'; const vertexShader = "modules/hair/avg-color/accumulate/copy.vert"; exports.default = vertexShader;
#!/bin/bash -x # # Usage: # # $ ./scripts/update-gh-pages.sh v0.6.0 origin # tag=${1:-master} remote=${2:-origin} ori_branch=$(git rev-parse --symbolic-full-name --abbrev-ref HEAD) tmpdir=$(mktemp -d) cleanup() { rm -r $tmpdir } trap cleanup INT TERM cp -r doc/_build/html/ $tmpdir git ls-files --others | tar cf $tmpdir/untracked.tar -T - if [[ -d .gh-pages-skeleton ]]; then cp -r .gh-pages-skeleton $tmpdir fi git fetch $remote git checkout gh-pages if [[ $? -ne 0 ]]; then git checkout --orphan gh-pages if [[ $? -ne 0 ]]; then >&2 echo "Failed to switch to 'gh-pages' branch." cleanup exit 1 fi preexisting=0 else preexisting=1 git fetch $remote git pull fi if [[ $preexisting == 1 ]]; then while [[ "$(git log -1 --pretty=%B)" == Volatile* ]]; do # overwrite previous docs git reset --hard HEAD~1 done else git reset --hard fi git clean -xfd if [[ $preexisting == 1 ]]; then mv v*/ $tmpdir git rm -rf * > /dev/null fi cp -r $tmpdir/html/ $tag if [[ $preexisting == 1 ]]; then mv $tmpdir/v*/ . fi if [[ -d $tmpdir/.gh-pages-skeleton ]]; then cp -r $tmpdir/.gh-pages-skeleton/. . fi touch .nojekyll if [[ "$tag" == v* ]]; then if [[ -L latest ]]; then rm latest fi ln -s $tag latest commit_msg="Release docs for $tag" else if [[ $preexisting == 1 ]]; then commit_msg="Volatile ($tag) docs" else commit_msg="Initial commit" fi fi git add -f . >/dev/null git commit -m "$commit_msg" if [[ $preexisting == 1 ]]; then git push -f $remote gh-pages else git push --set-upstream $remote gh-pages fi git checkout $ori_branch tar xf $tmpdir/untracked.tar cleanup
<gh_stars>10-100 package com.createchance.imageeditor.transitions; import com.createchance.imageeditor.drawers.BowTieVerticalTransDrawer; /** * Bow tie vertical transition. * * @author createchance * @date 2018/12/31 */ public class BowTieVerticalTransition extends AbstractTransition { private static final String TAG = "BowTieVerticalTransitio"; public BowTieVerticalTransition() { super(BowTieVerticalTransition.class.getSimpleName(), TRANS_BOW_TIE_VERTICAL); } @Override protected void getDrawer() { mDrawer = new BowTieVerticalTransDrawer(); } }
<gh_stars>1-10 // import React from 'react' // import { Page, Document } from 'react-pdf' import Equation from '@matejmazur/react-katex' import Modal from 'react-modal' // TODO: PDF support via "react-pdf" package has numerous troubles building // with next.js so I'm choosing to disable support for now. // const Pdf = ({ file, children, ...rest }) => { // const [numPages, setNumPages] = React.useState(null) // function onDocumentLoadSuccess({ numPages }) { // setNumPages(numPages) // } // return ( // <Document file={file} onLoadSuccess={onDocumentLoadSuccess} {...rest}> // {Array.from(new Array(numPages), (_, index) => ( // <Page key={`page_${index + 1}`} pageNumber={index + 1} /> // ))} // </Document> // ) // } export { Equation, Modal }
<filename>src/server/modules/ContextFilter/vos/TypesPathElt.ts export default class TypesPathElt { public constructor( public from_api_type_id: string, public from_field_id: string, public to_api_type_id: string, public to_field_id: string, public from_path_index: number, public to_path_index: number, public next_path_elt: TypesPathElt = null, ) { } }
def initialize_classifier(data, dataset): """ Initialize a classifier based on the dataset. Args: data: An object providing access to the dataset. dataset: A string indicating the name of the dataset. Returns: An instance of the classifier based on the dataset, or None if the dataset is not recognized. """ if dataset == 'mnist': return lenet.LeNet5() elif dataset in ('svhn', 'fashion'): return resnet.ResNet(data.nc, data.ny) else: return None
import shutil import os def process_and_parse(param_list, param_keys, mean_params, scale_params, filename, cwd, mndo, binary): # Set params in worker dir data.set_params(param_list, param_keys, mean_params, scale_params, scr=cwd) # Calculate properties properties_list = mndo.calculate_file(filename, scr=cwd, mndo_cmd=binary) # NOTE JCK properties_list is a generator, so complete parsing on worker properties_list = list(properties_list) return properties_list
#!/bin/bash #---------------------------------------- #Put your program name in place of "DEMO" name='BOSSHELL.8xp' #---------------------------------------- mkdir "bin" || echo "" convpng mv -f ./bos_gfx.* ./src/gfx/ echo "compiling to $name" ~/CEdev/bin/fasmg src/bos.asm bin/$name echo $name echo "Wrote binary to $name." read -p "Finished. Press any key to exit"
curl --include --request GET http://localhost:3000/arts
#!/bin/bash # Copyright 2016 The Bazel 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. # This script constructs the final Jekyll tree by combining the static Jekyll # site files with generated documentation, such as the Build Encyclopedia and # Skylark Library. It then constructs the site directory structure for # Bazel documentation at HEAD by moving all documentation into the # /versions/master directory and adding redirects from the root of the site. # This way, URLs of the form https://docs.bazel.build/foo.html will be # redirected to https://docs.bazel.build/versions/master/foo.html. set -eu readonly OUTPUT=${PWD}/$1 shift readonly JEKYLL_BASE=${PWD}/$1 shift readonly SKYLARK_RULE_DOCS=${PWD}/$1 shift readonly BE_ZIP=${PWD}/$1 shift readonly SL_ZIP=${PWD}/$1 shift readonly CLR_HTML=${PWD}/$1 # Create temporary directory that is removed when this script exits. readonly TMP=$(mktemp -d "${TMPDIR:-/tmp}/tmp.XXXXXXXX") readonly OUT_DIR="$TMP/out" trap "rm -rf ${TMP}" EXIT readonly VERSION="${DOC_VERSION:-master}" readonly VERSION_DIR="$OUT_DIR/versions/$VERSION" # Unpacks the base Jekyll tree, Build Encyclopedia, Skylark Library, and # command line reference. function setup { mkdir -p "$OUT_DIR" cd "$OUT_DIR" tar -xf "${JEKYLL_BASE}" mkdir -p "$VERSION_DIR" mv "$OUT_DIR"/docs/* "$VERSION_DIR" rm -r "$OUT_DIR"/docs # Unpack the Build Encyclopedia into versions/master/be local be_dir="$VERSION_DIR/be" mkdir -p "$be_dir" unzip -qq "$BE_ZIP" -d "$be_dir" mv "$be_dir/be-nav.html" "$OUT_DIR/_includes" # Unpack the Skylark Library into versions/master/skylark/lib local sl_dir="$VERSION_DIR/skylark/lib" mkdir -p "$sl_dir" unzip -qq "$SL_ZIP" -d "$sl_dir" mv "$sl_dir/skylark-nav.html" "$OUT_DIR/_includes" # Copy the command line reference. cp "$CLR_HTML" "$VERSION_DIR" } # Helper function for copying a Skylark rule doc. function copy_skylark_rule_doc { local rule_family=$1 local rule_family_name=$2 local be_dir="$VERSION_DIR/be" ( cat <<EOF --- layout: documentation title: ${rule_family_name} Rules --- EOF cat "$TMP/skylark/$rule_family/README.md"; ) > "$be_dir/${rule_family}.md" } # Copies the READMEs for Skylark rules bundled with Bazel. function unpack_skylark_rule_docs { local tmp_dir=$TMP/skylark mkdir -p $tmp_dir cd "$tmp_dir" tar -xf "${SKYLARK_RULE_DOCS}" copy_skylark_rule_doc pkg "Packaging" } # Processes a documentation page, such as replacing Blaze with Bazel. function process_doc { local f=$1 local tempf=$(mktemp -t bazel-doc-XXXXXX) chmod +w $f cat "$f" | sed 's,\.md,.html,g;s,Blaze,Bazel,g;s,blaze,bazel,g' > "$tempf" cat "$tempf" > "$f" } # Performs fixup on each doc, such as replacing instances of 'blaze' with # 'bazel'. function process_docs { for f in $(find "$VERSION_DIR" -name "*.html"); do process_doc $f done for f in $(find "$VERSION_DIR" -name "*.md"); do process_doc $f done } # Generates a redirect for a documentation page under /versions/master. function gen_redirect { local output_dir=$OUT_DIR/$(dirname $f) if [[ ! -d "$output_dir" ]]; then mkdir -p "$output_dir" fi local src_basename=$(basename $f) local md_basename="${src_basename%.*}.md" local html_file="${f%.*}.html" local redirect_file="$output_dir/$md_basename" if [[ -e "$redirect_file" ]]; then echo "Cannot create redirect file $redirect_file. File exists." exit 1 fi cat > "$redirect_file" <<EOF --- layout: redirect redirect: /versions/$VERSION/$html_file --- EOF } # During setup, all documentation under docs are moved to the /versions/master # directory as the documentation from HEAD. # # This function henerates a redirect from the root of the site for the given # doc page under /versions/master so that https://docs.bazel.build/foo.html # will be redirected to https://docs.bazel.build/versions/master/foo.html function gen_redirects { pushd "$VERSION_DIR" > /dev/null for f in $(find . -name "*.html" -type f); do gen_redirect $f done for f in $(find . -name "*.md" -type f); do gen_redirect $f done popd > /dev/null } # Creates a tar archive containing the final Jekyll tree. function package_output { cd "$OUT_DIR" tar -hcf $OUTPUT $(find . -type f | sort) } function main { setup unpack_skylark_rule_docs process_docs gen_redirects package_output } main
#!/bin/bash # Copyright (c) 2014, Stanford University # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Given a year and the name of a quarter ('fall', 'winter', etc.), # write CSV to stdout that contains course name, year, quarter, # start date, and end date of the course. One course per line. # Without a -y argument, all years are exported; without a -q # all quarters (of each requested year) are exported. # # Uses the modulestore MongoDB directly. Can be used from CL. # # Usable from CL, but also used by cronRefreshModulStore.sh. USAGE="Usage: generateCourseInfoCSV.sh [-y yyyy] [-q {fall | winter | spring | summer}]" YEAR=0 QUARTER='all' DATA_SINCE=2012 # --------------------- Process Input Args ------------- # Keep track of number of optional args the user provided: NEXT_ARG=0 while getopts ":q:y:" opt do case $opt in q) QUARTER=$OPTARG NEXT_ARG=$((NEXT_ARG + 2)) ;; y) YEAR=$OPTARG NEXT_ARG=$((NEXT_ARG + 2)) ;; \?) # Illegal option; the getopts provided the error message echo $USAGE exit 1 ;; esac done # Shift past all the optional parms: shift ${NEXT_ARG} #echo $YEAR,$QUARTER #exit 0 if [[ ! $YEAR =~ ^-?[0-9]+$ ]] then echo "Year must be of format yyyy" exit 1 fi if [[ ! (($QUARTER == 'all') || \ ($QUARTER == 'fall') || \ ($QUARTER == 'winter') || \ ($QUARTER == 'spring') || \ ($QUARTER == 'summer') \ )]] then echo $USAGE exit 1 fi # ------------------------- Establish Quarter Sequence ---------- if [[ $QUARTER == 'fall' ]] then NEXT_QUARTER='winter' elif [[ $QUARTER == 'winter' ]] then NEXT_QUARTER='spring' elif [[ $QUARTER == 'spring' ]] then NEXT_QUARTER='summer' elif [[ $QUARTER == 'summer' ]] then NEXT_QUARTER='fall' fi # ----------------------- Create JavaScript -------------- # Create a JavaScript that will be run within a Mongo shell # further down. The scripts queries Mongo for all courses # within the given quarter's start/end dates. Catching the # resulting db cursor, the JavaScript writes to stdout one # CSV line after another: <courseName>,<year>,<quarter>,<startDate>,<endDate> QUERY='courseCursor = db.modulestore.find({"_id.category": "course", "metadata.start": {$gte: quarterStartDate, $lt: nextQuarterStartDate}}, {"metadata.start": true, "metadata.end": true} ); ' # Place a Java script into a tmp file for subsequent input into # MongoDB: JAVASCRIPT_FILE=mktemp echo 'var year = '$YEAR'; var quarter = '\"$QUARTER\"'; var quartersToCover; if (quarter == "all") { quartersToCover = ["fall", "winter", "spring", "summer"]; // Without the following print statement, Mongo ouputs // the above array to stdout...who knows why. Workaround: // Print an empty line, and remove it later (see grep below): print(''); } else { quartersToCover = [quarter]; switch (quarter) { case "fall": quartersToCover.push("winter"); break; case "winter": quartersToCover.push("spring"); break; case "spring": quartersToCover.push("summer"); break; case "summer": quartersToCover.push("fall"); break; } // Without the following print statement, Mongo ouputs // the number 2 to stdout, in spite of the --quiet option. // Workaround: Print an empty line, and remove it later (see grep below): print(''); } var quarterStartDate; var nextQuarterStartDate; var thisYear = parseInt(year); if (thisYear == 0) { thisYear = '$DATA_SINCE'; // Same stupid need for an empty line // to keep MongoDB from printing the // value of $DATA_SINCE: print(''); } var moreYearsToDo = true; var currYear = new Date().getFullYear(); var theQuarterIndx = 0; var nextQuarterIndx = 1; print("course_display_name,year,quarter,start_date,end_date"); while (moreYearsToDo) { var fallQuarterStartDate = thisYear + "-09-10T00:00:00Z"; var winterQuarterStartDate = thisYear+1 + "-01-01T00:00:00Z"; var springQuarterStartDate = thisYear+1 + "-03-01T00:00:00Z"; var summerQuarterStartDate = thisYear+1 + "-06-15T00:00:00Z"; var summerQuarterEndDate = thisYear+1 + "-09-10T00:00:00Z"; var currQuarter = quartersToCover[theQuarterIndx]; switch (currQuarter) { case "fall": quarterStartDate = fallQuarterStartDate; nextQuarterStartDate = winterQuarterStartDate; break; case "winter": quarterStartDate = winterQuarterStartDate; nextQuarterStartDate = springQuarterStartDate; break; case "spring": quarterStartDate = springQuarterStartDate; nextQuarterStartDate = summerQuarterStartDate; break; case "summer": quarterStartDate = summerQuarterStartDate; nextQuarterStartDate = summerQuarterEndDate; break; } //************************ //print("quarter: " + quarter); //print("currQuarter: " + currQuarter); //print("quartersToCover:" + quartersToCover); //print("quarterStartDate: " + quarterStartDate); //print("nextQuarterStartDate: " + nextQuarterStartDate); //print("currYear: " + currYear); //print("thisYear: " + thisYear); //print("year: " + year); //print("theQuarterIndx: " + theQuarterIndx); //print("nextQuarterIndx: " + nextQuarterIndx); //************************ courseCursor = db.modulestore.find({"_id.category": "course", "metadata.start": {$gte: quarterStartDate, $lt: nextQuarterStartDate} }, {"metadata.start": true, "metadata.end": true} ); while (true) { doc = courseCursor.hasNext() ? courseCursor.next() : null; if (doc === null) { break; } course_display_name = doc._id.org + "/" + doc._id.course + "/" + doc._id.name; //************************ //print("course_display_name: " + course_display_name); //************************ print(doc._id.org + "/" + doc._id.course + "/" + doc._id.name + "," + year + "," + currQuarter + "," + doc.metadata.start + "," + doc.metadata.end); } // Done with one quarter if (quarter != "all" && year > 0) { moreYearsToDo = false; continue; } // Doing multiple quarters. what is the next quarter? theQuarterIndx += 1; if (theQuarterIndx > quartersToCover.length - 1) { // Did all quarters of current academic year: theQuarterIndx = 0; // Do just one year? if (year > 0) { // We are to do just one academic year: moreYearsToDo = false; continue; } } if (currQuarter == "fall") { // Spring quarter happens in second // calendar year of the academic year: thisYear += 1; if (thisYear > currYear) { moreYearsToDo = false; continue; } } //************* //print("moreYearsToDo: " + moreYearsToDo); //print("currQuarter: " + currQuarter); //************* } // end while(moreYearsToDo) ' > $JAVASCRIPT_FILE #******************** #cat $JAVASCRIPT_FILE #exit #******************** # Run the JavaScript inside mongodb; output to stdout. # When Mongo processes the above Javascript, it outputs # two lines at the end: 'false', and 'bye', even with the # --quiet flag. We need to suppress these to obtain a clean # .csv output. # # Additionally, to prevent Mongo from outputting the result of the first # Javascript conditional we had to add a newline in that # script (see above in the script). We need to suppress # this empty line as well # # The following pipe into grep does these suppressions: mongo modulestore --quiet < $JAVASCRIPT_FILE | grep --invert-match "^false$\|^bye$\|^$" rm $JAVASCRIPT_FILE
#!/bin/bash xcodebuild archive -archivePath ./archive/app.xcarchive -workspace $HFWorkspacePath -scheme $HFScheme -configuration $HFConfiguration -sdk $HFSdk #-sdk iphoneos9.3 #-configuration [Debug/Release] #chmod+x 文件名解决权限问题
<filename>plugins/src/main/java/org/moskito/control/plugins/mail/MailNotificationConfig.java package org.moskito.control.plugins.mail; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.configureme.annotations.Configure; import org.configureme.annotations.ConfigureMe; import org.moskito.control.core.status.StatusChangeEvent; import org.moskito.control.plugins.notifications.config.BaseNotificationProfileConfig; import org.moskito.control.plugins.notifications.config.NotificationStatusChange; /** * Mail configuration unit for per-status notification of specified recipients. * * @author <NAME> */ @ConfigureMe @SuppressFBWarnings(value = {"EI_EXPOSE_REP2", "EI_EXPOSE_REP"}, justification = "This is the way configureMe works, it provides beans for access") public class MailNotificationConfig extends BaseNotificationProfileConfig{ /** * List of component statuses to send notifications. * If empty - notifications will send on all statuses */ @Configure private NotificationStatusChange[] notificationStatusChanges = new NotificationStatusChange[0]; /** * Mail recipients. */ @Configure private String[] recipients; public NotificationStatusChange[] getStatusChanges() { return notificationStatusChanges; } /** * Check is this notifications config is configured to catch up this event. * Check is carried out by event application and status * @param event event to check * @return true - message should be send to recipients of this config * false - no */ public boolean isAppliableToEvent(StatusChangeEvent event){ // Check is this config contains application if(notificationStatusChanges.length == 0) return true; // No status change configured. All statuses pass for (NotificationStatusChange statusChange : notificationStatusChanges) if(statusChange.isAppliableToEvent(event.getStatus().getHealth(), event.getOldStatus().getHealth())) return true; // Status change found in statuses change array return false; // event don`t match any status change criteria } public String[] getRecipients() { return recipients; } public void setRecipients(String[] recipients) { this.recipients = recipients; } public void setNotificationStatusChanges(NotificationStatusChange[] notificationStatusChanges) { this.notificationStatusChanges = notificationStatusChanges; } }
<reponame>alexadam/project-templates<filename>projects/react-redux-tk/client/numbers.tsx import React, {useState} from 'react'; interface INumberProps { initValue: number } const Numbers = (props: INumberProps) => { const [value, setValue] = useState(props.initValue) const onIncrement = () => { setValue(value + 1) } const onDecrement = () => { setValue(value - 1) } return ( <div> Number is {value} <div> <button onClick={onIncrement}>+</button> <button onClick={onDecrement}>-</button> </div> </div> ) } export default Numbers // interface INumbersProps { // initValue: number // } // interface INumbersState { // value: number // } // export default class Numbers // extends React.Component<INumbersProps, INumbersState> { // constructor(props: INumbersProps) { // super(props) // } // componentWillMount = () => { // this.setState({ // value: this.props.initValue // }) // } // onIncrement = () => { // let newVal = this.state.value + 1 // this.setState({ // value: newVal // }) // } // onDecrement = () => { // let newVal = this.state.value - 1 // this.setState({ // value: newVal // }) // } // render = () => { // return ( // <div> // Number is {this.state.value} // <div> // <button onClick={this.onIncrement}>+</button> // <button onClick={this.onDecrement}>-</button> // </div> // </div> // ) // } // }
#!/bin/sh fancy_echo() { local fmt="$1"; shift # shellcheck disable=SC2059 printf "\n$fmt\n" "$@" } if ! command -v brew >/dev/null; then fancy_echo "Installing Homebrew ..." curl -fsS \ 'https://raw.githubusercontent.com/Homebrew/install/master/install' | ruby append_to_zshrc '# recommended by brew doctor' # shellcheck disable=SC2016 append_to_zshrc 'export PATH="/usr/local/bin:$PATH"' 1 export PATH="/usr/local/bin:$PATH" fi if brew list | grep -Fq brew-cask; then fancy_echo "Uninstalling old Homebrew-Cask ..." brew uninstall --force brew-cask fi fancy_echo "Installing git with Homebrew ..." brew install git brew tap caskroom/cask brew cask install github-desktop fancy_echo "Setting up Github SSH key pairs." echo "Please enter your github email." read github_email ssh-keygen -t rsa -b 4096 -C $github_email fancy_echo "Starting ssh-agent in the background." eval "$(ssh-agent -s)" fancy_echo "Adding your SSH key to ssh-agent." ssh-add ~/.ssh/id_rsa fancy_echo "Copying SSH key to your clipboard." pbcopy < ~/.ssh/id_rsa.pub fancy_echo "Add key to github to finish setup." echo "Press enter to open instructions." read throwaway_input open https://help.github.com/articles/adding-a-new-ssh-key-to-your-github-account/ open https://github.com/settings/keys
package porter import ( "fmt" "os" "path/filepath" "strconv" yaml "gopkg.in/yaml.v2" "github.com/pkg/errors" "github.com/deislabs/porter/pkg/config" "github.com/deislabs/porter/pkg/context" "github.com/deislabs/porter/pkg/mixin" output "github.com/deislabs/porter/pkg/outputs" ) type RunOptions struct { config *config.Config File string Action string parsedAction config.Action } func NewRunOptions(c *config.Config) RunOptions { return RunOptions{ config: c, } } func (o *RunOptions) Validate() error { err := o.defaultDebug() if err != nil { return err } err = o.validateAction() if err != nil { return err } return nil } func (o *RunOptions) validateAction() error { if o.Action == "" { o.Action = os.Getenv(config.EnvACTION) if o.config.Debug { fmt.Fprintf(o.config.Err, "DEBUG: defaulting action to %s (%s)\n", config.EnvACTION, o.Action) } } o.parsedAction = config.Action(o.Action) return nil } func (o *RunOptions) defaultDebug() error { // if debug was manually set, leave it if o.config.Debug { return nil } rawDebug, set := os.LookupEnv(config.EnvDEBUG) if !set { return nil } debug, err := strconv.ParseBool(rawDebug) if err != nil { return errors.Wrapf(err, "invalid PORTER_DEBUG, expected a bool (true/false) but got %s", rawDebug) } if debug { fmt.Fprintf(o.config.Err, "DEBUG: defaulting debug to %s (%t)\n", config.EnvDEBUG, debug) o.config.Debug = debug } return nil } func (p *Porter) Run(opts RunOptions) error { claimName := os.Getenv(config.EnvClaimName) bundleName := os.Getenv(config.EnvBundleName) fmt.Fprintf(p.Out, "executing %s action from %s (claim: %s) defined in %s\n", opts.parsedAction, bundleName, claimName, opts.File) err := p.Config.LoadManifestFrom(opts.File) if err != nil { return err } steps, err := p.Manifest.GetSteps(opts.parsedAction) if err != nil { return err } err = steps.Validate(p.Manifest) if err != nil { return errors.Wrap(err, "invalid action configuration") } mixinsDir, err := p.GetMixinsDir() if err != nil { return err } err = p.FileSystem.MkdirAll(context.MixinOutputsDir, 0755) if err != nil { return errors.Wrapf(err, "could not create outputs directory %s", context.MixinOutputsDir) } for _, step := range steps { if step != nil { err := p.Manifest.ResolveStep(step) if err != nil { return errors.Wrap(err, "unable to resolve sourced values") } // Hand over values needing masking in context output streams p.Context.SetSensitiveValues(p.Manifest.GetSensitiveValues()) runner := p.loadRunner(step, opts.parsedAction, mixinsDir) err = runner.Validate() if err != nil { return errors.Wrap(err, "mixin validation failed") } description, _ := step.GetDescription() fmt.Fprintln(p.Out, description) err = runner.Run() if err != nil { return errors.Wrap(err, "mixin execution failed") } outputs, err := p.readMixinOutputs() if err != nil { return errors.Wrap(err, "could not read step outputs") } err = p.Manifest.ApplyStepOutputs(step, outputs) if err != nil { return err } // Apply any Bundle Outputs declared in this step err = p.ApplyBundleOutputs(opts, outputs) if err != nil { return err } } } fmt.Fprintln(p.Out, "execution completed successfully!") return nil } type ActionInput struct { action config.Action Steps []*config.Step `yaml:"steps"` } // MarshalYAML marshals the step nested under the action // install: // - helm: // ... // Solution from https://stackoverflow.com/a/42547226 func (a *ActionInput) MarshalYAML() (interface{}, error) { // encode the original b, err := yaml.Marshal(a.Steps) if err != nil { return nil, err } // decode it back to get a map var tmp interface{} err = yaml.Unmarshal(b, &tmp) if err != nil { return nil, err } stepMap := tmp.([]interface{}) actionMap := map[string]interface{}{ string(a.action): stepMap, } return actionMap, nil } func (p *Porter) loadRunner(s *config.Step, action config.Action, mixinsDir string) *mixin.Runner { name := s.GetMixinName() mixinDir := filepath.Join(mixinsDir, name) r := mixin.NewRunner(name, mixinDir, true) r.Command = string(action) r.Context = p.Context input := &ActionInput{ action: action, Steps: []*config.Step{s}, } inputBytes, _ := yaml.Marshal(input) r.Input = string(inputBytes) return r } func (p *Porter) readMixinOutputs() (map[string]string, error) { outputs := map[string]string{} outfiles, err := p.FileSystem.ReadDir(context.MixinOutputsDir) if err != nil { return nil, errors.Wrapf(err, "could not list %s", context.MixinOutputsDir) } for _, outfile := range outfiles { if outfile.IsDir() { continue } outpath := filepath.Join(context.MixinOutputsDir, outfile.Name()) contents, err := p.FileSystem.ReadFile(outpath) if err != nil { return nil, errors.Wrapf(err, "could not read output file %s", outpath) } outputs[outfile.Name()] = string(contents) err = p.FileSystem.Remove(outpath) if err != nil { return nil, err } } return outputs, nil } // ApplyBundleOutputs writes the provided outputs to the proper location // in the execution environment func (p *Porter) ApplyBundleOutputs(opts RunOptions, outputs map[string]string) error { for outputKey, outputValue := range outputs { // Iterate through bundle outputs declared in the manifest for _, bundleOutput := range p.Manifest.Outputs { // If a given step output matches a bundle output, proceed if outputKey == bundleOutput.Name { doApply := true // If ApplyTo array non-empty, default doApply to false // and only set to true if at least one entry matches current Action if len(bundleOutput.ApplyTo) > 0 { doApply = false for _, applyTo := range bundleOutput.ApplyTo { if opts.Action == applyTo { doApply = true } } } if doApply { // Ensure outputs directory exists if err := p.FileSystem.MkdirAll(config.BundleOutputsDir, 0755); err != nil { return errors.Wrap(err, "unable to ensure CNAB outputs directory exists") } outpath := filepath.Join(config.BundleOutputsDir, bundleOutput.Name) outputType, ok, err := bundleOutput.Schema.GetType() if !ok && err != nil { return errors.Wrap(err, "unable to get output type") } // Create data structure with relevant data for use in listing/showing later output := output.Output{ Name: bundleOutput.Name, Sensitive: bundleOutput.Sensitive, Type: outputType, Value: outputValue, } data, err := output.JSONMarshal() if err != nil { return errors.Wrap(err, "unable to marshal output") } err = p.FileSystem.WriteFile(outpath, data, 0755) if err != nil { return errors.Wrapf(err, "unable to write output file %s", outpath) } } } } } return nil }
12 unique palindromes can be made using the letters 'bcd': b, c, d, bb, cc, dd, bcb, cdc, dbd, bbb, ccc, ddd.
import math def is_prime(n): if n <= 1: return False if n == 2: return True if n > 2 and n % 2 == 0: return False max_div = math.floor(math.sqrt(n)) for i in range(3, 1 + max_div, 2): if n % i == 0: return False return True primes = [] number = 2 while len(primes) < 100: if is_prime(number): primes.append(number) number += 1 print(primes)
import React from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import styles from './linkRedes.module.scss'; const LinkRedes = (props) => { let url = '' let img = '' if(props.color) switch(props.red){ case 'whatsapp': url = "https://wa.me/"+props.user img = '/images/icons/whatsapp-white.svg' break; case 'facebook': url = "https://facebook.com/"+props.user img = '/images/icons/facebook-white.svg' break; case 'instagram': url = "https://instagram.com/"+props.user img = '/images/icons/instagram-white.svg' break; default: url = "/" break; } else switch(props.red){ case 'whatsapp': url = "https://wa.me/"+props.user img = '/images/icons/whatsapp.svg' break; case 'facebook': url = "https://facebook.com/"+props.user img = '/images/icons/facebook.svg' break; case 'instagram': url = "https://instagram.com/"+props.user img = '/images/icons/instagram.svg' break; default: url = "/" break; } return ( <a className={styles.redesLink} target="_blank" href={url} rel="noopener noreferrer" > <img className={'mx-2 lazyload'} src={img} alt={props.red}/> </a> ) } export default LinkRedes;
#/bin/bash -f # Copyright (c) 2015 Open Source Medical Software Corporation. # All Rights Reserved. REPLACEME_SV_SPECIAL_COMPILER_SCRIPT export CC=CL rm -Rf REPLACEME_SV_TOP_BIN_DIR_TCL mkdir -p REPLACEME_SV_TOP_BIN_DIR_TCL chmod u+w,a+rx REPLACEME_SV_TOP_BIN_DIR_TCL cd ../REPLACEME_SV_TCL_DIR/win nmake -f makefile.vc MACHINE=AMD64 INSTALLDIR="REPLACEME_SV_TOP_BIN_DIR_TCL" OPTS=msvcrt,threads hose nmake -f makefile.vc MACHINE=AMD64 INSTALLDIR="REPLACEME_SV_TOP_BIN_DIR_TCL" OPTS=msvcrt,threads release nmake -f makefile.vc MACHINE=AMD64 INSTALLDIR="REPLACEME_SV_TOP_BIN_DIR_TCL" OPTS=msvcrt,threads install chmod -R a+rwx REPLACEME_SV_TOP_BIN_DIR_TCL cd ../.. cd REPLACEME_SV_TK_DIR/win nmake -f makefile.vc MACHINE=AMD64 TCLDIR="REPLACEME_SV_TOP_SRC_DIR_TCL" INSTALLDIR="REPLACEME_SV_TOP_BIN_DIR_TK" OPTS=msvcrt,threads hose nmake -f makefile.vc MACHINE=AMD64 TCLDIR="REPLACEME_SV_TOP_SRC_DIR_TCL" INSTALLDIR="REPLACEME_SV_TOP_BIN_DIR_TK" OPTS=msvcrt,threads release nmake -f makefile.vc MACHINE=AMD64 TCLDIR="REPLACEME_SV_TOP_SRC_DIR_TCL" INSTALLDIR="REPLACEME_SV_TOP_BIN_DIR_TK" OPTS=msvcrt,threads install chmod -R a+rwx REPLACEME_SV_TOP_BIN_DIR_TK nmake -f makefile.vc MACHINE=AMD64 TCLDIR="REPLACEME_SV_TOP_SRC_DIR_TCL" INSTALLDIR= OPTS=msvcrt,threads hose cd ../.. cd REPLACEME_SV_TCL_DIR/win nmake -f makefile.vc MACHINE=AMD64 INSTALLDIR="REPLACEME_SV_TOP_BIN_DIR_TCL" OPTS=msvcrt,threads hose cd ../../BuildHelpers export SV_TOPLEVEL_BINDIR_CYGWIN=`cygpath "REPLACEME_SV_TOP_BIN_DIR_TCL"` cd ../tcllib-1.17 $SV_TOPLEVEL_BINDIR_CYGWIN/bin/tclsh8?t.exe installer.tcl -no-gui -no-wait cd ../BuildHelpers chmod -R a+rx $SV_TOPLEVEL_BINDIR_CYGWIN cd ../tklib-0.6 $SV_TOPLEVEL_BINDIR_CYGWIN/bin/tclsh8?t.exe installer.tcl -no-gui -no-wait cd ../BuildHelpers chmod -R a+rx $SV_TOPLEVEL_BINDIR_CYGWIN # copy names required for opencascade cp -f $SV_TOPLEVEL_BINDIR_CYGWIN/bin/tclsh86t.exe $SV_TOPLEVEL_BINDIR_CYGWIN/bin/tclsh86.exe cp -f $SV_TOPLEVEL_BINDIR_CYGWIN/bin/wish86t.exe $SV_TOPLEVEL_BINDIR_CYGWIN/bin/wish86.exe cp -f $SV_TOPLEVEL_BINDIR_CYGWIN/bin/tcl86t.dll $SV_TOPLEVEL_BINDIR_CYGWIN/bin/tcl86.dll cp -f $SV_TOPLEVEL_BINDIR_CYGWIN/bin/tk86t.dll $SV_TOPLEVEL_BINDIR_CYGWIN/bin/tk86.dll cp -f $SV_TOPLEVEL_BINDIR_CYGWIN/lib/tcl86t.lib $SV_TOPLEVEL_BINDIR_CYGWIN/lib/tcl86.lib cp -f $SV_TOPLEVEL_BINDIR_CYGWIN/lib/tk86t.lib $SV_TOPLEVEL_BINDIR_CYGWIN/lib/tk86.lib REPLACEME_SV_SPECIAL_COMPILER_END_SCRIPT
/** * The MIT License * Copyright (c) 2014 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package cormoran.pepper.io; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class TestCachedPathMatcher { @Test public void testCache() { PathMatcher decorated = Mockito.mock(PathMatcher.class); CachedPathMatcher cachedMatcher = new CachedPathMatcher(decorated, "someRegex"); Path path = Mockito.mock(Path.class); // Return true then false: as we cache, we should always return true Mockito.when(decorated.matches(path)).thenReturn(true, false); // First try: we get true Assert.assertTrue(cachedMatcher.matches(path)); // Second try: we get cached true Assert.assertTrue(cachedMatcher.matches(path)); // Ensure underlying is actually false Assert.assertFalse(decorated.matches(path)); Assert.assertTrue(cachedMatcher.matches(path)); } @Test public void testHumanToString_Regex() { PathMatcher rawMatcher = FileSystems.getDefault().getPathMatcher("regex:"); PathMatcher cachedPathMatcher = CachedPathMatcher.fromRegex("Prefix.*"); // Demonstrate we provide a useful toString while jdk class misses a useful .toString Assert.assertFalse(rawMatcher.toString().contains("Prefix")); Assert.assertEquals("regex:Prefix.*", cachedPathMatcher.toString()); } @Test public void testHumanToString_Glob() { PathMatcher rawMatcher = FileSystems.getDefault().getPathMatcher("regex:"); PathMatcher cachedPathMatcher = CachedPathMatcher.fromRegex("Prefix.*"); // Demonstrate we provide a useful toString while jdk class misses a useful .toString Assert.assertFalse(rawMatcher.toString().contains("Prefix")); Assert.assertEquals("regex:Prefix.*", cachedPathMatcher.toString()); } @Test public void testRegexOnFile() { PathMatcher cachedPathMatcher = CachedPathMatcher.fromRegexOverFilename("Prefix.*"); Path pathOk = Paths.get("/youpi", "PrefixOui"); Path pathArg = Paths.get("/youpi", "NotPrefixOui"); Assert.assertTrue(cachedPathMatcher.matches(pathOk)); Assert.assertFalse(cachedPathMatcher.matches(pathArg)); } }
#!/usr/bin/env python import lxml.etree as ET import sys if len(sys.argv) != 4: print("Usage: %s inputfile.xml transformation.xsl outputfile" % sys.argv[0]) sys.exit(1) dom = ET.parse(sys.argv[1]) xslt = ET.parse(sys.argv[2]) transform = ET.XSLT(xslt) newdom = transform(dom) html=str(newdom) with open (sys.argv[3], 'w') as out_file: print(html, file=out_file)
/** * @name: PyHouse/src/Modules/Web/js/8pdate.js * @author: <NAME> * @contact: <EMAIL> * @copyright: (c) 2015 by <NAME> * @license: MIT License * @note: Created on June 18, 2015 * @summary: Displays the update element * */ helpers.Widget.subclass(update, 'UpdateWidget').methods( function __init__(self, node) { update.UpdateWidget.upcall(self, '__init__', node); }, // ============================================================================ /** * Place the widget in the workspace. * * @param self * is <"Instance" of undefined.update.UpdateWidget> * @returns a deferred */ function ready(self) { function cb_widgetready(res) { self.hideWidget(); } var uris = collectIMG_src(self.node, null); var l_defer = loadImages(uris); l_defer.addCallback(cb_widgetready); return l_defer; }, /** * Show the update widget */ function startWidget(self) { self.node.style.display = 'block'; showSelectionButtons(self); self.fetchDataFromServer(); }, // ============================================================================ /** * This triggers getting the data from the server. */ function fetchDataFromServer(self) { function cb_fetchDataFromServer(p_json) { globals.Computer = JSON.parse(p_json); self.buildLcarSelectScreen(); } function eb_fetchDataFromServer(p_result) { Divmod.debug('---', 'update.eb_fetchDataFromServer() was called. ERROR = ' + p_result); } var l_defer = self.callRemote("getServerData"); // @ web_update.py l_defer.addCallback(cb_fetchDataFromServer); l_defer.addErrback(eb_fetchDataFromServer); return false; }, /** * Build a screen full of buttons - One for each item and some actions. */ function buildLcarSelectScreen(self) { var l_button_html = buildLcarSelectionButtonsTable(globals.Computer.Update, 'handleMenuOnClick'); var l_html = build_lcars_top('Update', 'lcars-salmon-color'); l_html += build_lcars_middle_menu(15, l_button_html); l_html += build_lcars_bottom(); self.nodeById('SelectionButtonsDiv').innerHTML = l_html; }, /** * Event handler for selection buttons. * * The user can click on a selection button or the "Back" button. * * @param self * is <"Instance" of undefined.update.UpdateWidget> * @param p_version * is the node of the button that was clicked. */ function handleMenuOnClick(self, p_version) { var l_ix = p_version.name; var l_name = p_version.value; globals.Computer.VersionIx = l_ix; globals.Computer.VersionName = l_name; if (l_ix <= 1000) { // One of the update buttons. var l_obj = globals.Computer.Version[l_ix]; globals.Computer.VersionObj = l_obj; showDataEntryScreen(self); self.buildDataEntryScreen(l_obj, 'handleDataEntryOnClick'); } else if (l_ix == 10002) { // The "Back" button self.showWidget('HouseMenu'); } }, // ============================================================================ /** * Build a screen full of data entry fields. */ function buildDataEntryScreen(self, p_entry, p_handler) { var l_obj = arguments[1]; var l_html = build_lcars_top('Version Data', 'lcars-salmon-color'); l_html += build_lcars_middle_menu(20, self.buildEntry(l_obj, p_handler)); l_html += build_lcars_bottom(); self.nodeById('DataEntryDiv').innerHTML = l_html; }, function buildEntry(self, p_obj, p_handler, p_onchange) { var l_html = ''; l_html = buildBaseEntry(self, p_obj, l_html); l_html = self.buildNodeEntry(p_obj, l_html); l_html = buildLcarEntryButtons(p_handler, l_html); return l_html; }, function buildNodeEntry(self, p_obj, p_html) { p_html += buildTextWidget(self, 'Addr', 'Broker Address', p_obj.BrokerAddress); p_html += buildTextWidget(self, 'Port', 'Port', p_obj.BrokerPort); return p_html; }, function fetchEntry(self) { var l_data = fetchBaseEntry(self); l_data = self.fetchNodeEntry(l_data); return l_data; }, function fetchNodeEntry(self, p_data) { p_data.BrokerAddress = fetchTextWidget(self, 'Addr'); p_data.BrokerPort = fetchTextWidget(self, 'Port'); return p_data; }, function createEntry(self) { var l_data = createBaseEntry(self, Object.keys(globals.Computer.Nodes).length); l_data = self.createNodeEntry(l_data); return l_data; }, function createNodeEntry(self, p_data) { p_data.BrokerAddress = ''; p_data.BrokerPort = ''; return p_data; }, // ============================================================================ /** * Event handler for update buttons at bottom of entry portion of this widget. * Get the possibly changed data and send it to the server. * * @param self * is <"Instance" of undefined.update.updateWidget> * @param p_node * is the button node that was clicked on */ function handleDataEntryOnClick(self, p_node) { function cb_handleDataEntryOnClick(p_json) { self.startWidget(); } function eb_handleDataEntryOnClick(p_reason) { Divmod.debug('---', 'update.eb_handleDataEntryOnClick() was called. ERROR =' + p_reason); } var l_ix = p_node.name; var l_defer; var l_json; switch (l_ix) { case '10003': // Change Button l_json = JSON.stringify(self.fetchEntry()); l_defer = self.callRemote("saveUpdateData", l_json); // @ web_update l_defer.addCallback(cb_handleDataEntryOnClick); l_defer.addErrback(eb_handleDataEntryOnClick); break; case '10002': // Back button showSelectionButtons(self); break; case '10004': // Delete button var l_obj = self.fetchEntry(); l_obj.Delete = true; l_json = JSON.stringify(l_obj); l_defer = self.callRemote("saveupdateData", l_json); // @ web_rooms l_defer.addCallback(cb_handleDataEntryOnClick); l_defer.addErrback(eb_handleDataEntryOnClick); break; default: Divmod.debug('---', 'update.handleDataEntryOnClick(Default) was called. l_ix:' + l_ix); break; } // return false stops the resetting of the server. return false; }); // Divmod.debug('---', 'update.handleMenuOnClick(1) was called. ' + l_ix + ' ' + // l_name); // console.log("update.handleMenuOnClick() - l_obj = %O", l_obj); // ### END DBK
def delete_item(lst, item): if item in lst: lst.remove(item) return lst
<reponame>Katreque/marreta const fs = require('fs'); const LOCAL_TXT = 'C:\\ProgramData\\Local\\Temp\\.nfeasy-cache\\host-log.txt'; var lerLog = function() { return new Promise((resolve, reject) => { fs.readFile(LOCAL_TXT, 'latin1', ((err, data) => { if (!!err) { return reject(err); } return resolve(data); })); }) } var deletarLog = function() { return new Promise((resolve, reject) => { fs.unlinkSync(LOCAL_TXT, function(err){ if (!!err) { return reject(err); } return resolve(); }) }) } module.exports = { lerLog: lerLog, deletarLog: deletarLog }
<reponame>saurabhprasun20/server-just-one<gh_stars>0 package ch.uzh.ifi.seal.soprafs20.controller; import ch.uzh.ifi.seal.soprafs20.entity.Game; import ch.uzh.ifi.seal.soprafs20.rest.dto.GameGetDTO; import ch.uzh.ifi.seal.soprafs20.rest.dto.GamePostDTO; import ch.uzh.ifi.seal.soprafs20.rest.dto.GamePutDTO; import ch.uzh.ifi.seal.soprafs20.rest.mapper.DTOMapper; import ch.uzh.ifi.seal.soprafs20.service.GameService; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import org.springframework.http.ResponseEntity; import java.util.ArrayList; import java.util.List; import java.net.URI; /** * Game Controller * This class is responsible for handling all REST request that are related to an existing game. * The controller will receive the request and delegate the execution to the LoginService and finally return the result. */ @RestController public class GameController { private GameService gameService; GameController(GameService gameService) { this.gameService = gameService; } @PostMapping("/game") public ResponseEntity createGame(@RequestHeader("X-Auth-Token") String token, @RequestBody GamePostDTO gamePostDTO) { long gameId = gameService.createGame(gamePostDTO.getPlayerIds()); URI location = ServletUriComponentsBuilder .fromCurrentRequest() .buildAndExpand(String.format("%d", gameId)) .toUri(); return ResponseEntity.created(location).build(); } @GetMapping("/game/{id}") @ResponseStatus(HttpStatus.OK) @ResponseBody public GameGetDTO getGameInfo(@RequestHeader("X-Auth-Token") String token, @PathVariable("id") long id) { Game game = gameService.getExistingGame(id); return DTOMapper.INSTANCE.convertEntityToGameGetDTO(game); } @PutMapping("/game/{id}/number") @ResponseStatus(HttpStatus.OK) @ResponseBody public void chooseWord( @RequestHeader("X-Auth-Token") String token, @PathVariable("id") long id, @RequestBody GamePutDTO gamePutDTO) { return; } @DeleteMapping("/game/{id}/number") @ResponseStatus(HttpStatus.OK) @ResponseBody public void rejectWord(@RequestHeader("X-Auth-Token") String token, @PathVariable("id") long id) { return; } @PutMapping("/game/{id}/clue") @ResponseStatus(HttpStatus.OK) @ResponseBody public void clue( @RequestHeader("X-Auth-Token") String token, @PathVariable("id") long id, @RequestBody GamePutDTO gamePutDTO) { return; } @PutMapping("/game/{id}/guess") @ResponseStatus(HttpStatus.OK) @ResponseBody public GamePutDTO guess( @RequestHeader("X-Auth-Token") String token, @PathVariable("id") long id, @RequestBody GamePutDTO gamePutDTO) { return gamePutDTO; } @DeleteMapping("/game/{id}") @ResponseStatus(HttpStatus.OK) @ResponseBody public void wrapup(@RequestHeader("X-Auth-Token") String token, @PathVariable("id") long id) { return; } }
source "$(dirname "${BASH_SOURCE}")"/../imos-bashrc || exit 1 eval "echo \"${PS1}\"" > '/dev/null'
f2py -c -m raytracing raytracing.f90 cp raytracing*.so ../weltgeist/
import '../styles/login.css'
public class BankAccount { // Instance variables private int accountNumber; private String accountName; private double currentBalance; // Constructor public BankAccount(int accountNumber, String accountName, double currentBalance) { this.accountNumber = accountNumber; this.accountName = accountName; this.currentBalance = currentBalance; // Getters and Setters public int getAccountNumber() { return accountNumber; } public String getAccountName() { return accountName; } public double getCurrentBalance() { return currentBalance; } public void setAccountNumber(int accountNumber) { this.accountNumber = accountNumber; } public void setAccountName(String accountName) { this.accountName = accountName; } public void setCurrentBalance(double currentBalance) { this.currentBalance = currentBalance; } // Other methods public void deposit(double amount) { currentBalance += amount; } public void withdraw(double amount) { if (amount <= currentBalance) currentBalance -= amount; else System.out.println("Insufficient Balance"); } public void showAccountInfo() { System.out.println("Account Number: " + accountNumber); System.out.println("Account Name: " + accountName); System.out.println("Current Balance: " + currentBalance); } }
package jua.ast; import jua.evaluator.LuaRuntimeException; import jua.evaluator.Scope; import jua.objects.LuaObject; import jua.objects.LuaString; import jua.token.TokenOperator; public class ExpressionConcatenation extends ExpressionBinary { ExpressionConcatenation(TokenOperator token, Expression lhs, Expression rhs) { super(token, lhs, rhs); } @Override public LuaObject evaluate(Scope scope) throws LuaRuntimeException { LuaString res = LuaString.valueOf(lhs.evaluate(scope)); res.append(LuaString.valueOf(rhs.evaluate(scope))); return res; } }
sudo docker run -v $(pwd):/code mythril/myth -x /code/contracts/TokenLoan.sol >> mythrilResult.txt
import { TodoItem } from "@/use/localApi"; import { ActionContext } from "vuex"; import { createStoreClient } from "../httpClient"; import { JuteBagState } from "../types"; import { TodoListState } from "./types"; // FIXME: provide as generic util function function prepareStore( context: ActionContext<TodoListState, JuteBagState>, storeKey: string ): { valid: boolean; url: string } { const result = { valid: false, url: "" }; const isLoggedIn = context.rootGetters["app/userLoggedIn"] as boolean; if (!isLoggedIn) { console.error("User is not logged in, unable to sync"); context.commit("setSyncState", { syncState: "SYNC_ERROR" }); return result; } const user = context.rootGetters["app/user"] as string; const url = "/clob-storage/" + encodeURI(user) + "/" + storeKey; return { valid: true, url }; } export default { /** * Adds (creates) the item and a corresponding category if it does not exist. * If the item is added, * * @param context * @param args description of the category, of type {itemName, categoryName} */ async addItem( context: ActionContext<TodoListState, JuteBagState>, { itemName, categoryName }: { itemName: string; categoryName: string } ): Promise<void> { context.commit("addItem", { itemName, categoryName }); }, async activateItem( context: ActionContext<TodoListState, JuteBagState>, { itemId, categoryId }: { itemId: string; categoryId: string } ): Promise<void> { context.commit("activateItem", { itemId, categoryId }); }, async updateQuantity( context: ActionContext<TodoListState, JuteBagState>, { itemId, quantity }: { itemId: string; quantity: number } ): Promise<void> { context.commit("setQuantity", { itemId, quantity }); }, async deleteItem( context: ActionContext<TodoListState, JuteBagState>, { itemId }: { itemId: string } ): Promise<void> { context.commit("deleteTodoTask", { itemId }); }, addTodoTask( context: ActionContext<TodoListState, JuteBagState>, data: { todoLabel: string; taskLabel: string; } ): void { context.commit("addTask", data); }, raiseTask( context: ActionContext<TodoListState, JuteBagState>, data: { todoLabel: string; taskLabel: string } ): void { context.commit("raiseTask", data); }, createTodoItem( context: ActionContext<TodoListState, JuteBagState>, newItemLabel: string ): void { const newItem = { label: newItemLabel, nextActionTime: new Date(), taskList: [], } as TodoItem; context.commit("addTodoItem", newItem); }, deleteTodoItem( context: ActionContext<TodoListState, JuteBagState>, todoLabel: string ): void { context.commit("deleteTodoItem", todoLabel); }, deleteTodoTask( context: ActionContext<TodoListState, JuteBagState>, data: { todoLabel: string; taskLabel: string } ): void { context.commit("deleteTodoTask", data); }, changeDate( context: ActionContext<TodoListState, JuteBagState>, data: { todoLabel: string; newDate: Date } ): void { context.commit("changeDate", data); }, async upload( context: ActionContext<TodoListState, JuteBagState> ): Promise<void> { context.commit("setSyncState", { syncState: "SYNCING" }); const api = prepareStore(context, "todolist"); if (!api.valid) { context.commit("setSyncState", { syncState: "SYNC_ERROR" }); return; } const stringifiedData = JSON.stringify( context.getters["getRemoteDataExcerpt"] ); // console.log("Pushing data:", stringifiedData); console.log("PUTTING TO TO ", api.url); const httpClient = createStoreClient( context.rootGetters, (mutation: string, data: any) => context.commit(mutation, data, { root: true }) ); console.log( "remote date excerpt:", context.getters["getRemoteDataExcerpt"] ); httpClient .PUT(api.url, context.getters["getRemoteDataExcerpt"], "JSON") // fetch(api.url, { // method: "PUT", // headers: { // "Content-Type": "application/json", // }, // body: stringifiedData, // }) .then((res) => res.json()) .then((json) => { console.log("received PUT result:" + JSON.stringify(json)); context.commit("setSyncState", { syncState: "SYNC" }); }) .catch((err) => { console.log("POST error: " + err); context.commit("setSyncState", { syncState: "SYNC_ERROR" }); }); // await new Promise((resolve) => setTimeout(resolve, 2000)); // context.commit("setSyncState", { syncState: "SYNC" }); }, async download( context: ActionContext<TodoListState, JuteBagState> ): Promise<void> { context.commit("setSyncState", { syncState: "SYNCING" }); const api = prepareStore(context, "todolist"); if (!api.valid) { context.commit("setSyncState", { syncState: "SYNC_ERROR" }); return; } let jsonResponse: { todolist: { key: string; user: unknown; content: string; }; }; const httpClient = createStoreClient( context.rootGetters, (mutation: string, data: any) => context.commit(mutation, data, { root: true }) ); try { console.log("===========================API URL =", api.url); jsonResponse = await httpClient.GET(api.url).then((res) => res.json()); // jsonResponse = await fetch(api.url).then((res) => res.json()); } catch (e) { console.log("Error on download", e); context.commit("setSyncState", { syncState: "SYNC_ERROR" }); return; } if (jsonResponse) { const content = JSON.parse(jsonResponse.todolist.content); console.log("Received object:", content); context.commit("setRemoteData", content); context.commit("setSyncState", { syncState: "SYNC" }); } }, };
#!/bin/bash sudo cp /app/config/docker/varnish /etc/default/varnish sudo cp /app/config/docker/default.vlc /etc/varnish/default.vcl sudo service varnish restart sudo service postgresql start sudo -u postgres psql postgres -c "ALTER USER postgres WITH PASSWORD 'connect';" sudo -u postgres createdb -O postgres spring sudo service postgresql restart sudo ln -s /etc/activemq/instances-available/main /etc/activemq/instances-enabled/main sudo service activemq restart chmod 0755 /app/gradlew cd /app # run flyway to update DB sudo ./gradlew flywayMigrate # build and package app sudo ./gradlew clean build
import matplotlib.pyplot as plt data_set = [9, 11, 8, 10, 12, 5, 10] plt.hist(data_set, bins=5) plt.title('Histogram of data set') plt.xlabel('Values') plt.ylabel('Count') plt.show()
#!/bin/bash # # Usage: # ./table.sh <function name> set -o nounset set -o pipefail set -o errexit readonly WWW=_tmp/www readonly CSV=_tmp/table.csv link-static() { ln -s -f -v \ $PWD/../ajax.js \ $PWD/table-sort.js \ $PWD/table-sort.css \ $WWW } _html-header() { cat <<EOF <!DOCTYPE html> <html> <head> <title>table-sort.js Example</title> <!-- for ajaxGet, UrlHash, etc. --> <script type="text/javascript" src="ajax.js"></script> <link rel="stylesheet" type="text/css" href="table-sort.css" /> <script type="text/javascript" src="table-sort.js"></script> </head> <body onload="initPage(gUrlHash, gTableStates, kStatusElem);" onhashchange="onHashChange(gUrlHash, gTableStates, kStatusElem);"> <p id="status"></p> <table id="mytable"> <colgroup> <col type="number" /> <col type="case-insensitive" /> </colgroup> EOF } # NOTE: There is no initial sort? _html-footer() { cat <<EOF <tfoot> <tr> <td>Footer 1</td> <td>Footer 2</td> </tr> </tfoot> </table> <!-- page globals --> <script type="text/javascript"> var gUrlHash = new UrlHash(location.hash); var gTableStates = {}; var kStatusElem = document.getElementById('status'); function initPage(urlHash, tableStates, statusElem) { var elem = document.getElementById('mytable'); makeTablesSortable(urlHash, [elem], tableStates); updateTables(urlHash, tableStates, statusElem); } function onHashChange(urlHash, tableStates, statusElem) { updateTables(urlHash, tableStates, statusElem); } </script> </body> </html> EOF } write-csv() { cat >$CSV <<EOF metric,fraction A,0.21 B,0.001 C,0.0009 D,0.0001 -,0.1 F,- EOF } print-table() { _html-header ./csv_to_html.py \ --col-format 'metric <a href="metric.html#metric={metric}">{metric}</a>' \ --as-percent fraction \ < $CSV _html-footer } write-table() { mkdir -p $WWW link-static write-csv local out=$WWW/table-example.html print-table >$out ls -l $out } "$@"
1. Establish the teams’ goals and what is causing the dispute. 2. Develop a list of potential solutions. 3. Analyze each potential solution and consider each team’s position. 4. Make sure that all parties involved in the dispute are present and involved in the negotiation process. 5. Reach agreement on a resolution that is acceptable to both teams. 6. Document the resolution and take all necessary steps to implement the resolution. 7. Monitor the resolution to ensure it is effective.
package com.benny.openlauncher.util; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.support.v4.app.ActivityCompat; import android.view.Gravity; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.afollestad.materialdialogs.MaterialDialog; import com.benny.openlauncher.R; import com.benny.openlauncher.activity.Home; import com.benny.openlauncher.core.interfaces.App; import com.benny.openlauncher.core.interfaces.AppDeleteListener; import com.benny.openlauncher.core.interfaces.AppUpdateListener; import com.benny.openlauncher.core.interfaces.IconDrawer; import com.benny.openlauncher.core.interfaces.IconProvider; import com.benny.openlauncher.core.manager.Setup; import com.benny.openlauncher.core.model.IconLabelItem; import com.benny.openlauncher.core.model.Item; import com.benny.openlauncher.core.util.BaseIconProvider; import com.mikepenz.fastadapter.commons.adapters.FastItemAdapter; import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.UUID; public class AppManager implements Setup.AppLoader<AppManager.App> { private static AppManager ref; public Context getContext() { return context; } private Context context; public PackageManager getPackageManager() { return packageManager; } private PackageManager packageManager; private List<App> apps = new ArrayList<>(); private List<App> nonFilteredApps = new ArrayList<>(); public final List<AppUpdateListener<App>> updateListeners = new ArrayList<>(); public final List<AppDeleteListener<App>> deleteListeners = new ArrayList<>(); public boolean recreateAfterGettingApps; private AsyncTask task; public static AppManager getInstance(Context context) { return ref == null ? (ref = new AppManager(context)) : ref; } public AppManager(Context c) { this.context = c; this.packageManager = c.getPackageManager(); } public App findApp(Intent intent) { String packageName = intent.getComponent().getPackageName(); String className = intent.getComponent().getClassName(); for (App app : apps) { if (app.className.equals(className) && app.packageName.equals(packageName)) { return app; } } return null; } public List<App> getApps() { return apps; } public List<App> getNonFilteredApps() { return nonFilteredApps; } public void clearListener() { updateListeners.clear(); deleteListeners.clear(); } public void init() { getAllApps(); } private void getAllApps() { if (task == null || task.getStatus() == AsyncTask.Status.FINISHED) task = new AsyncGetApps().execute(); else if (task.getStatus() == AsyncTask.Status.RUNNING) { task.cancel(false); task = new AsyncGetApps().execute(); } } public void startPickIconPackIntent(final Activity activity) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory("com.anddoes.launcher.THEME"); FastItemAdapter<IconLabelItem> fastItemAdapter = new FastItemAdapter<>(); final List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent, 0); Collections.sort(resolveInfos, new ResolveInfo.DisplayNameComparator(packageManager)); final MaterialDialog d = new MaterialDialog.Builder(activity) .adapter(fastItemAdapter, null) .title((activity.getString(R.string.dialog__icon_pack_title))) .build(); fastItemAdapter.add(new IconLabelItem(activity, R.drawable.ic_launcher, R.string.label_default, -1) .withIconGravity(Gravity.START) .withOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { recreateAfterGettingApps = true; AppSettings.get().setIconPack(""); getAllApps(); d.dismiss(); } })); for (int i = 0; i < resolveInfos.size(); i++) { final int mI = i; fastItemAdapter.add(new IconLabelItem(activity, resolveInfos.get(i).loadIcon(packageManager), resolveInfos.get(i).loadLabel(packageManager).toString(), -1) .withIconGravity(Gravity.START) .withOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { recreateAfterGettingApps = true; AppSettings.get().setIconPack(resolveInfos.get(mI).activityInfo.packageName); getAllApps(); d.dismiss(); } else { Tool.toast(context, (activity.getString(R.string.dialog__icon_pack_info_toast))); ActivityCompat.requestPermissions(Home.launcher, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Home.REQUEST_PERMISSION_STORAGE); } } })); } d.show(); } public void onReceive(Context p1, Intent p2) { getAllApps(); } // ----------------------- // AppLoader interface // ----------------------- @Override public void loadItems() { getAllApps(); } @Override public List<App> getAllApps(Context context) { return getApps(); } @Override public App findItemApp(Item item) { return findApp(item.getIntent()); } @Override public App createApp(Intent intent) { try { ResolveInfo info = packageManager.resolveActivity(intent, 0); App app = new App(getContext(), info, packageManager); if (apps != null && !apps.contains(app)) apps.add(app); return app; } catch (Exception e) { return null; } } @Override public void onAppUpdated(Context p1, Intent p2) { onReceive(p1, p2); } @Override public void notifyUpdateListeners(List<App> apps) { Iterator<AppUpdateListener<App>> iter = updateListeners.iterator(); while (iter.hasNext()) { if (iter.next().onAppUpdated(apps)) { iter.remove(); } } } @Override public void notifyRemoveListeners(List<App> apps) { Iterator<AppDeleteListener<App>> iter = deleteListeners.iterator(); while (iter.hasNext()) { if (iter.next().onAppDeleted(apps)) { iter.remove(); } } } @Override public void addUpdateListener(AppUpdateListener updateListener) { updateListeners.add(updateListener); } @Override public void removeUpdateListener(AppUpdateListener updateListener) { updateListeners.remove(updateListener); } @Override public void addDeleteListener(AppDeleteListener deleteListener) { deleteListeners.add(deleteListener); } @Override public void removeDeleteListener(AppDeleteListener deleteListener) { deleteListeners.remove(deleteListener); } private class AsyncGetApps extends AsyncTask { private List<App> tempApps; @Override protected void onPreExecute() { tempApps = new ArrayList<>(apps); super.onPreExecute(); } @Override protected void onCancelled() { tempApps = null; super.onCancelled(); } @Override protected Object doInBackground(Object[] p1) { apps.clear(); nonFilteredApps.clear(); Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.addCategory(Intent.CATEGORY_LAUNCHER); List<ResolveInfo> activitiesInfo = packageManager.queryIntentActivities(intent, 0); Collections.sort(activitiesInfo, new Comparator<ResolveInfo>() { @Override public int compare(ResolveInfo p1, ResolveInfo p2) { return Collator.getInstance().compare(p1.loadLabel(packageManager).toString(), p2.loadLabel(packageManager).toString()); } }); for (ResolveInfo info : activitiesInfo) { App app = new App(context, info, packageManager); nonFilteredApps.add(app); } List<String> hiddenList = AppSettings.get().getHiddenAppsList(); if (hiddenList != null) { for (int i = 0; i < nonFilteredApps.size(); i++) { boolean shouldGetAway = false; for (String hidItemRaw : hiddenList) { if ((nonFilteredApps.get(i).packageName + "/" + nonFilteredApps.get(i).className).equals(hidItemRaw)) { shouldGetAway = true; break; } } if (!shouldGetAway) { apps.add(nonFilteredApps.get(i)); } } } else { for (ResolveInfo info : activitiesInfo) apps.add(new App(context, info, packageManager)); } AppSettings appSettings = AppSettings.get(); if (!appSettings.getIconPack().isEmpty() && Tool.isPackageInstalled(appSettings.getIconPack(), packageManager)) { IconPackHelper.themePacs(AppManager.this, Tool.dp2px(appSettings.getIconSize(), context), appSettings.getIconPack(), apps); } return null; } @Override protected void onPostExecute(Object result) { notifyUpdateListeners(apps); List<App> removed = Tool.getRemovedApps(tempApps, apps); if (removed.size() > 0) { notifyRemoveListeners(removed); } if (recreateAfterGettingApps) { recreateAfterGettingApps = false; if (context instanceof Home) ((Home) context).recreate(); } super.onPostExecute(result); } } public static class App implements com.benny.openlauncher.core.interfaces.App { public String label, packageName, className; public BaseIconProvider iconProvider; public ResolveInfo info; public App(Context context, ResolveInfo info, PackageManager pm) { this.info = info; iconProvider = Setup.imageLoader().createIconProvider(info.loadIcon(pm)); label = info.loadLabel(pm).toString(); packageName = info.activityInfo.packageName; className = info.activityInfo.name; if (packageName.equals("com.benny.openlauncher")) { label = context.getString(R.string.ol_settings); } } @Override public boolean equals(Object o) { if (o instanceof App) { App temp = (App) o; return this.packageName.equals(temp.packageName); } else { return false; } } @Override public String getLabel() { return label; } @Override public String getPackageName() { return packageName; } @Override public String getClassName() { return className; } @Override public BaseIconProvider getIconProvider() { return iconProvider; } } public static abstract class AppUpdatedListener implements AppUpdateListener<App> { private String listenerID; public AppUpdatedListener() { listenerID = UUID.randomUUID().toString(); } @Override public boolean equals(Object obj) { return obj instanceof AppUpdatedListener && ((AppUpdatedListener) obj).listenerID.equals(this.listenerID); } } }
<reponame>i-apples/goman const fs = require('fs'); const path = require('path'); const webpack = require('webpack'); function deleteDir(dir) { var files = []; if (fs.existsSync(dir)) { files = fs.readdirSync(dir); files.forEach(function (file, index) { var curDir = dir + "/" + file; if (fs.statSync(curDir).isDirectory()) { // recurse deleteJS(curDir); } else { // delete file fs.unlinkSync(curDir); } }); fs.rmdirSync(dir); } }; var isDev = false; if (process.env && process.env.NODE_ENV === 'dev') { isDev = true; } //总是清除之前生成的文件 var distDir = path.join(__dirname, 'static', 'js'); deleteDir(distDir); var config = { entry: { vendor: ['es6-promise', 'vue', 'vue-router', 'vue-i18n', 'echarts', 'lodash', 'axios', 'moment', 'iview-style', 'iview', 'highlight.js-style', 'highlight.js'], app: ['./ts/main.ts'] }, output: { filename: '[name].min.js', path: distDir }, resolve: { extensions: ['.ts', '.js', '.vue'], alias: { 'iview-style': 'iview/dist/styles/iview.css', 'highlight.js-style': 'highlight.js/styles/default.css' } }, module: { rules: [ { test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.vue$/, loader: 'vue-loader', options: { esModule: true } }, { test: /\.ts$/, loader: 'ts-loader', options: { appendTsSuffixTo: [/\.vue$/] } }, { test: /\.(png|jpg|gif|woff|woff2|svg|eot|ttf)$/, loader: 'url-loader', options: { name: './static/img/[hash].[ext]' } } ] }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: Infinity }) ] } if (isDev) { config.watch = true; config.devtool = '#cheap-module-eval-source-map'; config.plugins.unshift( new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"development"' } }) ); } else { config.plugins.unshift( new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }) ); config.plugins.unshift( new webpack.optimize.UglifyJsPlugin({ minimize: true }) ); //生产模式,删除 go/statik 目录重新生成 deleteDir(path.join(__dirname, '..', 'go', 'statik')); } module.exports = config;
#!/bin/sh # Backup user home directories and call system backup script # depending on how long it is since last backup. # The backup schedule timestamp checkfile is called backup_interval_checkfile, # and for root script user it is read from /opt, for normal users from ~/.config/. # Rsync excludes are read from ~/.config/backup_exclude. backup() { scriptsdir=${1:-$HOME} backupmountpoint=/mnt/raidstorage backupdir=backups/misc/home_dirs/ [ ! -e $backupmountpoint ] && return if [ "$(whoami)" = "root" ] then checkfile=/opt/backup_interval_checkfile else checkfile=~/.config/backup_interval_checkfile fi [ ! -e $checkfile ] && touch $checkfile lastsyncmisc=$(expr $(date +%s) - $(stat -c %Z $checkfile)) sync=0 # 302400 seconds = 84 hours, or 3½ days. [ $lastsyncmisc -gt 302400 ] && sync=1 if [ $sync -eq 1 ] then backup=$(mount | grep $backupmountpoint) if [ ! "$backup" ] then echo "Mounting $backupmountpoint..." sudo mount $backupmountpoint fi backup=$(mount | grep $backupmountpoint) if [ ! "$backup" ] then echo "Unable to mount $backupmountpoint! Aborting backup." sleep 3 return 1 fi touch $checkfile if test "$(whoami)" = "root" then dircmd="find /home/ -maxdepth 1 -mindepth 1 -type d" else dircmd="ls -d /home/$(whoami)" fi for user in $($dircmd | sed "s/.*\///g") do userbackupdir=$backupmountpoint/$backupdir/$user excludes=/home/$user/.config/backup_exclude if [ -e $excludes ] then excludes="--exclude-from=$excludes" else excludes="" fi echo "Backing up $user's home directory..." rsync -a $excludes --delete /home/$user/ $userbackupdir/ date > $userbackupdir/last_backup_timestamp.txt chown $user:$user $userbackupdir $userbackupdir/last_backup_timestamp.txt echo done echo "Starting general backup." sudo $scriptsdir/backup_local.sh misconly fi } backup $(dirname "$(readlink -f "$0")")
import cv2 import numpy as np import argparse def click_event(event, x, y, flags, params): if event == cv2.EVENT_LBUTTONDOWN: cv2.circle(base_image_copy, (x,y), 4, (0,0,255), -1) points.append([x, y]) if len(points) <= 4: cv2.imshow('image', base_image_copy) # Let's sort the points in the following order # Top-Left, Top-Right, Bottom-Right, Bottom-Left def sort_pts(points): sorted_pts = np.zeros((4, 2), dtype="float32") s = np.sum(points, axis=1) sorted_pts[0] = points[np.argmin(s)] sorted_pts[2] = points[np.argmax(s)] diff = np.diff(points, axis=1) sorted_pts[1] = points[np.argmin(diff)] sorted_pts[3] = points[np.argmax(diff)] return sorted_pts if __name__=='__main__': parser = argparse.ArgumentParser() parser.add_argument('--base_img', type=str, help='Path to the base image', required=True) parser.add_argument('--subject_img', type=str, help='Path to the subject image', required=True) parser.add_argument('--debug', type=bool, help='Enable debug', default=False) args = vars(parser.parse_args()) points = [] base_image = cv2.imread(args['base_img']) base_image_copy = base_image.copy() subject_image = cv2.imread(args['subject_img']) cv2.imshow('image', base_image_copy) cv2.setMouseCallback('image', click_event) cv2.waitKey(0) cv2.destroyAllWindows() sorted_pts = sort_pts(points) h_base, w_base, c_base = base_image.shape h_subject, w_subject = subject_image.shape[:2] pts1 = np.float32([[0, 0], [w_subject, 0], [w_subject, h_subject], [0, h_subject]]) pts2 = np.float32(sorted_pts) # Get the transformation matrix and use it to get the warped image of the subject transformation_matrix = cv2.getPerspectiveTransform(pts1, pts2) warped_img = cv2.warpPerspective(subject_image, transformation_matrix, (w_base, h_base)) # Create a mask mask = np.zeros(base_image.shape, dtype=np.uint8) roi_corners = np.int32(sorted_pts) # Fill in the region selected with white color filled_mask = mask.copy() cv2.fillConvexPoly(filled_mask, roi_corners, (255, 255, 255)) # Invert the mask color inverted_mask = cv2.bitwise_not(filled_mask) # Bitwise AND the mask with the base image masked_image = cv2.bitwise_and(base_image, inverted_mask) if args['debug']: cv2.imshow('Warped Image', warped_img) cv2.imshow('Mask Created', mask) cv2.imshow('Mask after filling', filled_mask) cv2.imshow('Inverting Mask colors', inverted_mask) cv2.imshow('Masked Image', masked_image) cv2.waitKey(0) cv2.destroyAllWindows() # Using Bitwise OR to merge the two images output = cv2.bitwise_or(warped_img, masked_image) cv2.imshow('Fused Image', output) cv2.imwrite('Final_Output.png', output) cv2.waitKey(0) cv2.destroyAllWindows()
package streams; import org.apache.kafka.streams.StreamsConfig; import io.confluent.kafka.serializers.AbstractKafkaAvroSerDeConfig; import java.util.Properties; import java.util.Map; import static java.util.Collections.singletonMap; public class StreamsConfiguration { public static Properties streamsConfiguration() { final Properties streamsConfiguration = new Properties(); // Give the Streams application a unique name. The name must be unique in the Kafka cluster // against which the application is run. streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "device-events-processing"); // Where to find Kafka broker(s). streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:29092"); return streamsConfiguration; } public static Map<String, String> schemaRegistry() { return singletonMap(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, "http://localhost:8090"); } }
<filename>src/ch14/racehorse141.java package ch14; import static java.lang.System.*; /** * Project: ch14 * Date: 2/26/2018 * * @author <NAME> */ public class racehorse141 extends Thread { private String name; public racehorse141(String n) { name = n; } public void run() { long startTime = currentTimeMillis(); for (int i = 1; i <= 100; i++) { out.println(name + " : " + i); } long time = currentTimeMillis() - startTime; out.printf("%s is Done with priority: %d in %dms\n", name, getPriority(), time); } }
<filename>commands/reaction/dance.js<gh_stars>0 const Discord = require('discord.js'); /* const animaction = require('../../util/animaction/animaction'); */ module.exports = { name: 'dance', description: "Muestra tus pasos owo", aliases: ['jig', 'prance'], usage: ' [Usuario]', cooldown: 2, args: 0, catergory: 'Reacción', async execute(client, message, args) { message.react('848437798292946956'); const embed = new Discord.MessageEmbed() .setColor('RANDOM') .setThumbnail(`https://cdn.discordapp.com/emojis/848437798292946956.gif?v=1`) .setDescription('Hola nwn, soy **KitsuneCode**, al parecer este comando aun esta en construcción, pero si gustas ayudarme con gifs para estas acciones sientete libre de contactarme [aqui](https://discord.gg/r3SPkEjNjC)') .setImage(`https://media.discordapp.net/attachments/839297635890102272/850836563772047371/proximamente.gif`) .setFooter('Anime: Kono Subarashii Sekai ni Shukufuku wo!') return message.channel.send(embed); /* message.react('✨'); if (message.mentions.members.size === 0) { const dance = animaction.dance(); const botaction = [ `**${message.author.username}** esta bailando :3`, `**${message.author.username}** muestra sus grandes pasos!! .w.` ] randombot = botaction[Math.floor(Math.random() * Math.floor(botaction.length))]; const embed = new Discord.MessageEmbed() .setColor('RANDOM') .setDescription(randombot) .setImage(dance) return message.channel.send(embed); } const member = message.mentions.members.first(); const dance = animaction.dance(); if (member.user.id === message.author.id) { const embed = new Discord.MessageEmbed() .setColor('RANDOM') .setDescription(`**${message.author.username}** esta bailando frente a un espejo .w.`) .setImage(dance) return message.channel.send(embed); } else if (member.user.id === client.user.id) { const botaction = [ `**${message.author.username}** esta bailando conmigo, grandes pasos amig@ .w.`, `**${message.author.username}** se puso a bailar conmigo -Se alegra- nwn` ] randombot = botaction[Math.floor(Math.random() * Math.floor(botaction.length))]; const embed = new Discord.MessageEmbed() .setColor('RANDOM') .setDescription(randombot) .setImage(dance) return message.channel.send(embed); } else { const randomaction = [ `**${message.author.username}** se puso a bailar con **${member.user.username}** >w<`, `**${message.author.username}** demuestra sus pasos a **${member.user.username}**!!! :D` ] //Respuestas posibles randomsg = randomaction[Math.floor(Math.random() * Math.floor(randomaction.length))]; const embed = new Discord.MessageEmbed() .setColor('RANDOM') .setDescription(randombot) .setImage(dance) return message.channel.send(embed); } */ } };
#! /bin/bash # # Copyright 2017 David Hein # # Licensed under the MIT License. If the LICENSE file is missing, you # can find the MIT license terms here: https://opensource.org/licenses/MIT docker-compose --file docker-compose-tests.yaml up --no-build --timeout 2 -d
pacman -S --noconfirm git rsync if [ ! -d "/home/appveyor/.ssh" ]; then mkdir "/home/appveyor/.ssh" fi echo -e "Host $1\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config cp "$(dirname "$0")/id_rsa" ~/.ssh/id_rsa echo "copying $3 from $(cygpath -u "$2") to root@$1:/web/downloads/$4" rsync -avh -e "ssh -p 2458" --include="*/" --include="$3" --exclude="*" "$(cygpath -u "$2")/" "root@$1:/web/downloads/$4"
<reponame>elishahyousaf/linkedin-exercise-files<filename>Chap02/02_09.py # syntax error print("Hello world") # runtime error 10 * (2/0) # semantic error name = "Alice" print("Hello name")
#!/usr/bin/env bash # setting the locale, some users have issues with different locales, this forces the correct one export LC_ALL=en_US.UTF-8 HOSTS="www.baidu.com google.com github.com example.com" get_ssid() { # Check OS case $(uname -s) in Linux) SSID=$(iw dev | sed -nr 's/^\t\tssid (.*)/\1/p') if [ -n "$SSID" ]; then printf '%s' "$SSID" else echo 'Ethernet' fi ;; Darwin) if /System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport -I | grep -E ' SSID' | cut -d ':' -f 2 | sed 's/ ^*//g' &> /dev/null; then echo "$(/System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport -I | grep -E ' SSID' | cut -d ':' -f 2)" | sed 's/ ^*//g' else echo 'Ethernet' fi ;; CYGWIN*|MINGW32*|MSYS*|MINGW*) # leaving empty - TODO - windows compatability ;; *) ;; esac } main() { network="Offline" for host in $HOSTS; do if ping -q -c 1 -W 1 $host &>/dev/null; then network="$(get_ssid)" break fi done echo "$network" } #run main driver function main
#!/bin/sh echo "git push" git config --global user.email "travis@travis-ci.org" git config --global user.name "Travis CI" git config --global push.default current git checkout ${TRAVIS_BRANCH} echo "https://mightguy:$1@github.com/mightguy/Solr-Cloud-Manager.git" git push "https://mightguy:$1@github.com/mightguy/Solr-Cloud-Manager.git"
// Function to return gcd of a and b def gcd(a, b): if a == 0 : return b return gcd(b % a, a) # Driver program to test above function a = 6 b = 8 if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b)) else: print('not found') # Output: # GCD of 6 and 8 is 2
var fs = require('fs') , async = require('async') function sizeOfDir(dir, callback) { fs.lstat(dir, function(err, stat) { if (err) return callback(err); if (!stat.isDirectory()) return callback(null, stat.size); fs.readdir(dir, function(err, files) { if (err) return callback(err.code === 'EACCES' ? null : err, 0); async.parallel(files.map(function(file) { return async.apply(sizeOfDir, dir + '/' + file); }), function(err, results) { if (err) return callback(err); return callback(null, results.reduce(function(sum, value) { return sum + value; }, 0)); }); }); }); } var dir = process.argv[2] || process.cwd(); sizeOfDir(dir, function(err, size) { if (err) throw err; total_mb = size / 1024 / 1024; console.log("%s: %d MB", dir, total_mb.toFixed(3)); });
<gh_stars>0 /** @module ecs/raw/animation/FadeOutAnimation */ import DrawablesComponent from "/scripts/ecs/comp/graph/DrawablesComponent.js" import Animation from "./Animation.js" export default class FadeOutAnimation extends Animation { static NAME = "fadeout" frame(entity, relTime) { const { drawables } = entity.components.get(DrawablesComponent) for (const [, drawable] of drawables) drawable.texture.color.a = 1 - relTime return this } get name() { return FadeOutAnimation.NAME } clone() { return new FadeOutAnimation(this.cloneConfig()) } copy() { return new FadeOutAnimation(this.copyConfig()) } }
<reponame>Doogie13/postman package me.srgantmoomoo.postman.api.event.events; import me.srgantmoomoo.postman.api.event.Event; public class CanCollideCheckEvent extends Event { }
<reponame>youzhengjie9/cloud-yblog package com.boot.feign.log; import com.boot.pojo.LoginLog; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; /** * ???????????????? * 实测:如果feign接口写了fallback方法,即使在fallback方法里面抛出Runtime异常也不能让全局事务回滚======== * ????????????????????????????????? * 所以,暂时把fallback方法取消 */ //@FeignClient(value = "cloud-yblog-log",fallback = LoginLogFeignImpl.class) @FeignClient(value = "cloud-yblog-log") @Component public interface LoginLogFeign { @ResponseBody @PostMapping(path = "/feign/loginlog/insertLoginLog") public String insertLoginLog(@RequestBody LoginLog loginLog); }
fn handle_file(fin: &mut Resource) -> Result<(), i32> { let mut inp = [0u8; 16]; fin.read(&mut inp).map_err(|e| { error!("couldn't read: {:?}", e); 1 })?; info!("flushing random file"); fin.flush().map_err(|e| { error!("error: {:?}", e); 1 })?; Ok(()) }
def delete(self): # Check for valid authentication token auth_token = self.request.headers.get('Authorization') if not auth_token or not validate_token(auth_token): self.response.set_status(401) return # Extract resource identifier from the request resource_id = self.request.get('resource_id') # Check if the resource exists and delete it if resource_id in server_database: del server_database[resource_id] self.response.set_status(204) else: self.response.set_status(404)
def get_word_lengths(words): # initialize empty list lengths = [] # iterate over the list of words for word in words: # append the length of each word to lengths lengths.append(len(word)) # return the list of lengths return lengths
REM FILE NAME: Ora_kill.sql REM LOCATION: Security Administration\Utilities REM FUNCTION: Kills a non-essential Oracle session REM FUNCTION: REM TESTED ON: 8.1.5, 8.1.7, 9.0.1 REM PLATFORM: non-specific REM REQUIRES: REM REM This is a part of the Knowledge Xpert for Oracle Administration library. REM Copyright (C) 2001 Quest Software REM All rights reserved. REM REM******************** Knowledge Xpert for Oracle Administration ******************** REM REM DEPENDANCIES: kill_ses.sql REM REM*********************************************************************************** SET heading off termout off verify off echo off SPOOL rep_out\kill_all.sql SELECT 'execute kill_session(' || CHR (39) || sid || CHR (39) || ',' || CHR (39) || serial# || CHR (39) || ');' FROM v$session WHERE username IS NOT NULL OR username <> 'SYS' / SPOOL off START rep_out\kill_all.sql
package com.Card; /** * Created by woramet on 12/20/15. */ public class Card implements Comparable<Card>{ private Suit suit; private CardValue value; public Card(Suit suit, CardValue value) { this.suit = suit; this.value = value; } public Suit getSuit() { return suit; } public CardValue getValue() { return value; } public int getIntValue() { return value.getCardValue(); } @Override public String toString() { return value.toString()+suit.toString(); } public int compareTo(Card o) { return this.value.getCardValue() - o.value.getCardValue(); } }
import constants from "../core/constants"; import Move from "../models/move"; export default class Board { constructor() { this.board = new Array(9); this.board = this.board.map(function() { return null; }); this.emptySpaces = 9; } clone() { var retVal = new Board(); retVal.init(this.board.slice(0)); return retVal; } init(initialBoard) { this.board = initialBoard; initialBoard.map(function(item) { if(item != null) { this.emptySpaces--; } }, this); } getPlayerAt(row, col) { return this.board[(row - 1) * 3 + (col - 1)]; } setPlayerAt(row, col, player) { if(this.getPlayerAt(row, col) == null) { this.board[(row - 1) * 3 + (col - 1)] = player; this.emptySpaces--; } } getPossibleMovesForPlayer(player) { var retMoves = []; for(var i = 0; i < 9; i++) { var row = Math.floor(i / 3) + 1; var col = i % 3 + 1; if(this.getPlayerAt(row, col) == null) { retMoves.push(new Move(row, col, player)); } } return retMoves; } getAvailableSpaces() { return this.emptySpaces; } isGameOver() { return (this.emptySpaces == 0 || this.getGameWinner() != false); } getGameWinner() { if(this.getPlayerAt(1,1) != null && this.getPlayerAt(1,1) == this.getPlayerAt(1,2) && // X X X this.getPlayerAt(1,2) == this.getPlayerAt(1,3)) { // _ _ _ return this.getPlayerAt(1,1); // _ _ _ } else if(this.getPlayerAt(1,1) != null && this.getPlayerAt(1,1) == this.getPlayerAt(2,1) && // X _ _ this.getPlayerAt(2,1) == this.getPlayerAt(3,1)) { // X _ _ return this.getPlayerAt(1,1); // X _ _ } else if(this.getPlayerAt(1,1) != null && this.getPlayerAt(1,1) == this.getPlayerAt(2,2) && // X _ _ this.getPlayerAt(2,2) == this.getPlayerAt(3,3)){ // _ X _ return this.getPlayerAt(1,1); // _ _ X } else if(this.getPlayerAt(2,1) != null && this.getPlayerAt(2,1) == this.getPlayerAt(2,2) && // _ _ _ this.getPlayerAt(2,2) == this.getPlayerAt(2,3)) { // X X X return this.getPlayerAt(2,1); // _ _ _ } else if(this.getPlayerAt(3,1) != null && this.getPlayerAt(3,1) == this.getPlayerAt(3,2) && // _ _ _ this.getPlayerAt(3,2) == this.getPlayerAt(3,3)) { // _ _ _ return this.getPlayerAt(3,1); // X X X } else if(this.getPlayerAt(1,2) != null && this.getPlayerAt(1,2) == this.getPlayerAt(2,2) && // _ X _ this.getPlayerAt(2,2) == this.getPlayerAt(3,2)) { // _ X _ return this.getPlayerAt(1,2); // _ X _ } else if(this.getPlayerAt(1,3) != null && this.getPlayerAt(1,3) == this.getPlayerAt(2,3) && // _ _ X this.getPlayerAt(2,3) == this.getPlayerAt(3,3)) { // _ _ X return this.getPlayerAt(1,3); // _ _ X } else if(this.getPlayerAt(1,3) != null && this.getPlayerAt(1,3) == this.getPlayerAt(2,2) && // _ _ X this.getPlayerAt(2,2) == this.getPlayerAt(3,1)) { // _ X _ return this.getPlayerAt(1,3); // X _ _ } else if(this.emptySpaces == 0) { return constants.PLAYERS.NOONE; } else { return false; } } }
/* * Copyright 2018 Genentech Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export default { methods: { /** * Image pixel size is computed from the binning or super-resolution factor, the detector's physical pixel size, the post-mag (of the detector), the calibrated mag (of the microscope): * - if super-resolution was used: image_pixel_size_in_A = detector_physical_pixel_size_in_um * 10000.0 * / calibrated_magnification_unitless / post_magnification_factor_for_detector / supersampling_factor * - if super-resolution was not used: image_pixel_size_A = detector_physical_pixel_size_in_um * 10000.0 * / calibrated_magnification_unitless / post_magnification_factor_for_detector * binning_factor. * @param microscopySession Session to get the calculation from. * @returns Calculated image pixel size. */ calculateImagePixelSize (microscopySession) { let imagePixelSize = null if (microscopySession.electronDetector && microscopySession.electronDetector.pixelLinearDimensionUm && microscopySession.calibratedMagnification) { if (microscopySession.superResolution && microscopySession.supersamplingFactor && microscopySession.supersamplingFactor > 0) { imagePixelSize = microscopySession.electronDetector.pixelLinearDimensionUm * 10000 / (microscopySession.calibratedMagnification * microscopySession.supersamplingFactor) } else if (!microscopySession.superResolution && microscopySession.pixelBinning && microscopySession.pixelBinning > 0) { imagePixelSize = microscopySession.electronDetector.pixelLinearDimensionUm * 10000 * microscopySession.pixelBinning / microscopySession.calibratedMagnification } } return imagePixelSize }, /** * The exposure rate is calculated: * - if counting_mode == false, compute exposure rate as follows: Exposure_rate_eA2s * = exposure_rate_cps / detector_counts_per_electron_factor / (image_pixel_size_A)^2 * - if counting_mode == true, compute exposure rate as follows: Exposure_rate_eA2s * = exposure_rate_eps / (image_pixel_size_A)^2. * @param microscopySession Session to get the calculation from. * @returns Calculated exposure rate. */ calculateExposureRate (microscopySession) { let imagePixelSize = this.calculateImagePixelSize(microscopySession) let microscopeExposureRate = parseFloat(microscopySession.exposureRate) return !imagePixelSize || imagePixelSize <= 0 || !microscopeExposureRate || microscopeExposureRate <= 0 || !microscopySession.electronDetector || (microscopySession.countingMode && !microscopySession.electronDetector.countsPerElectronsFactor) ? null : microscopySession.exposureRate / ((microscopySession.countingMode ? 1 : microscopySession.electronDetector.countsPerElectronsFactor) * Math.pow(imagePixelSize, 2)) }, /** * Total exposure is calculated: * total_exposure = exposure_duration [seconds, given by user] * exposure_rate [calculated above, in electrons/Å ^2^ /s]. * @param microscopySession Session to get the calculation from. * @returns Calculated total exposure. */ calculateTotalExposure (microscopySession) { let exposureRate = this.calculateExposureRate(microscopySession) let exposureDuration = parseFloat(microscopySession.exposureDuration) return !(exposureDuration > 0) || !exposureRate ? null : microscopySession.exposureDuration * exposureRate }, /** * Frame duration is calculated: * frame_duration = exposure_duration / number_of_frames. * @param microscopySession Session to get the calculation from. * @returns Calculated frame duration. */ calculateFrameDuration (microscopySession) { let exposureDuration = parseFloat(microscopySession.exposureDuration) let numberOfFrames = parseInt(microscopySession.numberOfFrames) return !(exposureDuration > 0) || !(numberOfFrames > 0) ? null : exposureDuration / microscopySession.numberOfFrames }, /** * Exposure per frame is calculated: * exposure_per_frame = total_exposure [calculated above] / number of frames. * @param microscopySession Session to get the calculation from. * @returns Calculated exposure per frame. */ calculateExposurePerFrame (microscopySession) { let totalExposure = this.calculateTotalExposure(microscopySession) let numberOfFrames = parseInt(microscopySession.numberOfFrames) return !totalExposure || !(numberOfFrames > 0) ? null : totalExposure / numberOfFrames }, /** * Check if objectiveAperture can be choose for microscope * @param microscope * @param objectiveAperture * @returns {boolean} */ isApplicableObjectiveAperture: function (microscope, objectiveAperture) { const availableApertures = [microscope.objectiveAperture1, microscope.objectiveAperture2, microscope.objectiveAperture3, microscope.objectiveAperture4] if (objectiveAperture) { for (let i = 0; i < availableApertures.length; i++) { if (!!availableApertures[i].phasePlate === !!objectiveAperture.phasePlate && (availableApertures[i].diameter === objectiveAperture.diameter || objectiveAperture.diameter !== 0 && !objectiveAperture.diameter && !availableApertures[i].diameter)) { return true } } } return false }, /** * Check if accelerationVoltageKV is on microscope list * @param microscope * @param accelerationVoltageKV * @returns {boolean} */ isApplicableAccelerationVoltageKV: function (microscope, accelerationVoltageKV) { return microscope.availableVoltagesKV.indexOf(accelerationVoltageKV) >= 0 }, /** * Check if condenser2ApertureDiameter can be choose for microscope * @param microscope * @param condenser2ApertureDiameter * @returns {boolean} */ isApplicableCondenser2ApertureDiameter: function (microscope, condenser2ApertureDiameter) { return [microscope.condenser1ApertureDiameter, microscope.condenser2ApertureDiameter, microscope.condenser3ApertureDiameter, microscope.condenser4ApertureDiameter] .indexOf(condenser2ApertureDiameter) >= 0 }, isApplicableMagnification: function (electronDetector, magnification) { return electronDetector.availableMagnifications.map(m => m.nominalMagnification).indexOf(magnification) >= 0 }, /** * Returns default objectiveAperture from microscope * @param microscope * @returns {ObjectiveAperture} */ getDefaultObjectiveAperture: function (microscope) { return [microscope.objectiveAperture1, microscope.objectiveAperture2, microscope.objectiveAperture3, microscope.objectiveAperture4][(microscope.defaultObjectiveApertureIndex || 1) - 1] }, /** * Returns default value for condenser2ApertureDiameter from microscope * @param microscope * @returns {*} */ getDefaultCondenser2ApertureDiameter: function (microscope) { return [microscope.condenser1ApertureDiameter, microscope.condenser2ApertureDiameter, microscope.condenser3ApertureDiameter, microscope.condenser4ApertureDiameter][(microscope.defaultCondenserApertureIndex || 1) - 1] } } }
<reponame>varconf/varconf-server<gh_stars>10-100 package dao import ( "bytes" "database/sql" "fmt" "strings" "time" "varconf-server/core/dao/common" ) type ConfigData struct { ConfigId int64 `json:"configId" DB_COL:"config_id" DB_PK:"config_id" DB_TABLE:"config"` AppId int64 `json:"appId" DB_COL:"app_id"` Key string `json:"key" DB_COL:"key"` Value string `json:"value" DB_COL:"value"` Desc string `json:"desc" DB_COL:"desc"` Status int `json:"status" DB_COL:"status"` Operate int `json:"operate" DB_COL:"operate"` CreateTime common.JsonTime `json:"createTime" DB_COL:"create_time"` CreateBy string `json:"createBy" DB_COL:"create_by"` UpdateTime common.JsonTime `json:"updateTime" DB_COL:"update_time"` UpdateBy string `json:"updateBy" DB_COL:"update_by"` ReleaseTime *common.JsonTime `json:"releaseTime" DB_COL:"release_time"` ReleaseBy *string `json:"releaseBy" DB_COL:"release_by"` } type QueryConfigData struct { ConfigId int64 AppId int64 Status int Key string LikeKey string Start int64 End int64 } const ( // 1-未发布、2-已发布 STATUS_UN = 1 STATUS_IN = 2 ) const ( // 1-新增、2-更新、3-删除 OPERATE_NEW = 1 OPERATE_UPDATE = 2 OPERATE_DELETE = 3 ) type ConfigDao struct { common.Dao } func NewConfigDao(db *sql.DB) *ConfigDao { configDao := ConfigDao{common.Dao{DB: db}} return &configDao } func (_self *ConfigDao) QueryConfigs(query QueryConfigData) []*ConfigData { sql, values := _self.prepareSelectedQuery(false, query) configs := make([]*ConfigData, 0) success, err := _self.StructSelect(&configs, sql, values...) if err != nil { panic(err) } if success { return configs } return nil } func (_self *ConfigDao) CountConfigs(query QueryConfigData) int64 { sql, values := _self.prepareSelectedQuery(true, query) return _self.Count(sql, values...) } func (_self *ConfigDao) InsertConfig(data *ConfigData) int64 { rowCnt, err := _self.StructInsert(data, false) if err != nil { panic(err) } return rowCnt } func (_self *ConfigDao) SelectedUpdateConfig(data ConfigData) int64 { sql, values := _self.prepareSelectedUpdate(data) rowCnt, err := _self.Exec(sql, values...) if err != nil { panic(err) } return rowCnt } func (_self *ConfigDao) DeleteConfig(appId, configId int64) int64 { sql := "DELETE FROM `config` WHERE `app_id` = ? AND `config_id` = ?" rowCnt, err := _self.Exec(sql, appId, configId) if err != nil { panic(err) } return rowCnt } func (_self *ConfigDao) BatchUpdateConfig(status int, date time.Time, user string, configIds []int64) int64 { values := make([]interface{}, 0) sql := "UPDATE `config` SET `status` = ?, `update_time` = ?, `update_by` = ? WHERE `config_id` in " values = append(values, status) values = append(values, date) values = append(values, user) var ids bytes.Buffer for _, configId := range configIds { ids.WriteString(fmt.Sprintf("%d, ", configId)) } sql = sql + "(" + strings.Trim(ids.String(), ", ") + ")" rowCnt, err := _self.Exec(sql, values...) if err != nil { panic(err) } return rowCnt } func (_self *ConfigDao) BatchDeleteConfig(configIds []int64) int64 { values := make([]interface{}, 0) sql := "DELETE FROM `config` WHERE `config_id` in " var ids bytes.Buffer for _, configId := range configIds { ids.WriteString(fmt.Sprintf("%d, ", configId)) } sql = sql + "(" + strings.Trim(ids.String(), ", ") + ")" rowCnt, err := _self.Exec(sql, values...) if err != nil { panic(err) } return rowCnt } func (_self *ConfigDao) prepareSelectedQuery(count bool, query QueryConfigData) (string, []interface{}) { buffer := bytes.Buffer{} buffer.WriteString("SELECT") if count { buffer.WriteString(" COUNT(1)") } else { buffer.WriteString(" *") } buffer.WriteString(" FROM `config` WHERE 1 = 1") values := make([]interface{}, 0) if query.ConfigId != 0 { buffer.WriteString(" AND `config_id` = ?") values = append(values, query.ConfigId) } if query.AppId != 0 { buffer.WriteString(" AND `app_id` = ?") values = append(values, query.AppId) } if query.Status != 0 { buffer.WriteString(" AND `Status` = ?") values = append(values, query.Status) } if query.Key != "" { buffer.WriteString(" AND `key` = ?") values = append(values, query.Key) } if query.LikeKey != "" { buffer.WriteString(" AND `key` like '" + query.LikeKey + "%'") } if query.Start >= 0 && query.End > 0 { buffer.WriteString(" LIMIT ?, ?") values = append(values, query.Start, query.End) } return buffer.String(), values } func (_self *ConfigDao) prepareSelectedUpdate(data ConfigData) (string, []interface{}) { buffer := bytes.Buffer{} buffer.WriteString("UPDATE `config` SET ") values := make([]interface{}, 0) if data.AppId != 0 { values = append(values, data.AppId) buffer.WriteString("`app_id` = ?,") } if data.Key != "" { values = append(values, data.Key) buffer.WriteString("`key` = ?,") } if data.Value != "" { values = append(values, data.Value) buffer.WriteString("`value` = ?,") } if data.Desc != "" { values = append(values, data.Desc) buffer.WriteString("`desc` = ?,") } if data.Status != 0 { values = append(values, data.Status) buffer.WriteString("`status` = ?,") } if data.Operate != 0 { values = append(values, data.Operate) buffer.WriteString("`operate` = ?,") } if !data.CreateTime.IsZero() { values = append(values, data.CreateTime) buffer.WriteString("`create_time` = ?,") } if data.CreateBy != "" { values = append(values, data.CreateBy) buffer.WriteString("`create_by` = ?,") } if !data.UpdateTime.IsZero() { values = append(values, data.UpdateTime) buffer.WriteString("`update_time` = ?,") } if data.UpdateBy != "" { values = append(values, data.UpdateBy) buffer.WriteString("`update_by` = ?,") } if data.ReleaseTime != nil { values = append(values, data.ReleaseTime) buffer.WriteString("`release_time` = ?,") } if data.ReleaseBy != nil { values = append(values, data.ReleaseBy) buffer.WriteString("`release_by` = ?,") } sql := strings.TrimSuffix(buffer.String(), ",") + " WHERE `config_id` = ?" values = append(values, data.ConfigId) return sql, values }
<reponame>verbit-ai/resque-prioritize<gh_stars>0 # frozen_string_literal: true RSpec.describe Resque::Plugins::Prioritize::Serializer do describe '#serialize' do subject { described_class.serialize(original, **vars) } let(:original) { TestWorker } let(:vars) { {test: 1, lal: 2, lol: :lalka} } it { is_expected.to eq 'TestWorker{{test}:1}{{lal}:2}{{lol}:lalka}' } context 'when vars present' do let(:vars) { {} } it { is_expected.to eq 'TestWorker' } end context 'when original is string' do let(:original) { 'TestWorker_string' } it { is_expected.to eq 'TestWorker_string{{test}:1}{{lal}:2}{{lol}:lalka}' } end context 'when original is nil' do let(:original) {} it { is_expected.to eq '{{test}:1}{{lal}:2}{{lol}:lalka}' } end end describe '#extract' do subject { ->(*var_keys) { described_class.extract(string, *var_keys) } } let(:string) { 'TestWorker{{priority}:10}{{uuid}:123}{{test}:test data}' } its_call { is_expected.to ret(rest: string) } its_call(:lal) { is_expected.to ret(rest: string, lal: nil) } its_call(:uuid) { is_expected.to ret(rest: 'TestWorker{{priority}:10}{{test}:test data}', uuid: '123') } its_call(:uuid, :test, :priority, :lal) { is_expected.to ret( rest: 'TestWorker', priority: '10', test: 'test data', uuid: '123', lal: nil ) } end end
<filename>src/app/components/groups/show/index.ts export * from './show.component';
class AddPlayerIdToActor < ActiveRecord::Migration def change add_reference :actors, :player, index: true end end
import javax.swing.*; public class BarChart { // method to display the barchart public static void drawBarChart(int []data){ // create a frame JFrame frame = new JFrame("Bar Chart"); // set the size of the frame frame.setSize(500,500); // set the visibility of the barchart frame.setVisible(true); // Create a 4-value tuple for each data point int numDataPoints = data.length; int[] xPoints = new int[numDataPoints]; int[] yPoints = new int[numDataPoints]; int[] widths = new int[numDataPoints]; int[] heights = new int[numDataPoints]; // Generate the x- and y-axis coordinates and widths and heights of each bar int x0 = 50; int y0 = 400; int barWidth = 20; for(int i = 0; i < numDataPoints; i++) { xPoints[i] = x0; yPoints[i] = y0 - data[i]; widths[i] = barWidth; heights[i] = data[i]; x0 += barWidth; } // plot barchart JPanel panel = new JPanel() { @Override protected void paintComponent(java.awt.Graphics g) { for(int i=0;i<numDataPoints;i++) g.fillRect(xPoints[i], yPoints[i], widths[i],heights[i]); } }; frame.add(panel); } // Main Method public static void main(String[] args) { // Create a data set int[] data = {2, 8, 5, 9, 14, 6}; // Call the data visualization method drawBarChart(data); } }
# Create cache directory. mkdir -p $XDG_CACHE_HOME/zsh # Set history file. HISTFILE=$XDG_CACHE_HOME/zsh/history # Load Base16 color scheme. source $BASE16_SHELL/base16-$BASE16_THEME-$BASE16_TYPE.sh
#!/bin/sh set -xe command='python3 ./buildtest/buildtest.py' if [[ $1 == '--shell' ]]; then command='bash' fi docker run --rm -it -v $(realpath .):/app -w /app debian:stretch sh -c " apt update && apt install make && make install-build-dependencies && pip3 install -r requirements.txt && $command "
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "os" "github.com/flo80/redirect/pkg/storage" ) //LoadFromFile loads configuration from a file (as json) func mapRedirectorFromFile(configFile string, redirector *storage.MapRedirect) error { file, err := os.Open(configFile) if err != nil { return fmt.Errorf("configuration file %v not found: %v", configFile, err) } decoder := json.NewDecoder(file) err = decoder.Decode(redirector) if err != nil { return fmt.Errorf("could not parse configuration file: %v", err) } log.Printf("decoded configuration file") if err = file.Close(); err != nil { return fmt.Errorf("could not close configuration file: %v ", err) } log.Printf("loaded configuration file %v", configFile) return nil } //SaveMapRedirectorToFile saves configuration to a file (as json) func SaveMapRedirectorToFile(configFile string, redirector *storage.MapRedirect) error { log.Printf("Trying to save config to file: %v", configFile) b, err := json.MarshalIndent(redirector, "", " ") if err != nil { return fmt.Errorf("could not marshall config file: %v", err) } err = ioutil.WriteFile(configFile, b, 0644) if err != nil { return fmt.Errorf("could not write config file: %v", err) } log.Printf("Config file %v written", configFile) return nil }
<filename>StorageStats/Config.h /* * Config.h * * Created on: 07.01.2017 * Author: goldim */ #pragma once #include <boost/property_tree/ptree.hpp> #include <string> class ptree; class Config { public: Config(const std::string &path); ~Config() = default; std::string get(const std::string &key) const; std::string get(const std::string &key, const std::string &defVal) const; std::string get(const std::string &section, const std::string &key, const std::string &defVal) const; void set(const std::string &key, const std::string &value); private: std::string _Path; boost::property_tree::ptree _Tree; };
cat 01_01_rarefied_otus_ed-fromCorrected.fasta ../References.fasta >> OTUs_Ref.fasta mafft OTUs_Ref.fasta > OTUs_Ref.mafft.fasta FastTreeMP -nt -gamma -no2nd -fastest -spr 4 -log fasttree.log -quiet OTUs_Ref.mafft.fasta > OTUs_Ref.mafft.fasttree.newick
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeInclude = void 0; var fs_1 = require("fs"); var path_1 = require("path"); var files_1 = require("./files"); var includeLevel = 0; function makeInclude(factory) { return function (md) { var nextImageRenderer = md.renderer.rules.image; md.renderer.rules.image = function (tokens, idx, options, env, self) { var _a; var token = tokens[idx]; var src = token.attrGet("src"); if (src) { var cwd = env.cwd; var file = src; if (!path_1.isAbsolute(file)) { file = path_1.join(cwd, file); } if (files_1.isFile(file) && file.endsWith(".md")) { if (includeLevel > 10) { throw new Error("Include level too deep"); } var mdSource = fs_1.readFileSync(file); var md_1 = factory(); includeLevel++; var result = md_1.render(mdSource.toString(), {}); includeLevel--; return result; } } return (_a = nextImageRenderer === null || nextImageRenderer === void 0 ? void 0 : nextImageRenderer(tokens, idx, options, env, self)) !== null && _a !== void 0 ? _a : ""; }; }; } exports.makeInclude = makeInclude; //# sourceMappingURL=include.js.map
<gh_stars>1-10 //编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性: // // // 每行的元素从左到右升序排列。 // 每列的元素从上到下升序排列。 // // // // // 示例 1: // // //输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21 //,23,26,30]], target = 5 //输出:true // // // 示例 2: // // //输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21 //,23,26,30]], target = 20 //输出:false // // // // // 提示: // // // m == matrix.length // n == matrix[i].length // 1 <= n, m <= 300 // -10⁹ <= matrix[i][j] <= 10⁹ // 每行的所有元素从左到右升序排列 // 每列的所有元素从上到下升序排列 // -10⁹ <= target <= 10⁹ // // Related Topics 数组 二分查找 分治 矩阵 👍 813 👎 0 package algorithm_200 // 利用原有排序, // 从 matrix[0][n-1] , target 大,则跳到下一行最后一个数; // target 小于该数,则 target 在该行,再遍历; // 遍历行的时候,如果 target < matrix[m][n] ,那 target < matrix[m+1][n] , // 即遍历下一行时,第 n 列及大于 n 列的数都大于 target func searchMatrix(matrix [][]int, target int) bool { var x, y = len(matrix[0]) - 1, 0 for x >= 0 && y < len(matrix) { if matrix[y][x] == target { return true } if matrix[y][x] < target { y++ } else { x-- } } return false }
<filename>src/main/java/org/hiro/things/sticktype/IceBolt.java package org.hiro.things.sticktype; import org.hiro.Global; import org.hiro.StickMethod; import org.hiro.character.Player; import org.hiro.things.Stick; import org.hiro.things.StickEnum; public class IceBolt extends Stick { public IceBolt(){ super(); } @Override public void shake(Player player) { StickMethod.fire_bolt(player.getPosition(), Global.delta, "ice"); Global.ws_info[StickEnum.IceBolt.getValue()].know(); this.use(); } }
export * from './god-stuff'; export * from './error'; export { parsePostgresUrl } from './utils'; //# sourceMappingURL=index.d.ts.map
import random class ParticleSimulator: def __init__(self, x, y): self.x = x self.y = y def move(self, steps): for _ in range(steps): direction = random.choice(['up', 'down', 'left', 'right']) if direction == 'up': self.y += 1 elif direction == 'down': self.y -= 1 elif direction == 'left': self.x -= 1 elif direction == 'right': self.x += 1 def get_position(self): return (self.x, self.y) def simulate_particle_movement(x, y, num_steps): simulator = ParticleSimulator(x, y) positions = [(x, y)] for _ in range(num_steps): simulator.move(1) positions.append(simulator.get_position()) return positions
# test continue within exception handler def f(): lst = [1, 2, 3] for x in lst: print('a', x) try: if x == 2: raise Exception except Exception: continue print('b', x) f()
<filename>www/dungeons/dungeon8.js<gh_stars>1-10 /** * @fileoverview Create dungeon. * @author <EMAIL> (<NAME>) */ /** * Setup calls for dungeon. * @type {ace.Dungeon} */ ace.dungeons = ace.dungeons || {}; var dungeon = new ace.Dungeon('dungeons/dungeon8.png'); ace.dungeons['8'] = dungeon; ace.dungeons['8'].name = 'Dungeon8'; //------------------------------------------------- // Room 0,3 //------------------------------------------------- var room = dungeon.addRoom(0,3); room.exitByFacing['left'] = ace.WALL; room.exitByFacing['right'] = ace.OPEN; room.addActor('BarredDoor',232,616); room.exitByFacing['up'] = ace.OPEN; room.exitByFacing['down'] = ace.WALL; room.addActor('Darknut',56,584); room.addActor('Darknut',88,632); room.addActor('Darknut',88,568); room.addActor('Statue',104,616,{type:'leftcyan'}); room.addActor('SecretKey',136,616); room.addActor('Statue',152,616,{type:'rightcyan'}); room.addActor('Darknut',168,632); room.addActor('Darknut',168,568); room.addActor('Darknut',200,584); //------------------------------------------------- // Room 0,4 //------------------------------------------------- var room = dungeon.addRoom(0,4); room.exitByFacing['left'] = ace.WALL; room.exitByFacing['right'] = ace.BOMBABLE; room.addActor('BombHole',232,792); room.exitByFacing['up'] = ace.WALL; room.exitByFacing['down'] = ace.OPEN; room.addActor('Fire',80,808); room.addActor('OldMan',128,800); room.addActor('Fire',176,808); //------------------------------------------------- // Room 1,0 //------------------------------------------------- var room = dungeon.addRoom(1,0); room.exitByFacing['left'] = ace.WALL; room.exitByFacing['right'] = ace.OPEN; room.exitByFacing['up'] = ace.WALL; room.exitByFacing['down'] = ace.WALL; room.addActor('CaveExit', 3*256+128, 0, {teleportTo: [3475,312,0]}); room.addActor('OldMan', 3*256+128, 90, {'text1': ace.UNDER_CONSTRUCTION_MESSAGE }); room.addActor('Gibdo',296,88); room.addActor('Gibdo',312,120); room.addActor('Bubble',312,56); room.addActor('Bubble',344,104); room.addActor('DarknutBlue',344,72); room.addActor('Gibdo',360,120); room.addActor('Block',360,88,{type:'gray'}); room.addActor('Block',376,104,{type:'gray'}); room.addActor('Block',376,72,{type:'gray'}); room.addActor('Block',392,120,{type:'gray'}); room.addActor('book',392,104); room.addActor('Stairs',392,88); room.addActor('Block',392,56,{type:'gray'}); room.addActor('Block',408,104,{type:'gray'}); room.addActor('Block',408,72,{type:'gray'}); room.addActor('Darknut',424,136); room.addActor('Block',424,88,{type:'gray'}); room.addActor('Darknut',424,40); //------------------------------------------------- // Room 1,2 //------------------------------------------------- var room = dungeon.addRoom(1,2); room.exitByFacing['left'] = ace.WALL; room.exitByFacing['right'] = ace.OPEN; room.exitByFacing['up'] = ace.WALL; room.exitByFacing['down'] = ace.WALL; room.addActor('Statue',296,488,{type:'leftgray'}); room.addActor('Statue',296,392,{type:'leftgray'}); room.addActor('Darknut',344,424); room.addActor('Darknut',376,456); room.addActor('Darknut',376,424); room.addActor('SecretKey',392,440); room.addActor('Statue',472,488,{type:'rightgray'}); room.addActor('Statue',472,392,{type:'rightgray'}); //------------------------------------------------- // Room 1,3 //------------------------------------------------- var room = dungeon.addRoom(1,3); room.exitByFacing['left'] = ace.OPEN; room.addActor('BarredDoor',280,616); room.exitByFacing['right'] = ace.WALL; room.exitByFacing['up'] = ace.BOMBABLE; room.addActor('BombHole',384,680); room.exitByFacing['down'] = ace.WALL; room.addActor('Block',312,648,{type:'gray'}); room.addActor('Block',312,632,{type:'gray'}); room.addActor('Block',312,616,{type:'gray'}); room.addActor('Block',312,600,{type:'gray'}); room.addActor('Block',312,584,{type:'gray'}); room.addActor('Block',328,648,{type:'gray'}); room.addActor('Block',328,584,{type:'gray'}); room.addActor('Block',344,648,{type:'gray'}); room.addActor('PolsVoice',344,600); room.addActor('Block',344,584,{type:'gray'}); room.addActor('PolsVoice',344,568); room.addActor('Block',360,648,{type:'gray'}); room.addActor('Block',360,584,{type:'gray'}); room.addActor('Block',376,648,{type:'gray'}); room.addActor('Block',376,616,{type:'gray'}); room.addActor('Block',376,584,{type:'gray'}); room.addActor('Block',392,648,{type:'gray'}); room.addActor('a',392,632); room.addActor('Block',392,616,{type:'gray'}); room.addActor('Block',392,584,{type:'gray'}); room.addActor('Block',408,648,{type:'gray'}); room.addActor('Stairs',408,632); room.addActor('Block',408,616,{type:'gray'}); room.addActor('Block',408,584,{type:'gray'}); room.addActor('Block',424,648,{type:'gray'}); room.addActor('Block',424,632,{type:'gray'}); room.addActor('Block',424,616,{type:'gray'}); room.addActor('PolsVoice',424,600); room.addActor('Block',424,584,{type:'gray'}); room.addActor('PolsVoice',424,568); room.addActor('Block',440,584,{type:'gray'}); room.addActor('Block',456,664,{type:'gray'}); room.addActor('Block',456,648,{type:'gray'}); room.addActor('Block',456,632,{type:'gray'}); room.addActor('Block',456,616,{type:'gray'}); room.addActor('Block',456,600,{type:'gray'}); room.addActor('Block',456,584,{type:'gray'}); room.addActor('SecretKey',472,664); //------------------------------------------------- // Room 1,4 //------------------------------------------------- var room = dungeon.addRoom(1,4); room.exitByFacing['left'] = ace.BOMBABLE; room.addActor('BombHole',280,792); room.exitByFacing['right'] = ace.WALL; room.exitByFacing['up'] = ace.OPEN; room.addActor('BarredDoor',384,856); room.exitByFacing['down'] = ace.BOMBABLE; room.addActor('BombHole',384,728); room.addActor('Block',296,840,{type:'gray'}); room.addActor('Block',296,824,{type:'gray'}); room.addActor('Block',296,808,{type:'gray'}); room.addActor('SecretHeartContainer',296,744); room.addActor('Block',312,840,{type:'gray'}); room.addActor('Block',312,824,{type:'gray'}); room.addActor('Block',312,808,{type:'gray'}); room.addActor('Block',328,840,{type:'gray'}); room.addActor('Block',328,824,{type:'gray'}); room.addActor('Block',328,760,{type:'gray'}); room.addActor('Block',344,840,{type:'gray'}); room.addActor('Block',344,824,{type:'gray'}); room.addActor('Block',360,840,{type:'gray'}); room.addActor('Gleeok',384,824); room.addActor('Block',408,840,{type:'gray'}); room.addActor('Block',424,840,{type:'gray'}); room.addActor('Block',424,824,{type:'gray'}); room.addActor('Block',440,840,{type:'gray'}); room.addActor('Block',440,824,{type:'gray'}); room.addActor('Block',440,760,{type:'gray'}); room.addActor('Block',456,840,{type:'gray'}); room.addActor('Block',456,824,{type:'gray'}); room.addActor('Block',456,808,{type:'gray'}); room.addActor('Block',472,840,{type:'gray'}); room.addActor('Block',472,824,{type:'gray'}); room.addActor('Block',472,808,{type:'gray'}); //------------------------------------------------- // Room 1,5 //------------------------------------------------- var room = dungeon.addRoom(1,5); room.exitByFacing['left'] = ace.WALL; room.exitByFacing['right'] = ace.WALL; room.exitByFacing['up'] = ace.WALL; room.exitByFacing['down'] = ace.OPEN; room.addActor('Block',312,1000,{type:'gray'}); room.addActor('Block',312,984,{type:'gray'}); room.addActor('Block',312,968,{type:'gray'}); room.addActor('Block',312,952,{type:'gray'}); room.addActor('Block',312,936,{type:'gray'}); room.addActor('Block',328,1000,{type:'gray'}); room.addActor('Block',328,936,{type:'gray'}); room.addActor('Block',344,1000,{type:'gray'}); room.addActor('Statue',344,968,{type:'leftgray'}); room.addActor('Block',344,936,{type:'gray'}); room.addActor('Block',360,1000,{type:'gray'}); room.addActor('Statue',360,984,{type:'leftgray'}); room.addActor('Block',360,936,{type:'gray'}); room.addActor('Block',376,1000,{type:'gray'}); room.addActor('TriforcePiece',384,960); room.addActor('Block',392,1000,{type:'gray'}); room.addActor('Block',408,1000,{type:'gray'}); room.addActor('Statue',408,984,{type:'rightgray'}); room.addActor('Block',408,936,{type:'gray'}); room.addActor('Block',424,1000,{type:'gray'}); room.addActor('Statue',424,968,{type:'rightgray'}); room.addActor('Block',424,936,{type:'gray'}); room.addActor('Block',440,1000,{type:'gray'}); room.addActor('Block',440,936,{type:'gray'}); room.addActor('Block',456,1000,{type:'gray'}); room.addActor('Block',456,984,{type:'gray'}); room.addActor('Block',456,968,{type:'gray'}); room.addActor('Block',456,952,{type:'gray'}); room.addActor('Block',456,936,{type:'gray'}); //------------------------------------------------- // Room 2,0 //------------------------------------------------- var room = dungeon.addRoom(2,0); room.exitByFacing['left'] = ace.OPEN; room.addActor('BarredDoor',536,88); room.exitByFacing['right'] = ace.OPEN; room.exitByFacing['up'] = ace.WALL; room.exitByFacing['down'] = ace.WALL; room.addActor('CaveExit', 3*256+128, 0, {teleportTo: [3475,312,0]}); room.addActor('Statue',616,88,{type:'leftcyan'}); room.addActor('Manhandla',632,120); room.addActor('SecretRupee',648,88); room.addActor('Patra',664,104); room.addActor('Statue',664,88,{type:'rightcyan'}); //------------------------------------------------- // Room 2,2 //------------------------------------------------- var room = dungeon.addRoom(2,2); room.exitByFacing['left'] = ace.OPEN; room.exitByFacing['right'] = ace.OPEN; room.exitByFacing['up'] = ace.OPEN; room.exitByFacing['down'] = ace.WALL; room.addActor('PolsVoice',552,440); room.addActor('Block',552,392,{type:'gray'}); room.addActor('Block',568,472,{type:'gray'}); room.addActor('Block',568,408,{type:'gray'}); room.addActor('Block',584,488,{type:'gray'}); room.addActor('Block',584,424,{type:'gray'}); room.addActor('Gibdo',600,456); room.addActor('Block',600,440,{type:'gray'}); room.addActor('Gibdo',600,424); room.addActor('Block',616,456,{type:'gray'}); room.addActor('Block',632,472,{type:'gray'}); room.addActor('Keese',632,456); room.addActor('Keese',632,424); room.addActor('SecretKey',648,440); room.addActor('Block',648,408,{type:'gray'}); room.addActor('Block',664,424,{type:'gray'}); room.addActor('PolsVoice',680,488); room.addActor('Block',680,440,{type:'gray'}); room.addActor('Block',696,456,{type:'gray'}); room.addActor('Block',696,392,{type:'gray'}); room.addActor('Block',712,472,{type:'gray'}); room.addActor('Block',712,408,{type:'gray'}); room.addActor('Block',728,488,{type:'gray'}); //------------------------------------------------- // Room 2,3 //------------------------------------------------- var room = dungeon.addRoom(2,3); room.exitByFacing['left'] = ace.WALL; room.exitByFacing['right'] = ace.OPEN; room.addActor('LockedDoor',744,616); room.exitByFacing['up'] = ace.OPEN; room.addActor('BarredDoor',640,680); room.exitByFacing['down'] = ace.OPEN; room.addActor('Gohma',656,648); //------------------------------------------------- // Room 2,4 //------------------------------------------------- var room = dungeon.addRoom(2,4); room.exitByFacing['left'] = ace.WALL; room.exitByFacing['right'] = ace.WALL; room.exitByFacing['up'] = ace.WALL; room.exitByFacing['down'] = ace.OPEN; room.addActor('Fire',592,808); room.addActor('OldMan',640,800); room.addActor('OldMan',656,816); room.addActor('Fire',688,808); room.addActor('OldMan',704,816); //------------------------------------------------- // Room 2,5 //------------------------------------------------- var room = dungeon.addRoom(2,5); room.exitByFacing['left'] = ace.WALL; room.exitByFacing['right'] = ace.BOMBABLE; room.addActor('BombHole',744,968); room.exitByFacing['up'] = ace.OPEN; room.exitByFacing['down'] = ace.WALL; room.addActor('Rupee',616,968); room.addActor('Rupee',632,1000,{xOffset:8}); room.addActor('Rupee',632,984); room.addActor('Rupee',632,968); room.addActor('Rupee',632,952); room.addActor('Rupee',632,936,{xOffset:8}); room.addActor('Rupee',648,984); room.addActor('Rupee',648,968); room.addActor('Rupee',648,952); room.addActor('Rupee',664,968); //------------------------------------------------- // Room 2,6 //------------------------------------------------- var room = dungeon.addRoom(2,6); room.exitByFacing['left'] = ace.WALL; room.exitByFacing['right'] = ace.BOMBABLE; room.addActor('BombHole',744,1144); room.exitByFacing['up'] = ace.WALL; room.exitByFacing['down'] = ace.OPEN; room.addActor('Block',552,1096,{type:'gray'}); room.addActor('Block',568,1176,{type:'gray'}); room.addActor('Block',568,1112,{type:'gray'}); room.addActor('Block',584,1192,{type:'gray'}); room.addActor('Block',584,1128,{type:'gray'}); room.addActor('Block',600,1144,{type:'gray'}); room.addActor('PolsVoice',616,1176); room.addActor('Block',616,1160,{type:'gray'}); room.addActor('Block',632,1176,{type:'gray'}); room.addActor('PolsVoice',632,1144); room.addActor('SecretBomb',648,1144); room.addActor('Block',648,1112,{type:'gray'}); room.addActor('Block',664,1128,{type:'gray'}); room.addActor('PolsVoice',664,1112); room.addActor('PolsVoice',680,1176); room.addActor('Block',680,1144,{type:'gray'}); room.addActor('PolsVoice',680,1128); room.addActor('Block',696,1160,{type:'gray'}); room.addActor('Block',696,1096,{type:'gray'}); room.addActor('Block',712,1176,{type:'gray'}); room.addActor('Block',712,1112,{type:'gray'}); room.addActor('Block',728,1192,{type:'gray'}); //------------------------------------------------- // Room 3,0 //------------------------------------------------- var room = dungeon.addRoom(3,0); room.exitByFacing['left'] = ace.OPEN; room.exitByFacing['right'] = ace.OPEN; room.exitByFacing['up'] = ace.OPEN; room.exitByFacing['down'] = ace.OPEN; room.addActor('OldMan', 3*256+128, 90, {'text1': ace.UNDER_CONSTRUCTION_MESSAGE }); room.addActor('CaveExit', 3*256+128, 0, {teleportTo: [3475,312,0]}); room.addActor('Statue',824,120,{type:'leftcyan'}); room.addActor('Statue',824,88,{type:'leftcyan'}); room.addActor('Statue',824,56,{type:'leftcyan'}); room.addActor('Statue',872,120,{type:'leftcyan'}); room.addActor('Statue',872,88,{type:'leftcyan'}); room.addActor('Statue',872,56,{type:'leftcyan'}); room.addActor('Statue',920,120,{type:'rightcyan'}); room.addActor('Statue',920,88,{type:'rightcyan'}); room.addActor('Statue',920,56,{type:'rightcyan'}); room.addActor('Statue',968,120,{type:'rightcyan'}); room.addActor('Statue',968,88,{type:'rightcyan'}); room.addActor('Statue',968,56,{type:'rightcyan'}); //------------------------------------------------- // Room 3,1 //------------------------------------------------- var room = dungeon.addRoom(3,1); room.exitByFacing['left'] = ace.WALL; room.exitByFacing['right'] = ace.WALL; room.exitByFacing['up'] = ace.BOMBABLE; room.addActor('BombHole',896,328); room.exitByFacing['down'] = ace.OPEN; room.addActor('SecretRupee',904,264); room.addActor('Manhandla',936,280); room.addActor('Patra',968,264); //------------------------------------------------- // Room 3,2 //------------------------------------------------- var room = dungeon.addRoom(3,2); room.exitByFacing['left'] = ace.OPEN; room.addActor('BarredDoor',792,440); room.exitByFacing['right'] = ace.OPEN; room.addActor('LockedDoor',1000,440); room.exitByFacing['up'] = ace.OPEN; room.addActor('BarredDoor',896,504); room.exitByFacing['down'] = ace.BOMBABLE; room.addActor('BombHole',896,376); room.addActor('Statue',808,488,{type:'leftcyan'}); room.addActor('Statue',808,392,{type:'leftcyan'}); room.addActor('DarknutBlue',888,440); room.addActor('SecretKey',904,440); room.addActor('DarknutBlue',920,456); room.addActor('DarknutBlue',936,488); room.addActor('DarknutBlue',936,424); room.addActor('DarknutBlue',968,472); room.addActor('Statue',984,488,{type:'rightcyan'}); room.addActor('Statue',984,392,{type:'rightcyan'}); //------------------------------------------------- // Room 3,3 //------------------------------------------------- var room = dungeon.addRoom(3,3); room.exitByFacing['left'] = ace.OPEN; room.addActor('LockedDoor',792,616); room.exitByFacing['right'] = ace.WALL; room.exitByFacing['up'] = ace.OPEN; room.addActor('LockedDoor',896,680); room.exitByFacing['down'] = ace.OPEN; room.addActor('Gibdo',824,648); room.addActor('Gibdo',856,664); room.addActor('Gibdo',856,600); room.addActor('Bubble',888,616); room.addActor('SecretRupee',904,616); room.addActor('Bubble',920,632); room.addActor('DarknutBlue',936,664); room.addActor('Darknut',936,600); room.addActor('Darknut',968,648); //------------------------------------------------- // Room 3,4 //------------------------------------------------- var room = dungeon.addRoom(3,4); room.exitByFacing['left'] = ace.WALL; room.exitByFacing['right'] = ace.OPEN; room.addActor('BarredDoor',1000,792); room.exitByFacing['up'] = ace.BOMBABLE; room.addActor('BombHole',896,856); room.exitByFacing['down'] = ace.OPEN; room.addActor('LockedDoor',896,728); room.addActor('DarknutBlue',824,824); room.addActor('Statue',872,792,{type:'leftcyan'}); room.addActor('DarknutBlue',920,808); room.addActor('Statue',920,792,{type:'rightcyan'}); room.addActor('DarknutBlue',936,840); room.addActor('DarknutBlue',936,776); room.addActor('DarknutBlue',968,824); //------------------------------------------------- // Room 3,5 //------------------------------------------------- var room = dungeon.addRoom(3,5); room.exitByFacing['left'] = ace.BOMBABLE; room.addActor('BombHole',792,968); room.exitByFacing['right'] = ace.WALL; room.exitByFacing['up'] = ace.OPEN; room.addActor('LockedDoor',896,1032); room.exitByFacing['down'] = ace.BOMBABLE; room.addActor('BombHole',896,904); room.addActor('SecretMap',904,968); room.addActor('Manhandla',936,984); //------------------------------------------------- // Room 3,6 //------------------------------------------------- var room = dungeon.addRoom(3,6); room.exitByFacing['left'] = ace.BOMBABLE; room.addActor('BombHole',792,1144); room.exitByFacing['right'] = ace.OPEN; room.addActor('BarredDoor',1000,1144); room.exitByFacing['up'] = ace.OPEN; room.addActor('BarredDoor',896,1208); room.exitByFacing['down'] = ace.OPEN; room.addActor('LockedDoor',896,1080); room.addActor('Statue',808,1192,{type:'leftcyan'}); room.addActor('Statue',808,1096,{type:'leftcyan'}); room.addActor('Gohma',896,1176); room.addActor('Statue',984,1192,{type:'rightcyan'}); room.addActor('Statue',984,1096,{type:'rightcyan'}); //------------------------------------------------- // Room 3,7 //------------------------------------------------- var room = dungeon.addRoom(3,7); room.exitByFacing['left'] = ace.WALL; room.exitByFacing['right'] = ace.WALL; room.exitByFacing['up'] = ace.WALL; room.exitByFacing['down'] = ace.OPEN; room.addActor('BarredDoor',896,1256); room.addActor('Darknut',824,1352); room.addActor('Darknut',856,1368); room.addActor('Darknut',856,1304); room.addActor('SecretBomb',904,1320); room.addActor('Darknut',936,1304); room.addActor('Darknut',968,1352); //------------------------------------------------- // Room 4,0 //------------------------------------------------- var room = dungeon.addRoom(4,0); room.exitByFacing['left'] = ace.OPEN; room.exitByFacing['right'] = ace.WALL; room.exitByFacing['up'] = ace.WALL; room.exitByFacing['down'] = ace.WALL; room.addActor('CaveExit', 3*256+128, 0, {teleportTo: [3475,312,0]}); room.addActor('Water',1064,136); room.addActor('Water',1064,120); room.addActor('Water',1064,104); room.addActor('Water',1064,72); room.addActor('Water',1064,56); room.addActor('Water',1064,40); room.addActor('Water',1080,136); room.addActor('Water',1080,40); room.addActor('Water',1096,136); room.addActor('Water',1096,104); room.addActor('Water',1096,88); room.addActor('Water',1096,72); room.addActor('Water',1096,40); room.addActor('Water',1112,136); room.addActor('Water',1112,104); room.addActor('Water',1112,72); room.addActor('Water',1112,40); room.addActor('Water',1128,136); room.addActor('Water',1128,120); room.addActor('Water',1128,104); room.addActor('Water',1128,72); room.addActor('Water',1128,56); room.addActor('Water',1128,40); room.addActor('Water',1144,120); room.addActor('Keese',1144,72); room.addActor('Water',1144,56); room.addActor('Water',1160,120); room.addActor('Bubble',1160,104); room.addActor('SecretKey',1160,88); room.addActor('Zol',1160,72); room.addActor('Water',1160,56); room.addActor('Water',1176,136); room.addActor('Water',1176,120); room.addActor('Water',1176,104); room.addActor('Water',1176,72); room.addActor('Water',1176,56); room.addActor('Water',1176,40); room.addActor('Water',1192,136); room.addActor('Water',1192,104); room.addActor('Water',1192,72); room.addActor('Water',1192,40); room.addActor('Water',1208,136); room.addActor('Water',1208,104); room.addActor('Water',1208,88); room.addActor('Water',1208,72); room.addActor('Water',1208,40); room.addActor('WaterAndKeese',1224,136); room.addActor('Zol',1224,120); room.addActor('Bubble',1224,56); room.addActor('Water',1224,40); room.addActor('Water',1240,136); room.addActor('Water',1240,120); room.addActor('WaterAndKeese',1240,104); room.addActor('Bubble',1240,88); room.addActor('Water',1240,72); room.addActor('Water',1240,56); room.addActor('Water',1240,40); //------------------------------------------------- // Room 4,2 //------------------------------------------------- var room = dungeon.addRoom(4,2); room.exitByFacing['left'] = ace.OPEN; room.addActor('LockedDoor',1048,440); room.exitByFacing['right'] = ace.WALL; room.exitByFacing['up'] = ace.WALL; room.exitByFacing['down'] = ace.WALL; room.addActor('Water',1064,456); room.addActor('Water',1080,456); room.addActor('Water',1096,456); room.addActor('PolsVoice',1112,488); room.addActor('Water',1112,456); room.addActor('PolsVoice',1112,392); room.addActor('Water',1128,456); room.addActor('Water',1144,456); room.addActor('Water',1160,456); room.addActor('Compass',1160,440); room.addActor('PolsVoice',1160,424); room.addActor('Water',1176,456); room.addActor('Water',1192,456); room.addActor('PolsVoice',1192,424); room.addActor('Water',1208,456); room.addActor('PolsVoice',1224,472); room.addActor('Water',1224,456); room.addActor('PolsVoice',1224,408); room.addActor('Water',1240,456); room.addActor('PolsVoice',1240,440); //------------------------------------------------- // Room 4,4 //------------------------------------------------- var room = dungeon.addRoom(4,4); room.exitByFacing['left'] = ace.OPEN; room.addActor('BarredDoor',1048,792); room.exitByFacing['right'] = ace.WALL; room.exitByFacing['up'] = ace.WALL; room.exitByFacing['down'] = ace.WALL; room.addActor('Darknut',1112,840); room.addActor('Darknut',1112,744); room.addActor('Gibdo',1160,808); room.addActor('SecretBomb',1160,792); room.addActor('Gibdo',1160,776); room.addActor('Block',1192,840,{type:'gray'}); room.addActor('Block',1192,824,{type:'gray'}); room.addActor('Gibdo',1192,808); room.addActor('Bubble',1192,776); room.addActor('Block',1192,760,{type:'gray'}); room.addActor('Block',1192,744,{type:'gray'}); room.addActor('Block',1208,840,{type:'gray'}); room.addActor('Block',1208,824,{type:'gray'}); room.addActor('Block',1208,808,{type:'gray'}); room.addActor('DarknutBlue',1208,792); room.addActor('Block',1208,776,{type:'gray'}); room.addActor('Block',1208,760,{type:'gray'}); room.addActor('Block',1208,744,{type:'gray'}); room.addActor('Block',1224,840,{type:'gray'}); room.addActor('Block',1224,824,{type:'gray'}); room.addActor('Block',1224,808,{type:'gray'}); room.addActor('a',1224,792); room.addActor('Block',1224,776,{type:'gray'}); room.addActor('Block',1224,760,{type:'gray'}); room.addActor('Block',1224,744,{type:'gray'}); room.addActor('Block',1240,840,{type:'gray'}); room.addActor('Block',1240,824,{type:'gray'}); room.addActor('Block',1240,808,{type:'gray'}); room.addActor('Stairs',1240,792); room.addActor('Block',1240,776,{type:'gray'}); room.addActor('Block',1240,760,{type:'gray'}); room.addActor('Block',1240,744,{type:'gray'}); //------------------------------------------------- // Room 4,6 //------------------------------------------------- var room = dungeon.addRoom(4,6); room.exitByFacing['left'] = ace.OPEN; room.exitByFacing['right'] = ace.WALL; room.exitByFacing['up'] = ace.WALL; room.exitByFacing['down'] = ace.WALL; room.addActor('Darknut',1112,1192); room.addActor('DarknutBlue',1112,1096); room.addActor('Block',1128,1144,{type:'gray'}); room.addActor('Block',1144,1160,{type:'gray'}); room.addActor('Block',1144,1128,{type:'gray'}); room.addActor('Block',1160,1176,{type:'gray'}); room.addActor('Darknut',1160,1160); room.addActor('Stairs',1160,1144); room.addActor('PolsVoice',1160,1128); room.addActor('Block',1160,1112,{type:'gray'}); room.addActor('Block',1176,1160,{type:'gray'}); room.addActor('Block',1176,1128,{type:'gray'}); room.addActor('Block',1192,1144,{type:'gray'}); room.addActor('PolsVoice',1224,1112); room.addActor('DarknutBlue',1240,1144);
export PYTHONPATH=$PYTHONPATH:`pwd` # export CUDA_LAUNCH_BLOCKING=1 # for debug CUDA_VISIBLE_DEVICES=0 python3 demo/demo.py --config-file configs/InstanceSegmentation/pointrend_rcnn_R_50_FPN_1x_coco.yaml \ --input '/cluster/work/cvl/leikel/hr_bound_project/detectron2-exp8-detach-semantic-light-details-nop1-postconv/sel_coco_images/*.jpg' \ --output 'result_vis_pointrend_coco_selnew/' \ --opts MODEL.WEIGHTS ./model_final_736f5a.pkl #--opts MODEL.WEIGHTS ./output/bmask_rcnn_r50_2x_cityscapes_post/model_final.pth
<reponame>rayyildiz/gocql // +build appengine package murmur import "encoding/binary" func getBlock(data []byte, n int) (int64, int64) { k1 := binary.LittleEndian.Uint64(data[n*16:]) k2 := binary.LittleEndian.Uint64(data[(n*16)+8:]) return int64(k1), int64(k2) }
<reponame>yunfeiyang1916/micro-go-course package transport import ( "context" "encoding/json" "errors" "net/http" "os" "github.com/go-kit/kit/log" "github.com/go-kit/kit/transport" kithttp "github.com/go-kit/kit/transport/http" "github.com/gorilla/mux" "github.com/yunfeiyang1916/micro-go-course/hystrix/goods/endpoint" ) var ( ErrorBadRequest = errors.New("invalid request parameter") ) // MakeHttpHandler make http handler use mux func MakeHttpHandler(ctx context.Context, endpoints *endpoint.GoodsEndpoints) http.Handler { r := mux.NewRouter() kitLog := log.NewLogfmtLogger(os.Stderr) kitLog = log.With(kitLog, "ts", log.DefaultTimestampUTC) kitLog = log.With(kitLog, "caller", log.DefaultCaller) options := []kithttp.ServerOption{ kithttp.ServerErrorHandler(transport.NewLogErrorHandler(kitLog)), kithttp.ServerErrorEncoder(encodeError), } r.Methods("GET").Path("/goods/detail").Handler(kithttp.NewServer( endpoints.GoodsDetailEndpoint, decodeGoodsDetailRequest, encodeJSONResponse, options..., )) return r } func decodeGoodsDetailRequest(ctx context.Context, r *http.Request) (interface{}, error) { id := r.URL.Query().Get("id") if id == "" { return nil, ErrorBadRequest } return endpoint.GoodsDetailRequest{ Id: id, }, nil } func encodeJSONResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { w.Header().Set("Content-Type", "application/json;charset=utf-8") return json.NewEncoder(w).Encode(response) } func encodeError(_ context.Context, err error, w http.ResponseWriter) { w.Header().Set("Content-Type", "application/json; charset=utf-8") switch err { default: w.WriteHeader(http.StatusInternalServerError) } json.NewEncoder(w).Encode(map[string]interface{}{ "error": err.Error(), }) }
import pandas as pd country_data = [ ["Afghanistan", "Kabul"], ["Albania", "Tirana"], ["Algeria", "Algiers"], ["Andorra", "Andorra la Vella"], ["Angola", "Luanda"], ["Antigua and Barbuda", "St. John's"], ["Argentina", "Buenos Aires"], ["Armenia", "Yerevan"], ["Australia", "Canberra"], ["Austria", "Vienna"] ] df = pd.DataFrame(country_data, columns=["Country", "Capital"]) print(df)
<reponame>Morning-Train/FormData<gh_stars>0 const gulp = require("gulp"), babel = require("gulp-babel"); gulp.task("default", ["build"], () => { }); /* ------------------------------- Build with babel ------------------------------- */ gulp.task("build", () => { return gulp.src("./FormData.js") .pipe(babel()) .pipe(gulp.dest("./build")); });
# Generated by Django 3.0.8 on 2020-08-28 20:58 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('definitions', '0014_auto_20200826_0159'), ('definitions', '0014_auto_20200828_2056'), ] operations = [ ]
#!/bin/bash -ex dart example/main.dart dartanalyzer --fatal-hints . pub run test pub run dependency_validator --ignore=functional_data_generator,sum_types_generator,test_coverage dev/format_dart_code.sh --set-exit-if-changed pub publish --dry-run
function convertStringToCamelCase(str) { let result = str[0].toUpperCase() + str.substring(1); for (let i = 0; i < result.length; i++) { if (result[i] === " ") { result = result.substring(0, i) + result[i + 1].toUpperCase() + result.substring(i + 2); } } return result; }
/** * split a string by a provided delimiter (none '' by default) and skip first n-delimiters */ import util from '../util/index' function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } function split(input, delimiter, skip) { let _regexp, _matches, _splitted, _temp; if (util.isUndefined(input) || !util.isString(input)) { return null; } if (util.isUndefined(delimiter)) delimiter = ''; if (isNaN(skip)) skip = 0; _regexp = new RegExp(escapeRegExp(delimiter), 'g'); _matches = input.match(_regexp); if (util.isNull(_matches) || skip >= _matches.length) { return [input]; } if (skip === 0) return input.split(delimiter); _splitted = input.split(delimiter); _temp = _splitted.splice(0, skip + 1); _splitted.unshift(_temp.join(delimiter)); return _splitted; } export default split
#!/bin/bash # testing before publish #npm run lint && npm run build && npm run test && npm run typescript-test if [ $? = 0 ]; then # purge dist rm -fr dist # babel transform es6 into es5 babel src --out-dir dist/npm/es5/src --copy-files babel libs --out-dir dist/npm/es5/libs --copy-files babel build/npm/index.js --out-file dist/npm/es5/index.js export BABEL_ENV=production babel src --out-dir dist/npm/es6/src --copy-files babel libs --out-dir dist/npm/es6/libs --copy-files # keep es6 for next.js cp build/npm/next.js next.js else echo 'Code cant be verify, plz check ~' fi
<gh_stars>1-10 # frozen_string_literal: true module ApplicationHelper def page_title @page_title ||= 'haiafara.ro' end end
#!/usr/bin/env bash set -o posix ## This command starts the release in the foreground, i.e. ## standard out is routed to the current terminal session. set -e set -m if [ ! -z "$RELEASE_READ_ONLY" ]; then fail "Cannot start a release with RELEASE_READ_ONLY set!" fi require_cookie [ -f "$REL_DIR/$REL_NAME.boot" ] && BOOTFILE="$REL_NAME" || BOOTFILE=start FOREGROUNDOPTIONS="-noshell -noinput +Bd" # Setup beam-required vars PROGNAME="${0#*/}" export PROGNAME # Store passed arguments since they will be erased by `set` ARGS="$*" # Start the VM, executing pre and post start hooks run_hooks pre_start # Build an array of arguments to pass to exec later on # Build it here because this command will be used for logging. set -- "$BINDIR/erlexec" $FOREGROUNDOPTIONS \ -boot "$REL_DIR/$BOOTFILE" \ -boot_var ERTS_LIB_DIR "$ERTS_LIB_DIR" \ -env ERL_LIBS "$REL_LIB_DIR" \ -pa "$CONSOLIDATED_DIR" \ -args_file "$VMARGS_PATH" \ -config "$SYS_CONFIG_PATH" \ -mode "$CODE_LOADING_MODE" \ ${ERL_OPTS} \ -extra ${EXTRA_OPTS} # Dump environment info for logging purposes if [ ! -z "$VERBOSE" ]; then echo "Exec: $*" -- "${1+$ARGS}" echo "Root: $ROOTDIR" fi; post_start_fg() { sleep 2 run_hooks post_start } if [ ! -z "$OTP_VER" ] && [ "$OTP_VER" -ge 20 ]; then post_start_fg & exec "$@" -- "${1+$ARGS}" else "$@" -- "${1+$ARGS}" & __bg_pid=$! run_hooks post_start wait $__bg_pid __exit_code=$? run_hooks post_stop exit $__exit_code fi
#!/bin/bash echo 'cocos2d-x template installer' COCOS2D_VER='cocos2d-2.0-rc2-x-2.0.1' BASE_TEMPLATE_DIR="/Library/Application Support/Developer/Shared/Xcode" BASE_TEMPLATE_USER_DIR="$HOME/Library/Application Support/Developer/Shared/Xcode" force= user_dir= usage(){ cat << EOF usage: $0 [options] Install / update templates for ${COCOS2D_VER} OPTIONS: -f force overwrite if directories exist -h this help -u install in user's Library directory instead of global directory EOF } while getopts "fhu" OPTION; do case "$OPTION" in f) force=1 ;; h) usage exit 0 ;; u) user_dir=1 ;; esac done # Make sure only root can run our script if [[ ! $user_dir && "$(id -u)" != "0" ]]; then echo "" echo "Error: This script must be run as root in order to copy templates to ${BASE_TEMPLATE_DIR}" 1>&2 echo "" echo "Try running it with 'sudo', or with '-u' to install it only you:" 1>&2 echo " sudo $0" 1>&2 echo "or:" 1>&2 echo " $0 -u" 1>&2 exit 1 fi # Make sure root and user_dir is not executed at the same time if [[ $user_dir && "$(id -u)" == "0" ]]; then echo "" echo "Error: Do not run this script as root with the '-u' option." 1>&2 echo "" echo "Either use the '-u' option or run it as root, but not both options at the same time." 1>&2 echo "" echo "RECOMMENDED WAY:" 1>&2 echo " $0 -u -f" 1>&2 echo "" exit 1 fi copy_files(){ # SRC_DIR="${SCRIPT_DIR}/${1}" rsync -r --exclude=.svn "$1" "$2" } check_dst_dir(){ if [[ -d $DST_DIR ]]; then if [[ $force ]]; then echo "removing old libraries: ${DST_DIR}" rm -rf "${DST_DIR}" else echo "templates already installed. To force a re-install use the '-f' parameter" exit 1 fi fi echo ...creating destination directory: $DST_DIR mkdir -p "$DST_DIR" } # copy_base_mac_files(){ # echo ...copying cocos2dx files # copy_files cocos2dx "$LIBS_DIR" # echo ...copying CocosDenshion files # copy_files CocosDenshion "$LIBS_DIR" # } copy_base_files(){ echo ...copying cocos2dx files copy_files cocos2dx "$LIBS_DIR" echo ...copying CocosDenshion files copy_files CocosDenshion "$LIBS_DIR" } copy_cocos2d_files(){ echo ...copying cocos2d files copy_files cocos2dx "$LIBS_DIR" copy_files licenses/LICENSE_cocos2d-x.txt "$LIBS_DIR" } copy_cocosdenshion_files(){ echo ...copying CocosDenshion files copy_files CocosDenshion "$LIBS_DIR" # copy_files licenses/LICENSE_CocosDenshion.txt "$LIBS_DIR" } copy_extensions_files(){ echo ...copying extension files copy_files extensions "$LIBS_DIR" } # copy_cocosdenshionextras_files(){ # echo ...copying CocosDenshionExtras files # copy_files CocosDenshion/CocosDenshionExtras "$LIBS_DIR" # } # copy_fontlabel_files(){ # echo ...copying FontLabel files # copy_files external/FontLabel "$LIBS_DIR" # copy_files licenses/LICENSE_FontLabel.txt "$LIBS_DIR" # } # copy_cocoslive_files(){ # echo ...copying cocoslive files # copy_files cocoslive "$LIBS_DIR" # echo ...copying TouchJSON files # copy_files external/TouchJSON "$LIBS_DIR" # copy_files licenses/LICENSE_TouchJSON.txt "$LIBS_DIR" # } print_template_banner(){ echo '' echo '' echo '' echo "$1" echo '----------------------------------------------------' echo '' } # Xcode4 templates copy_xcode4_project_templates(){ TEMPLATE_DIR="$HOME/Library/Developer/Xcode/Templates/cocos2d-x/" print_template_banner "Installing Xcode 4 cocos2d-x iOS template" DST_DIR="$TEMPLATE_DIR" check_dst_dir LIBS_DIR="$DST_DIR""lib_cocos2dx.xctemplate/libs/" mkdir -p "$LIBS_DIR" copy_cocos2d_files LIBS_DIR="$DST_DIR""lib_cocosdenshion.xctemplate/libs/" mkdir -p "$LIBS_DIR" copy_cocosdenshion_files LIBS_DIR="$DST_DIR""lib_extensions.xctemplate/libs/" mkdir -p "$LIBS_DIR" copy_extensions_files echo ...copying template files copy_files template/xcode4/ "$DST_DIR" echo done! print_template_banner "Installing Xcode 4 Chipmunk iOS template" LIBS_DIR="$DST_DIR""lib_chipmunk.xctemplate/libs/" mkdir -p "$LIBS_DIR" echo ...copying Chipmunk files copy_files external/chipmunk "$LIBS_DIR" copy_files licenses/LICENSE_chipmunk.txt "$LIBS_DIR" echo done! print_template_banner "Installing Xcode 4 Box2d iOS template" LIBS_DIR="$DST_DIR""lib_box2d.xctemplate/libs/" mkdir -p "$LIBS_DIR" echo ...copying Box2D files copy_files external/Box2D "$LIBS_DIR" copy_files licenses/LICENSE_box2d.txt "$LIBS_DIR" echo done! print_template_banner "Installing Xcode 4 lua iOS template" LIBS_DIR="$DST_DIR""lib_lua.xctemplate/libs/" mkdir -p "$LIBS_DIR" echo ...copying lua files copy_files scripting/lua "$LIBS_DIR" copy_files licenses/LICENSE_lua.txt "$LIBS_DIR" copy_files licenses/LICENSE_tolua++.txt "$LIBS_DIR" echo done! print_template_banner "Installing Xcode 4 JS iOS template" LIBS_DIR="$DST_DIR""lib_js.xctemplate/libs/javascript" mkdir -p "$LIBS_DIR" echo ...copying js files copy_files scripting/javascript/bindings "$LIBS_DIR" copy_files licenses/LICENSE_js.txt "$LIBS_DIR" echo done! echo ...copying spidermonkey files LIBS_DIR="$DST_DIR""lib_spidermonkey.xctemplate/libs/javascript" mkdir -p "$LIBS_DIR" copy_files scripting/javascript/spidermonkey-ios "$LIBS_DIR" echo done! # Move File Templates to correct position # DST_DIR="$HOME/Library/Developer/Xcode/Templates/File Templates/cocos2d/" # OLD_DIR="$HOME/Library/Developer/Xcode/Templates/cocos2d/" # print_template_banner "Installing Xcode 4 CCNode file templates..." # check_dst_dir # mv -f "$OLD_DIR""/CCNode class.xctemplate" "$DST_DIR" echo done! } copy_xcode4_project_templates
<filename>2021-05-09/吉林宝商城/pages/searchProduct/searchProduct.js Page({ data:{}, onLoad:function(options){ // 页面初始化 options为页面跳转所带来的参数 }, onReady:function(){ // 页面渲染完成 }, onShow:function(){ // 页面显示 }, onHide:function(){ // 页面隐藏 }, onUnload:function(){ // 页面关闭 }, tosearch:function(){ wx.navigateTo({ url: 'seller_order/seller_order' }) } })
<reponame>richardmarston/cim4j package cim4j; import java.util.List; import java.util.Map; import java.util.HashMap; import cim4j.SeasonDayTypeSchedule; import java.lang.ArrayIndexOutOfBoundsException; import java.lang.IllegalArgumentException; import cim4j.Switch; /* A schedule of switch positions. If RegularTimePoint.value1 is 0, the switch is open. If 1, the switch is closed. */ public class SwitchSchedule extends SeasonDayTypeSchedule { private BaseClass[] SwitchSchedule_class_attributes; private BaseClass[] SwitchSchedule_primitive_attributes; private java.lang.String rdfid; public void setRdfid(java.lang.String id) { rdfid = id; } private abstract interface PrimitiveBuilder { public abstract BaseClass construct(java.lang.String value); }; private enum SwitchSchedule_primitive_builder implements PrimitiveBuilder { LAST_ENUM() { public BaseClass construct (java.lang.String value) { return new cim4j.Integer("0"); } }; } private enum SwitchSchedule_class_attributes_enum { Switch, LAST_ENUM; } public SwitchSchedule() { SwitchSchedule_primitive_attributes = new BaseClass[SwitchSchedule_primitive_builder.values().length]; SwitchSchedule_class_attributes = new BaseClass[SwitchSchedule_class_attributes_enum.values().length]; } public void updateAttributeInArray(SwitchSchedule_class_attributes_enum attrEnum, BaseClass value) { try { SwitchSchedule_class_attributes[attrEnum.ordinal()] = value; } catch (ArrayIndexOutOfBoundsException aoobe) { System.out.println("No such attribute: " + attrEnum.name() + ": " + aoobe.getMessage()); } } public void updateAttributeInArray(SwitchSchedule_primitive_builder attrEnum, BaseClass value) { try { SwitchSchedule_primitive_attributes[attrEnum.ordinal()] = value; } catch (ArrayIndexOutOfBoundsException aoobe) { System.out.println("No such attribute: " + attrEnum.name() + ": " + aoobe.getMessage()); } } public void setAttribute(java.lang.String attrName, BaseClass value) { try { SwitchSchedule_class_attributes_enum attrEnum = SwitchSchedule_class_attributes_enum.valueOf(attrName); updateAttributeInArray(attrEnum, value); System.out.println("Updated SwitchSchedule, setting " + attrName); } catch (IllegalArgumentException iae) { super.setAttribute(attrName, value); } } /* If the attribute is a String, it is a primitive and we will make it into a BaseClass */ public void setAttribute(java.lang.String attrName, java.lang.String value) { try { SwitchSchedule_primitive_builder attrEnum = SwitchSchedule_primitive_builder.valueOf(attrName); updateAttributeInArray(attrEnum, attrEnum.construct(value)); System.out.println("Updated SwitchSchedule, setting " + attrName + " to: " + value); } catch (IllegalArgumentException iae) { super.setAttribute(attrName, value); } } public java.lang.String toString(boolean topClass) { java.lang.String result = ""; java.lang.String indent = ""; if (topClass) { for (SwitchSchedule_primitive_builder attrEnum: SwitchSchedule_primitive_builder.values()) { BaseClass bc = SwitchSchedule_primitive_attributes[attrEnum.ordinal()]; if (bc != null) { result += " SwitchSchedule." + attrEnum.name() + "(" + bc.debugString() + ")" + " " + bc.toString(false) + System.lineSeparator(); } } for (SwitchSchedule_class_attributes_enum attrEnum: SwitchSchedule_class_attributes_enum.values()) { BaseClass bc = SwitchSchedule_class_attributes[attrEnum.ordinal()]; if (bc != null) { result += " SwitchSchedule." + attrEnum.name() + "(" + bc.debugString() + ")" + " " + bc.toString(false) + System.lineSeparator(); } } result += super.toString(true); } else { result += "(SwitchSchedule) RDFID: " + rdfid; } return result; } public final java.lang.String debugName = "SwitchSchedule"; public java.lang.String debugString() { return debugName; } public void setValue(java.lang.String s) { System.out.println(debugString() + " is not sure what to do with " + s); } public BaseClass construct() { return new SwitchSchedule(); } };
<reponame>JimNero009/moto from .models import rds_backends from ..core.models import base_decorator mock_rds = base_decorator(rds_backends)
from time import sleep target_time = 10 def up_timer(time): for i in range(1,time+1): print(i) sleep(1) print("時間です!") def down_timer(time): for i in range(time, 0, -1): print(i) sleep(1) print("時間です!") up_timer(target_time) down_timer(target_time)
/* * Copyright (c) 2006-2016, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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. */ #include "flash-journal-strategy-sequential/flash_journal_crc.h" #include "flash-journal-strategy-sequential/flash_journal_private.h" #include "flash-journal-strategy-sequential/flash_journal_strategy_sequential.h" #include "support_funcs.h" #include <string.h> #include <stdio.h> SequentialFlashJournal_t *activeJournal; /* * forward declarations of static-inline helper functions. */ static inline int32_t mtdGetTotalCapacity(ARM_DRIVER_STORAGE *mtd, uint64_t *capacityP); static inline int32_t flashJournalStrategySequential_format_sanityChecks(ARM_DRIVER_STORAGE *mtd, uint32_t numSlots); static inline int32_t flashJournalStrategySequential_read_sanityChecks(SequentialFlashJournal_t *journal, const void *blob, size_t sizeofBlob); static inline int32_t flashJournalStrategySequential_log_sanityChecks(SequentialFlashJournal_t *journal, const void *blob, size_t sizeofBlob); static inline int32_t flashJournalStrategySequential_commit_sanityChecks(SequentialFlashJournal_t *journal); int32_t flashJournalStrategySequential_format(ARM_DRIVER_STORAGE *mtd, uint32_t numSlots, FlashJournal_Callback_t callback) { int32_t rc; if ((rc = flashJournalStrategySequential_format_sanityChecks(mtd, numSlots)) != JOURNAL_STATUS_OK) { return rc; } ARM_STORAGE_INFO mtdInfo; if (mtd->GetInfo(&mtdInfo) < ARM_DRIVER_OK) { return JOURNAL_STATUS_STORAGE_API_ERROR; } uint64_t mtdAddr; if (mtdGetStartAddr(mtd, &mtdAddr) < JOURNAL_STATUS_OK) { return JOURNAL_STATUS_STORAGE_API_ERROR; } formatInfoSingleton.mtd = mtd; formatInfoSingleton.mtdAddr = mtdAddr; formatInfoSingleton.callback = callback; formatInfoSingleton.mtdProgramUnit = mtdInfo.program_unit; if ((rc = setupSequentialJournalHeader(&formatInfoSingleton.header, mtd, mtdInfo.total_storage, numSlots)) != JOURNAL_STATUS_OK) { return rc; } /* initialize MTD */ rc = mtd->Initialize(formatHandler); if (rc < ARM_DRIVER_OK) { return JOURNAL_STATUS_STORAGE_API_ERROR; } else if (rc == ARM_DRIVER_OK) { return JOURNAL_STATUS_OK; /* An asynchronous operation is pending; it will result in a completion callback * where the rest of processing will take place. */ } if (rc != 1) { return JOURNAL_STATUS_STORAGE_API_ERROR; /* synchronous completion is expected to return 1 */ } /* progress the rest of the create state-machine */ return flashJournalStrategySequential_format_progress(ARM_DRIVER_OK, ARM_STORAGE_OPERATION_INITIALIZE); } /** * Validate a header at the start of the MTD. * * @param [in/out] headerP * Caller-allocated header which gets filled in during validation. * @return JOURNAL_STATUS_OK if the header is sane. As a side-effect, the memory * pointed to by 'headerP' is initialized with the header. */ int32_t readAndVerifyJournalHeader(SequentialFlashJournal_t *journal, SequentialFlashJournalHeader_t *headerP) { if (headerP == NULL) { return JOURNAL_STATUS_PARAMETER; } int32_t rc = journal->mtd->ReadData(journal->mtdStartOffset, headerP, sizeof(SequentialFlashJournalHeader_t)); if (rc < ARM_DRIVER_OK) { return JOURNAL_STATUS_STORAGE_IO_ERROR; } else if (rc == ARM_DRIVER_OK) { ARM_STORAGE_CAPABILITIES mtdCaps = journal->mtd->GetCapabilities(); if (!mtdCaps.asynchronous_ops) { return JOURNAL_STATUS_ERROR; /* asynchronous_ops must be set if MTD returns ARM_DRIVER_OK. */ } return JOURNAL_STATUS_ERROR; /* TODO: handle init with pending asynchronous activity. */ } if ((headerP->genericHeader.magic != FLASH_JOURNAL_HEADER_MAGIC) || (headerP->genericHeader.version != FLASH_JOURNAL_HEADER_VERSION) || (headerP->genericHeader.sizeofHeader != sizeof(SequentialFlashJournalHeader_t)) || (headerP->magic != SEQUENTIAL_FLASH_JOURNAL_HEADER_MAGIC) || (headerP->version != SEQUENTIAL_FLASH_JOURNAL_HEADER_VERSION)) { return JOURNAL_STATUS_NOT_FORMATTED; } uint32_t expectedCRC = headerP->genericHeader.checksum; headerP->genericHeader.checksum = 0; flashJournalCrcReset(); uint32_t computedCRC = flashJournalCrcCummulative((const unsigned char *)&headerP->genericHeader, sizeof(SequentialFlashJournalLogHead_t)); if (computedCRC != expectedCRC) { //printf("readAndVerifyJournalHeader: checksum mismatch during header verification: expected = %u, computed = %u\n", (unsigned int) expectedCRC, (unsigned int) computedCRC); return JOURNAL_STATUS_METADATA_ERROR; } return JOURNAL_STATUS_OK; } int32_t flashJournalStrategySequential_initialize(FlashJournal_t *_journal, ARM_DRIVER_STORAGE *mtd, const FlashJournal_Ops_t *ops, FlashJournal_Callback_t callback) { int32_t rc; /* initialize MTD */ rc = mtd->Initialize(mtdHandler); if (rc < ARM_DRIVER_OK) { memset(_journal, 0, sizeof(FlashJournal_t)); return JOURNAL_STATUS_STORAGE_API_ERROR; } if (rc == ARM_DRIVER_OK) { ARM_STORAGE_CAPABILITIES mtdCaps = mtd->GetCapabilities(); if (!mtdCaps.asynchronous_ops) { return JOURNAL_STATUS_ERROR; /* asynchronous_ops must be set if MTD returns ARM_DRIVER_OK. */ } return JOURNAL_STATUS_ERROR; /* TODO: handle init with pending asynchronous activity. */ } SequentialFlashJournal_t *journal; activeJournal = journal = (SequentialFlashJournal_t *)_journal; journal->state = SEQUENTIAL_JOURNAL_STATE_NOT_INITIALIZED; journal->mtd = mtd; /* Setup start address within MTD. */ if ((rc = mtdGetStartAddr(journal->mtd, &journal->mtdStartOffset)) != JOURNAL_STATUS_OK) { return rc; } /* fetch MTD's total capacity */ uint64_t mtdCapacity; if ((rc = mtdGetTotalCapacity(mtd, &mtdCapacity)) != JOURNAL_STATUS_OK) { return rc; } ARM_STORAGE_INFO mtdInfo; if ((rc = mtd->GetInfo(&mtdInfo)) != ARM_DRIVER_OK) { return JOURNAL_STATUS_STORAGE_API_ERROR; } SequentialFlashJournalHeader_t journalHeader; if ((rc = readAndVerifyJournalHeader(journal, &journalHeader)) != JOURNAL_STATUS_OK) { return rc; } /* initialize the journal structure */ memcpy(&journal->ops, ops, sizeof(FlashJournal_Ops_t)); journal->mtdCapabilities = mtd->GetCapabilities(); /* fetch MTD's capabilities */ journal->firstSlotOffset = journalHeader.genericHeader.journalOffset; journal->numSlots = journalHeader.numSlots; journal->sizeofSlot = journalHeader.sizeofSlot; /* effective capacity */ journal->info.capacity = journal->sizeofSlot - roundUp_uint32(sizeof(SequentialFlashJournalLogHead_t), mtdInfo.program_unit) - roundUp_uint32(sizeof(SequentialFlashJournalLogTail_t), mtdInfo.program_unit); journal->info.program_unit = mtdInfo.program_unit; journal->callback = callback; journal->prevCommand = FLASH_JOURNAL_OPCODE_INITIALIZE; if ((rc = discoverLatestLoggedBlob(journal)) != JOURNAL_STATUS_OK) { return rc; } return 1; /* synchronous completion */ } FlashJournal_Status_t flashJournalStrategySequential_getInfo(FlashJournal_t *_journal, FlashJournal_Info_t *infoP) { SequentialFlashJournal_t *journal; activeJournal = journal = (SequentialFlashJournal_t *)_journal; memcpy(infoP, &journal->info, sizeof(FlashJournal_Info_t)); return JOURNAL_STATUS_OK; } int32_t flashJournalStrategySequential_read(FlashJournal_t *_journal, void *blob, size_t sizeofBlob) { SequentialFlashJournal_t *journal; activeJournal = journal = (SequentialFlashJournal_t *)_journal; if (journal->prevCommand != FLASH_JOURNAL_OPCODE_READ_BLOB) { journal->read.logicalOffset = 0; } int32_t rc; if ((rc = flashJournalStrategySequential_read_sanityChecks(journal, blob, sizeofBlob)) != JOURNAL_STATUS_OK) { return rc; } journal->read.blob = blob; journal->read.sizeofBlob = sizeofBlob; if (journal->read.logicalOffset == 0) { { /* Establish the sanity of this slot before proceeding with the read. */ uint32_t headSequenceNumber; SequentialFlashJournalLogTail_t tail; if (slotIsSane(journal, SLOT_ADDRESS(journal, journal->currentBlobIndex), &headSequenceNumber, &tail) != 1) { /* TODO: rollback to an older slot. */ return JOURNAL_STATUS_STORAGE_IO_ERROR; } } journal->read.mtdOffset = SLOT_ADDRESS(journal, journal->currentBlobIndex) + sizeof(SequentialFlashJournalLogHead_t); } else { /* journal->read.offset is already set from the previous read execution */ // printf("flashJournalStrategySequential_read: continuing read of %lu from offset %lu\n", sizeofBlob, (uint32_t)journal->read.offset); } journal->read.dataBeingRead = blob; journal->read.amountLeftToRead = ((journal->info.sizeofJournaledBlob - journal->read.logicalOffset) < sizeofBlob) ? (journal->info.sizeofJournaledBlob - journal->read.logicalOffset) : sizeofBlob; // printf("amount left to read %u\n", journal->read.amountLeftToRead); journal->state = SEQUENTIAL_JOURNAL_STATE_READING; journal->prevCommand = FLASH_JOURNAL_OPCODE_READ_BLOB; return flashJournalStrategySequential_read_progress(); } int32_t flashJournalStrategySequential_readFrom(FlashJournal_t *_journal, size_t offset, void *blob, size_t sizeofBlob) { SequentialFlashJournal_t *journal; activeJournal = journal = (SequentialFlashJournal_t *)_journal; journal->read.logicalOffset = offset; int32_t rc; if ((rc = flashJournalStrategySequential_read_sanityChecks(journal, blob, sizeofBlob)) != JOURNAL_STATUS_OK) { return rc; } journal->read.blob = blob; journal->read.sizeofBlob = sizeofBlob; journal->read.mtdOffset = SLOT_ADDRESS(journal, journal->currentBlobIndex) + sizeof(SequentialFlashJournalLogHead_t) + offset; journal->read.dataBeingRead = blob; journal->read.amountLeftToRead = ((journal->info.sizeofJournaledBlob - journal->read.logicalOffset) < sizeofBlob) ? (journal->info.sizeofJournaledBlob - journal->read.logicalOffset) : sizeofBlob; // printf("amount left to read %u\n", journal->read.amountLeftToRead); journal->state = SEQUENTIAL_JOURNAL_STATE_READING; journal->prevCommand = FLASH_JOURNAL_OPCODE_READ_BLOB; return flashJournalStrategySequential_read_progress(); } int32_t flashJournalStrategySequential_log(FlashJournal_t *_journal, const void *blob, size_t size) { SequentialFlashJournal_t *journal; activeJournal = journal = (SequentialFlashJournal_t *)_journal; int32_t rc; if ((rc = flashJournalStrategySequential_log_sanityChecks(journal, blob, size)) != JOURNAL_STATUS_OK) { return rc; } journal->log.blob = blob; journal->log.sizeofBlob = size; if (journal->prevCommand != FLASH_JOURNAL_OPCODE_LOG_BLOB) { /* * This is the first log in the sequence. We have to begin by identifying a new slot and erasing it. */ /* choose the next slot */ uint32_t logBlobIndex = journal->currentBlobIndex + 1; if (logBlobIndex == journal->numSlots) { logBlobIndex = 0; } /* setup an erase for the slot */ journal->log.mtdEraseOffset = SLOT_ADDRESS(journal, logBlobIndex); journal->state = SEQUENTIAL_JOURNAL_STATE_LOGGING_ERASE; /* start with erasing the log region */ journal->prevCommand = FLASH_JOURNAL_OPCODE_LOG_BLOB; } else { /* This is a continuation of an ongoing logging sequence. */ journal->log.dataBeingLogged = blob; journal->log.amountLeftToLog = size; } /* progress the state machine for log() */ return flashJournalStrategySequential_log_progress(); } int32_t flashJournalStrategySequential_commit(FlashJournal_t *_journal) { SequentialFlashJournal_t *journal; activeJournal = journal = (SequentialFlashJournal_t *)_journal; int32_t rc; if ((rc = flashJournalStrategySequential_commit_sanityChecks(journal)) != JOURNAL_STATUS_OK) { return rc; } if (journal->prevCommand == FLASH_JOURNAL_OPCODE_LOG_BLOB) { /* the tail has already been setup during previous calls to log(); we can now include it in the crc32. */ journal->log.tail.crc32 = flashJournalCrcCummulative((const unsigned char *)&journal->log.tail, sizeof(SequentialFlashJournalLogTail_t)); flashJournalCrcReset(); journal->log.mtdOffset = journal->log.mtdTailOffset; journal->log.dataBeingLogged = (const uint8_t *)&journal->log.tail; journal->log.amountLeftToLog = sizeof(SequentialFlashJournalLogTail_t); journal->state = SEQUENTIAL_JOURNAL_STATE_LOGGING_TAIL; } else { uint32_t logBlobIndex = journal->currentBlobIndex + 1; if (logBlobIndex == journal->numSlots) { logBlobIndex = 0; } journal->log.mtdEraseOffset = SLOT_ADDRESS(journal, logBlobIndex); journal->state = SEQUENTIAL_JOURNAL_STATE_LOGGING_ERASE; } journal->prevCommand = FLASH_JOURNAL_OPCODE_COMMIT; return flashJournalStrategySequential_log_progress(); } int32_t flashJournalStrategySequential_reset(FlashJournal_t *_journal) { SequentialFlashJournal_t *journal; activeJournal = journal = (SequentialFlashJournal_t *)_journal; journal->state = SEQUENTIAL_JOURNAL_STATE_RESETING; journal->prevCommand = FLASH_JOURNAL_OPCODE_RESET; return flashJournalStrategySequential_reset_progress(); } int32_t mtdGetTotalCapacity(ARM_DRIVER_STORAGE *mtd, uint64_t *capacityP) { /* fetch MTD's INFO */ ARM_STORAGE_INFO mtdInfo; int32_t rc = mtd->GetInfo(&mtdInfo); if (rc != ARM_DRIVER_OK) { return JOURNAL_STATUS_STORAGE_API_ERROR; } *capacityP = mtdInfo.total_storage; return JOURNAL_STATUS_OK; } int32_t flashJournalStrategySequential_format_sanityChecks(ARM_DRIVER_STORAGE *mtd, uint32_t numSlots) { /* * basic parameter checking */ if ((mtd == NULL) || (numSlots == 0)) { return JOURNAL_STATUS_PARAMETER; } ARM_STORAGE_INFO mtdInfo; if (mtd->GetInfo(&mtdInfo) < ARM_DRIVER_OK) { return JOURNAL_STATUS_STORAGE_API_ERROR; } if (mtdInfo.total_storage == 0) { return JOURNAL_STATUS_STORAGE_API_ERROR; } uint64_t mtdAddr; if (mtdGetStartAddr(mtd, &mtdAddr) < JOURNAL_STATUS_OK) { return JOURNAL_STATUS_STORAGE_API_ERROR; } if (mtd->GetBlock(mtdAddr, NULL) < ARM_DRIVER_OK) { /* check validity of journal's start address */ return JOURNAL_STATUS_PARAMETER; } if (mtd->GetBlock(mtdAddr + mtdInfo.total_storage - 1, NULL) < ARM_DRIVER_OK) { /* check validity of the journal's end address */ return JOURNAL_STATUS_PARAMETER; } if ((mtdAddr % mtdInfo.program_unit) != 0) { /* ensure that the journal starts at a programmable unit */ return JOURNAL_STATUS_PARAMETER; } if ((mtdAddr % LCM_OF_ALL_ERASE_UNITS) != 0) { /* ensure that the journal starts and ends at an erase-boundary */ return JOURNAL_STATUS_PARAMETER; } return JOURNAL_STATUS_OK; } int32_t flashJournalStrategySequential_read_sanityChecks(SequentialFlashJournal_t *journal, const void *blob, size_t sizeofBlob) { if ((journal == NULL) || (blob == NULL) || (sizeofBlob == 0)) { return JOURNAL_STATUS_PARAMETER; } if ((journal->state == SEQUENTIAL_JOURNAL_STATE_NOT_INITIALIZED) || (journal->state == SEQUENTIAL_JOURNAL_STATE_INIT_SCANNING_LOG_HEADERS)) { return JOURNAL_STATUS_NOT_INITIALIZED; } if (journal->state != SEQUENTIAL_JOURNAL_STATE_INITIALIZED) { return JOURNAL_STATUS_ERROR; /* journal is in an un-expected state. */ } // printf("read sanity checks: logicalOffset = %lu, sizeofJournaledBlob = %lu\n", (uint32_t)journal->read.logicalOffset, (uint32_t)journal->info.sizeofJournaledBlob); if ((journal->info.sizeofJournaledBlob == 0) || (journal->read.logicalOffset >= journal->info.sizeofJournaledBlob)) { journal->read.logicalOffset = 0; return JOURNAL_STATUS_EMPTY; } return JOURNAL_STATUS_OK; } int32_t flashJournalStrategySequential_log_sanityChecks(SequentialFlashJournal_t *journal, const void *blob, size_t sizeofBlob) { if ((journal == NULL) || (blob == NULL) || (sizeofBlob == 0)) { return JOURNAL_STATUS_PARAMETER; } if ((journal->state == SEQUENTIAL_JOURNAL_STATE_NOT_INITIALIZED) || (journal->state == SEQUENTIAL_JOURNAL_STATE_INIT_SCANNING_LOG_HEADERS)) { return JOURNAL_STATUS_NOT_INITIALIZED; } if ((journal->state != SEQUENTIAL_JOURNAL_STATE_INITIALIZED) && (journal->state != SEQUENTIAL_JOURNAL_STATE_LOGGING_BODY)) { return JOURNAL_STATUS_ERROR; /* journal is in an un-expected state. */ } if (journal->state == SEQUENTIAL_JOURNAL_STATE_INITIALIZED) { if (sizeofBlob > journal->info.capacity) { return JOURNAL_STATUS_BOUNDED_CAPACITY; /* adding this log chunk would cause us to exceed capacity (write past the tail). */ } } else if (journal->state == SEQUENTIAL_JOURNAL_STATE_LOGGING_BODY) { if (journal->log.mtdOffset + sizeofBlob > journal->log.mtdTailOffset) { return JOURNAL_STATUS_BOUNDED_CAPACITY; /* adding this log chunk would cause us to exceed capacity (write past the tail). */ } } /* ensure that the request is at least as large as the minimum program unit */ if (sizeofBlob < journal->info.program_unit) { return JOURNAL_STATUS_SMALL_LOG_REQUEST; } return JOURNAL_STATUS_OK; } int32_t flashJournalStrategySequential_commit_sanityChecks(SequentialFlashJournal_t *journal) { if (journal == NULL) { return JOURNAL_STATUS_PARAMETER; } if (journal->state == SEQUENTIAL_JOURNAL_STATE_LOGGING_BODY) { if (journal->prevCommand != FLASH_JOURNAL_OPCODE_LOG_BLOB) { return JOURNAL_STATUS_ERROR; } if ((journal->log.mtdOffset == ARM_STORAGE_INVALID_OFFSET) || (journal->log.mtdTailOffset == ARM_STORAGE_INVALID_OFFSET) || (journal->log.mtdTailOffset < journal->log.mtdOffset) || (journal->log.tail.sizeofBlob == 0) || (journal->log.tail.sizeofBlob > journal->info.capacity)) { return JOURNAL_STATUS_ERROR; /* journal is in an un-expected state. */ } } return JOURNAL_STATUS_OK; }
/** * Created by bparadie on 3/1/15. */ /** * @param {*=}o * @param {*=}u */ function require(o,u){}
#!/bin/sh # Check for CLEAN_CILIUM_BPF_STATE and CLEAN_CILIUM_STATE # is there for backwards compatibility as we've used those # two env vars in our old kubernetes yaml files. if [ "${CILIUM_BPF_STATE}" = "true" ] \ || [ "${CLEAN_CILIUM_BPF_STATE}" = "true" ]; then cilium cleanup -f --bpf-state fi if [ "${CILIUM_ALL_STATE}" = "true" ] \ || [ "${CLEAN_CILIUM_STATE}" = "true" ]; then cilium cleanup -f --all-state fi if [ "${CILIUM_WAIT_BPF_MOUNT}" = "true" ]; then until mount | grep "/sys/fs/bpf type bpf"; do echo "BPF filesystem is not mounted yet"; sleep 1; done fi;