text
stringlengths
1
1.05M
<filename>src/utils/useFocusTrap/useFocusTrap.js import React, { useEffect, useRef, useCallback } from 'react'; import { focusOnFirstDescendent, focusOnLastDescendent } from './utils'; const FocusRing = ({ topFocusBumperRef, bottomFocusBumperRef, children }) => { return ( <div> <div ref={topFocusBumperRef} tabIndex="0" /> {children} <div ref={bottomFocusBumperRef} tabIndex="0" /> </div> ); }; const openFocusTraps = new Set(); const getLastItemInSet = (set) => { const array = Array.from(set); return array[array.length - 1]; }; const useFocusTrap = ({ active, returnFocusToSource = true, initialFocusRef }) => { const ref = useRef(); const topFocusBumperRef = useRef(); const bottomFocusBumperRef = useRef(); const InternalFocusRing = useCallback( ({ children }) => ( <FocusRing topFocusBumperRef={topFocusBumperRef} bottomFocusBumperRef={bottomFocusBumperRef}> {children} </FocusRing> ), [], ); InternalFocusRing.displayName = 'FocusRing'; useEffect(() => { if (active) { const sourceFocusElement = returnFocusToSource && document.activeElement; const currentFocusRef = ref.current; if (!currentFocusRef) { return; } if (openFocusTraps.size > 0) { document.removeEventListener('focusin', getLastItemInSet(openFocusTraps), true); } if (initialFocusRef) { const currentInitialFocusRef = initialFocusRef.current; if (currentInitialFocusRef) { const foundFocus = focusOnFirstDescendent(currentInitialFocusRef); if (!foundFocus) { focusOnFirstDescendent(topFocusBumperRef.current); } } } else if (typeof initialFocusRef === 'undefined') { focusOnFirstDescendent(currentFocusRef); } else { focusOnFirstDescendent(topFocusBumperRef.current); } const trapFocus = (event) => { if (!currentFocusRef.contains(event.target)) { if (document.activeElement === event.target) { if (event.target === topFocusBumperRef.current) { // Reset the focus to the last element when focusing in reverse (shift-tab) focusOnLastDescendent(currentFocusRef); } else { // Reset the focus to the first element after reaching // the last element or any other element outside of the focus trap focusOnFirstDescendent(currentFocusRef); } } } }; openFocusTraps.add(trapFocus); document.addEventListener('focusin', trapFocus, true); return function cleanup() { document.removeEventListener('focusin', trapFocus, true); openFocusTraps.delete(trapFocus); if (sourceFocusElement) { sourceFocusElement.focus(); } if (openFocusTraps.size > 0) { document.addEventListener('focusin', getLastItemInSet(openFocusTraps), true); } }; } }, [active, returnFocusToSource, ref, initialFocusRef]); return { ref, FocusRing: InternalFocusRing }; }; export default useFocusTrap;
const { EPROTONOSUPPORT } = require('constants'); var fs = require('fs'); fs.appendFile('myfile1.txt', "selamat pagi", function(err) { if (err) throw err; console.log("saved"); }); fs.open('myfile2.txt', 'r', function(err, file) { if (err) throw err; console.log("saved file2"); }); fs.open('myfile2.txt', 'w+', function(err, file) { if (err) throw err; let content = "hello dari barat"; fs.writeFile(file, content, (err) => { if (err) throw err; console.log("saved for flag w+"); }); fs.readFile(file, (err, data) => { if (err) throw err; console.log("isi file 2 " + data.toString('utf8')); }); });
<gh_stars>0 /* * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.dbflute.logic.jdbc.metadata.identity.factory; import javax.sql.DataSource; import org.dbflute.logic.jdbc.metadata.identity.DfIdentityExtractor; import org.dbflute.logic.jdbc.metadata.identity.DfIdentityExtractorDB2; import org.dbflute.properties.facade.DfDatabaseTypeFacadeProp; /** * @author jflute * @since 0.8.1 (2008/10/10 Friday) */ public class DfIdentityExtractorFactory { protected final DataSource _dataSource; protected final DfDatabaseTypeFacadeProp _databaseTypeFacadeProp; /** * @param dataSource The data source. (NotNull) * @param databaseTypeFacadeProp The facade properties for database type. (NotNull) */ public DfIdentityExtractorFactory(DataSource dataSource, DfDatabaseTypeFacadeProp databaseTypeFacadeProp) { _dataSource = dataSource; _databaseTypeFacadeProp = databaseTypeFacadeProp; } /** * @return The extractor of DB comments. (NullAllowed) */ public DfIdentityExtractor createIdentityExtractor() { if (_databaseTypeFacadeProp.isDatabaseDB2()) { final DfIdentityExtractorDB2 extractor = new DfIdentityExtractorDB2(); extractor.setDataSource(_dataSource); return extractor; } return null; } }
<filename>angularapp/filters.js 'use strict'; var filters = angular.module('haoshiyou.filters', []);
class TaskManager: def __init__(self): self.tasks = [] def add_task(self, task): self.tasks.append(task) def remove_task(self, task): if task in self.tasks: self.tasks.remove(task) def get_tasks(self): return self.tasks def num_tasks(self): return len(self.tasks) def generate_url(self): return 'http://example.com/tasks'
func calculateTotalCost(cart: [[String: Any]]) -> Double { var totalCost: Double = 0.0 for item in cart { if let price = item["price"] as? Double { totalCost += price } } return totalCost }
<filename>src/out.hpp #ifndef __OUT_HPP__ #define __OUT_HPP__ #include <iostream> class out{ private: out(std::ostream& o, bool discard) : o(o), discard(discard) {} std::ostream& o; bool discard = false; public: void flush(){ std::flush(o); } static out cout(unsigned int level){ return out(std::cout, level > verbosity_level); } static out cerr(unsigned int level){ return out(std::cerr, level > verbosity_level); } template<typename T> out& operator<<(const T& t){ if(!discard) o << t; return *this; } out& operator<<(std::ostream& (*f)(std::ostream&)){ if(!discard) f(o); return *this; } static unsigned int verbosity_level; }; #endif // __OUT_HPP__
rm -rf *.xcarchive rm -f *.ipa rm -rf *.app rm -f DistributionSummary.plist rm -f ExportOptions.plist rm -f Packaging.log rm -rf app rm -f app.zip # rm -f Podfile.lock # rm -rf Pods # rm -rf *.xcworkspace
import React, { useReducer, useEffect } from "react"; import PlanetList from "../planet-list/planet-list.component.js"; import SelectedPlanet from "./selected-planet/selected-planet.component.js"; import { get } from "lodash"; import { getPlanets } from "../utils/api.js"; import { Button } from "@react-mf/styleguide"; export default function PlanetPage(props) { const initialState = { planets: [], loading: false, page: 0, nextPage: false, }; const [state, dispatch] = useReducer(reducer, initialState); useEffect(() => { dispatch({ type: "fetchPlanets" }); }, []); const { page, nextPage, loading } = state; const { pathname } = props.location; const regexSearch = /[0-9]+/.exec(pathname); const selected = get(regexSearch, "[0]"); useEffect(() => { if (page > 0) { const req$ = getPlanets(page).subscribe((results) => { dispatch({ type: "addPlanets", payload: { nextPage: !!results.next, results: results.results, }, }); }); } }, [page]); return ( <div> <div className="flex"> <div className="p-6 w-1/3"> {nextPage ? ( <Button disabled={loading || !nextPage} loading={loading} onClick={() => { dispatch({ type: "fetchPlanets" }); }} > Fetch More Planets </Button> ) : null} <PlanetList {...state} /> </div> <div className="w-2/3 p-6 border-l-2 border-white"> <div className="selectedPlanet"> <SelectedPlanet selectedId={selected} /> </div> </div> </div> </div> ); } function reducer(state, action) { const newState = { ...state }; switch (action.type) { case "addPlanets": const { payload } = action; newState.loading = false; newState.nextPage = payload.nextPage; newState.planets = [...newState.planets, ...payload.results]; return newState; case "fetchPlanets": newState.loading = true; newState.page = newState.page + 1; return newState; default: return state; } }
#!/bin/bash #SBATCH --account=def-dkulic #SBATCH --mem=8000M # memory per node #SBATCH --time=23:00:00 # time (DD-HH:MM) #SBATCH --output=/project/6001934/lingheng/Double_DDPG_Job_output/continuous_BipedalWalkerHardcore-v2_ddpg_hardcopy_epsilon_greedy_seed2_run1_%N-%j.out # %N for node name, %j for jobID module load qt/5.9.6 python/3.6.3 nixpkgs/16.09 gcc/7.3.0 boost/1.68.0 cuda cudnn source ~/tf_cpu/bin/activate python ./ddpg_discrete_action.py --env BipedalWalkerHardcore-v2 --random-seed 2 --exploration-strategy epsilon_greedy --summary-dir ../Double_DDPG_Results_no_monitor/continuous/BipedalWalkerHardcore-v2/ddpg_hardcopy_epsilon_greedy_seed2_run1 --continuous-act-space-flag --double-ddpg-flag --target-hard-copy-flag
<reponame>lgoldstein/communitychest package net.community.chest.net; import java.util.Arrays; import java.util.Collections; import java.util.List; import net.community.chest.util.collection.CollectionsUtils; /** * <P>Copyright 2007 as per GPLv2</P> * * <P>Known protocol(s)</P> * @author <NAME>. * @since Sep 20, 2007 12:51:56 PM */ public enum NetProtocolType { SMTP, IMAP4, POP3, FTP, HTTP, HTTPS, SNMP, DNS; public static final List<NetProtocolType> VALUES=Collections.unmodifiableList(Arrays.asList(values())); public static NetProtocolType fromString (final String s) { return CollectionsUtils.fromString(VALUES, s, false); } }
#!/usr/bin/env zsh # TRADES (Imagnette) echo "开始训练 1......" CUDA_VISIBLE_DEVICES=0,1,2,3 python train_trades_cifar10.py --model preactresnet --AT-method TRADES --dataset Imagnette --gpu-id 2,3 --seed 1 wait echo "开始训练 2......" CUDA_VISIBLE_DEVICES=0,1,2,3 python train_trades_cifar10.py --model preactresnet --AT-method TRADES --dataset Imagnette --gpu-id 2,3 --seed 2 wait echo "开始训练 3......" CUDA_VISIBLE_DEVICES=0,1,2,3 python train_trades_cifar10.py --model preactresnet --AT-method TRADES --dataset Imagnette --gpu-id 2,3 --seed 3 wait echo "开始训练 4......" CUDA_VISIBLE_DEVICES=0,1,2,3 python train_trades_cifar10.py --model preactresnet --AT-method TRADES --dataset Imagnette --gpu-id 2,3 --seed 4 wait echo "开始训练 5......" CUDA_VISIBLE_DEVICES=0,1,2,3 python train_trades_cifar10.py --model preactresnet --AT-method TRADES --dataset Imagnette --gpu-id 2,3 --seed 5 wait echo "结束训练......"
package de.schub.marathon_scaler.Customer; import com.google.gson.Gson; import com.orbitz.consul.Consul; import com.orbitz.consul.async.ConsulResponseCallback; import com.orbitz.consul.model.ConsulResponse; import com.orbitz.consul.model.kv.Value; import com.orbitz.consul.option.QueryOptionsBuilder; import com.orbitz.consul.util.ClientUtil; import javax.inject.Inject; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.stream.Collectors; public class CustomerStorage extends Observable { private final Consul consul; private final Gson gson; @Inject public CustomerStorage(Consul consul, Gson gson) { this.consul = consul; this.gson = gson; } public Customer get(int id) { return get(consul.keyValueClient().getValueAsString("customer/" + id).get()); } private Customer get(String json) { return gson.fromJson(json, Customer.class); } public Map<Integer, Customer> getAll() { return getFromValues(consul.keyValueClient().getValues("/customer")); } public GroupTemplate getGroupTemplate() { return new GroupTemplate(gson, consul.keyValueClient().getValueAsString("customer/template").get()); } private Map<Integer, Customer> getFromValues(List<Value> values) { return values.stream() .filter(value -> value.getKey().matches("^customer/[0-9]+$")) .map( value -> get( ClientUtil.decodeBase64((value.getValue())) ) ) .collect(Collectors.toMap(Customer::getId, customer -> customer)); } public void registerEventSubscriber(CustomerEventSubscriber subscriber) { consul.keyValueClient().getValues( "/customer", QueryOptionsBuilder.builder().blockMinutes(1, 0).build(), new ConsulResponseCallback<List<Value>>() { long index; @Override public void onComplete(ConsulResponse<List<Value>> consulResponse) { subscriber.onUpdate(getGroupTemplate(), getFromValues(consulResponse.getResponse())); index = consulResponse.getIndex(); consul.keyValueClient() .getValues( "/customer", QueryOptionsBuilder.builder().blockMinutes(10, index).build(), this ); } @Override public void onFailure(Throwable throwable) { throwable.printStackTrace(); consul.keyValueClient() .getValues( "/customer", QueryOptionsBuilder.builder().blockMinutes(10, index).build(), this ); } } ); } public interface CustomerEventSubscriber { void onUpdate(GroupTemplate template, Map<Integer, Customer> customers); } }
<reponame>pashchenkoromak/jParcs<filename>sys_prog/java/io/github/lionell/lab1/CliquesFinder.java package io.github.lionell.lab1; import com.google.common.collect.ImmutableSet; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import io.github.lionell.lab1.util.IntSet; import io.github.lionell.lab1.util.IteratorUtils; /** * Finds all maximum cliques in graph based on Hamming distance between words. Edge between two * words exists iff distance is equal to maximal one(for whole graph G). * * @author lionell */ public class CliquesFinder { private final List<String> words; private final List<Set<Integer>> g; private final Set<Set<Integer>> ans = new HashSet<>(); public CliquesFinder(List<String> words) { this.words = words; g = createGraph(); } Set<Set<String>> findCliques() { find(IntSet.of().toSet(), IntSet.range(0, words.size()).toSet(), IntSet.of().toSet()); return generateResult(); } private void find(Set<Integer> r, Set<Integer> p, Set<Integer> x) { if (p.isEmpty()) { if (x.isEmpty() && r.size() > 1) { ans.add(ImmutableSet.copyOf(r)); } return; } int u = IteratorUtils.getRandom(p.iterator(), p.size()); for (int v : IntSet.of(p).addAll(x).removeAll(g.get(u)).toSet()) { find( IntSet.of(r).add(v).toSet(), IntSet.of(p).retainAll(g.get(v)).toSet(), IntSet.of(x).retainAll(g.get(v)).toSet()); p.remove(v); x.add(v); } } private List<Set<Integer>> createGraph() { int maxDistance = findMaxDistance(); System.out.println("Max distance = " + maxDistance); List<Set<Integer>> g = new ArrayList<>(); for (int i = 0; i < words.size(); i++) { g.add(new HashSet<>()); } for (int i = 0; i < words.size(); i++) { for (int j = i + 1; j < words.size(); j++) { if (distance(words.get(i), words.get(j)) == maxDistance) { g.get(i).add(j); g.get(j).add(i); } } } return g; } private int findMaxDistance() { int res = 0; for (int i = 0; i < words.size(); i++) { for (int j = i + 1; j < words.size(); j++) { res = Math.max(res, distance(words.get(i), words.get(j))); } } return res; } private static int distance(String a, String b) { int res = Math.abs(a.length() - b.length()); for (int i = 0; i < Math.min(a.length(), b.length()); i++) { if (a.charAt(i) != b.charAt(i)) { res++; } } return res; } private Set<Set<String>> generateResult() { Set<Set<String>> res = new HashSet<>(); for (Set<Integer> v : ans) { res.add(v.stream().map(words::get).collect(Collectors.toSet())); } return res; } }
#include <iostream> #include <string> #include <set> using namespace std; int main() { string s; getline(cin, s); set<char> chars; string result; for (char c : s) { if (chars.find(c) == chars.end()) { result += c; chars.insert(c); } } cout << result << endl; return 0; }
total = 0 for x in range(1, 101): if x%3 == 0 or x%5 == 0: total += x print("The sum is %d." %total)
list_a = [1, 2, 3, 4, 5] #function to calculate even and odd values def calculate_even_odd(list_a): #initialize counters for even and odd numbers even_counter = 0 odd_counter = 0 #check for even and odd numbers for int in list_a: if int % 2 == 0: even_counter += 1 else: odd_counter += 1 return (even_counter, odd_counter) #call function even_odd = calculate_even_odd(list_a) #print even and odd numbers print("Number of even numbers:",even_odd[0]) print("Number of odd numbers:", even_odd[1])
#!/bin/bash # # Purpose: Custom Xray Commands Master Script # Requirements: jq | curl | Xray credentials # Author: Loren Y # SCRIPT_DIR=`dirname $0`; PARENT_SCRIPT_DIR="$(dirname "$SCRIPT_DIR")" PARENT2_SCRIPT_DIR="$(dirname "$PARENT_SCRIPT_DIR")" if [ ! -f $PARENT_SCRIPT_DIR/json/xrayValues.json ]; then SCRIPT_VERSION=$(jq -r .script_version $PARENT_SCRIPT_DIR/metadata.json) echo "Welcome to Loren's Custom Xray commands master script. You're on version $SCRIPT_VERSION. Creating $PARENT_SCRIPT_DIR/json/..." $PARENT_SCRIPT_DIR/common/installPrerequisites.sh echo "Could not find xrayValues.json, generating:" while true; do echo "Enter your Xray URL (e.g. http://localhost:8000):" read xray_url if [ "$(curl -s $xray_url/api/v1/system/ping | jq -r .status)" != "pong" ]; then echo "Xray doesn't look to be either running or reachable from here." else break fi done echo "Enter your $xray_url username:" read username echo "Enter your $xray_url password:" read -s password while true; do echo "Enter your \$XRAY_HOME location (e.g. /Users/loreny/.jfrog/xray):" read xray_home if [ "$xray_home" != "/" ]; then xray_home=$(echo $xray_home | sed 's:/*$::') fi if [ ! -d "$xray_home" ]; then echo "$xray_home doesnt exist." else break fi done while true; do echo "Enter your Xray Directory location (e.g. /Users/loreny/xray):" read xray_dir if [ "$xray_dir" != "/" ]; then xray_dir=$(echo $xray_dir | sed 's:/*$::') fi if [ ! -d "$xray_dir" ]; then echo "$xray_dir doesnt exist." else break fi done echo "Select your Xray installation type:" select install_type in "docker" "centos" "debian" "redhat" "ubuntu"; do case $install_type in docker ) break;; centos ) break;; debian ) break;; redhat ) break;; ubuntu ) break;; esac done echo "Creating $PARENT_SCRIPT_DIR/json/xrayValues.json" echo -e "{\"username\":\""$username"\", \"password\":\""$password"\", \"xray_home\":\""$xray_home"\", \"xray_url\":\""$xray_url"\", \"xray_dir\":\""$xray_dir"\", \"install_type\":\""$install_type"\"}" > $PARENT_SCRIPT_DIR/json/xrayValues.json fi XRAY_HOME=$(jq -r '.xray_home' $PARENT_SCRIPT_DIR/json/xrayValues.json) XRAY_URL=$(jq -r '.xray_url' $PARENT_SCRIPT_DIR/json/xrayValues.json) XRAY_CREDS=$(jq -r '"\(.username):\(.password)"' $PARENT_SCRIPT_DIR/json/xrayValues.json) XRAY_DIR=$(jq -r '.xray_dir' $PARENT_SCRIPT_DIR/json/xrayValues.json) case "$1" in check) $PARENT_SCRIPT_DIR/common/upgradeScriptToLatest.sh;; upgrade) $SCRIPT_DIR/upgradeXrayToLatest.sh;; restart) $XRAY_DIR/xray restart;; status) curl -u $XRAY_CREDS $XRAY_URL/api/v1/system/ping; echo "";; baseUrl) $SCRIPT_DIR/setBaseUrl.sh;; start) $XRAY_DIR/xray start;; stop) $XRAY_DIR/xray stop;; ps) $XRAY_DIR/xray ps;; default) $XRAY_DIR/xray $2;; disableRestart) $SCRIPT_DIR/disableRestart.sh;; *) echo $"Usage: xray (commands ... )"; echo "commands:"; echo " check = Check for latest script version and optionally upgrade"; echo " upgrade = Upgrade Xray to latest, or a specified version"; echo " restart = Restart Xray"; echo " start = Start Xray"; echo " status = Xray Status"; echo " stop = Stop Xray"; echo " ps = Xray microservices' status" echo " baseUrl = Change Xray Base URL to current internal IP"; echo " disableRestart = Disable Xray Docker restart"; echo " default = Normal Xray command script + [options]";; esac
from flask import Flask, request import threading app = Flask(__name__) def process_sentence(sentence): # Implement the processing logic for the given sentence # Example: Reversing the sentence return sentence[::-1] def proc_stop(): # Implement the logic to stop any running processes or threads # Example: Stopping the Flask application func = request.environ.get('werkzeug.server.shutdown') if func is None: raise RuntimeError('Not running with the Werkzeug Server') func() @app.route("/process", methods=['POST']) def process(): data = request.get_json() sentence = data.get('sentence') processed_sentence = process_sentence(sentence) return processed_sentence @app.route("/stop") def stop(): proc_stop() return "kill thread" if __name__ == '__main__': app.run()
<filename>src/www/index.py<gh_stars>0 #!/bin/python3 # author: <NAME> import sys from flask import redirect, url_for, send_file from env import Env from www import app, login_required from loguru import logger from utils.crypto import b64decode max_file_view_limit = 1024*1024 @app.route('/') @app.route('/index') @login_required def index(): return redirect(url_for('view_courses')) @app.route('/log') def print_log(): log = Env.log_file.read_text() import ansi2html converter = ansi2html.Ansi2HTMLConverter() html = converter.convert(log) return '<h1>Automate log</h1>' + html @app.route('/log/clear') @login_required def clear_log(): Env.log_file.unlink() Env.log_file.touch() logger.configure(handlers=[ dict(sink=sys.stdout), dict(sink=Env.log_file, colorize=True) ]) logger.info('--- log file cleared ---') return redirect('/log') @app.route('/file/<string:data>/<string:as_name>') def serve_file(data: str, as_name: str): result = b64decode(data) local = Env.root.joinpath(*result['url']) assert local.parts[-2] in ('input', 'output', '.error') if local.exists(): if local.stat().st_size > max_file_view_limit: return send_file(str(local), mimetype='text/plain', as_attachment=True, attachment_filename=as_name) else: return send_file(str(local), mimetype='text/plain', attachment_filename=as_name) return 'File not found' # return send_file(str(local), mimetype='text/plain', as_attachment=True, attachment_filename=as_name)
""" Flask API to return customer data """ import sqlite3 from flask import Flask, jsonify, request, g DATABASE = 'customer_database.db' app = Flask(__name__) def get_db(): db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(DATABASE) return db @app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None) if db is not None: db.close() @app.route('/customers', methods=['GET']) def get_customers(): query_parameters = request.args sqlCursor = get_db().cursor().execute("SELECT * FROM customers") customers = [dict(zip([key[0] for key in sqlCursor.description], row)) for row in sqlCursor.fetchall()] if len(query_parameters) > 0: customers = filter_customers(customers, query_parameters) return jsonify(customers) def filter_customers(customers, query_parameters): filtering_params = {} for param in query_parameters: if param not in ['name']: return "Input not valid" filtering_params[param] = query_parameters[param] filtered_customers = [] for customer in customers: for key in filtering_params.keys(): if customer[key] == filtering_params[key]: filtered_customers.append(customer) return filtered_customers if __name__ == "__main__": app.run(host="localhost", port=5000, debug=True)
//#region IMPORTS import type Pose from '../../armature/Pose'; import type { IKChain } from '../rigs/IKChain'; import QuatUtil from '../../maths/QuatUtil'; import Vec3Util from '../../maths/Vec3Util'; import { quat } from 'gl-matrix'; import SwingTwistBase from './support/SwingTwistBase'; //#endregion function lawcos_sss( aLen: number, bLen: number, cLen: number ): number{ // Law of Cosines - SSS : cos(C) = (a^2 + b^2 - c^2) / 2ab // The Angle between A and B with C being the opposite length of the angle. let v = ( aLen*aLen + bLen*bLen - cLen*cLen ) / ( 2 * aLen * bLen ); if( v < -1 ) v = -1; // Clamp to prevent NaN Errors else if( v > 1 ) v = 1; return Math.acos( v ); } class LimbSolver extends SwingTwistBase{ bendDir : number = 1; // Switching to Negative will flip the rotation arc invertBend(): this{ this.bendDir = -this.bendDir; return this; } resolve( chain: IKChain, pose: Pose, debug?:any ): void{ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Start by Using SwingTwist to target the bone toward the EndEffector const ST = this._swingTwist const [ rot, pt ] = ST.getWorldRot( chain, pose, debug ); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ let b0 = chain.links[ 0 ], b1 = chain.links[ 1 ], alen = b0.len, blen = b1.len, clen = Vec3Util.len( ST.effectorPos, ST.originPos ), prot : quat = [0,0,0,0], rad : number; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // FIRST BONE rad = lawcos_sss( alen, clen, blen ); // Get the Angle between First Bone and Target. QuatUtil.pmulAxisAngle( rot, ST.orthoDir, -rad * this.bendDir, rot ); // Use the Axis X to rotate by Radian Angle quat.copy( prot, rot ); // Save For Next Bone as Starting Point. QuatUtil.pmulInvert( rot, rot, pt.rot ); // To Local pose.setLocalRot( b0.idx, rot ); // Save to Pose //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // SECOND BONE // Need to rotate from Right to Left, So take the angle and subtract it from 180 to rotate from // the other direction. Ex. L->R 70 degrees == R->L 110 degrees rad = Math.PI - lawcos_sss( alen, blen, clen ); quat.mul( rot, prot, b1.bind.rot ); // Get the Bind WS Rotation for this bone QuatUtil.pmulAxisAngle( rot, ST.orthoDir, rad * this.bendDir, rot ); // Rotation that needs to be applied to bone. QuatUtil.pmulInvert( rot, rot, prot ); // To Local Space pose.setLocalRot( b1.idx, rot ); // Save to Pose } } export default LimbSolver;
#!/bin/bash echo Put echo into maintenance mode docker-machine ssh bravo sudo docker node update --availability drain echo echo Inspect the node docker-machine ssh bravo sudo docker node inspect --pretty echo echo Inspect the status of the Swarm docker-machine ssh bravo sudo docker node ls echo Monitor the transition between versions watch 'docker-machine ssh bravo sudo docker service ps redis'
#!/bin/bash doTempFileTesting(){ # NEEDS THIS TO BE SET BEFORE CALL : # testedFile="" if [ ! -r "${testedFile}" ] || [ ! -e "${testedFile}" ] || [ ! -f "${testedFile}" ] || [ ! -s "${testedFile}" ]; then echo "Temporary file not found or empty file : ${testedFile}" >&2 echo "EXITING!!" >&2 exit 1 fi } doTempFileInfo(){ # NEEDS THIS TO BE SET BEFORE CALL : # testedFile="" if [ ! -r "${testedFile}" ] || [ ! -e "${testedFile}" ] || [ ! -f "${testedFile}" ] || [ ! -s "${testedFile}" ]; then echo "Temporary file not found or empty file : ${testedFile}" >&2 echo "Continuing, but may create some NONSENSE data.." >&2 #echo "EXITING!!" >&2 #exit 1 fi } doTempFileFYI(){ # NEEDS THIS TO BE SET BEFORE CALL : # testedFile="" if [ ! -r "${testedFile}" ] || [ ! -e "${testedFile}" ] || [ ! -f "${testedFile}" ] || [ ! -s "${testedFile}" ]; then echo "Probably harmless : file not found or empty file : ${testedFile}" >&2 #echo "EXITING!!" >&2 #exit 1 fi }
import { Router } from 'express' import { celebrate, Joi, Segments } from 'celebrate' import UsersController from '../controllers/UsersController' import isAuthenticated from '@server/middlewares/isAuthenticated' const usersRouter = Router() const usersController = new UsersController() usersRouter.get('/', isAuthenticated, usersController.index) usersRouter.post( '/', celebrate({ [Segments.BODY]: { name: Joi.string().required(), email: Joi.string().email().required(), password: Joi.string().required(), }, }), usersController.create, ) export default usersRouter
def check_duplicates(input_list): seen = set() for num in input_list: if num in seen: return "Things are not ok" seen.add(num) return "There are no duplicates" # Example usage input_list1 = [1, 2, 3, 4, 5] input_list2 = [1, 2, 3, 4, 2] print(check_duplicates(input_list1)) # Output: There are no duplicates print(check_duplicates(input_list2)) # Output: Things are not ok
<gh_stars>1-10 package kbasesearchengine.main; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import kbasesearchengine.GetObjectsInput; import kbasesearchengine.GetObjectsOutput; import kbasesearchengine.ObjectData; import kbasesearchengine.SearchObjectsInput; import kbasesearchengine.SearchObjectsOutput; import kbasesearchengine.SearchTypesInput; import kbasesearchengine.SearchTypesOutput; import kbasesearchengine.TypeDescriptor; import kbasesearchengine.tools.Utils; /** This class is a Q&D fix to reduce the transport problems when returning narratives from * search, since they contain a number of fields which are extremely long strings often full of * javascript that are useless for displaying to a user. * * Longer term fix will be adding the ability to run custom code for a type when indexing said * type. * * Currently the class is only tested via integration tests as it is expected to have a * relatively short lifetime. * * @author <EMAIL> * */ public class TemporaryNarrativePruner implements SearchInterface { // narrative fields to remove. private static final List<String> FIELDS_TO_NUKE = Arrays.asList( "source", "code_output", "app_output", "app_info", "app_input", "job_ids"); private final SearchInterface source; /** Create a narrative pruner. * @param source the wrapped {@link SearchInterface}. */ public TemporaryNarrativePruner(final SearchInterface source) { Utils.nonNull(source, "source"); this.source = source; } @Override public SearchTypesOutput searchTypes(final SearchTypesInput params, final String user) throws Exception { return source.searchTypes(params, user); } @Override public SearchObjectsOutput searchObjects(final SearchObjectsInput params, final String user) throws Exception { final SearchObjectsOutput searchObjects = source.searchObjects(params, user); return searchObjects.withObjects(clean(searchObjects.getObjects())); } @Override public GetObjectsOutput getObjects(GetObjectsInput params, String user) throws Exception { final GetObjectsOutput getObjects = source.getObjects(params, user); return getObjects.withObjects(clean(getObjects.getObjects())); } @Override public Map<String, TypeDescriptor> listTypes(final String uniqueType) throws Exception { return source.listTypes(uniqueType); } // this method modifies the input in place private List<ObjectData> clean(final List<ObjectData> objectData) { for (final ObjectData od: objectData) { if (od.getType().equals("Narrative")) { od.setData(null); // nuke the raw data final Map<String, String> keyprops = new HashMap<>(od.getKeyProps()); for (final String field: FIELDS_TO_NUKE) { keyprops.remove(field); } od.setKeyProps(keyprops); } } return objectData; } }
<reponame>backwardn/gudgeon package resolver import ( "fmt" log "github.com/sirupsen/logrus" "net" "strconv" "strings" "time" "github.com/miekg/dns" "github.com/chrisruffalo/gudgeon/pool" "github.com/chrisruffalo/gudgeon/util" ) const ( defaultPort = uint(53) defaultTLSPort = uint(853) portDelimeter = ":" protoDelimeter = "/" ) // how many workers to spawn const workers = 1 // how many requests to buffer const requestBuffer = 1 // how long to wait before timing out the connection var defaultDeadline = 350 * time.Millisecond var validProtocols = []string{"udp", "tcp", "tcp-tls"} type dnsSource struct { dnsServer string port uint remoteAddress string protocol string network string pool pool.DnsPool } func (dnsSource *dnsSource) Name() string { return dnsSource.remoteAddress + "/" + dnsSource.protocol } func (dnsSource *dnsSource) Load(specification string) { dnsSource.port = 0 dnsSource.dnsServer = "" dnsSource.protocol = "" // determine first if there is an attached protocol if strings.Contains(specification, protoDelimeter) { split := strings.Split(specification, protoDelimeter) if len(split) > 1 && util.StringIn(strings.ToLower(split[1]), validProtocols) { specification = split[0] dnsSource.protocol = strings.ToLower(split[1]) } } // need to determine if a port comes along with the address and parse it out once if strings.Contains(specification, portDelimeter) { split := strings.Split(specification, portDelimeter) if len(split) > 1 { dnsSource.dnsServer = split[0] var err error parsePort, err := strconv.ParseUint(split[1], 10, 32) // recover from error if err != nil { dnsSource.port = 0 } else { dnsSource.port = uint(parsePort) } } } else { dnsSource.dnsServer = specification } // set defaults if missing if "" == dnsSource.protocol { dnsSource.protocol = "udp" } // the network should be just tcp, really dnsSource.network = dnsSource.protocol if "tcp-tls" == dnsSource.protocol { dnsSource.network = "tcp" } // recover from parse errors or use default port in event port wasn't set if dnsSource.port == 0 { if "tcp-tls" == dnsSource.protocol { dnsSource.port = defaultTLSPort } else { dnsSource.port = defaultPort } } // check final output if ip := net.ParseIP(dnsSource.dnsServer); ip != nil { // save/parse remote address once dnsSource.remoteAddress = fmt.Sprintf("%s%s%d", dnsSource.dnsServer, portDelimeter, dnsSource.port) } // create pool dnsSource.pool = pool.DefaultDnsPool(dnsSource.protocol, dnsSource.remoteAddress) } func (dnsSource *dnsSource) handle(co *dns.Conn, request *dns.Msg) (*dns.Msg, error) { // update deadline waiting for write to succeed _ = co.SetWriteDeadline(time.Now().Add(defaultDeadline)) // write message if err := co.WriteMsg(request); err != nil { return nil, err } // read response with deadline _ = co.SetReadDeadline(time.Now().Add(defaultDeadline)) response, err := co.ReadMsg() if response != nil && response.MsgHdr.Id != request.MsgHdr.Id { log.Warnf("Response id (%d) does not match request id (%d) for question:\n%s", response.MsgHdr.Id, request.MsgHdr.Id, request.String()) } if err != nil { return nil, err } return response, nil } func (dnsSource *dnsSource) query(request *dns.Msg) (*dns.Msg, error) { conn, err := dnsSource.pool.Get() // discard on error during connection if err != nil { dnsSource.pool.Discard(conn) return nil, err } // need to discard nil con to avoid jamming up the way it works if conn == nil { dnsSource.pool.Discard(conn) return nil, fmt.Errorf("No connection provided by pool") } response, err := dnsSource.handle(conn, request) if err != nil { dnsSource.pool.Discard(conn) } else { dnsSource.pool.Release(conn) } return response, err } func (dnsSource *dnsSource) Answer(rCon *RequestContext, context *ResolutionContext, request *dns.Msg) (*dns.Msg, error) { // this is considered a recursive query so don't if recursion was not requested if request == nil || !request.MsgHdr.RecursionDesired { return nil, nil } // forward message without interference response, err := dnsSource.query(request) if err != nil { return nil, err } // do not set reply here (doesn't seem to matter, leaving this comment so nobody decides to do it in the future without cause) // response.SetReply(request) // set source as answering source if context != nil && !util.IsEmptyResponse(response) && context.SourceUsed == "" { context.SourceUsed = dnsSource.Name() } // otherwise just return return response, nil } func (dnsSource *dnsSource) Close() { dnsSource.pool.Shutdown() }
from microbit import * from enum import * class CRASH(object): """基本描述 碰撞传感器 Args: RJ_pin (pin): 连接端口 """ def __init__(self, RJ_pin): if RJ_pin == J1: self.__pin = pin8 elif RJ_pin == J2: self.__pin = pin12 elif RJ_pin == J3: self.__pin = pin14 elif RJ_pin == J4: self.__pin = pin16 self.__pin.set_pull(self.__pin.PULL_UP) def crash_is_pressed(self) -> bool: """基本描述 碰撞传感器被按下 Returns: boolean: 按下返回True, 未按下返回False """ if self.__pin.read_digital() == 0: return True else: return False if __name__ == '__main__': button = CRASH(J1) while True: if button.crash_is_pressed(): display.show(Image.HAPPY) else: display.show(Image.SAD)
const http = require("http"); const app = require("./config/express"); const port = 3000; http.createServer(app).listen(port, function() { console.log("Servidor iniciado na porta 3000"); });
echo Stop VLC kill -9 `cat player.pid`
#! /bin/bash PACKAGE="xz" VERSION=$1 FOLD_NAME="$PACKAGE-$VERSION" if [ -z "$CORES" ]; then CORES='4' fi tar xf "$PACKAGE_DIR/$FOLD_NAME.tar.xz" pushd "$FOLD_NAME" # Prevent an error sed -e '/mf\.buffer = NULL/a next->coder->mf.size = 0;' \ -i src/liblzma/lz/lz_encoder.c # Configure the source ./configure --prefix=/usr \ --disable-static \ --docdir=/usr/share/doc/xz-$VERSION # Build using the configured sources make -j "$CORES" # Install the built package if [ "$INSTALL_SOURCES" -eq 1 ]; then make install mv -v /usr/bin/{lzma,unlzma,lzcat,xz,unxz,xzcat} /bin mv -v /usr/lib/liblzma.so.* /lib ln -svf ../../lib/$(readlink /usr/lib/liblzma.so) /usr/lib/liblzma.so fi popd rm -rf "$FOLD_NAME"
def find_view_function(url_path: str) -> str: for pattern in urlpatterns: pattern_path = pattern[0] view_function = pattern[1] if pattern_path == url_path: return pattern[2] elif "<str:" in pattern_path: pattern_prefix = pattern_path.split("<str:")[0] if url_path.startswith(pattern_prefix): return pattern[2] return "Not Found"
<filename>python_modules/dagster/dagster/core/storage/output_manager.py from abc import ABC, abstractmethod, abstractproperty from dagster.core.definitions.definition_config_schema import ( convert_user_facing_definition_config_schema, ) from dagster.core.definitions.resource import ResourceDefinition class IOutputManagerDefinition: @abstractproperty def output_config_schema(self): """The schema for per-output configuration for outputs that are managed by this manager""" class OutputManagerDefinition(ResourceDefinition, IOutputManagerDefinition): """Definition of an output manager resource. An OutputManagerDefinition is a :py:class:`ResourceDefinition` whose resource_fn returns an :py:class:`OutputManager`. OutputManagers are used to handle the outputs of solids. """ def __init__( self, resource_fn=None, config_schema=None, description=None, output_config_schema=None, required_resource_keys=None, version=None, ): self._output_config_schema = convert_user_facing_definition_config_schema( output_config_schema ) super(OutputManagerDefinition, self).__init__( resource_fn=resource_fn, config_schema=config_schema, description=description, required_resource_keys=required_resource_keys, version=version, ) @property def output_config_schema(self): return self._output_config_schema def copy_for_configured(self, description, config_schema, _): return OutputManagerDefinition( config_schema=config_schema, description=description or self.description, resource_fn=self.resource_fn, required_resource_keys=self.required_resource_keys, output_config_schema=self.output_config_schema, ) class OutputManager(ABC): """Base class for user-provided output managers. OutputManagers are used to handle the outputs of solids. """ @abstractmethod def handle_output(self, context, obj): """Handles an output produced by a solid. Usually, this means materializing it to persistent storage. Args: context (OutputContext): The context of the step output that produces this object. obj (Any): The data object to be handled. """
<gh_stars>1-10 /* * Copyright 2018-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.filippov.data.validation.tool.model.datasource; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; @Getter @Builder @EqualsAndHashCode public class DatasourceQuery { private final DatasourceTable table; private final DatasourceColumn keyColumn; private final DatasourceColumn dataColumn; DatasourceQuery(DatasourceTable table, DatasourceColumn keyColumn, DatasourceColumn dataColumn) { if (table == null) { throw new IllegalArgumentException("Incorrect input: table is null"); } if (keyColumn == null) { throw new IllegalArgumentException("Incorrect input: keyColumn is null"); } if (dataColumn == null) { throw new IllegalArgumentException("Incorrect input: dataColumn is null"); } this.table = table; this.keyColumn = keyColumn; this.dataColumn = dataColumn; } public String toString() { return "DatasourceQuery(keyColumn=" + this.getKeyColumn() + ", dataColumn=" + this.getDataColumn() + ")"; } }
# Generated by Django 3.2.7 on 2021-12-01 13:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("connector_airflow", "0017_cluster_auto_sync"), ] operations = [ migrations.AlterField( model_name="dag", name="sample_config", field=models.JSONField(blank=True, default=dict), ), migrations.AlterField( model_name="dagrun", name="conf", field=models.JSONField(blank=True, default=dict), ), ]
<reponame>danishkiani94/RC-RN-TEMPLATE import { StyleSheet } from 'react-native' export default StyleSheet.create({ applicationView: { flex: 1, }, container: { flex: 1, justifyContent: 'center', backgroundColor: 'white', }, welcome: { fontSize: 20, textAlign: 'center', }, myImage: { width: 200, height: 200, alignSelf: 'center', }, })
import os import re import sys from sys import version_info from . import porter_stemmer class Analyzer: """This app collects all of the words in a text file (which the user provides), removes any stop words found in another file (which the user also provides), removes all non-alphabetical text, stems all remaining words into their root form, computes the frequency of each term, and prints out the 20 most commonly occurring terms in descending order of frequency. """ def __init__(self): self.prompt = None self.establish_input_method() @staticmethod def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') @staticmethod def greeting(): print ('******************************************************************************************************') print (' Text File Analyzer') print ('******************************************************************************************************') print ('This app collects all of the words in a text file (which you provide), removes any stop words found') print ('in another file (which you also provide), removes all non-alphabetical text, stems all remaining') print ('words into their root form, computes the frequency of each term, and prints out the 20 most commonly') print ('occurring terms in descending order of frequency.') print('') def establish_input_method(self): if version_info.major == 3: # Python3 is being used, so use 'input' method self.prompt = input elif version_info.major == 2: # Python2 is being used, so use 'raw_input' method try: self.prompt = raw_input except NameError: pass def get_input_words(self): """Prompt user for input file location, read the file, then return a list of the words it contains """ filename = self.prompt("Please enter the path of the text file to be analyzed (e.g., input/Text1.txt): ") if os.path.isfile(filename): input_text = open(filename, 'r').read() return self.remove_punctuation(input_text) else: print("This file does not exist. Please try again.") return [] @staticmethod def remove_punctuation(text): """Remove punctuation from text; return list of each word in text""" return re.sub(r'[^\w\s]', '', text).split() def get_stopwords(self): """Prompt user for stopwords file location, read the file, then return a list of words it contains """ stopwords_file = self.prompt("Please enter the path of the stopwords file (e.g., input/stopwords.txt): ") if os.path.isfile(stopwords_file): # Create list of stopwords from file return open(stopwords_file, 'r').read().split() else: print("This file does not exist. Please try again.") return [] @staticmethod def remove_stop_words(input_words, stopwords): """Return a list of 'filtered_words' from the provided list of 'input_words' by removing any words from the provided list of 'stopwords' """ filtered_words = [] for word in input_words: if not word.lower() in stopwords: filtered_words.append(word) return filtered_words @staticmethod def stem(words): """Return a list of 'stemmed_words' from the provided list of 'words' by using a Porter Stemming Algorithm to stem all words to their morphological root (e.g., jumping, jumps, jumped -> jump) """ p = porter_stemmer.PorterStemmer() stemmed_words = [] for word in words: stemmed_words.append(p.stem(word, 0, len(word)-1)) return stemmed_words @staticmethod def compute_term_frequency(words): """Return a 'frequency' dict from the provided list of 'words' which contains each word (key) and the number of times it appears (value) """ frequency = dict() for word in words: if word not in frequency.keys(): frequency[word] = 1 else: frequency[word] += 1 return frequency @staticmethod def sort_top_terms(frequency, count): """Return a 'top_common_terms' list of tuples from the provided 'frequency' dict which contains the top 'count' number of key/value pairs, in descending order """ top_common_terms = [] all_common_terms = sorted(frequency.items(), key=lambda x: x[1], reverse=True) for i in range (count): top_common_terms.append(all_common_terms[i]) return top_common_terms @staticmethod def print_top_terms(terms): """Print the provided 'terms' list of tuples""" print('') print('After filtering out stopwords, the provided text contains these 20 most commonly occurring root terms:') print('------------------------------------------------------------------------------------------------------') for term in terms: print(term[0] + ' : ' + str(term[1]) + ' occurrences') print('')
import java.util.StringTokenizer; public class Tokenizer { public static void main(String[] args) { String str = "Hello World"; // Create the tokenizer StringTokenizer st = new StringTokenizer(str); // Create the array String[] arr = new String[st.countTokens()]; // Parse the input string into tokens for(int i = 0; i < st.countTokens(); i++){ arr[i] = st.nextToken(); } // Print the tokens for (String token : arr) { System.out.println(token); } } }
<gh_stars>0 package authenticator import ( "bytes" "context" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/url" "os" "time" "github.com/alesr/callbacksrv" "github.com/alesr/pocketoauth2/httputil" ) const ( authURLTemplate string = "https://getpocket.com/auth/authorize?request_token=%s&redirect_uri=%s" endpointAuthorize string = "/oauth/authorize" endpointRequestToken string = "/oauth/request" xErrorHeader string = "X-Error" // 1 minute since we need to wait for the user to authorize request token in the browser defaultAuthCtxTimeout time.Duration = time.Minute ) var ( _ Authenticator = (*Service)(nil) // Enumerate the possible errors that can be returned by the authenticator. ErrMissingConsumerKey = errors.New("missing consumer key") ErrMissingHost = errors.New("missing host") ErrMissingRedirectURI = errors.New("missing redirect URI") ) type Authenticator interface { Authenticate(ctx context.Context) (string, string, error) } type Service struct { // Dependencies httpCli *http.Client userAuthzChan chan struct{} // Configuration host string redirectURI string // Credentials consumerKey string accessToken string username string } func New(host string, consumerKey string, redirectURI string) (*Service, error) { // Input Validation if host == "" { return nil, ErrMissingHost } if consumerKey == "" { return nil, ErrMissingConsumerKey } if redirectURI == "" { return nil, ErrMissingRedirectURI } return &Service{ httpCli: httputil.BaseClient(), host: host, consumerKey: consumerKey, redirectURI: redirectURI, }, nil } func (s *Service) Authenticate(ctx context.Context) (string, string, error) { if s.accessToken != "" && s.username != "" { return s.accessToken, s.username, nil } authzCtx, cancel := context.WithTimeout(ctx, defaultAuthCtxTimeout) defer cancel() requestToken, err := s.obtainRequestToken(authzCtx) if err != nil { return "", "", err } authzURL := fmt.Sprintf(authURLTemplate, requestToken, s.redirectURI) notifyCh := make(chan struct{}, 1) quitCh := make(chan os.Signal, 1) go callbacksrv.Serve(notifyCh, quitCh) fmt.Printf("\n\nAwaiting user authorization:\n\t%s\n\n", authzURL) <-notifyCh quitCh <- os.Interrupt fmt.Print("Authorization granted!\n\n") accessToken, err := s.obtainAccessToken(authzCtx, requestToken) if err != nil { return "", "", err } s.accessToken = accessToken.Val s.username = accessToken.Username return accessToken.Val, accessToken.Username, nil } func (s *Service) ClearCredentials() { s.accessToken = "" s.username = "" } // obtainRequestToken obtains a request token from Pocket. func (s *Service) obtainRequestToken(ctx context.Context) (string, error) { reqTokenInput := requestTokenRequest{ ConsumerKey: s.consumerKey, RedirectURI: s.redirectURI, } b, err := json.Marshal(reqTokenInput) if err != nil { return "", fmt.Errorf("could not marshal request body: %s", err) } req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.host+endpointRequestToken, bytes.NewBuffer(b)) if err != nil { return "", fmt.Errorf("could not create request: %s", err) } resp, err := s.makeRequest(ctx, req, http.StatusOK) if err != nil { return "", fmt.Errorf("could not make request for request token: %s", err) } payload, err := ioutil.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("could not read response body: %s", err) } defer resp.Body.Close() values, err := url.ParseQuery(string(payload)) if err != nil { return "", fmt.Errorf("could not parse response body: %s", err) } requestToken := values.Get("code") if requestToken == "" { return "", errors.New("missing request token code in api response") } return requestToken, nil } // obtainAccessToken obtains an access token from Pocket given a request token. func (s *Service) obtainAccessToken(ctx context.Context, requestToken string) (*accessTokenResponse, error) { accessTokenReq := accessTokenRequest{ ConsumerKey: s.consumerKey, Code: requestToken, } b, err := json.Marshal(accessTokenReq) if err != nil { return nil, fmt.Errorf("could not marshal request body: %s", err) } req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.host+endpointAuthorize, bytes.NewBuffer(b)) if err != nil { return nil, fmt.Errorf("could not create request: %s", err) } resp, err := s.makeRequest(ctx, req, http.StatusOK) if err != nil { return nil, fmt.Errorf("could not make request for access token: %s", err) } payload, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("could not read response body: %s", err) } defer resp.Body.Close() values, err := url.ParseQuery(string(payload)) if err != nil { return nil, fmt.Errorf("could not parse response body: %s", err) } accessToken, username := values.Get("access_token"), values.Get("username") if accessToken == "" { return nil, errors.New("empty access token in API response") } return &accessTokenResponse{ Val: accessToken, Username: username, }, nil } func (s *Service) makeRequest(ctx context.Context, req *http.Request, expectedStatusCode int) (*http.Response, error) { req.Header.Set("Content-Type", "application/json; charset=UTF8") resp, err := s.httpCli.Do(req) if err != nil { return nil, fmt.Errorf("could not make request: %s", err) } if resp.StatusCode != expectedStatusCode { return nil, fmt.Errorf( "unexpected status code '%s': %s", http.StatusText(resp.StatusCode), resp.Header.Get(xErrorHeader), ) } return resp, nil }
###################################################################### # Copyright © 2021. TIBCO Software Inc. # This file is subject to the license terms contained # in the license file that is distributed with this file. ###################################################################### #!/bin/bash FSREST_BUILD_NUM=009 if [ ! -f license_accepted.txt ]; then read -p "You must accept the License Agreement before proceeding. Press ENTER key to read the License. Press q to finish reading." yn less ../../TIB_fs-restapi_1.0.0_license.txt while true; do read -p "Do you accept the license? (y/n) " yn case $yn in [Yy]* ) echo "You have accepted the license."; echo "License accepted on $(date)" > license_accepted.txt; break;; [Nn]* ) echo "you did not agree the License Agreement. Exiting the deployment!"; exit;; * ) echo "Please answer yes or no.";; esac done fi while true; do echo "Do you want to deploy TIBCO FSRest service?" read -p "(y/n) " yn case $yn in [Yy]* ) install_fsrest=yes; break;; [Nn]* ) break;; * ) echo "Please answer yes or no.";; esac done if [ "$install_fsrest" = "yes" ]; then source setenv.sh if [ "${DOCKER_REGISTRY}" = "" ]; then docker run --name fsrest --env-file=docker.env \ -d -p 30100:8080 fsrest:${FSREST_BUILD_NUM} else docker run --name fsrest --env-file=docker.env \ -d -p 30100:8080 ${DOCKER_REGISTRY}/fsrest:${FSREST_BUILD_NUM} fi fi echo "##########################################################################################" echo "Starting the docker container of TIBCO FSRest is finished now!!!" echo "##########################################################################################" echo exit
package com.prt2121.fire; import com.firebase.client.Firebase; import android.app.Application; /** * Created by pt2121 on 8/20/15. */ public class FireApp extends Application { @Override public void onCreate() { super.onCreate(); } }
function closestPackageJson(filePath: string): string | null { const path = require('path'); const fs = require('fs'); let currentDir = path.dirname(filePath); while (currentDir !== '/') { const packageJsonPath = path.join(currentDir, 'package.json'); if (fs.existsSync(packageJsonPath)) { return packageJsonPath; } currentDir = path.dirname(currentDir); } return null; }
import { boosts } from "./boosts/boosts.js"; import { boostShop } from "./boosts/boosts-shop.js"; // the S stands for Shop export interface SItem { name: string; description: string; cost: number | string; // in cycles tpc?: number | string; cpp?: number | string; tpm?: number | string; ref?: number; // ref for boosts } // upgrades are tpc, idles are tpm export const items: { upgrades: SItem[], cpp: SItem[], idle: SItem[], boosts: SItem[] } = { upgrades: [{ name: "Inspiration", description: "The idea is the start of everything!", cost: 10, tpc: 1 }, { name: "Typing.com", description: "Time to learn to type!", cost: 12, tpc: 5 }, { name: "NotePad", description: "A featureless editor", cost: 16, tpc: 10 }, { name: "Pastebin", description: "Nowhere else to host", cost: 21, tpc: 15 }, { name: "Hastebin", description: "It's pastebin but with an H!", cost: 90, tpc: 45 }, { name: "NotePad++", description: "It's evolution! Still featureless...", cost: 115, tpc: 50 }, { name: "SourceB.in", description: "Another bin?!?", cost: 146, tpc: 55 }, { name: "Whitespace", description: "[ ] [\t]", cost: 304, tpc: 70 }, { name: "Indentation Error", description: "Did you use four spaces?!?", cost: 495, tpc: 80 }, { name: "Windows Powershell", description: "At least `clear` works", cost: 1315, tpc: 100 }, { name: "NullPointerException", description: "Segmentation fault (core dumped)", cost: 3489, tpc: 120 }, { name: "Stack Overflow", description: "To understand recursion, you must first understand recursion.", cost: 15079, tpc: 150 }, { name: "Windows Powershell+", description: "The better version of Windows Powershell.", cost: 51065, tpc: 175 }, { name: "Stack Overflow II", description: "That place where you ask questions", cost: 172925, tpc: 200 }, { name: "Hoisting", description: "Use it before you define it!", cost: "1983009", tpc: 250 }, { name: "Personal Care Robot", description: "You now don't have to spend time combing your hair all day!", cost: "9537000000000", tpc: 300 }, { name: "<NAME>", description: "The ultimate mouse.", cost: "2.274e7", tpc: 400 }, { name: "Github account", description: "Don't lose any of your code!", cost: "3.429e10", tpc: 450 }, { name: "Learn a new language", description: "Now you can share even more code!", cost: "3.9323e11", tpc: 500 }], cpp: [{ name: "Popular", description: "You are now slightly popular.", cost: 10, cpp: 1 }, { name: "Meme", description: "Haha funnies", cost: 14, cpp: 5 }, { name: "Friends", description: "bff", cost: 19, cpp: 10 }, { name: "Subscribers", description: "A real subscriber!", cost: 27, cpp: 15 }, { name: "Paparazzi", description: "Get in those shots!", cost: 38, cpp: 20 }, { name: "Internet Stranger", description: "The best kind of fan!", cost: 76, cpp: 30 }, { name: "<NAME>", description: "Uhh... that's too much?!", cost: 149, cpp: 40 }, { name: "Yourself", description: "Nobody loves me like me", cost: 295, cpp: 50 }, { name: "<NAME>", description: "When friend just isn't enough", cost: 580, cpp: 60 }, { name: "Mailing List", description: "They were probably tricked into it", cost: 1140, cpp: 70 }, { name: "Advertisement", description: "Is it really worth it?", cost: 1600, cpp: 75 }, { name: "Tracking", description: "Personalized fans!", cost: 2242, cpp: 80 }, { name: "Significant Other", description: "<3", cost: 4411, cpp: 90 }, { name: "<NAME>", description: "They support you... no matter what!", cost: 8677, cpp: 100 }, { name: "Bot", description: "Backup when all else fails", cost: 17069, cpp: 110 }, { name: "AI Bot", description: "Acts like a fan, but is it a fan?", cost: 23940, cpp: 120 }, { name: "Superiority Complex", description: "I'm the best! Probably! Maybe...", cost: 47094, cpp: 125 }], idle: [{ name: "Idle Machine", description: "Your first idle!", cost: 5, tpm: 1 }, { name: "Code Robot", description: "Please click all the bugs to continue.", cost: 21, tpm: 5 }, { name: "StackOverflow Commitee", description: "Free code review!", cost: 41, tpm: 10 }, { name: "Intern", description: "Free code!", cost: 61, tpm: 15 }, { name: "Code AI", description: "One day it'll write binary", cost: 81, tpm: 20 }, { name: "Debugger", description: "Isn't that just spamming prints?", cost: 101, tpm: 25 }, { name: "<NAME>", description: "There is nothing you can't hack anymore.", cost: 121, tpm: 30 }, { name: "Macros", description: "Let the code do it's job!", cost: 141, tpm: 35 }, { name: "VSCode Debugger", description: "Now you debug all your code... Without prints!", cost: 161, tpm: 40 }, { name: "<NAME>", description: "I mean you payed for it...", cost: 181, tpm: 45 }, { name: "Google", description: "Google is your best friend... When it works!", cost: 201, tpm: 50 }, { name: "Bing", description: "There's search engines, and then there's bing", cost: 221, tpm: 55 }, { name: "<NAME>", description: "The OG coder remastered!", cost: 241, tpm: 60 }, { name: "Discord Server", description: "Get distracted in #bots with a bot called Cycle!", cost: 261, tpm: 65 }, { name: "Slack Server", description: "Slack off", cost: 281, tpm: 70 }, { name: "Linter", description: "Your worst enemy! But it helps you?", cost: 301, tpm: 75 }, { name: "Eslint", description: "Don't forget to spend time configuring it!", cost: 341, tpm: 85 }, { name: "Webpack", description: "Now you can generate small code!", cost: 381, tpm: 95 }, { name: "Jest", description: "Test-Driven Development is the best!", cost: 401, tpm: 100 }], boosts: boostShop.map(n => { const ref = boosts[n.ref]; return { name: ref.name, description: ref.description, cost: n.cost, ref: n.ref }; }) };
<gh_stars>0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package brooklyn.demo; import javax.jms.Connection; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.qpid.client.AMQConnectionFactory; import org.apache.qpid.configuration.ClientProperties; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; /** Publishes messages to a queue on a Qpid broker at a given URL. */ public class Publish { public static final String QUEUE = "'amq.direct'/'testQueue'; { node: { type: queue } }"; public static void main(String...argv) throws Exception { Preconditions.checkElementIndex(0, argv.length, "Must specify broker URL"); String url = argv[0]; // Set Qpid client properties System.setProperty(ClientProperties.AMQP_VERSION, "0-10"); System.setProperty(ClientProperties.DEST_SYNTAX, "ADDR"); // Connect to the broker AMQConnectionFactory factory = new AMQConnectionFactory(url); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { // Create a producer for the queue Queue destination = session.createQueue(QUEUE); MessageProducer messageProducer = session.createProducer(destination); // Send 100 messages for (int n = 0; n < 100; n++) { String body = String.format("test message %03d", n+1); TextMessage message = session.createTextMessage(body); messageProducer.send(message); System.out.printf("Sent message %s\n", body); } } catch (Exception e) { System.err.printf("Error while sending - %s\n", e.getMessage()); System.err.printf("Cause: %s\n", Throwables.getStackTraceAsString(e)); } finally { session.close(); connection.close(); } } }
///////////////////////////////////////////////////////////////////////////// // Name: emulator.cpp // Purpose: Emulator wxWidgets sample // Author: <NAME> // Modified by: // Created: 04/01/98 // Copyright: (c) <NAME> // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWidgets headers) #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wx/confbase.h" #include "wx/fileconf.h" #include "wx/cmdline.h" #include "wx/image.h" #include "wx/file.h" #include "wx/filename.h" #ifdef __WXX11__ #include "wx/x11/reparent.h" #endif #include "emulator.h" // ---------------------------------------------------------------------------- // resources // ---------------------------------------------------------------------------- // the application icon (under Windows it is in resources) #ifndef wxHAS_IMAGES_IN_RESOURCES #include "emulator.xpm" #endif // ---------------------------------------------------------------------------- // event tables and other macros for wxWidgets // ---------------------------------------------------------------------------- // the event tables connect the wxWidgets events with the functions (event // handlers) which process them. It can be also done at run-time, but for the // simple menu events like this the static method is much simpler. wxBEGIN_EVENT_TABLE(wxEmulatorFrame, wxFrame) EVT_MENU(Emulator_Quit, wxEmulatorFrame::OnQuit) EVT_MENU(Emulator_About, wxEmulatorFrame::OnAbout) EVT_CLOSE(wxEmulatorFrame::OnCloseWindow) wxEND_EVENT_TABLE() // Create a new application object: this macro will allow wxWidgets to create // the application object during program execution (it's better than using a // static object for many reasons) and also declares the accessor function // wxGetApp() which will return the reference of the right type (i.e. wxEmulatorApp and // not wxApp) wxIMPLEMENT_APP(wxEmulatorApp); static const wxCmdLineEntryDesc sg_cmdLineDesc[] = { { wxCMD_LINE_OPTION, "u", "use-display", "display number to use (default 100)" }, { wxCMD_LINE_SWITCH, "h", "help", "displays help on the command line parameters" }, { wxCMD_LINE_SWITCH, "v", "version", "print version" }, { wxCMD_LINE_PARAM, NULL, NULL, "config file 1", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL }, wxCMD_LINE_DESC_END }; // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // the application class // ---------------------------------------------------------------------------- wxEmulatorApp::wxEmulatorApp() { m_xnestWindow = NULL; m_containerWindow = NULL; m_displayNumber = wxT("100"); m_xnestPID = 0; } // 'Main program' equivalent: the program execution "starts" here bool wxEmulatorApp::OnInit() { #if wxUSE_LOG wxLog::DisableTimestamp(); #endif // wxUSE_LOG wxInitAllImageHandlers(); wxString currentDir = wxGetCwd(); // Use argv to get current app directory m_appDir = wxFindAppPath(argv[0], currentDir, wxT("WXEMUDIR")); // If the development version, go up a directory. #ifdef __WXMSW__ if ((m_appDir.Right(5).CmpNoCase(wxT("DEBUG")) == 0) || (m_appDir.Right(11).CmpNoCase(wxT("DEBUGSTABLE")) == 0) || (m_appDir.Right(7).CmpNoCase(wxT("RELEASE")) == 0) || (m_appDir.Right(13).CmpNoCase(wxT("RELEASESTABLE")) == 0) ) m_appDir = wxPathOnly(m_appDir); #endif // Parse the command-line parameters and options wxCmdLineParser parser(sg_cmdLineDesc, argc, argv); int res; { wxLogNull log; res = parser.Parse(); } if (res == -1 || res > 0 || parser.Found(wxT("h"))) { #ifdef __X__ wxLog::SetActiveTarget(new wxLogStderr); #endif parser.Usage(); return false; } if (parser.Found(wxT("v"))) { #ifdef __X__ wxLog::SetActiveTarget(new wxLogStderr); #endif wxString msg; msg.Printf(wxT("wxWidgets PDA Emulator (c) <NAME>, 2002 Version %.2f, %s"), wxEMULATOR_VERSION, __DATE__); wxLogMessage(msg); return false; } if (parser.Found(wxT("u"), & m_displayNumber)) { // Should only be number, so strip out anything before // and including a : character if (m_displayNumber.Find(wxT(':')) != -1) { m_displayNumber = m_displayNumber.AfterFirst(wxT(':')); } } if (parser.GetParamCount() == 0) { m_emulatorInfo.m_emulatorFilename = wxT("default.wxe"); } else if (parser.GetParamCount() > 0) { m_emulatorInfo.m_emulatorFilename = parser.GetParam(0); } // Load the emulation info if (!LoadEmulator(m_appDir)) { //wxMessageBox(wxT("Sorry, could not load this emulator. Please check bitmaps are valid.")); return false; } // create the main application window wxEmulatorFrame *frame = new wxEmulatorFrame(wxT("wxEmulator"), wxPoint(50, 50), wxSize(450, 340)); #if wxUSE_STATUSBAR frame->SetStatusText(m_emulatorInfo.m_emulatorTitle, 0); wxString sizeStr; sizeStr.Printf(wxT("Screen: %dx%d"), (int) m_emulatorInfo.m_emulatorScreenSize.x, (int) m_emulatorInfo.m_emulatorScreenSize.y); frame->SetStatusText(sizeStr, 1); #endif // wxUSE_STATUSBAR m_containerWindow = new wxEmulatorContainer(frame, wxID_ANY); frame->SetClientSize(m_emulatorInfo.m_emulatorDeviceSize.x, m_emulatorInfo.m_emulatorDeviceSize.y); // and show it (the frames, unlike simple controls, are not shown when // created initially) frame->Show(true); #ifdef __WXX11__ m_xnestWindow = new wxAdoptedWindow; wxString cmd; cmd.Printf(wxT("Xnest :%s -geometry %dx%d"), m_displayNumber.c_str(), (int) m_emulatorInfo.m_emulatorScreenSize.x, (int) m_emulatorInfo.m_emulatorScreenSize.y); // Asynchronously executes Xnest m_xnestPID = wxExecute(cmd); if (0 == m_xnestPID) { frame->Destroy(); wxMessageBox(wxT("Sorry, could not run Xnest. Please check your PATH.")); return false; } wxReparenter reparenter; if (!reparenter.WaitAndReparent(m_containerWindow, m_xnestWindow, wxT("Xnest"))) { wxMessageBox(wxT("Sorry, could not reparent Xnest..")); frame->Destroy(); return false; } #endif m_containerWindow->DoResize(); // success: wxApp::OnRun() will be called which will enter the main message // loop and the application will run. If we returned false here, the // application would exit immediately. return true; } // Prepend the current program directory to the name wxString wxEmulatorApp::GetFullAppPath(const wxString& filename) const { wxString path(m_appDir); if (path.Last() != '\\' && path.Last() != '/' && filename[0] != '\\' && filename[0] != '/') #ifdef __X__ path += '/'; #else path += '\\'; #endif path += filename; return path; } // Load the specified emulator. // For now, hard-wired. TODO: make this configurable bool wxEmulatorApp::LoadEmulator(const wxString& appDir) { // Load config file and bitmaps return m_emulatorInfo.Load(appDir); } // ---------------------------------------------------------------------------- // main frame // ---------------------------------------------------------------------------- // frame constructor wxEmulatorFrame::wxEmulatorFrame(const wxString& title, const wxPoint& pos, const wxSize& size) : wxFrame(NULL, wxID_ANY, title, pos, size) { // set the frame icon SetIcon(wxICON(emulator)); #if wxUSE_MENUS // create a menu bar wxMenu *menuFile = new wxMenu; // the "About" item should be in the help menu wxMenu *helpMenu = new wxMenu; helpMenu->Append(Emulator_About, wxT("&About\tF1"), wxT("Show about dialog")); menuFile->Append(Emulator_Quit, wxT("E&xit\tAlt-X"), wxT("Quit this program")); // now append the freshly created menu to the menu bar... wxMenuBar *menuBar = new wxMenuBar(); menuBar->Append(menuFile, wxT("&File")); menuBar->Append(helpMenu, wxT("&Help")); // ... and attach this menu bar to the frame SetMenuBar(menuBar); #endif // wxUSE_MENUS #if wxUSE_STATUSBAR // create a status bar just for fun (by default with 1 pane only) CreateStatusBar(2); #endif // wxUSE_STATUSBAR } // event handlers void wxEmulatorFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) { // true is to force the frame to close Close(true); } void wxEmulatorFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) { wxString msg; msg.Printf( wxT("wxEmulator is an environment for testing embedded X11 apps.\n")); wxMessageBox(msg, wxT("About wxEmulator"), wxOK | wxICON_INFORMATION, this); } void wxEmulatorFrame::OnCloseWindow(wxCloseEvent& WXUNUSED(event)) { #ifdef __WXX11__ if (wxGetApp().m_xnestWindow) { wxGetApp().m_xnestWindow->SetHandle((WXWindow) NULL); } #endif this->Destroy(); if (wxGetApp().m_xnestPID > 0) { wxKill(wxGetApp().m_xnestPID); wxGetApp().m_xnestPID = 0; } } wxIMPLEMENT_CLASS(wxEmulatorContainer, wxWindow); wxBEGIN_EVENT_TABLE(wxEmulatorContainer, wxWindow) EVT_SIZE(wxEmulatorContainer::OnSize) EVT_PAINT(wxEmulatorContainer::OnPaint) EVT_ERASE_BACKGROUND(wxEmulatorContainer::OnEraseBackground) wxEND_EVENT_TABLE() wxEmulatorContainer::wxEmulatorContainer(wxWindow* parent, wxWindowID id): wxWindow(parent, id, wxDefaultPosition, wxDefaultSize) { } void wxEmulatorContainer::OnSize(wxSizeEvent& WXUNUSED(event)) { DoResize(); } void wxEmulatorContainer::DoResize() { wxSize sz = GetClientSize(); if (wxGetApp().m_xnestWindow #ifdef __WXX11__ && wxGetApp().m_xnestWindow->X11GetMainWindow() #endif ) { int deviceWidth = wxGetApp().m_emulatorInfo.m_emulatorDeviceSize.x; int deviceHeight = wxGetApp().m_emulatorInfo.m_emulatorDeviceSize.y; int x = wxMax(0, (int) ((sz.x - deviceWidth)/2.0)); int y = wxMax(0, (int) ((sz.y - deviceHeight)/2.0)); x += wxGetApp().m_emulatorInfo.m_emulatorScreenPosition.x; y += wxGetApp().m_emulatorInfo.m_emulatorScreenPosition.y; wxGetApp().m_xnestWindow->Move(x, y); } Refresh(); } void wxEmulatorContainer::OnPaint(wxPaintEvent& WXUNUSED(event)) { wxPaintDC dc(this); wxSize sz = GetClientSize(); if (wxGetApp().m_emulatorInfo.m_emulatorBackgroundBitmap.IsOk()) { int deviceWidth = wxGetApp().m_emulatorInfo.m_emulatorDeviceSize.x; int deviceHeight = wxGetApp().m_emulatorInfo.m_emulatorDeviceSize.y; int x = wxMax(0, (int) ((sz.x - deviceWidth)/2.0)); int y = wxMax(0, (int) ((sz.y - deviceHeight)/2.0)); dc.DrawBitmap(wxGetApp().m_emulatorInfo.m_emulatorBackgroundBitmap, x, y); } } void wxEmulatorContainer::OnEraseBackground(wxEraseEvent& event) { wxDC* dc wxDUMMY_INITIALIZE(NULL); if (event.GetDC()) { dc = event.GetDC(); } else { dc = new wxClientDC(this); } dc->SetBackground(wxBrush(wxGetApp().m_emulatorInfo.m_emulatorBackgroundColour)); dc->Clear(); if (!event.GetDC()) delete dc; } // Information about the emulator decorations void wxEmulatorInfo::Copy(const wxEmulatorInfo& info) { m_emulatorFilename = info.m_emulatorFilename; m_emulatorTitle = info.m_emulatorTitle; m_emulatorDescription = info.m_emulatorDescription; m_emulatorScreenPosition = info.m_emulatorScreenPosition; m_emulatorScreenSize = info.m_emulatorScreenSize; m_emulatorBackgroundBitmap = info.m_emulatorBackgroundBitmap; m_emulatorBackgroundBitmapName = info.m_emulatorBackgroundBitmapName; m_emulatorBackgroundColour = info.m_emulatorBackgroundColour; m_emulatorDeviceSize = info.m_emulatorDeviceSize; } // Initialisation void wxEmulatorInfo::Init() { m_emulatorDeviceSize = wxSize(260, 340); m_emulatorScreenSize = wxSize(240, 320); } // Loads bitmaps bool wxEmulatorInfo::Load(const wxString& appDir) { // Try to find absolute path wxString absoluteConfigPath = m_emulatorFilename; if ( !::wxIsAbsolutePath(absoluteConfigPath) ) { wxString currDir = wxGetCwd(); absoluteConfigPath = currDir + wxString(wxFILE_SEP_PATH) + m_emulatorFilename; if ( !wxFile::Exists(absoluteConfigPath) ) { absoluteConfigPath = appDir + wxString(wxFILE_SEP_PATH) + m_emulatorFilename; } } if ( !wxFile::Exists(absoluteConfigPath) ) { wxString str; str.Printf( wxT("Could not find config file %s"), absoluteConfigPath.c_str() ); wxMessageBox(str); return false; } wxString rootPath = wxPathOnly(absoluteConfigPath); { wxFileConfig config(wxT("wxEmulator"), wxT("wxWidgets"), absoluteConfigPath, wxEmptyString, wxCONFIG_USE_LOCAL_FILE); config.Read(wxT("/General/title"), & m_emulatorTitle); config.Read(wxT("/General/description"), & m_emulatorDescription); config.Read(wxT("/General/backgroundBitmap"), & m_emulatorBackgroundBitmapName); wxString colString; if (config.Read(wxT("/General/backgroundColour"), & colString) || config.Read(wxT("/General/backgroundColor"), & colString) ) { m_emulatorBackgroundColour = wxHexStringToColour(colString); } int x = 0, y = 0, w = 0, h = 0, dw = 0, dh = 0; config.Read(wxT("/General/screenX"), & x); config.Read(wxT("/General/screenY"), & y); config.Read(wxT("/General/screenWidth"), & w); config.Read(wxT("/General/screenHeight"), & h); if (config.Read(wxT("/General/deviceWidth"), & dw) && config.Read(wxT("/General/deviceHeight"), & dh)) { m_emulatorDeviceSize = wxSize(dw, dh); } m_emulatorScreenPosition = wxPoint(x, y); m_emulatorScreenSize = wxSize(w, h); } if (!m_emulatorBackgroundBitmapName.empty()) { wxString absoluteBackgroundBitmapName = rootPath + wxString(wxFILE_SEP_PATH) + m_emulatorBackgroundBitmapName; if ( !wxFile::Exists(absoluteBackgroundBitmapName) ) { wxString str; str.Printf( wxT("Could not find bitmap %s"), absoluteBackgroundBitmapName.c_str() ); wxMessageBox(str); return false; } wxBitmapType type = wxDetermineImageType(m_emulatorBackgroundBitmapName); if (type == wxBITMAP_TYPE_INVALID) return false; if (!m_emulatorBackgroundBitmap.LoadFile(m_emulatorBackgroundBitmapName, type)) { wxString str; str.Printf( wxT("Could not load bitmap file %s"), m_emulatorBackgroundBitmapName.c_str() ); wxMessageBox(str); return false; } m_emulatorDeviceSize = wxSize(m_emulatorBackgroundBitmap.GetWidth(), m_emulatorBackgroundBitmap.GetHeight()); } return true; } // Returns the image type, or -1, determined from the extension. wxBitmapType wxDetermineImageType(const wxString& filename) { wxString path, name, ext; wxFileName::SplitPath(filename, & path, & name, & ext); ext.MakeLower(); if (ext == wxT("jpg") || ext == wxT("jpeg")) return wxBITMAP_TYPE_JPEG; if (ext == wxT("gif")) return wxBITMAP_TYPE_GIF; if (ext == wxT("bmp")) return wxBITMAP_TYPE_BMP; if (ext == wxT("png")) return wxBITMAP_TYPE_PNG; if (ext == wxT("pcx")) return wxBITMAP_TYPE_PCX; if (ext == wxT("tif") || ext == wxT("tiff")) return wxBITMAP_TYPE_TIFF; return wxBITMAP_TYPE_INVALID; } // Convert a colour to a 6-digit hex string wxString wxColourToHexString(const wxColour& col) { wxString hex; hex += wxDecToHex(col.Red()); hex += wxDecToHex(col.Green()); hex += wxDecToHex(col.Blue()); return hex; } // Convert 6-digit hex string to a colour wxColour wxHexStringToColour(const wxString& hex) { unsigned char r = (unsigned char)wxHexToDec(hex.Mid(0, 2)); unsigned char g = (unsigned char)wxHexToDec(hex.Mid(2, 2)); unsigned char b = (unsigned char)wxHexToDec(hex.Mid(4, 2)); return wxColour(r, g, b); } // Find the absolute path where this application has been run from. // argv0 is wxTheApp->argv[0] // cwd is the current working directory (at startup) // appVariableName is the name of a variable containing the directory for this app, e.g. // MYAPPDIR. This is checked first. wxString wxFindAppPath(const wxString& argv0, const wxString& cwd, const wxString& appVariableName) { wxString str; // Try appVariableName if (!appVariableName.empty()) { str = wxGetenv(appVariableName); if (!str.empty()) return str; } if (wxIsAbsolutePath(argv0)) return wxPathOnly(argv0); else { // Is it a relative path? wxString currentDir(cwd); if (!wxEndsWithPathSeparator(currentDir)) currentDir += wxFILE_SEP_PATH; str = currentDir + argv0; if ( wxFile::Exists(str) ) return wxPathOnly(str); } // OK, it's neither an absolute path nor a relative path. // Search PATH. wxPathList pathList; pathList.AddEnvList(wxT("PATH")); str = pathList.FindAbsoluteValidPath(argv0); if (!str.empty()) return wxPathOnly(str); // Failed return wxEmptyString; }
cat "underscore.js" "encoding.js" "common.js" "log-full.js" "mime.js" "buffer.js" "request.js" "crypto.js" "stream.js" "chromesocketxhr.js" "connection.js" "webapp.js" "websocket.js" "upnp.js" "handlers.js" "httplib.js" > wsc-chrome.min.js
<filename>src/js/upload.js $(document).ready(init()); function init() { $('.file-upload-modal .modal-content form').submit(function (e) { upload(e); }); } function upload(e) { e.preventDefault(); var fileName = $('.file-upload-modal .modal-content form').find("input[type=file], textarea").val(); var formData = new FormData($('.file-upload-modal .modal-content form')[0]); if (fileName === "") { bootbox.alert("No file choosen"); return; } $('#loadingModal').modal('show'); $('#fileUploadModal > div').addClass('hidden'); $.ajax({ url: '/file/do_upload', type: 'POST', data: formData, // async: false, cache: false, contentType: false, processData: false, success: function (data) { var returnedData = jQuery.parseJSON(data); $('#loadingModal').modal('hide'); if (returnedData["error"]) { bootbox.alert(returnedData["error_msg"], function(){ $('#fileUploadModal > div').removeClass('hidden'); }); } else { location.reload(); } }, error: function(){ $('#fileUploadModal > div').removeClass('hidden'); bootbox.alert('Something went wrong! Please try again'); } }); return false; }
#!/bin/sh # script for execution of deployed applications # # Sets up the MCR environment for the current $ARCH and executes # the specified command. # exe_name=$0 exe_dir=`dirname "$0"` echo "------------------------------------------" if [ "x$1" = "x" ]; then echo Usage: echo $0 \<deployedMCRroot\> args else echo Setting up environment variables MCRROOT="$1" echo --- LD_LIBRARY_PATH=.:${MCRROOT}/runtime/glnxa64 ; LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/bin/glnxa64 ; LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/sys/os/glnxa64; export LD_LIBRARY_PATH; echo LD_LIBRARY_PATH is ${LD_LIBRARY_PATH}; shift 1 args= while [ $# -gt 0 ]; do token=$1 args="${args} \"${token}\"" shift done eval "\"${exe_dir}/compute_multi_flow\"" $args fi exit
package main; import java.util.Scanner; public class DisplayCalendar { public static void main(String[] args) { Scanner input = new Scanner(System.in); int year = -1; while (year < 0) { System.out.print("Enter the year (Must be positive): "); year = input.nextInt(); } int day = -1; while ((day < 0) || (day > 6)) { System.out.print("Enter the first day of " + year + " (0-6) (0 = Sunday, 1 = Monday, ..., 6 = Saturday): "); day = input.nextInt(); } for (int month = 1; month <= 12; month++) { switch (month) { case 1: System.out.printf("%25s", "January"); break; case 2: System.out.printf("%26s", "February"); break; case 3: System.out.printf("%23s", "March"); break; case 4: System.out.printf("%23s", "April"); break; case 5: System.out.printf("%21s", "May"); break; case 6: System.out.printf("%22s", "June"); break; case 7: System.out.printf("%22s", "July"); break; case 8: System.out.printf("%24s", "August"); break; case 9: System.out.printf("%27s", "September"); break; case 10: System.out.printf("%25s", "October"); break; case 11: System.out.printf("%26s", "November"); break; case 12: System.out.printf("%26s", "December"); break; } System.out.println(" " + year); System.out.println("___________________________________________________"); System.out.println("Sun\tMon\tTues\tWed\tThu\tFri\tSat"); int daysOfCurrentMonth = 28; if (month == 2) { // Check if the year is a leap year boolean isLeapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); if (isLeapYear) { daysOfCurrentMonth = 29; } } else if (((month < 7) && (month % 2 == 0)) || ((month > 7) && (month % 2 == 1))) { daysOfCurrentMonth = 30; } else { daysOfCurrentMonth = 31; } int count = (day % 7); for (int spacing = 0; spacing < count; spacing++) { System.out.print("\t"); } for (int monthDay = 1; monthDay <= daysOfCurrentMonth; monthDay++) { if ((count % 7 == 0) && (monthDay > 1)) { System.out.printf("\n%2d\t", monthDay); } else { System.out.printf("%2d\t", monthDay); } count++; } System.out.println("\n"); day += daysOfCurrentMonth; } input.close(); } }
#!/bin/bash gcloud endpoints services deploy openapi-functions.yaml --project shadowsocks-218808
<gh_stars>0 package com.zhcs.utils; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; //***************************************************************************** /** * <p>Title:StringUtil</p> * <p>Description:字符串工具类</p> * <p>Copyright: Copyright (c) 2017</p> * <p>Company: 深圳市智慧城市管家信息科技有限公司</p> * @author 刘晓东 - Alter * @version v1.0 2017年2月23日 */ //***************************************************************************** public class StringUtil extends StringUtils { public static final SerializerFeature[] DEFAULT_FORMAT = {SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteEnumUsingToString, SerializerFeature.WriteNonStringKeyAsString, SerializerFeature.QuoteFieldNames, SerializerFeature.SkipTransientField, SerializerFeature.SortField, SerializerFeature.PrettyFormat}; //************************************************************************* /** * 【轉換】將以,分割的字符串轉換成字符串數組 * @param valStr * @return */ //************************************************************************* public static String[] StrList(String valStr){ int i = 0; String TempStr = valStr; String[] returnStr = new String[valStr.length() + 1 - TempStr.replace(",", "").length()]; valStr = valStr + ","; while (valStr.indexOf(',') > 0) { returnStr[i] = valStr.substring(0, valStr.indexOf(',')); valStr = valStr.substring(valStr.indexOf(',')+1 , valStr.length()); i++; } return returnStr; } //************************************************************************* /** * 【替換】字符串替換 * @param s 待替换的字符串 * @param s1 替换部分 * @param s2 替换值 * @return String 替换后的字符串 */ //************************************************************************* public static String replace(String s, String s1, String s2) { StringBuffer stringbuffer = new StringBuffer(); int i = s1.length(); for (int j = 0; (j = s.indexOf(s1)) != -1;) { stringbuffer.append(s.substring(0, j) + s2); s = s.substring(j + i); } stringbuffer.append(s); return stringbuffer.toString(); } //************************************************************************* /** * 【判斷】判斷字符串是否有效 * @param obj * @return */ //************************************************************************* @SuppressWarnings("rawtypes") public static boolean isValid(Object obj) { if (obj == null) { return false; } else if ((obj instanceof String) && obj.toString().trim().length() == 0) { return false; } else if ((obj instanceof List) && ((List) obj).size() == 0) { return false; } else if ((obj instanceof Map) && ((Map) obj).keySet().size() == 0) { return false; } return true; } //************************************************************************* /** * 【判斷】判斷字符串是否無效 * @param obj * @return */ //************************************************************************* public static boolean isBlank(Object obj) { return !isValid(obj); } //************************************************************************* /** * 【判斷】判斷字符串是否是int類型 * @param str * @return */ //************************************************************************* public static boolean isInt(String str) { if (str == null) return false; Pattern pattern = Pattern.compile("[-+]{0,1}[0-9]+"); return pattern.matcher(str).matches(); } //************************************************************************* /** * 【轉換】將字符串數字轉換成int * @param sInt * @return */ //************************************************************************* public static Integer strToInteger(String sInt) { Integer iRtn = 0; if (sInt == null || "".equals(sInt)) return 0; try { iRtn = Integer.valueOf(sInt); } catch (Exception e) { } return iRtn; } //************************************************************************* /** * 【轉換】將object類型的數據轉換成string類型數據 * @param obj * @return */ //************************************************************************* public static String valueOf(Object obj) { if (obj == null) { return ""; } else { return String.valueOf(obj); } } //************************************************************************* /** * 【轉換】將object類型的數據轉換成string類型數據,無限噢時將返回默認值 * @param obj 待轉換數據 * @param defaultString 默認值 * @return */ //************************************************************************* public static String valueOf(Object obj, String defaultString) { if (obj == null) { return defaultString; } else { return String.valueOf(obj); } } //************************************************************************* /** * 【過濾】過濾json類型字符串 * @param content * @return */ //************************************************************************* public static String filterJsonChar(String content) { StringBuilder sb = new StringBuilder(content.length() + 20); for (int i = 0; i < content.length(); i++) { char c = content.charAt(i); switch (c) { case '\"': sb.append("\\\""); break; case '\\': sb.append("\\\\"); break; case '/': sb.append("\\/"); break; case '\b': sb.append("\\b"); break; case '\f': sb.append("\\f"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; default: sb.append(c); } } return sb.toString(); } //************************************************************************* /** * 【取得】四捨五入取指定數字 * @param number 數字 * @param sacle 小數位數 * @return */ //************************************************************************* public static double round(double number, int sacle) { BigDecimal b = new BigDecimal(number); double f1 = b.setScale(sacle, BigDecimal.ROUND_HALF_UP).doubleValue(); return f1; } //************************************************************************* /** * 【取得】捨去指定小數位數數字 * @param number 數字 * @param sacle 捨去小數位數 * @return */ //************************************************************************* public static double fix(double number, int sacle) { String num = StringUtil.valueOf(number); int idx = num.indexOf("."); if (idx == -1) { return number; } else { String s = num.substring(idx); num = num.substring(0, idx) + s.substring(0, sacle+1 < s.length() ? sacle+1 : s.length()); } return Double.parseDouble(num); } //************************************************************************* /** * 【取得】向上取整 * @param number * @return */ //************************************************************************* public static double ceil(double number) { return Math.ceil(number); } //************************************************************************* /** * 【取得】向下取整 * @param number * @return */ //************************************************************************* public static double floor(double number) { return Math.floor(number); } //************************************************************************* /** * 【取得】將手機號碼的關鍵數字進行*替換 * @param number * @return */ //************************************************************************* public static String ReplaceMobile(String number) { return number.replaceAll("(?<=\\d{3})\\d(?=\\d{4})", "*"); } //************************************************************************* /** * 【取得】補零方法 * @param strSource 原字符串 * @param iLen 所需長度 * @param iDirection 0 表示左補零 其它表示右補零 * @return */ //************************************************************************* public static String fillZero(String strSource, int iLen, int iDirection) { if (strSource == null) return ""; if (strSource.length() > iLen) { return strSource.substring(0, iLen); } if (iDirection == 0) { return StringUtil.leftPad(strSource, iLen, "0"); } else { return StringUtil.rightPad(strSource, iLen, "0"); } } //************************************************************************* /** * 【轉換】將字符串數組轉換成為List * @param array * @return */ //************************************************************************* public static List<String> array2list(String[] array){ List<String> list = new ArrayList<String>(); Collections.addAll(list, array); return list; } //************************************************************************* /** * 【轉換】將string類型數據轉換成ASCII碼 * @param value * @return */ //************************************************************************* public static String stringToAscii(String value) { StringBuffer sbu = new StringBuffer(); char[] chars = value.toCharArray(); for (int i = 0; i < chars.length; i++) { if(i != chars.length - 1) { sbu.append((int)chars[i]).append(","); } else { sbu.append((int)chars[i]); } } return StringUtil.valueOf(sbu); } //************************************************************************* /** * 【轉換】將ASCII碼數據轉換成爲string類型數據 * @param value * @return */ //************************************************************************* public static String asciiToString(String value) { StringBuffer sbu = new StringBuffer(); String[] chars = value.split(","); for (int i = 0; i < chars.length; i++) { sbu.append((char) Integer.parseInt(chars[i])); } return StringUtil.valueOf(sbu); } //************************************************************************* /** * 【取得】過濾html標簽 * @param s * @return */ //************************************************************************* public static String guoHtml(String s) { if (StringUtil.isValid(s)) { return s.replaceAll("<[.[^<]]*>", "").replaceAll("\"","").replaceAll("\'",""); } else { return s; } } //************************************************************************* /** * 【获取】使用正则获取到模板中的自定义参数 * @param text * @return */ //************************************************************************* public static List<String> extractMessageByRegular(String text, boolean ispro){ List<String> list=new ArrayList<String>(); //Pattern p = Pattern.compile("(\\[[^\\]]*\\])"); Pattern p = Pattern.compile("(\\{\\{|\\{)(.*?)(\\}\\}|\\})"); Matcher m = p.matcher(text); while(m.find()){ if(ispro){ list.add(m.group(0)); } else { list.add(m.group(2)); } } return list; } /** * @param obj 需要转换的java bean * @param <T> 入参对象类型泛型 * @return 对应的json字符串 */ public static <T> String toJson(T obj) { return JSON.toJSONString(obj/*, DEFAULT_FORMAT*/); } /** * 通过Map生成一个json字符串 * * @param map 需要转换的map * @return json串 */ public static String toJson(Map<String, Object> map) { return JSON.toJSONString(map/*, DEFAULT_FORMAT*/); } /** * 将字符串转换成JSON字符串 * * @param jsonString json字符串 * @return 转换成的json对象 */ public static JSONObject getJSONFromString(final String jsonString) { if (isBlank(jsonString)) { return new JSONObject(); } return JSON.parseObject(jsonString); } /** * 美化传入的json,使得该json字符串容易查看 * * @param jsonString 需要处理的json串 * @return 美化后的json串 */ public static String prettyFormatJson(String jsonString) { return JSON.toJSONString(getJSONFromString(jsonString), true); } //************************************************************************* /** * 【获取】获取倒序list * @param list * @return */ //************************************************************************* public static <T> List<T> ListReverse(List<T> list) { Collections.reverse(list); return list; } /** * list 转 string * @param list * @return */ public static String listToString(List<?> list) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)).append(","); } return sb.toString().substring(0, sb.toString().length() - 1); } //************************************************************************* /** * 【获取】拷贝list到另一个list * @param list 源 * @param list2 目的地 * @return */ //************************************************************************* public static <T> List<T> ListCopy(List<T> list, List<T> list2) { Collections.copy(list2, list); return list2; } public static void main(String[] args) { // String a = "1"; // System.out.println(fillZero(a, 5, 0)); // System.out.println(Math.random()); Map<String, Object> map = new HashMap<String, Object>(); map.put("data", 123123); map.put("data2", "123123"); System.out.println(toJson(map)); } }
#!/usr/bin/env bash # Tags: no-replicated-database, no-parallel # Tag no-replicated-database: Unsupported type of ALTER query CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh . "$CURDIR"/../shell_config.sh ALTER_OUT_STRUCTURE='command_type String, partition_id String, part_name String' ATTACH_OUT_STRUCTURE='old_part_name String' FREEZE_OUT_STRUCTURE='backup_name String, backup_path String , part_backup_path String' # setup ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS table_for_freeze;" ${CLICKHOUSE_CLIENT} --query "CREATE TABLE table_for_freeze (key UInt64, value String) ENGINE = MergeTree() ORDER BY key PARTITION BY key % 10;" ${CLICKHOUSE_CLIENT} --query "INSERT INTO table_for_freeze SELECT number, toString(number) from numbers(10);" # also for old syntax ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS table_for_freeze_old_syntax;" ${CLICKHOUSE_CLIENT} --query "CREATE TABLE table_for_freeze_old_syntax (dt Date, value String) ENGINE = MergeTree(dt, (value), 8192);" ${CLICKHOUSE_CLIENT} --query "INSERT INTO table_for_freeze_old_syntax SELECT toDate('2021-03-01'), toString(number) from numbers(10);" ${CLICKHOUSE_CLIENT} --query "ALTER TABLE table_for_freeze FREEZE WITH NAME 'test_01417' FORMAT TSVWithNames SETTINGS alter_partition_verbose_result = 1;" \ | ${CLICKHOUSE_LOCAL} --structure "$ALTER_OUT_STRUCTURE, $FREEZE_OUT_STRUCTURE" \ --query "SELECT command_type, partition_id, part_name, backup_name FROM table" ${CLICKHOUSE_CLIENT} --query "ALTER TABLE table_for_freeze FREEZE PARTITION '3' WITH NAME 'test_01417_single_part' FORMAT TSVWithNames SETTINGS alter_partition_verbose_result = 1;" \ | ${CLICKHOUSE_LOCAL} --structure "$ALTER_OUT_STRUCTURE, $FREEZE_OUT_STRUCTURE" \ --query "SELECT command_type, partition_id, part_name, backup_name FROM table" ${CLICKHOUSE_CLIENT} --query "ALTER TABLE table_for_freeze DETACH PARTITION '3';" ${CLICKHOUSE_CLIENT} --query "INSERT INTO table_for_freeze VALUES (3, '3');" ${CLICKHOUSE_CLIENT} --query "ALTER TABLE table_for_freeze ATTACH PARTITION '3' FORMAT TSVWithNames SETTINGS alter_partition_verbose_result = 1;" \ | ${CLICKHOUSE_LOCAL} --structure "$ALTER_OUT_STRUCTURE, $ATTACH_OUT_STRUCTURE" \ --query "SELECT command_type, partition_id, part_name, old_part_name FROM table" ${CLICKHOUSE_CLIENT} --query "ALTER TABLE table_for_freeze DETACH PARTITION '5';" ${CLICKHOUSE_CLIENT} --query "ALTER TABLE table_for_freeze FREEZE PARTITION '7' WITH NAME 'test_01417_single_part_7', ATTACH PART '5_6_6_0' FORMAT TSVWithNames SETTINGS alter_partition_verbose_result = 1;" \ | ${CLICKHOUSE_LOCAL} --structure "$ALTER_OUT_STRUCTURE, $FREEZE_OUT_STRUCTURE, $ATTACH_OUT_STRUCTURE" \ --query "SELECT command_type, partition_id, part_name, backup_name, old_part_name FROM table" # Unfreeze partition ${CLICKHOUSE_CLIENT} --query "ALTER TABLE table_for_freeze UNFREEZE PARTITION '7' WITH NAME 'test_01417_single_part_7' FORMAT TSVWithNames SETTINGS alter_partition_verbose_result = 1;" \ | ${CLICKHOUSE_LOCAL} --structure "$ALTER_OUT_STRUCTURE, $FREEZE_OUT_STRUCTURE" \ --query "SELECT command_type, partition_id, part_name, backup_name FROM table" # Freeze partition with old syntax ${CLICKHOUSE_CLIENT} --query "ALTER TABLE table_for_freeze_old_syntax FREEZE PARTITION '202103' WITH NAME 'test_01417_single_part_old_syntax' FORMAT TSVWithNames SETTINGS alter_partition_verbose_result = 1;" \ | ${CLICKHOUSE_LOCAL} --structure "$ALTER_OUT_STRUCTURE, $FREEZE_OUT_STRUCTURE" \ --query "SELECT command_type, partition_id, part_name, backup_name FROM table" # Unfreeze partition with old syntax ${CLICKHOUSE_CLIENT} --query "ALTER TABLE table_for_freeze_old_syntax UNFREEZE PARTITION '202103' WITH NAME 'test_01417_single_part_old_syntax' FORMAT TSVWithNames SETTINGS alter_partition_verbose_result = 1;" \ | ${CLICKHOUSE_LOCAL} --structure "$ALTER_OUT_STRUCTURE, $FREEZE_OUT_STRUCTURE" \ --query "SELECT command_type, partition_id, part_name, backup_name FROM table" # Unfreeze the whole backup with SYSTEM query ${CLICKHOUSE_CLIENT} --query "ALTER TABLE table_for_freeze FREEZE PARTITION '7' WITH NAME 'test_01417_single_part_7_system'" ${CLICKHOUSE_CLIENT} --query "DROP TABLE table_for_freeze" ${CLICKHOUSE_CLIENT} --query "ALTER TABLE table_for_freeze UNFREEZE PARTITION '7' WITH NAME 'test_01417_single_part_7_system'" 2>/dev/null rc=$? if [ $rc -eq 0 ]; then echo "ALTER query shouldn't unfreeze removed table. Code: $rc" exit 1 fi ${CLICKHOUSE_CLIENT} --query "SYSTEM UNFREEZE WITH NAME 'test_01417_single_part_7_system'" \ | ${CLICKHOUSE_LOCAL} --structure "$ALTER_OUT_STRUCTURE, $FREEZE_OUT_STRUCTURE" \ --query "SELECT command_type, partition_id, part_name, backup_name FROM table" # teardown ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS table_for_freeze;" ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS table_for_freeze_old_syntax;"
import { Button, Grid, LinearProgress } from '@material-ui/core' import { FormikControls } from 'components' import { Form, Formik } from 'formik' import React from 'react' import * as Yup from 'yup' export const FormikContainer = (props) => { const initialValues = { title: '', description: '', select: '', checkbox: '', radio: '', } const validationSchema = Yup.object({ title: Yup.string().required('Required'), description: Yup.string().required('Required'), select: Yup.string().required('Required'), radio: Yup.string().required('Required'), checkbox: Yup.array().required('Required'), }) const onSubmit = (values, { setSubmitting }) => { setTimeout(() => { setSubmitting(false) alert(JSON.stringify(values, null, 2)) }, 500) } const selectOptions = [ { key: 'Pick A Value', value: '' }, { key: 'first', value: 'first' }, { key: 'second', value: 'second' }, { key: 'third', value: 'third' }, ] const radioOptions = [ { key: 'first', value: 'first' }, { key: 'second', value: 'second' }, { key: 'third', value: 'third' }, ] const checkedOptions = [ { key: 'Option 1', value: 'Option 1' }, { key: 'Option 2', value: 'Option 2' }, { key: 'Option 3', value: 'Option 3' }, ] return ( <Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={onSubmit}> {({ submitForm, isSubmitting }) => { return ( <Form> <Grid container direction={'column'} spacing={1}> <Grid item> <FormikControls control='input' name='title' label='Title' required={true} /> </Grid> <Grid item> <FormikControls control='textarea' name='description' label='Description' required={true} /> </Grid> <Grid item> <FormikControls control='select' name='select' label='Select' options={selectOptions} required={true} /> </Grid> <Grid item> <FormikControls control='radio' name='radio' label='Radio' options={radioOptions} required={true} /> </Grid> <Grid item> <FormikControls control='checkbox' name='checkbox' label='Checkbox' options={checkedOptions} required={true} /> </Grid> <Grid item> <FormikControls control='date' name='date' label='Date' required={true} /> </Grid> </Grid> {isSubmitting && <LinearProgress />} <br /> <Button variant='contained' color='primary' disabled={isSubmitting} onClick={submitForm}> Submit </Button> </Form> ) }} </Formik> ) }
def verify_password(password): if len(password) < 8 or len(password) > 15: return False has_upper = False has_lower = False has_num = False for l in password: if l.isupper(): has_upper = True elif l.islower(): has_lower = True elif l.isnumeric(): has_num = True return has_upper and has_lower and has_num
#!/bin/bash set -ev which shellcheck > /dev/null && shellcheck "$0" # Run shellcheck on this if available BUILD_NICKNAME=$(basename "$0" .sh) BUILD_DIR="./build-$BUILD_NICKNAME" # Adding Ubsan here, only added in GCC 4.9 ./configure.py --with-build-dir="$BUILD_DIR" --with-debug-info --with-sanitizer --cc-abi-flags='-fsanitize=undefined' make -j 2 -f "$BUILD_DIR"/Makefile "$BUILD_DIR"/botan-test
<reponame>GybiBite/Asteroids<filename>core/src/gybibite/asteroids/TypewriterTextAnim.java package gybibite.asteroids; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.TimeUtils; /** * Utility class to have a text "typewriter" effect where, when executed, the text will slowly form * character by character, such as when being actively typed out. After a short pause, it will * "untype" the characters until there is no more text on the screen. * * @author GybiBite */ public class TypewriterTextAnim { /** Font object to draw the text with */ private final BitmapFont font = new BitmapFont(Gdx.files.internal("fsex300.fnt"), Gdx.files.internal("fsex300.png"), false); /** X position of the text label */ float x; /** Y position of the text label */ float y; /** Full text to be displayed on the label */ String label; /** How many characters per second will be typed out */ float speed; /** How many seconds to pause before "untyping" the text */ float pauseInt; private String temp = ""; private long speedTimer; private boolean typing, untyping; /** * Creates a new typewriter text object at a certain point on the screen with a specific label and * speed */ public TypewriterTextAnim(float x, float y, float scale, String label, float speed, float pauseInt) { this.x = x; this.y = y; this.label = label; this.speed = speed; this.pauseInt = pauseInt; font.getData().setScale(scale); } public void render(SpriteBatch sb) { if (typing) { addChars(); } else if (untyping) { removeChars(); } else if (TimeUtils.timeSinceMillis(speedTimer) >= pauseInt) { untyping = true; } sb.begin(); font.draw(sb, temp, x, y, 0, Align.center, false); sb.end(); } public void setLabel(String label) { this.label = label; } public void startTyping() { typing = true; } private void addChars() { if (temp.length() < label.length()) { if (TimeUtils.timeSinceMillis(speedTimer) >= speed) { temp = temp + label.charAt(temp.length()); speedTimer = TimeUtils.millis(); } } else { typing = false; } } private void removeChars() { if (temp.length() > 0) { if (TimeUtils.timeSinceMillis(speedTimer) >= speed) { temp = temp.substring(0, temp.length() - 1); speedTimer = TimeUtils.millis(); } } else { untyping = false; speedTimer = TimeUtils.millis(); } } }
package org.lagalag.web.model.entity; import lombok.Data; @Data public class Place { private Long id; private String name; private String countryCode; private LatLng latLng; }
from cyder.cydns.nameserver.forms import Nameserver, NameserverForm, from cyder.cydns.views import cy_render class NSView(object): model = Nameserver form_class = NameserverForm queryset = Nameserver.objects.all() extra_context = {'obj_type': 'nameserver'}
<reponame>harry-xiaomi/SREWorks package com.alibaba.sreworks.job.master.jobtrigger.quartz; import com.alibaba.tesla.common.base.TeslaBaseResult; import com.alibaba.tesla.web.controller.BaseController; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * @author jinghua.yjh */ @Slf4j @RestController @RequestMapping("/quartz") public class QuartzController extends BaseController { @Autowired QuartzService quartzService; @RequestMapping(value = "checkCron", method = RequestMethod.GET) public TeslaBaseResult checkCron(String cron) throws Exception { quartzService.checkCron(cron); return buildSucceedResult("OK"); } @RequestMapping(value = "getNextTriggerTime", method = RequestMethod.GET) public TeslaBaseResult getNextTriggerTime(String cron, Integer size) throws Exception { if (size == null) { size = 5; } return buildSucceedResult(quartzService.getNextTriggerTime(cron, size)); } }
#!/bin/sh if [ "$(uname)" = "Linux" ]; then systemctl start couchbase-server elif [ "$(uname)" = "Darwin" ]; then output="$(open -a "Couchbase Server")" status="$?" [ "$status" -gt 1 ] && { printf "%s" "$output" exit $status } # We set a default timeout of 20 seconds, since cluster should be up by then. elapsed=0 # Curl request to Couchbase API should return with status 200, once up. until [ "$(curl -sL -w '%{http_code}' http://127.0.0.1:8091/ui/index.html -o /dev/null)" = "200" ] || [ "$elapsed" -ge 20 ]; do printf '=' elapsed=$((elapsed + 1)) sleep 1 done # Timed out and UI is still not available. if [ $elapsed -eq 20 ] && [ "$(curl -sL -w '%{http_code}' http://127.0.0.1:8091/ui/index.html -o /dev/null)" != "200" ]; then printf "\r\033[K \033[0;31mTimeout error : code %s\033[0m" "$(curl -sL -w '%{http_code}' http://127.0.0.1:8091/ui/index.html -o /dev/null)" exit 1 fi fi exit 0
package collins.kent.tutor.arithmetic; import java.util.Random; import collins.kent.tutor.Problem; import collins.kent.tutor.Meta; /*** * Produces a modulo problem involving integers. Avoids % 0. Operands are * intentionally low to keep the focus on the operation rather than the * mathematics. * * @author <NAME> * */ @Meta(skill="Perform the remainder operation on non-zero values") public class IntegerModuloProblem implements Problem { int operandLeft; int operandRight; @Override public Problem generate(Random rng) { operandLeft = rng.nextInt(10); operandRight = rng.nextInt(5); if (operandRight == 0) { operandRight = 3; operandLeft +=3; } return this; } @Override public String getStatement() { return operandLeft + " % " + operandRight; } @Override public String getAnswer() { return Integer.toString(operandLeft % operandRight); } }
import * as React from "react"; import { SvgIconProps } from "@material-ui/core/SvgIcon"; import { createSvgIcon } from "@material-ui/core"; const Pin = createSvgIcon( <> <path d="M50,2.5c-18.1,0-32.8,14-32.8,31.2c0,7.1,2.5,13.9,7.1,19.3L50,83.8L75.8,53c4.6-5.4,7.1-12.3,7.1-19.3 C82.8,16.5,68.1,2.5,50,2.5z M49.3,44c-6.5,0-11.8-5-11.8-11.2s5.3-11.2,11.8-11.2S61,26.6,61,32.8S55.8,44,49.3,44z" /> <path d="M31.3,90.3h37.3c2,0,3.6,1.6,3.6,3.6l0,0c0,2-1.6,3.6-3.6,3.6H31.3c-2,0-3.6-1.6-3.6-3.6l0,0 C27.8,91.9,29.4,90.3,31.3,90.3z" /> </>, "Pin" ); const PinIcon = (props: SvgIconProps): JSX.Element => ( <Pin viewBox="0 0 100 100" {...props} /> ); export default PinIcon;
/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 "PeripheralPins.h" /************RTC***************/ const PinMap PinMap_RTC[] = { {NC, OSC32KCLK, 0}, }; /************ADC***************/ const PinMap PinMap_ADC[] = { {PTB1, ADC0_SE1, 0}, {PTB3, ADC0_SE2, 0}, {PTB2, ADC0_SE3, 0}, {PTB18, ADC0_SE4, 0}, {PTA19, ADC0_SE5, 0}, {NC , NC , 0} }; /************DAC***************/ const PinMap PinMap_DAC[] = { {DAC0_OUT, DAC_0, 0}, {NC, NC, 0} }; /************I2C***************/ const PinMap PinMap_I2C_SDA[] = { {PTB1, I2C_0, 3}, {PTB17, I2C_1, 3}, {PTC1, I2C_0, 3}, {PTC3, I2C_1, 3}, {PTC7, I2C_1, 3}, {PTC16, I2C_0, 3}, {PTC18, I2C_1, 3}, {NC , NC , 0} }; const PinMap PinMap_I2C_SCL[] = { {PTB0, I2C_0, 3}, {PTB16, I2C_1, 3}, {PTB18, I2C_1, 3}, {PTC2, I2C_1, 3}, {PTC6, I2C_1, 3}, {PTC17, I2C_1, 3}, {PTC19, I2C_0, 3}, {NC , NC , 0} }; /************UART***************/ const PinMap PinMap_UART_TX[] = { {PTC3, LPUART_0, 4}, {PTC7, LPUART_0, 4}, {PTC18, LPUART_0, 4}, {NC , NC , 0} }; const PinMap PinMap_UART_RX[] = { {PTC2, LPUART_0, 4}, {PTC6, LPUART_0, 4}, {PTC17, LPUART_0, 4}, {NC , NC , 0} }; const PinMap PinMap_UART_CTS[] = { {PTC4, LPUART_0, 4}, {PTC19, LPUART_0, 4}, {NC , NC , 0} }; const PinMap PinMap_UART_RTS[] = { {PTC1, LPUART_0, 4}, {PTC5, LPUART_0, 4}, {PTC16, LPUART_0, 4}, {NC , NC , 0} }; /************SPI***************/ const PinMap PinMap_SPI_SCLK[] = { {PTA18, SPI_1, 2}, {PTC16, SPI_0, 2}, {NC , NC , 0} }; const PinMap PinMap_SPI_MOSI[] = { {PTA16, SPI_1, 2}, {PTC17, SPI_0, 2}, {NC , NC , 0} }; const PinMap PinMap_SPI_MISO[] = { {PTA17, SPI_1, 2}, {PTC18, SPI_0, 2}, {NC , NC , 0} }; const PinMap PinMap_SPI_SSEL[] = { {PTA1, SPI_1, 2}, {PTA19, SPI_1, 2}, {PTC19, SPI_0, 2}, {NC , NC , 0} }; /************PWM***************/ const PinMap PinMap_PWM[] = { /* TPM 0 */ {PTA16, PWM_1, 5}, {PTB0, PWM_2, 5}, {PTB1, PWM_3, 5}, {PTA2, PWM_4, 5}, {PTB18, PWM_1, 5}, {PTC3, PWM_2, 5}, {PTC1, PWM_3, 5}, {PTC16, PWM_4, 5}, /* TPM 1 */ {PTA0, PWM_5, 5}, {PTA1, PWM_6, 5}, {PTB2, PWM_5, 5}, {PTB3, PWM_6, 5}, {PTC4, PWM_5, 5}, {PTC5, PWM_6, 5}, /* TPM 2 */ {PTA18, PWM_7, 5}, {PTA19, PWM_8, 5}, {PTB16, PWM_7, 5}, {PTB17, PWM_8, 5}, {PTC6, PWM_7, 5}, {PTC7, PWM_8, 5}, {NC , NC , 0} };
import { Network } from './networks'; type ChangeAddressAction = { type: 'changeAddress', value: string | null }; type ChangeNetworkAction = { type: 'changeNetwork', value: Network }; export type Action = | ChangeAddressAction | ChangeNetworkAction;
import React, { Component} from 'react'; import { View, Text, TextInput, Image, StyleSheet, Dimensions, FlatList, TouchableHighlight, ActivityIndicator, ListView } from 'react-native'; import { Button, Subheader } from 'react-native-material-ui'; import simpleContacts from 'react-native-simple-contacts'; import * as Animatable from 'react-native-animatable'; import { List, ListItem, SearchBar } from "react-native-elements"; import firebase from 'react-native-firebase'; import { StackNavigator, NavigationActions } from 'react-navigation'; import FirebaseUtils from '../../static/firebase-utils'; // import DropDown, { Select, Option, OptionList } from 'react-native-selectme'; export default class CreateCallScreen extends Component { static navigationOptions = ({navigation}) => { return { title: 'Start A Call ', headerLeft: ( <Button onPress={() => navigation.goBack()} text="Back" /> ), } }; constructor() { super(); this.state = { callName: '', section: 0, contacts: [], filteredContacts: [], database: firebase.database(), loading: true, user: firebase.auth().currentUser, } this.finishCallCreation = this.finishCallCreation.bind(this); this.filterList = this.filterList.bind(this); this.renderHeader = this.renderHeader.bind(this); this.renderFooter = this.renderFooter.bind(this); this.itemPress = this.itemPress.bind(this); this.renderListItem = this.renderListItem.bind(this); } componentWillMount() { simpleContacts.getContacts().then((contacts) => { // Do something with the contacts const jsonContacts = JSON.parse(contacts); console.log(contacts) this.setState({ contacts: jsonContacts, filteredContacts: jsonContacts, loading: false, }) }); } finishCallCreation() { const { callName, contacts } = this.state; const that = this; FirebaseUtils.createCall(callName, contacts, () => { const resetAction = NavigationActions.reset({ index: 1, actions: [ NavigationActions.navigate({ routeName: 'Home' }), NavigationActions.navigate({ routeName: 'Details' }) ], }); that.props.navigation.dispatch(resetAction); }); } filterList(val) { let updatedList = this.state.contacts; updatedList = updatedList.filter(function(item){ return (item.number.toLowerCase().search(val.toLowerCase()) !== -1 || item.name.toLowerCase().search(val.toLowerCase()) !== -1); }); this.setState({filteredContacts: updatedList}); } renderListItem({item, index, onPress}) { if(item.selected) { return ( <ListItem containerStyle={{backgroundColor: 'rgba(10, 160, 217, 0.4)'}} title={item.name} subtitle={item.number} onPress={() => this.itemPress(index)} /> ) } else { return ( <ListItem title={item.name} subtitle={item.number} onPress={() => this.itemPress(index)} /> ); } } renderHeader() { return <SearchBar placeholder="Invite People" lightTheme round onChangeText={this.filterList}/>; }; renderFooter() { if (!this.state.loading) { return (null); } return ( <View style={{ paddingVertical: 20, borderTopWidth: 1, borderColor: "#CED0CE" }} > <ActivityIndicator animating size="large" /> </View> ); }; itemPress(i) { let filteredContacts = this.state.filteredContacts; if(filteredContacts[i].selected){ filteredContacts[i].selected = false; } else { filteredContacts[i].selected = true; } this.setState({ filteredContacts: filteredContacts, flip: !this.state.flip, }); } render() { const { section, callName, contacts, filteredContacts} = this.state; const selectedContacts = contacts.filter((item) => item.selected); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1.name !== r2.name}); const dataSource = ds.cloneWithRows(selectedContacts) return ( <View style={styles.createCallView}> {section === 0 && <View style={styles.nameView}> <CallDetails callName={callName} onChangeText={value => this.setState({ callName: value })} next={() => this.setState({section: 1})} /> </View> } {section === 1 && <InviteView contacts={filteredContacts} dataSource={dataSource} numSelected={selectedContacts.length} filterList={this.filterList} renderHeader={this.renderHeader} renderFooter={this.renderFooter} renderListItem={this.renderListItem} finish={this.finishCallCreation} flip={this.state.flip} /> } </View> ) } } const CallDetails = (props) => ( <Animatable.View animation="fadeInLeft"> <TextInput autoFocus style={styles.textInput} onChangeText={props.onChangeText} placeholder="<NAME>" value={props.callName} /> <Button raised primary text="Next" onPress={props.next} /> </Animatable.View> ); const InviteView = (props) => { return ( <Animatable.View style={styles.inviteView} animation="fadeInLeft"> <List style={styles.flatList}> <FlatList extraData={props.flip} style={styles.flatList} data={props.contacts} renderItem={(item, index) => props.renderListItem(item, index)} ListHeaderComponent={props.renderHeader} ListFooterComponent={props.renderFooter} /> </List> <View> <Text> Selected: {props.numSelected} </Text> <ListView horizontal={true} dataSource={props.dataSource} renderRow={(rowData) => <Text>{rowData.name}, </Text>} /> </View> <View style={styles.buttonView}> <Button raised primary text="Create" onPress={props.finish} style={{ container: { height: 50} }}/> </View> </Animatable.View> ) }; const styles = StyleSheet.create({ inviteView: { height: '100%', padding: 0, margin: 0, backgroundColor: '#fff', }, createCallView: { height: '100%', margin: 0, padding: 0, flex: 1, width: '100%', }, nameView: { flex: 1, justifyContent: 'center', alignSelf: 'center', width: '90%', }, textInput: { height: 40, marginTop: 15, marginBottom: 15, color: '#0aa0d9', fontSize: 30, textAlign: 'center', borderWidth: 0.5, borderColor: '#0aa0d9', borderRadius: 5, width: '100%', justifyContent: 'center', alignSelf: 'center', }, cancelButton: { marginTop: 5, }, flatList: { height: '80%', margin: 0, padding: 0, }, buttonView: { position: 'absolute', bottom: 0, width: '90%', marginBottom: 5, alignSelf: 'center', }, selectedView: { backgroundColor: '#fff', } });
<reponame>PierceLBrooks/Facialoid<gh_stars>1-10 // Author: <NAME> package com.piercelbrooks.common; import android.app.Activity; import android.app.Application; import android.content.Context; import android.os.Bundle; import androidx.annotation.DrawableRes; import androidx.multidex.MultiDex; import androidx.multidex.MultiDexApplication; import android.widget.Toast; public abstract class BasicApplication extends MultiDexApplication implements Application.ActivityLifecycleCallbacks, Citizen { private static final String TAG = "PLB-BaseApp"; public abstract @DrawableRes int getEmptyDrawable(); protected abstract void create(); protected abstract void terminate(); protected abstract void activityCreated(Activity activity); protected abstract void activityDestroyed(Activity activity); protected abstract void activityStarted(Activity activity); protected abstract void activityStopped(Activity activity); protected abstract void activityResumed(Activity activity); protected abstract void activityPaused(Activity activity); private Governor governor; private Preferences preferences; private Activity activity; public static BasicApplication getInstance() { return (BasicApplication)Governor.getInstance().getCitizen(Family.APPLICATION); } public Activity getActivity() { return activity; } public Preferences getPreferences() { return preferences; } public boolean makeToast(String message) { if (message == null) { return false; } if (activity == null) { return false; } activity.runOnUiThread(new Runner(new Runner(null), message) { @Override public void run() { super.run(); activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity, getMessage(), Constants.TOAST_DURATION).show(); } }); } }); return true; } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } @Override public void onCreate() { super.onCreate(); registerActivityLifecycleCallbacks(this); birth(); create(); } @Override public void onTerminate() { terminate(); unregisterActivityLifecycleCallbacks(this); death(); super.onTerminate(); } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { activityCreated(activity); } @Override public void onActivityStarted(Activity activity) { activityStarted(activity); } @Override public void onActivityResumed(Activity activity) { activityResumed(activity); this.activity = activity; } @Override public void onActivityPaused(Activity activity) { activityPaused(activity); if (this.activity == activity) { this.activity = null; } } @Override public void onActivityStopped(Activity activity) { activityStopped(activity); } @Override public void onActivityDestroyed(Activity activity) { activityDestroyed(activity); } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public Family getFamily() { return Family.APPLICATION; } @Override public void birth() { preferences = new Preferences(this); governor = new Governor(); governor.birth(); governor.register(this); } @Override public void death() { preferences = null; governor.unregister(this); governor.death(); governor = null; } }
var searchData= [ ['nameandtags_898',['NameAndTags',['../structCatch_1_1NameAndTags.html',1,'Catch']]], ['noncopyable_899',['NonCopyable',['../classCatch_1_1NonCopyable.html',1,'Catch']]], ['not_5fthis_5fone_900',['not_this_one',['../structCatch_1_1not__this__one.html',1,'Catch']]] ];
<gh_stars>0 /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ import React, { HTMLAttributes, FunctionComponent } from 'react'; import { CommonProps, keysOf } from '../common'; import classNames from 'classnames'; const sizeToClassNameMap = { s: 'euiLoadingSpinner--small', m: 'euiLoadingSpinner--medium', l: 'euiLoadingSpinner--large', xl: 'euiLoadingSpinner--xLarge', }; export const SIZES = keysOf(sizeToClassNameMap); export type EuiLoadingSpinnerSize = keyof typeof sizeToClassNameMap; export type EuiLoadingSpinnerProps = CommonProps & HTMLAttributes<HTMLDivElement> & { size?: EuiLoadingSpinnerSize; }; export const EuiLoadingSpinner: FunctionComponent<EuiLoadingSpinnerProps> = ({ size = 'm', className, ...rest }) => { const classes = classNames( 'euiLoadingSpinner', sizeToClassNameMap[size], className ); return <span className={classes} {...rest} />; };
<filename>js/utils/leaflet.js<gh_stars>1-10 // sets initial map view to UK coordinates export const map = L.map('map').setView([53.483959, -2.244644], 6); // Uses maptiler api to render street tiles with 512x512 size. Attributions to maptiler, openstreetmap and leaflet are also rendered on screen export const tileLayer = L.tileLayer( 'https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=vXHoLejq0rBnYbqJIdKe', { attribution: '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>', } ).addTo(map);
package core.framework.test.web; import core.framework.inject.Inject; import core.framework.test.IntegrationTest; import core.framework.web.site.Message; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * @author neo */ class MessageIntegrationTest extends IntegrationTest { @Inject Message message; @Test void getWithNotExistedKey() { assertThatThrownBy(() -> message.get("notExistedKey")) .isInstanceOf(Error.class) .hasMessageContaining("can not find message"); } }
package Polymorphism; public class Animal { void talk() { System.out.println("Animals can talk"); } } class Dog{ void talk() { System.out.println("Dogs can bark too."); } } class Cat { void talk() { System.out.println("Meow Meow!!"); } } class Driver{ public static void main(String[] args) { Animal animal=new Animal(); animal.talk(); Dog dog=new Dog(); dog.talk(); Cat cat=new Cat(); cat.talk(); } }
#!/usr/bin/env bash set -e host="authority0" shift cmd="$@" until curl --data '{"method":"web3_clientVersion","params":[],"id":1,"jsonrpc":"2.0"}' -H "Content-Type: application/json" -X POST "$host":8545; do >&2 echo "Parity is unavailable - sleeping" sleep 1 done >&2 echo "Parity is up - executing command" exec $cmd
import React from 'react'; import { v4 as uuidV4 } from 'uuid'; import { useToasts } from 'react-toast-notifications'; import { Layout } from '../components/Layout'; import classes from '../styles/Submit.module.css'; import { EmailSubscription } from '../components/EmailSubscription'; import { Loader } from '../components/Loader'; import { ProfileCard } from '../components/ProfileCard'; import { InputField } from '../components/InputField'; import { FileUpload } from '../components/FileUpload'; import { Dropdown } from '../components/Dropdown'; import { AuthUserContext } from '../context'; import { useInsertIntoDB } from '../hooks/useInsertIntoDB'; import { definitions } from '../types/supabase-types'; import { useFormValidator, validators } from '../hooks/useFormValidator'; import { throttle } from '../utils/throttle'; // eslint-disable-next-line export default function Submit() { const toast = useToasts(); const formValidator = useFormValidator(); const authUser = React.useContext(AuthUserContext); const insertOppToDb = useInsertIntoDB<definitions['opportunities']>(); const [companyLogoUri, setCompanyLogoUri] = React.useState<string>(''); const [opportunityType, setOpportunityType] = React.useState<string>(''); const [selectedLocation, setSelectedLocation] = React.useState<string>(''); const [suggestedLocations, setSuggestedLocations] = React.useState< { label: React.ReactNode; value: string }[] >([{ label: '', value: '' }]); React.useEffect(() => { const uid = uuidV4(); if (!authUser) { toast.addToast('You must be logged in to submit an Opportunity', { appearance: 'error', autoDismiss: false, id: uid, }); } return () => { toast.removeToast(uid); }; }, [authUser]); return ( <> <Layout left={<EmailSubscription />} right={<ProfileCard />}> <form className={classes.form} onReset={() => setCompanyLogoUri('')} onSubmit={(ev) => { ev.preventDefault(); if (authUser?.id) { const formData = new FormData(ev.target as HTMLFormElement); const opportunityData: definitions['opportunities'] = { author: authUser.id, id: uuidV4(), type: formValidator<string>( formData.get('opp-type'), validators.fnValidateString, 'opp-submit.type', ), location: formValidator<string>( formData.get('location'), validators.fnValidateString, 'opp-submit.location', ), opp_name: formValidator( formData.get('opportunity-title'), validators.fnValidateString, 'opp-submit.title', ), company_name: formValidator( formData.get('company-name'), validators.fnValidateString, 'opp-submit.company-name', ), apply_at: formValidator( formData.get('apply-at'), validators.fnValidateString, 'opp-submit.apply-at', ), eligibility: formData.get('eligibility')?.toString(), opp_deadline: formValidator( formData.get('last-date'), validators.fnValidateString, 'opp-submit.last-date', ), opp_description: formData .get('description') ?.toString() .replace(/\n/g, '\\n'), company_logo_url: formData.get('company-logo')?.toString(), }; insertOppToDb('opportunities', opportunityData).then( (val) => val.data && (ev.target as HTMLFormElement).reset(), ); } }} > <h3>Add a new Opportunity</h3> {/* <img src="https://i.ibb.co/g70HK8V/2021-06-15-11-38-11.png" alt="" /> */} <p> Saw an opportunity? Help others by listing it here! Let us rise by lifting others. </p> <div className={classes.row}> <label htmlFor="opp-type"> <span> Opportunity Type <span className={classes.color_red}>*</span> </span> <Dropdown onChange={(data) => setOpportunityType(data?.value || '')} data={[ { label: 'Full Time', value: 'FULLTIME' }, { label: 'Part Time', value: 'PARTTIME' }, { label: 'INTERNSHIP', value: 'INTERNSHIP' }, ]} /> <input type="hidden" name="opp-type" value={opportunityType} /> </label> {/* eslint-disable-next-line */} <label htmlFor="location"> <span> Location <span className={classes.color_red}>*</span> </span> <InputField type="hidden" id="location" name="location" value={selectedLocation} placeholder="Mumbai, Maharashtra" validator={validators.fnValidateString} /> <Dropdown data={suggestedLocations} onChange={(data) => setSelectedLocation(data?.value || '')} onFilterTextChange={(filterText) => throttle(async () => { try { const raw = await fetch( `/api/get-location-autocomplete?search=${filterText}`, ); const json = await raw.json(); const ddData = []; /* eslint-disable */ filterText && ddData.push({ label: filterText, value: filterText, }); /* eslint-enable */ for (let i = 0; i < json?.suggestions?.length; i += 1) { const place = json?.suggestions[i]; const fullAddr: string[] = []; const addr = place.address; /* eslint-disable */ addr.street && fullAddr.push(addr.street); addr.county && fullAddr.push(addr.county); addr.city && fullAddr.push(addr.city); addr.district && fullAddr.push(addr.district); addr.state && fullAddr.push(addr.state); addr.country && fullAddr.push(addr.country); addr.postalCode && fullAddr.push(addr.postalCode); /* eslint-enable */ const tmp = { label: fullAddr.join(', ').replace(/<\/?b>/gi, ''), value: fullAddr.join(', ').replace(/<\/?b>/gi, ''), }; ddData.push(tmp); } setSuggestedLocations(ddData); } catch (err) { setSuggestedLocations([ { label: filterText, value: filterText }, ]); } }, 400 /* throttle at 0.4s */)} /> </label> </div> {/* eslint-disable-next-line */} <label htmlFor="opportunity-title"> <span> Job Title/Opportunity Name <span className={classes.color_red}>*</span> </span> <InputField id="opportunity-title" type="text" name="opportunity-title" placeholder="SDE-I/Hackathon etc" validator={validators.fnValidateString} /> </label> <div className={classes.row}> {/* eslint-disable-next-line */} <label htmlFor="company"> <span> Company <span className={classes.color_red}>*</span> </span> <InputField id="company" type="text" name="company-name" placeholder="Google" validator={validators.fnValidateString} /> </label> {/* eslint-disable-next-line */} <label htmlFor="eligibility"> <span> Eligibility <span className={classes.color_red}>*</span> </span> <InputField id="eligibility" type="text" name="eligibility" placeholder="BTech" /> </label> </div> <label htmlFor="desc"> <span>Job Description</span> <textarea style={{ resize: 'vertical' }} id="desc" rows={7} placeholder="A detailed description" name="description" /> </label> {/* eslint-disable-next-line */} <label htmlFor="logo"> <span>Company Logo</span> {!companyLogoUri && ( <FileUpload className={classes.file_upload} onUpload={(uri: string) => setCompanyLogoUri(uri)} /> )} <input type="hidden" name="company-logo" value={companyLogoUri} /> {companyLogoUri && ( <div className={`${classes.file_upload} ${classes.clear_selected_file}`} > <span>Logo Selected!</span> <button type="button" onClick={() => setCompanyLogoUri('')}> ✕ </button> </div> )} </label> <div className={classes.row}> {/* eslint-disable-next-line */} <label htmlFor="apply"> <span> Apply at <span className={classes.color_red}>*</span> </span> <InputField id="apply" type="text" name="apply-at" placeholder="https://jobs.lever.com/path/to/job" validator={validators.fnValidateString} /> </label> {/* eslint-disable-next-line */} <label htmlFor="last-date"> <span> Last Date <span className={classes.color_red}>*</span> </span> <InputField type="date" id="last-date" name="last-date" validator={validators.fnValidateString} /> </label> </div> <div className={`${classes.row} ${classes.submit_reset_btn}`}> {/* eslint-disable-next-line */} <button type="reset">RESET</button> <button className="gradient" type="submit"> SUBMIT </button> </div> </form> <div style={{ margin: '5rem 0', display: 'flex', justifyContent: 'center', alignItems: 'center', }} > <Loader /> </div> </Layout> </> ); }
#!/bin/bash BASEDIR=$(dirname "$0") if [ $(ps -ef | grep -v grep | grep importLNJC05F.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importLNJC05F.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importLNJC05F.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importListOfAccount.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importListOfAccount.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importListOfAccount.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importLN3206F.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importLN3206F.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importLN3206F.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importReportInputPaymentOfCard.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importReportInputPaymentOfCard.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importReportInputPaymentOfCard.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importSBV.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importSBV.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importSBV.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importWoAllProd.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importWoAllProd.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importWoAllProd.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importWoMonthly.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importWoMonthly.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importWoMonthly.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importWoPayment.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importWoPayment.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importWoPayment.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importReportReleaseSale.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importReportReleaseSale.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importReportReleaseSale.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importSiteResult.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importSiteResult.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importSiteResult.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importCollateralInfo.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importCollateralInfo.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importCollateralInfo.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importListOfCusAssignedToPartner.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importListOfCusAssignedToPartner.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importListOfCusAssignedToPartner.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importTrialBalanceReport.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importTrialBalanceReport.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importTrialBalanceReport.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importThuHoiXe.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importThuHoiXe.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importThuHoiXe.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importLawsuit.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importLawsuit.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importLawsuit.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importK20190812.0244.R18.20191030.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importK20190812.0244.R18.20191030.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importK20190812.0244.R18.20191030.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importLNJC05Yesterday.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importLNJC05Yesterday.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importLNJC05Yesterday.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importListOfAccountYesterday.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importListOfAccountYesterday.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importListOfAccountYesterday.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importSBVYesterday.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importSBVYesterday.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importSBVYesterday.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importLNJC05FStartMonth.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importLNJC05FStartMonth.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importLNJC05FStartMonth.py" else echo "Worldfone ScanJob service is running" exit 0 fi if [ $(ps -ef | grep -v grep | grep importListOfAccountStartMonth.py | wc -l) -lt 1 ]; then /usr/local/bin/python3.6 ${BASEDIR}/importListOfAccountStartMonth.py > /dev/null 2>&1 & echo "RUN ${BASEDIR}/importListOfAccountStartMonth.py" else echo "Worldfone ScanJob service is running" exit 0 fi
package com.yoga.content.property.dto; import com.yoga.core.base.BaseDto; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.validation.constraints.NotNull; @Getter @Setter @NoArgsConstructor public class UpdateDto extends BaseDto { @NotNull(message = "选项ID不能为空") private Long id; private String code; private String name; private Long parentId; private String poster; }
<reponame>Codes4Fun/starweb /** * Given a set of strings such as search terms, this class allows you to search * for that string by prefix. * @author <NAME> * */ function PrefixStore() { // This is a naive implementation that simply stores all the prefixes in a // hashmap. A better solution would be to use a trie. // TODO(johntaylor): reimplement this, probably as a trie. var store = {}; var EMPTY_SET = {}; /** * Search for any queries matching this prefix. Note that the prefix is * case-independent. */ this.queryByPrefix = function (prefix) { var results = store[prefix.toLowerCase()]; if (results == null) { return EMPTY_SET; } return results; }; /** * Put a new string in the store. */ this.add = function (string) { // Add value to every prefix list. Not exactly space-efficient, but time's // getting on. for (var i = 0; i < string.length; ++i) { var prefix = string.substring(0, i + 1).toLowerCase(); var currentList = store[prefix]; if (currentList == null) { currentList = {}; store[prefix.toLowerCase()] = currentList; } currentList[string] = string; } }; /** * Put a whole load of objects in the store at once. * @param strings a collection of strings. */ this.addAll = function (strings) { strings.forEach(function (string) { add(string); }); }; }
<reponame>moziliar/main package seedu.weme.model; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.weme.model.Model.PREDICATE_SHOW_ALL_MEMES; import static seedu.weme.testutil.Assert.assertThrows; import static seedu.weme.testutil.TypicalMemes.ALICE; import static seedu.weme.testutil.TypicalMemes.BENSON; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import org.junit.jupiter.api.Test; import seedu.weme.commons.core.GuiSettings; import seedu.weme.model.meme.NameContainsKeywordsPredicate; import seedu.weme.testutil.MemeBookBuilder; public class ModelManagerTest { private ModelManager modelManager = new ModelManager(); @Test public void constructor() { assertEquals(new UserPrefs(), modelManager.getUserPrefs()); assertEquals(new GuiSettings(), modelManager.getGuiSettings()); assertEquals(new MemeBook(), new MemeBook(modelManager.getMemeBook())); } @Test public void setUserPrefs_nullUserPrefs_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> modelManager.setUserPrefs(null)); } @Test public void setUserPrefs_validUserPrefs_copiesUserPrefs() { UserPrefs userPrefs = new UserPrefs(); userPrefs.setMemeBookFilePath(Paths.get("weme/book/file/path")); userPrefs.setGuiSettings(new GuiSettings(1, 2, 3, 4)); modelManager.setUserPrefs(userPrefs); assertEquals(userPrefs, modelManager.getUserPrefs()); // Modifying userPrefs should not modify modelManager's userPrefs UserPrefs oldUserPrefs = new UserPrefs(userPrefs); userPrefs.setMemeBookFilePath(Paths.get("new/weme/book/file/path")); assertEquals(oldUserPrefs, modelManager.getUserPrefs()); } @Test public void setGuiSettings_nullGuiSettings_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> modelManager.setGuiSettings(null)); } @Test public void setGuiSettings_validGuiSettings_setsGuiSettings() { GuiSettings guiSettings = new GuiSettings(1, 2, 3, 4); modelManager.setGuiSettings(guiSettings); assertEquals(guiSettings, modelManager.getGuiSettings()); } @Test public void setMemeBookFilePath_nullPath_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> modelManager.setMemeBookFilePath(null)); } @Test public void setMemeBookFilePath_validPath_setsMemeBookFilePath() { Path path = Paths.get("weme/book/file/path"); modelManager.setMemeBookFilePath(path); assertEquals(path, modelManager.getMemeBookFilePath()); } @Test public void hasMeme_nullMeme_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> modelManager.hasMeme(null)); } @Test public void hasMeme_memeNotInMemeBook_returnsFalse() { assertFalse(modelManager.hasMeme(ALICE)); } @Test public void hasMeme_memeInMemeBook_returnsTrue() { modelManager.addMeme(ALICE); assertTrue(modelManager.hasMeme(ALICE)); } @Test public void getFilteredMemeList_modifyList_throwsUnsupportedOperationException() { assertThrows(UnsupportedOperationException.class, () -> modelManager.getFilteredMemeList().remove(0)); } @Test public void equals() { MemeBook memeBook = new MemeBookBuilder().withMeme(ALICE).withMeme(BENSON).build(); MemeBook differentMemeBook = new MemeBook(); UserPrefs userPrefs = new UserPrefs(); // same values -> returns true modelManager = new ModelManager(memeBook, userPrefs); ModelManager modelManagerCopy = new ModelManager(memeBook, userPrefs); assertTrue(modelManager.equals(modelManagerCopy)); // same object -> returns true assertTrue(modelManager.equals(modelManager)); // null -> returns false assertFalse(modelManager.equals(null)); // different types -> returns false assertFalse(modelManager.equals(5)); // different memeBook -> returns false assertFalse(modelManager.equals(new ModelManager(differentMemeBook, userPrefs))); // different filteredList -> returns false String[] keywords = ALICE.getName().fullName.split("\\s+"); modelManager.updateFilteredMemeList(new NameContainsKeywordsPredicate(Arrays.asList(keywords))); assertFalse(modelManager.equals(new ModelManager(memeBook, userPrefs))); // resets modelManager to initial state for upcoming tests modelManager.updateFilteredMemeList(PREDICATE_SHOW_ALL_MEMES); // different userPrefs -> returns false UserPrefs differentUserPrefs = new UserPrefs(); differentUserPrefs.setMemeBookFilePath(Paths.get("differentFilePath")); assertFalse(modelManager.equals(new ModelManager(memeBook, differentUserPrefs))); } }
import { GET_CAMPAIGNS_SUCCESS, SELECT_CAMPAIGN, SET_LOADING, PATCH_CAMPAIGN, GET_USER_SUCCESS, GET_USERS_SUCCESS, GET_USERME_SUCCESS, SET_EDIT, EDIT_ARTICLE, DELETE_ARTICLE, SUBMIT_ARTICLE, BLOG_PAGE_LOADED, } from "./actions"; import storage from "utils/storage"; const initialState = { selectedCampaign: storage.get("selectedCampaign") || null, campaigns: [], user: [], users: [], userme: [], isLoading: true, articles: [], }; const reducer = (state = initialState, action) => { switch (action.type) { case GET_CAMPAIGNS_SUCCESS: return { ...state, campaigns: action.payload, isLoading: false }; case GET_USER_SUCCESS: return { ...state, user: action.payload, isLoading: false }; case GET_USERS_SUCCESS: console.log(action.payload); return { ...state, users: action.payload, isLoading: false }; case BLOG_PAGE_LOADED: return { ...state, articles: action.payload }; case SUBMIT_ARTICLE: return { ...state, articles: [action.data.article].concat(state.articles), }; case DELETE_ARTICLE: return { ...state, articles: state.articles.filter( (article) => article._id !== action.payload ), }; case SET_EDIT: return { ...state, articleToEdit: action.payload }; case EDIT_ARTICLE: return { ...state, articles: state.articles.map((article) => { if (article._id === action.data.article._id) { return { ...action.data.article, }; } }), }; case GET_USERME_SUCCESS: return { ...state, userme: action.payload, isLoading: false }; case SELECT_CAMPAIGN: return { ...state, selectedCampaign: action.payload, isLoading: false }; case SET_LOADING: return { ...state, isLoading: action.payload, }; case PATCH_CAMPAIGN: return { ...state, campaigns: state.campaigns.map((campaign) => campaign.id === action.payload.id ? action.payload : campaign ), }; default: return state; } }; export default reducer;
#!s/bin/env bash docker build -t lucifer1004/machine-learning .
<gh_stars>0 package ca.bc.gov.educ.gtts.services; import ca.bc.gov.educ.gtts.exception.TraxBatchServiceException; import ca.bc.gov.educ.gtts.model.dto.students.api.GraduationStudentRecord; import java.util.List; import java.util.function.Predicate; /** * Trax batch service */ public interface TraxBatchService { void runTest(List<String> pens) throws TraxBatchServiceException; void runTest() throws TraxBatchServiceException; void runTest(Predicate<GraduationStudentRecord> optionalFilter) throws TraxBatchServiceException; }
<filename>src/icon/IconNavigation.tsx import React from 'react'; export interface IconNavigationProps extends React.SVGAttributes<SVGElement> { color?: string; size?: string | number; className?: string; style?: React.CSSProperties; } export const IconNavigation: React.SFC<IconNavigationProps> = ( props: IconNavigationProps ): React.ReactElement => { const { color, size, style, ...restProps } = props; return ( <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className="feather feather-navigation" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ verticalAlign: 'middle', ...style }} {...restProps} > <polygon points="3 11 22 2 13 21 11 13 3 11" /> </svg> ); }; IconNavigation.defaultProps = { color: 'currentColor', size: '1em', }; export default IconNavigation;
#!/bin/bash # Debug_eGui_Dhrystone.sh # Check Environment if [ -z ${IMPERAS_HOME} ]; then echo "IMPERAS_HOME not set. Please check environment setup." exit fi ${IMPERAS_ISS} --verbose --output imperas.log \ --program ../../../Applications/dhrystone/dhrystone.ARM_CORTEX_M0-O0-g.elf \ --processorvendor arm.ovpworld.org --processorname armm --variant ARMv6-M \ --numprocessors 1 \ --parameter UAL=1 --parameter endian=little \ --gdbegui --eguicommands "--breakonstartup main --continueonstartup" \ "$@"
import React, {useState, useEffect} from 'react'; import {TextInput, Text, FlatList} from 'react-native'; const App = () => { const [searchTerm, setSearchTerm] = useState(''); const [articles, setArticles] = useState([]); useEffect(() => { searchNews(searchTerm); }, [searchTerm]); const searchNews = (term) => { fetch(`https://newsapi.org/v2/everything?q=${term}&apiKey=abc123`) .then(response => response.json()) .then(data => setArticles(data.articles)) .catch(error => console.log(error)); }; return ( <> <TextInput value={searchTerm} onChangeText={setSearchTerm} style={{padding: 10, fontSize: 18}} placeholder="Search for news here" /> <FlatList data={articles} renderItem={({item}) => <Text>{item.title}</Text>} keyExtractor={item => item.title} /> </> ); }; export default App;
<reponame>GrahamA2/PushoverTWPlugin package io.waterworx.pushover; import push.AppInjector; import java.util.Date; import com.google.inject.Guice; import com.google.inject.Injector; import com.thingworx.metadata.annotations.ThingworxConfigurationTableDefinitions; import com.thingworx.metadata.annotations.ThingworxServiceDefinition; import com.thingworx.metadata.annotations.ThingworxServiceParameter; import com.thingworx.metadata.annotations.ThingworxServiceResult; import com.thingworx.things.Thing; //@formatter:off @ThingworxConfigurationTableDefinitions(tables = { @com.thingworx.metadata.annotations.ThingworxConfigurationTableDefinition(name = "PushoverConnector", description = "Pushover Application Connection Parameters", isMultiRow = false, ordinal = 0, dataShape = @com.thingworx.metadata.annotations.ThingworxDataShapeDefinition(fields = { @com.thingworx.metadata.annotations.ThingworxFieldDefinition(ordinal = 0, name = "APIToken", description = "your application's API token", baseType = "STRING", aspects = { "defaultValue:your.token", "friendlyName:API Token" }), }) ) }) public class PushoverConnector extends Thing { private static final long serialVersionUID = 1L; private final PushoverService pushover; private String apiToken = ""; public PushoverConnector() { Injector injector = Guice.createInjector(new AppInjector()); pushover = injector.getInstance(PushoverService.class); } @Override protected void initializeThing() throws Exception { // May need to move pushover here this.apiToken = ((String) getConfigurationData().getValue("PushoverConnector", "APIToken")); } @ThingworxServiceDefinition(name = "PushMessageShort", description = "Push a notification to a user or group") @ThingworxServiceResult(name = "Result", description = "Result", baseType = "STRING") public String PushMessageShort( @ThingworxServiceParameter(name = "user", description = "the user/group key (not e-mail address) of your user (or you)", baseType = "STRING", aspects = { "defaultValue:" }) String userID, @ThingworxServiceParameter(name = "message", description = "your message", baseType = "STRING", aspects = { "defaultValue:" }) String message) throws Exception { String status = pushover.push(apiToken, userID, message); return status; } @ThingworxServiceDefinition(name = "PushMessageLong", description = "Push a notification to a user or group includeing a title and URL") @ThingworxServiceResult(name = "Result", description = "Result", baseType = "STRING") public String PushMessageLong( @ThingworxServiceParameter(name = "user", description = "the user/group key (not e-mail address) of your user (or you)", baseType = "STRING", aspects = { "defaultValue:" }) String userID, @ThingworxServiceParameter(name = "message", description = "Your message", baseType = "STRING", aspects = { "defaultValue:" }) String message, @ThingworxServiceParameter(name = "device", description = "Your user's device name to send the message directly to that device, rather than all of the user's devices (multiple devices may be separated by a comma)", baseType = "STRING", aspects = { "defaultValue:" }) String device, @ThingworxServiceParameter(name = "title", description = "Your message's title, otherwise your app's name is used", baseType = "STRING", aspects = { "defaultValue:Thingwox Pushover Message" }) String title, @ThingworxServiceParameter(name = "url", description = "A supplementary URL to show with your message", baseType = "STRING", aspects = { "defaultValue:" }) String url, @ThingworxServiceParameter(name = "url_title", description = "A title for your supplementary URL, otherwise just the URL is shown", baseType = "STRING", aspects = { "defaultValue:" }) String url_title, @ThingworxServiceParameter(name = "priority", description = "Send as -2 to generate no notification/alert, -1 to always send as a quiet notification, 1 to display as high-priority and bypass the user's quiet hours, or 2 to also require confirmation from the user", baseType = "NUMBER", aspects = { "defaultValue:0" }) Double priority, @ThingworxServiceParameter(name = "timestamp", description = "A Unix timestamp of your message's date and time to display to the user, rather than the time your message is received by our API", baseType = "NUMBER", aspects = { "defaultValue:0" }) Double timestamp, @ThingworxServiceParameter(name = "sound", description = "The name of one of the sounds supported by device clients to override the user's default sound choice", baseType = "STRING", aspects = { "defaultValue:", "pushover" }) String sound) throws Exception { Integer vPriorty = priority.intValue(); Long vTimestamp = timestamp.longValue(); if (vTimestamp == 0) { Date now = new Date(); vTimestamp = new Long(now.getTime() / 1000); } String status = pushover.push(apiToken, userID, message,device,title,url,url_title,vPriorty,vTimestamp,sound); return status; } } // @formatter:on
<gh_stars>0 export const STORE_STORAGE_VERSION = "0.3";
travis_install_jdk() { local url vendor version license jdk certlink jdk="$1" vendor="$2" version="$3" case "${TRAVIS_CPU_ARCH}" in "arm64" | "s390x" | "ppc64le") travis_install_jdk_package "$version" ;; *) travis_install_jdk_ext_provider "$jdk" "$vendor" "$version" ;; esac } travis_install_jdk_ext_provider() { local url vendor version license jdk certlink jdk="$1" vendor="$2" version="$3" if [[ "$vendor" == openjdk ]]; then license=GPL elif [[ "$vendor" == oracle ]]; then license=BCL fi mkdir -p ~/bin url="https://$TRAVIS_APP_HOST/files/install-jdk.sh" if ! travis_download "$url" ~/bin/install-jdk.sh; then url="https://raw.githubusercontent.com/sormuras/bach/master/install-jdk.sh" travis_download "$url" ~/bin/install-jdk.sh || { echo "${ANSI_RED}Could not acquire install-jdk.sh. Stopping build.${ANSI_RESET}" >/dev/stderr travis_terminate 2 } fi chmod +x ~/bin/install-jdk.sh travis_cmd "export JAVA_HOME=~/$jdk" --echo # shellcheck disable=SC2016 travis_cmd 'export PATH="$JAVA_HOME/bin:$PATH"' --echo [[ "$TRAVIS_OS_NAME" == linux && "$vendor" == openjdk ]] && certlink=" --cacerts" # shellcheck disable=2088 travis_cmd "~/bin/install-jdk.sh --target \"$JAVA_HOME\" --workspace \"$TRAVIS_HOME/.cache/install-jdk\" --feature \"$version\" --license \"$license\"$certlink" --echo --assert } travis_install_jdk_package() { local JAVA_VERSION JAVA_VERSION="$1" sudo apt-get update -yqq PACKAGE="adoptopenjdk-${JAVA_VERSION}-hotspot" if ! dpkg -s "$PACKAGE" >/dev/null 2>&1; then if dpkg-query -l adoptopenjdk* >/dev/null 2>&1; then dpkg-query -l adoptopenjdk* | grep adoptopenjdk | awk '{print $2}' | xargs sudo dpkg -P fi sudo apt-get -yqq --no-install-suggests --no-install-recommends install "$PACKAGE" || true fi }
<gh_stars>0 #include "../include/infosqlitestore.h" #include "../include/sqlite_database.h" #include "../include/sqlite_statement.h" #include <infovalue.h> #include <stringconvert.h> //////////////////////////////////////// #if defined(__CYGWIN__) #include <iostream> #else #include <boost/log/trivial.hpp> #endif ///////////////////////////////////// namespace info { using namespace info_sqlite; ////////////////////////////////////// const std::string SQLiteStatHelper::DEFAULT_DATABASE_NAME("info_sets.sqlite"); ///////////////////////////////////// static const char *SQL_CREATE_DATASET = "CREATE TABLE IF NOT EXISTS dbdataset(" " datasetid INTEGER PRIMARY KEY AUTOINCREMENT," " optlock INTEGER NOT NULL DEFAULT 1," " sigle TEXT NOT NULL UNIQUE," " nom TEXT DEFAULT NULL," " description TEXT DEFAULT NULL," " status TEXT DEFAULT NULL" " )"; static const char *SQL_CREATE_VARIABLE = "CREATE TABLE IF NOT EXISTS dbvariable(" " variableid INTEGER PRIMARY KEY AUTOINCREMENT," " optlock INTEGER NOT NULL DEFAULT 1," " datasetid INTEGER NOT NULL," " sigle TEXT NOT NULL," " weight REAL NOT NULL DEFAULT 1," " vartype TEXT NOT NULL," " categvar INTEGER NOT NULL DEFAULT 0," " nbmodals INTEGER NOT NULL DEFAULT 0," " nom TEXT DEFAULT NULL," " description TEXT DEFAULT NULL," " genre TEXT DEFAULT NULL," " status TEXT DEFAULT NULL," " CONSTRAINT uc_variable UNIQUE (datasetid, sigle)," " CONSTRAINT fk_variable_dataset FOREIGN KEY (datasetid) REFERENCES dbdataset (datasetid) ON DELETE CASCADE" " )"; static const char *SQL_CREATE_INDIV = "CREATE TABLE IF NOT EXISTS dbindiv(" " individ INTEGER PRIMARY KEY AUTOINCREMENT," " optlock INTEGER NOT NULL DEFAULT 1," " datasetid INTEGER NOT NULL," " sigle TEXT NOT NULL," " weight REAL NOT NULL DEFAULT 1," " nom TEXT DEFAULT NULL," " description TEXT DEFAULT NULL," " status TEXT DEFAULT NULL," " CONSTRAINT uc_indiv UNIQUE (datasetid, sigle)," " CONSTRAINT fk_indiv_dataset FOREIGN KEY (datasetid) REFERENCES dbdataset (datasetid) ON DELETE CASCADE" " )"; static const char *SQL_CREATE_VALUE = "CREATE TABLE IF NOT EXISTS dbvalue(" " valueid INTEGER PRIMARY KEY AUTOINCREMENT," " optlock INTEGER NOT NULL DEFAULT 1," " variableid INTEGER NOT NULL," " individ INTEGER NOT NULL," " stringval TEXT NULL," " status TEXT DEFAULT NULL," " CONSTRAINT uc_value UNIQUE (variableid, individ)," " CONSTRAINT fk_value_variable FOREIGN KEY (variableid) REFERENCES dbvariable (variableid) ON DELETE CASCADE," " CONSTRAINT fk_value_indiv FOREIGN KEY (individ) REFERENCES dbindiv (individ) ON DELETE CASCADE" " )"; static const char *CREATE_SQL[] = { SQL_CREATE_DATASET, SQL_CREATE_VARIABLE, SQL_CREATE_INDIV, SQL_CREATE_VALUE, nullptr }; ///////////////////////////////////// static const char *SQL_FIND_ALL_DATASETS_IDS = "SELECT datasetid" " FROM dbdataset ORDER BY datasetid" " LIMIT :taken OFFSET ?"; static const char *SQL_FIND_ALL_DATASETS = "SELECT datasetid,optlock,sigle,nom,description,status" " FROM dbdataset ORDER BY sigle" " LIMIT ? OFFSET ?"; static const char *SQL_FIND_DATASET_BY_ID = "SELECT datasetid,optlock,sigle,nom,description,status" " FROM dbdataset WHERE datasetid = ?"; static const char *SQL_FIND_DATASET_BY_SIGLE = "SELECT datasetid,optlock,sigle,nom,description,status" " FROM dbdataset WHERE UPPER(LTRIM(RTRIM(sigle))) = ?"; static const char *SQL_INSERT_DATASET = "INSERT INTO dbdataset (sigle,nom,description,status)" " VALUES (?,?,?,?)"; static const char *SQL_UPDATE_DATASET = "UPDATE dbdataset SET optlock = optlock + 1," " sigle = ?, nom = ?, description = ?, status = ? WHERE datasetid = ?"; static const char *SQL_REMOVE_DATASET = "DELETE FROM dbdataset WHERE datasetid = ?"; static const char *SQL_FIND_DATASETS_COUNT = "SELECT COUNT(*) FROM dbdataset"; // static const char *SQL_FIND_DATASET_VARIABLES = "SELECT variableid, optlock, datasetid , sigle, vartype, categvar, nom, description, genre, status,weight,nbmodals" " FROM dbvariable WHERE datasetid = ?" " ORDER BY categvar DESC, sigle ASC" " LIMIT ? OFFSET ?"; static const char *SQL_FIND_DATASET_VARIABLES_IDS = "SELECT variableid FROM dbvariable WHERE datasetid = ?" " ORDER BY variableid" " LIMIT ? OFFSET ?"; static const char *SQL_VARIABLE_BY_ID = "SELECT variableid,optlock,datasetid,sigle,vartype,categvar,nom,description,genre,status,weight,nbmodals" " FROM dbvariable WHERE variableid = ?"; static const char *SQL_VARIABLE_BY_DATASET_AND_SIGLE = "SELECT variableid,optlock,datasetid,sigle,vartype,categvar,nom,description,genre,status,weight,nbmodals" " FROM dbvariable WHERE datasetid = ? AND UPPER(LTRIM(RTRIM(sigle))) = ?"; static const char *SQL_INSERT_VARIABLE = "INSERT INTO dbvariable (datasetid,sigle,vartype,categvar,nom,description,genre,status,weight,nbmodals)" " VALUES (?,?,?,?,?,?,?,?,?,?)"; static const char *SQL_UPDATE_VARIABLE = "UPDATE dbvariable SET optlock = optlock + 1," " sigle = ?, vartype = ?, categvar = ?, nom = ?, description = ?, genre = ?, status = ?,weight = ?,nbmodals = ? WHERE variableid = ?"; static const char *SQL_REMOVE_VARIABLE = "DELETE FROM dbvariable WHERE variableid = ?"; static const char *SQL_FIND_DATASET_VARIABLES_COUNT = "SELECT COUNT(*) FROM dbvariable WHERE datasetid = ?"; // static const char *SQL_FIND_DATASET_INDIVS_COUNT = "SELECT COUNT(*) FROM dbindiv" " WHERE datasetid = ?"; static const char *SQL_GET_DATASET_INDIV_IDS = "SELECT individ FROM dbindiv" " WHERE datasetid = ? ORDER BY individ ASC" " LIMIT ? OFFSET ?"; static const char *SQL_FIND_DATASET_INDIVS = "SELECT individ,optlock,datasetid,sigle,nom,description,status,weight" " FROM dbindiv WHERE datasetid = ? ORDER BY sigle" " LIMIT ? OFFSET ?"; static const char *SQL_INDIV_BY_ID = "SELECT individ,optlock,datasetid,sigle,nom,description,status,weight" " FROM dbindiv WHERE individ = ?"; static const char *SQL_INDIV_BY_DATASET_AND_SIGLE = "SELECT individ,optlock,datasetid,sigle,nom,description,status,weight" " FROM dbindiv WHERE datasetid = ? AND UPPER(LTRIM(RTRIM(sigle))) = ?"; static const char *SQL_INSERT_INDIV = "INSERT INTO dbindiv (datasetid,sigle,nom,description,status,weight)" " VALUES(?,?,?,?,?,?)"; static const char *SQL_UPDATE_INDIV = "UPDATE dbindiv SET optlock = OPTLOCK + 1," " sigle = ?, nom = ?, description = ?, status = ?,weight = ? WHERE individ = ?"; static const char *SQL_REMOVE_INDIV = "DELETE FROM dbindiv WHERE individ = ?"; // static const char *SQL_VALUE_BY_ID = "SELECT valueid,optlock,variableid,individ,stringval,status" " FROM dbvalue WHERE valueid = ?"; static const char *SQL_VALUES_BY_VARIABLE_INDIV = "SELECT valueid,optlock,variableid,individ,stringval,status" " FROM dbvalue WHERE variableid = ? AND individ = ?"; static const char *SQL_INSERT_VALUE = "INSERT INTO dbvalue (variableid,individ,stringval,status)" " VALUES(?,?,?,?)"; static const char *SQL_UPDATE_VALUE = "UPDATE dbvalue SET optlock = optlock + 1," " stringval = ?, status = ? WHERE valueid = ? "; static const char *SQL_REMOVE_VALUE = "DELETE from dbvalue WHERE valueid = ?"; static const char *SQL_FIND_DATASET_VALUES_COUNT = "SELECT COUNT(*)" " FROM dbvalue a, dbvariable b" " WHERE a.variableid = b.variableid AND b.datasetid = ?"; static const char *SQL_FIND_DATASET_VALUES = "SELECT a.valueid,a.optlock,a.variableid,a.individ,a.stringval,a.status" " FROM dbvalue a, dbvariable b" " WHERE a.variableid = b.variableid AND b.datasetid = ?" " ORDER BY a.variableid ASC, a.individ ASC" " LIMIT ? OFFSET ?"; static const char *SQL_VALUES_BY_VARIABLEID = "SELECT valueid,optlock,variableid,individ,stringval,status" " FROM dbvalue WHERE variableid = ?" " LIMIT ? OFFSET ?"; static const char *SQL_VALUES_BY_INDIVID = "SELECT valueid,optlock,variableid,individ,stringval,status" " FROM dbvalue WHERE individ = ?" " LIMIT ? OFFSET ?"; static const char *SQL_INDIV_VALUES_COUNT = "SELECT COUNT(*)" " FROM dbvalue WHERE individ = ?"; static const char *SQL_VARIABLE_VALUES_COUNT = "SELECT COUNT(*)" " FROM dbvalue WHERE variableid = ?"; static const char *SQL_VARIABLE_VALUES_DISTINCT = "SELECT DISTINCT stringval FROM dbvalue WHERE variableid = ?" " LIMIT ? OFFSET ?"; static const char *SQL_DELETE_VARIABLE_VALUES = "DELETE FROM dbvalue where variableid = ?"; static const char *SQL_DELETE_INDIV_VALUES = "DELETE FROM dbvalue where individ = ?"; static const char *SQL_FIND_DATASET_VARIABLES_TYPES = "SELECT variableid,vartype FROM dbvariable WHERE datasetid = ?"; static const char *SQL_FIND_VARIABLE_TYPE = "SELECT vartype FROM dbvariable WHERE variableid = ?"; /////////////////////////////////////// static void log_error(const std::exception & err) { #if defined(__CYGWIN__) std::cerr << "Error: " << err.what() << std::endl; #else BOOST_LOG_TRIVIAL(error) << err.what(); #endif// __CYGWIN__ } static void log_error(sqlite_error &err) { #if defined(__CYGWIN__) std::cerr << "SQLite Error: " << err.code() << ", " << err.what() << std::endl; #else BOOST_LOG_TRIVIAL(error) << "SQLite error: " << err.code() << " , " << err.what(); #endif // __CYGWIN } ///////////////////////////////////////////// static void convert_value(const std::string &stype, InfoValue &v) { if (stype == "integer") { int v0 = 0; v.get_value(v0); v = v0; } else if ((stype == "real") || (stype == "float")) { float v0 = 0.0f; v.get_value(v0); v = v0; } else if (stype == "double") { double v0 = 0.0;; v.get_value(v0); v = v0; } else if (stype == "boolean") { bool v0 = false; v.get_value(v0); v = v0; } }// convert_value static void convert_values(const SQLiteStatHelper::ints_string_map &types, SQLiteStatHelper::values_vector &vals) { for (auto it = vals.begin(); it != vals.end(); ++it) { SQLiteStatHelper::ValueType &v = *it; SQLiteStatHelper::IDTYPE key = v.variable_id(); auto jt = types.find(key); if (jt != types.end()) { SQLiteStatHelper::STRINGTYPE s = (*jt).second; InfoValue vx = v.value(); convert_value(s, vx); v.value(vx); } }// it }// convert_values static void convert_values(const SQLiteStatHelper::STRINGTYPE &stype, SQLiteStatHelper::values_vector &vals) { for (auto it = vals.begin(); it != vals.end(); ++it) { SQLiteStatHelper::ValueType &v = *it; InfoValue vx = v.value(); convert_value(stype, vx); v.value(vx); }// it }// convert_values ////////////////////////////////////////////// void SQLiteStatHelper::begin_transaction(void) { assert(this->is_valid()); if (this->m_intransaction) { return; } this->m_base->begin_transaction(); this->m_intransaction = true; } // begin_transaction void SQLiteStatHelper::commit_transaction(void) { assert(this->is_valid()); if (!this->m_intransaction) { return; } this->m_base->commit_transaction(); this->m_intransaction = false; } // commit_transaction void SQLiteStatHelper::rollback_transaction(void) { assert(this->is_valid()); if (!this->m_intransaction) { return; } try { this->m_base->rollback_transaction(); this->m_intransaction = false; } catch (...) {} this->m_intransaction = false; } // rollback_transaction /////////////////////////////////////// bool SQLiteStatHelper::find_dataset_variables_types(const DatasetType &oSet, ints_string_map &oMap) { assert(this->is_valid()); DatasetType xSet(oSet); oMap.clear(); if (!this->find_dataset(xSet)) { return (false); } try { IDTYPE nDatasetId = xSet.id(); SQLite_Statement q(*(this->m_base), SQL_FIND_DATASET_VARIABLES_TYPES); assert(q.get_parameters_count() == 1); q.bind(1, nDatasetId); q.exec(); assert(q.get_num_columns() == 2); while (q.move_next()) { IDTYPE key = 0; q.get_column(0, key); std::string val; q.get_column(1, val); oMap[key] = val; } return (true); } catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_dataset_variables_types bool SQLiteStatHelper::remove_indiv(const IndivType &oInd, bool bCommit /*= true*/) { assert(this->is_valid()); bool bInTrans = false; lock_type oLock(this->_mutex); try { if (bCommit) { this->begin_transaction(); bInTrans = true; } IndivType xind(oInd); if (!this->find_indiv(xind)) { return (false); } IDTYPE nId = xind.id(); SQLite_Statement q1(*(this->m_base), SQL_DELETE_INDIV_VALUES); assert(q1.get_parameters_count() == 1); q1.bind(1, nId); q1.exec(); SQLite_Statement q2(*(this->m_base), SQL_REMOVE_INDIV); assert(q2.get_parameters_count() == 1); q2.bind(1, nId); q2.exec(); if (bInTrans && bCommit) { this->commit_transaction(); } return (true); }// try catch (sqlite_error &err) { log_error(err); if (bInTrans) { this->rollback_transaction(); } } catch (std::exception &ex) { log_error(ex); if (bInTrans) { this->rollback_transaction(); } } return (false); }//remove_indiv bool SQLiteStatHelper::remove_variable(const VariableType &oVar, bool bCommit /*= true*/) { assert(this->is_valid()); bool bInTrans = false; lock_type oLock(this->_mutex); try { if (bCommit) { this->begin_transaction(); bInTrans = true; } VariableType xind(oVar); if (!this->find_variable(xind)) { return (false); } IDTYPE nId = xind.id(); SQLite_Statement q1(*(this->m_base), SQL_DELETE_VARIABLE_VALUES); assert(q1.get_parameters_count() == 1); q1.bind(1, nId); q1.exec(); SQLite_Statement q2(*(this->m_base), SQL_REMOVE_VARIABLE); assert(q2.get_parameters_count() == 1); q2.bind(1, nId); q2.exec(); if (bInTrans && bCommit) { this->commit_transaction(); } return (true); }// try catch (sqlite_error &err) { log_error(err); if (bInTrans) { this->rollback_transaction(); } } catch (std::exception &ex) { log_error(ex); if (bInTrans) { this->rollback_transaction(); } } return (false); }//remove_variable //////////////////// VALUES ///////////////////// bool SQLiteStatHelper::find_dataset_values_count(const DatasetType &oSet, size_t &nCount) { assert(this->is_valid()); try { DatasetType xSet(oSet); nCount = 0; if (!this->find_dataset(xSet)) { return (false); } IDTYPE nDatasetId = xSet.id(); SQLite_Statement q(*(this->m_base), SQL_FIND_DATASET_VALUES_COUNT); assert(q.get_parameters_count() == 1); q.bind(1, nDatasetId); q.exec(); assert(q.get_num_columns() == 1); if (q.move_next()) { int nx = 0; q.get_column(0, nx); nCount = (size_t)nx; } return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_dataset_values_count bool SQLiteStatHelper::find_dataset_values(const DatasetType &oSet, values_vector &oList, size_t skip /*= 0*/, size_t count /*= 100*/) { assert(this->is_valid()); try { oList.clear(); if (count < 1) { count = DATATRANSFER_CHUNK_SIZE; } DatasetType xSet(oSet); if (!this->find_dataset(xSet)) { return (false); } ints_string_map types; this->find_dataset_variables_types(xSet, types); IDTYPE nDatasetId = xSet.id(); SQLite_Statement q(*(this->m_base), SQL_FIND_DATASET_VALUES); assert(q.get_parameters_count() == 3); q.bind(1, nDatasetId); q.bind(2, (int)count); q.bind(3, (int)skip); q.exec(); while (q.move_next()) { ValueType cur; this->read_value(q, cur); cur.dataset_id(nDatasetId); oList.push_back(cur); } convert_values(types, oList); return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_dataset_values bool SQLiteStatHelper::find_variable_values(VariableType &oVar, values_vector &oList, size_t skip /*= 0*/, size_t count /*= 100*/) { assert(this->is_valid()); try { oList.clear(); if (count < 1) { count = DATATRANSFER_CHUNK_SIZE; } if (!this->find_variable(oVar)) { return (false); } STRINGTYPE stype; this->find_variable_type(oVar.id(), stype); IDTYPE nDatasetId = oVar.dataset_id(); IDTYPE nId = oVar.id(); SQLite_Statement q(*(this->m_base), SQL_VALUES_BY_VARIABLEID); assert(q.get_parameters_count() == 3); q.bind(1, nId); q.bind(2, (int)count); q.bind(3, (int)skip); q.exec(); while (q.move_next()) { ValueType cur; this->read_value(q, cur); cur.dataset_id(nDatasetId); oList.push_back(cur); } convert_values(stype, oList); return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); } bool SQLiteStatHelper::find_variable_distinct_values(VariableType &oVar, strings_vector &oList, size_t skip /*= 0*/, size_t count /*= 100*/) { assert(this->is_valid()); oList.clear(); try { oList.clear(); if (count < 1) { count = DATATRANSFER_CHUNK_SIZE; } if (!this->find_variable(oVar)) { return (false); } IDTYPE nId = oVar.id(); SQLite_Statement q(*(this->m_base), SQL_VARIABLE_VALUES_DISTINCT); assert(q.get_parameters_count() == 3); q.bind(1, nId); q.bind(2, (int)count); q.bind(3, (int)skip); q.exec(); while (q.move_next()) { std::string s; q.get_column(0, s); if (!s.empty()) { oList.push_back(s); } } return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_variable_distinct_values bool SQLiteStatHelper::find_variable_type(IDTYPE nVarId, STRINGTYPE stype) { assert(this->is_valid()); try { stype.clear(); SQLite_Statement q(*(this->m_base), SQL_FIND_VARIABLE_TYPE); assert(q.get_parameters_count() == 1); q.bind(1, nVarId); q.exec(); if (q.move_next()) { q.get_column(0, stype); } return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_variable_type bool SQLiteStatHelper::find_indiv_values_count(IndivType &oInd, size_t &nc) { assert(this->is_valid()); try { nc = 0; if (!this->find_indiv(oInd)) { return (false); } IDTYPE nId = oInd.id(); SQLite_Statement q(*(this->m_base), SQL_INDIV_VALUES_COUNT); assert(q.get_parameters_count() == 1); q.bind(1, nId); q.exec(); if (q.move_next()) { int nx = 0; q.get_column(0, nx); nc = (size_t)nx; } return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_indiv_values_count bool SQLiteStatHelper::find_variable_values_count(VariableType &oVar, size_t &nc) { assert(this->is_valid()); try { nc = 0; if (!this->find_variable(oVar)) { return (false); } IDTYPE nId = oVar.id(); SQLite_Statement q(*(this->m_base), SQL_VARIABLE_VALUES_COUNT); assert(q.get_parameters_count() == 1); q.bind(1, nId); q.exec(); if (q.move_next()) { int nx = 0; q.get_column(0, nx); nc = (size_t)nx; } return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_variable_values_count bool SQLiteStatHelper::find_indiv_values(IndivType &oInd, values_vector &oList, size_t skip /*= 0*/, size_t count /*= 100*/) { assert(this->is_valid()); oList.clear(); try { oList.clear(); if (count < 1) { count = DATATRANSFER_CHUNK_SIZE; } if (!this->find_indiv(oInd)) { return (false); } DatasetType xSet; xSet.id(oInd.dataset_id()); if (!this->find_dataset(xSet)) { return (false); } ints_string_map types; this->find_dataset_variables_types(xSet, types); IDTYPE nDatasetId = xSet.id(); IDTYPE nId = oInd.id(); SQLite_Statement q(*(this->m_base), SQL_VALUES_BY_INDIVID); assert(q.get_parameters_count() == 3); q.bind(1, nId); q.bind(2, (int)count); q.bind(3, (int)skip); q.exec(); while (q.move_next()) { ValueType cur; this->read_value(q, cur); cur.dataset_id(nDatasetId); oList.push_back(cur); } convert_values(types, oList); return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_indiv_values /// bool SQLiteStatHelper::maintains_values(const values_vector &oVals, bool bCommit /*= true*/, bool bRemove /*= false*/) { assert(this->is_valid()); bool bInTrans = false; lock_type oLock(this->_mutex); try { if (bCommit) { this->begin_transaction(); bInTrans = true; } SQLite_Statement qInsert(*(this->m_base), SQL_INSERT_VALUE); assert(qInsert.get_parameters_count() == 4); SQLite_Statement qUpdate(*(this->m_base), SQL_UPDATE_VALUE); assert(qUpdate.get_parameters_count() == 3); SQLite_Statement qRemove(*(this->m_base), SQL_REMOVE_VALUE); assert(qRemove.get_parameters_count() == 1); // for (auto &oVal : oVals) { const InfoValue &v = oVal.value(); bool mustRemove = bRemove; ValueType xVal(oVal); this->find_value(xVal); IDTYPE nId = xVal.id(); STRINGTYPE status = oVal.status(); if (nId != 0) { if (v.empty()) { mustRemove = true; } } if (mustRemove) { if (nId != 0) { qRemove.bind(1, nId); qRemove.exec(); }// nId } else if (oVal.is_writeable()) { if (nId != 0) { qUpdate.bind(1, v); qUpdate.bind(2, status); qUpdate.bind(3, nId); qUpdate.exec(); } else if (!v.empty()) { IDTYPE nVarId = oVal.variable_id(); IDTYPE nIndId = oVal.indiv_id(); qInsert.bind(1, nVarId); qInsert.bind(2, nIndId); qInsert.bind(3, v); qInsert.bind(4, status); qInsert.exec(); } } // writeable }// oVal // if (bCommit && bInTrans) { this->commit_transaction(); } return (true); }// try catch (sqlite_error &err) { log_error(err); if (bInTrans) { this->rollback_transaction(); } } catch (std::exception &ex) { log_error(ex); if (bInTrans) { this->rollback_transaction(); } } return (false); }//maintains_values bool SQLiteStatHelper::find_value(ValueType &cur) { assert(this->is_valid()); try { IDTYPE nId = cur.id(); SQLite_Statement q(*(this->m_base), SQL_VALUE_BY_ID); assert(q.get_parameters_count() == 1); q.bind(1, nId); q.exec(); if (q.move_next()) { ValueType cur; this->read_value(q, cur); return (true); } IDTYPE nVarId = cur.variable_id(); IDTYPE nIndId = cur.indiv_id(); SQLite_Statement q2(*(this->m_base), SQL_VALUES_BY_VARIABLE_INDIV); assert(q2.get_parameters_count() == 2); q2.bind(1, nVarId); q2.bind(2, nIndId); q2.exec(); if (q2.move_next()) { ValueType cur; this->read_value(q2, cur); return (true); } }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_value /////////////////////////////// INDIVS /////////////// bool SQLiteStatHelper::find_dataset_indivs_count(const DatasetType &oSet, size_t &nCount) { assert(this->is_valid()); try { DatasetType xSet(oSet); nCount = 0; if (!this->find_dataset(xSet)) { return (false); } IDTYPE nDatasetId = xSet.id(); SQLite_Statement q(*(this->m_base), SQL_FIND_DATASET_INDIVS_COUNT); assert(q.get_parameters_count() == 1); q.bind(1, nDatasetId); q.exec(); int nx = 0; if (q.move_next()) { q.get_column(0, nx); nCount = (size_t)nx; } return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_dataset_indivs_count bool SQLiteStatHelper::maintains_indivs(const indivs_vector &oInds, bool bCommit /*= true*/, bool bRemove /*= false*/) { assert(this->is_valid()); bool bInTrans = false; lock_type oLock(this->_mutex); // try { if (bCommit) { this->begin_transaction(); bInTrans = true; } SQLite_Statement qInsert(*(this->m_base), SQL_INSERT_INDIV); assert(qInsert.get_parameters_count() == 6); SQLite_Statement qUpdate(*(this->m_base), SQL_UPDATE_INDIV); assert(qUpdate.get_parameters_count() == 6); // for (auto &oInd : oInds) { IndivType xInd(oInd); this->find_indiv(xInd); IDTYPE nId = xInd.id(); if (bRemove) { if (nId != 0) { this->remove_indiv(xInd, false); }// nId } else if (oInd.is_writeable()) { STRINGTYPE sigle, name, status, desc; sigle = oInd.sigle(); name = oInd.name(); status = oInd.status(); desc = oInd.description(); double w = oInd.weight(); if (w < 0.0) { w = 0; } IDTYPE nDatasetId = oInd.dataset_id(); if (nId != 0) { qUpdate.bind(1, sigle); qUpdate.bind(2, name); qUpdate.bind(3, desc); qUpdate.bind(4, status); qUpdate.bind(5, w); qUpdate.bind(6, nId); qUpdate.exec(); } else { qInsert.bind(1, nDatasetId); qInsert.bind(2, sigle); qInsert.bind(3, name); qInsert.bind(4, desc); qInsert.bind(5, status); qInsert.bind(6, w); qInsert.exec(); } } }// oInd if (bCommit && bInTrans) { this->commit_transaction(); } return (true); }// try catch (sqlite_error &err) { log_error(err); if (bInTrans) { this->rollback_transaction(); } } catch (std::exception &ex) { log_error(ex); if (bInTrans) { this->rollback_transaction(); } } return (false); }//maintains_indivs bool SQLiteStatHelper::find_dataset_indivs_ids(const DatasetType &oSet, ints_vector &oList, size_t skip /*=0*/, size_t count /*=100*/) { assert(this->is_valid()); try { oList.clear(); if (count < 1) { count = DATATRANSFER_CHUNK_SIZE; } DatasetType xSet(oSet); if (!this->find_dataset(xSet)) { return (false); } IDTYPE nDatasetId = xSet.id(); SQLite_Statement q(*(this->m_base), SQL_GET_DATASET_INDIV_IDS); assert(q.get_parameters_count() == 3); q.bind(1, nDatasetId); q.bind(2, (int)count); q.bind(3, (int)skip); q.exec(); assert(q.get_num_columns() == 1); while (q.move_next()) { IDTYPE nId = 0; q.get_column(0, nId); if (nId != 0) { oList.push_back(nId); } } return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_dataset_indivs_ids bool SQLiteStatHelper::find_dataset_indivs(const DatasetType &oSet, indivs_vector &oList, size_t skip /*=0*/, size_t count /*=100*/) { assert(this->is_valid()); try { oList.clear(); if (count < 1) { count = DATATRANSFER_CHUNK_SIZE; } DatasetType xSet(oSet); if (!this->find_dataset(xSet)) { return (false); } IDTYPE nDatasetId = xSet.id(); SQLite_Statement q(*(this->m_base), SQL_FIND_DATASET_INDIVS); assert(q.get_parameters_count() == 3); q.bind(1, nDatasetId); q.bind(2, (int)count); q.bind(3, (int)skip); q.exec(); while (q.move_next()) { IndivType cur; this->read_indiv(q, cur); oList.push_back(cur); } return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_dataset_indivs //////////////////////////////////// bool SQLiteStatHelper::find_indiv(IndivType &cur) { assert(this->is_valid()); try { IDTYPE nId = cur.id(); if (nId != 0) { SQLite_Statement q(*(this->m_base), SQL_INDIV_BY_ID); assert(q.get_parameters_count() == 1); q.bind(1, nId); q.exec(); if (q.move_next()) { this->read_indiv(q, cur); return (true); } } STRINGTYPE sigle = cur.sigle(); IDTYPE nDatasetId = cur.dataset_id(); if ((!sigle.empty()) && (nDatasetId != 0)) { SQLite_Statement q(*(this->m_base), SQL_INDIV_BY_DATASET_AND_SIGLE); assert(q.get_parameters_count() == 2); q.bind(1, nDatasetId); q.bind(2, sigle); q.exec(); if (q.move_next()) { this->read_indiv(q, cur); return (true); } } return (false); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_indiv ////////////////////////////// VARIABLES ///// bool SQLiteStatHelper::find_dataset_variables_count(const DatasetType &oSet, size_t &nCount) { assert(this->is_valid()); try { DatasetType xSet(oSet); nCount = 0; if (!this->find_dataset(xSet)) { return (false); } IDTYPE nDatasetId = xSet.id(); SQLite_Statement q(*(this->m_base), SQL_FIND_DATASET_VARIABLES_COUNT); assert(q.get_parameters_count() == 1); q.bind(1, nDatasetId); q.exec(); assert(q.get_num_columns() == 1); if (q.move_next()) { int nx = 0; q.get_column(0, nx); nCount = nx; } return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_dataset_variables_count bool SQLiteStatHelper::maintains_variables(const variables_vector &oVars, bool bCommit /*= true*/, bool bRemove /*= false*/) { assert(this->is_valid()); bool bInTrans = false; lock_type oLock(this->_mutex); try { if (bCommit) { this->begin_transaction(); bInTrans = true; } SQLite_Statement qInsert(*(this->m_base), SQL_INSERT_VARIABLE); assert(qInsert.get_parameters_count() == 10); SQLite_Statement qUpdate(*(this->m_base), SQL_UPDATE_VARIABLE); assert(qUpdate.get_parameters_count() == 10); // for (auto &oVar : oVars) { VariableType xVar(oVar); this->find_variable(xVar); IDTYPE nId = xVar.id(); if (bRemove) { if (nId != 0) { this->remove_variable(xVar, false); }// nId } else if (oVar.is_writeable()) { STRINGTYPE sigle, name, status, desc, vartype, genre; sigle = oVar.sigle(); name = oVar.name(); status = oVar.status(); desc = oVar.description(); vartype = oVar.vartype(); genre = oVar.genre(); int nCateg = (oVar.is_categ()) ? 1 : 0; int nbModal = oVar.modalites_count(); IDTYPE nDatasetId = oVar.dataset_id(); double w = oVar.weight(); if (w < 0) { w = 0; } if (nId != 0) { qUpdate.bind(1, sigle); qUpdate.bind(2, vartype); qUpdate.bind(3, nCateg); qUpdate.bind(4, name); qUpdate.bind(5, desc); qUpdate.bind(6, genre); qUpdate.bind(7, status); qUpdate.bind(8, w); qUpdate.bind(9, nbModal); qUpdate.bind(10, nId); qUpdate.exec(); } else { qInsert.bind(1, nDatasetId); qInsert.bind(2, sigle); qInsert.bind(3, vartype); qInsert.bind(4, nCateg); qInsert.bind(5, name); qInsert.bind(6, desc); qInsert.bind(7, genre); qInsert.bind(8, status); qInsert.bind(9, w); qInsert.bind(10, nbModal); qInsert.exec(); } }// writeable }// oVar if (bCommit && bInTrans) { this->commit_transaction(); } return (true); }// try catch (sqlite_error &err) { log_error(err); if (bInTrans) { this->rollback_transaction(); } } catch (std::exception &ex) { log_error(ex); if (bInTrans) { this->rollback_transaction(); } } return (false); }//maintains_variables bool SQLiteStatHelper::find_dataset_variables_ids(const DatasetType &oSet, ints_vector &oList, size_t skip /*=0*/, size_t count /*=100*/) { assert(this->is_valid()); try { oList.clear(); if (count < 1) { count = DATATRANSFER_CHUNK_SIZE; } DatasetType xSet(oSet); if (!this->find_dataset(xSet)) { return (false); } IDTYPE nDatasetId = xSet.id(); SQLite_Statement q(*(this->m_base), SQL_FIND_DATASET_VARIABLES_IDS); assert(q.get_parameters_count() == 3); q.bind(1, nDatasetId); q.bind(2, (int)count); q.bind(3, (int)skip); q.exec(); assert(q.get_num_columns() == 1); while (q.move_next()) { IDTYPE nId = 0; q.get_column(0, nId); if (nId != 0) { oList.push_back(nId); } } return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_dataset_variables_ids bool SQLiteStatHelper::find_dataset_variables(const DatasetType &oSet, variables_vector &oList, size_t skip /*=0*/, size_t count /*=100*/) { assert(this->is_valid()); try { oList.clear(); if (count < 1) { count = DATATRANSFER_CHUNK_SIZE; } DatasetType xSet(oSet); if (!this->find_dataset(xSet)) { return (false); } IDTYPE nDatasetId = xSet.id(); SQLite_Statement q(*(this->m_base), SQL_FIND_DATASET_VARIABLES); assert(q.get_parameters_count() == 3); q.bind(1, nDatasetId); q.bind(2, (int)count); q.bind(3, (int)skip); q.exec(); while (q.move_next()) { VariableType cur; this->read_variable(q, cur); oList.push_back(cur); } return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_dataset_variables //////////////////////////////////// bool SQLiteStatHelper::find_variable(VariableType &cur) { assert(this->is_valid()); try { IDTYPE nId = cur.id(); if (nId != 0) { SQLite_Statement q(*(this->m_base), SQL_VARIABLE_BY_ID); assert(q.get_parameters_count() == 1); q.bind(1, nId); q.exec(); if (q.move_next()) { this->read_variable(q, cur); return (true); } } STRINGTYPE sigle = cur.sigle(); IDTYPE nDatasetId = cur.dataset_id(); if ((!sigle.empty()) && (nDatasetId != 0)) { SQLite_Statement q(*(this->m_base), SQL_VARIABLE_BY_DATASET_AND_SIGLE); assert(q.get_parameters_count() == 2); q.bind(1, nDatasetId); q.bind(2, sigle); q.exec(); if (q.move_next()) { this->read_variable(q, cur); return (true); } } return (false); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_variable ///////////////////////////////////////////////////// bool SQLiteStatHelper::remove_dataset(const DatasetType &cur, bool bCommit /*= true*/) { assert(this->is_valid()); bool bInTrans = false; lock_type oLock(this->_mutex); try { if (bCommit) { this->begin_transaction(); bInTrans = true; } DatasetType xSet(cur); if (!this->find_dataset(xSet)) { return (false); } IDTYPE nId = xSet.id(); { size_t nCount = 0; this->find_dataset_indivs_count(xSet, nCount); if (nCount > 0) { ints_vector oIds; this->find_dataset_indivs_ids(xSet, oIds, 0, nCount); std::for_each(oIds.begin(), oIds.end(), [&](const IDTYPE &aId) { IndivType xInd(aId); this->remove_indiv(xInd, false); }); } } { size_t nCount = 0; this->find_dataset_variables_count(xSet, nCount); if (nCount > 0) { ints_vector oIds; this->find_dataset_variables_ids(xSet, oIds, 0, nCount); std::for_each(oIds.begin(), oIds.end(), [&](const IDTYPE &aId) { VariableType xInd(aId); this->remove_variable(xInd, false); }); } } SQLite_Statement qq(*(this->m_base), SQL_REMOVE_DATASET); assert(qq.get_parameters_count() == 1); qq.bind(1, nId); qq.exec(); if (bCommit && bInTrans) { this->commit_transaction(); } return (true); }// try catch (sqlite_error &err) { log_error(err); if (bInTrans) { this->rollback_transaction(); } } catch (std::exception &ex) { log_error(ex); if (bInTrans) { this->rollback_transaction(); } } return (false); }// remove_dataset bool SQLiteStatHelper::maintains_dataset(DatasetType &cur, bool bCommit) { assert(this->is_valid()); if (!cur.is_writeable()) { return (false); } bool bInTrans = false; lock_type oLock(this->_mutex); try { if (bCommit) { this->begin_transaction(); bInTrans = true; } DatasetType xSet(cur); this->find_dataset(xSet); IDTYPE nId = xSet.id(); STRINGTYPE sigle, name, desc, status; sigle = cur.sigle(); name = cur.name(); status = cur.status(); desc = cur.description(); if (nId != 0) { SQLite_Statement q(*(this->m_base), SQL_UPDATE_DATASET); assert(q.get_parameters_count() == 5); q.bind(1, sigle); q.bind(2, name); q.bind(3, desc); q.bind(4, status); q.bind(5, nId); q.exec(); } else { SQLite_Statement q(*(this->m_base), SQL_INSERT_DATASET); assert(q.get_parameters_count() == 4); q.bind(1, sigle); q.bind(2, name); q.bind(3, desc); q.bind(4, status); q.exec(); } if (bCommit && bInTrans) { this->commit_transaction(); } return (this->find_dataset(cur)); }// try catch (sqlite_error &err) { log_error(err); if (bInTrans) { this->rollback_transaction(); } } catch (std::exception &ex) { log_error(ex); if (bInTrans) { this->rollback_transaction(); } } return (false); }// maintains_datase bool SQLiteStatHelper::find_dataset(DatasetType &cur) { assert(this->is_valid()); try { IDTYPE nId = cur.id(); if (nId != 0) { SQLite_Statement q(*(this->m_base), SQL_FIND_DATASET_BY_ID); assert(q.get_parameters_count() == 1); q.bind(1, nId); q.exec(); if (q.move_next()) { this->read_dataset(q, cur); return (true); } } STRINGTYPE sigle = cur.sigle(); if (!sigle.empty()) { SQLite_Statement q(*(this->m_base), SQL_FIND_DATASET_BY_SIGLE); assert(q.get_parameters_count() == 1); q.bind(1, sigle); q.exec(); if (q.move_next()) { this->read_dataset(q, cur); return (true); } } return (false); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }// find_dataset bool SQLiteStatHelper::find_all_datasets(datasets_vector &oList, size_t skip /* = 0*/, size_t count /* = 100 */) { assert(this->is_valid()); try { oList.clear(); if (count < 1) { count = DATATRANSFER_CHUNK_SIZE; } SQLite_Statement q(*(this->m_base), SQL_FIND_ALL_DATASETS); assert(q.get_parameters_count() == 2); q.bind(1, (int)count); q.bind(2, (int)skip); q.exec(); while (q.move_next()) { DatasetType cur; this->read_dataset(q, cur); oList.push_back(cur); } return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_all_datasets bool SQLiteStatHelper::find_all_datasets_ids(ints_vector &oList, size_t skip /* = 0*/, size_t count /* = 100 */) { assert(this->is_valid()); try { oList.clear(); if (count < 1) { count = DATATRANSFER_CHUNK_SIZE; } SQLite_Statement q(*(this->m_base), SQL_FIND_ALL_DATASETS_IDS); assert(q.get_parameters_count() == 2); q.bind(1, (int)count); q.bind(2, (int)skip); q.exec(); while (q.move_next()) { IDTYPE cur; q.get_column(0, cur); if (cur != 0) { oList.push_back(cur); } } return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_all_datasets_ids bool SQLiteStatHelper::find_all_datasets_count(size_t &nCount) { assert(this->is_valid()); try { nCount = 0; SQLite_Statement q(*(this->m_base), SQL_FIND_DATASETS_COUNT); q.exec(); assert(q.get_num_columns() == 1); if (q.move_next()) { int nx = 0; q.get_column(0, nx); nCount = (size_t)nx; } return (true); }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } return (false); }//find_dataset_variables_count //////////////////////////////////// void SQLiteStatHelper::read_dataset(SQLite_Statement &q, DatasetType &cur) { assert(q.get_num_columns() == 6); STRINGTYPE sSigle, sName, status, sDesc; IDTYPE nId; INTTYPE nVersion; q.get_column(0, nId); q.get_column(1, nVersion); q.get_column(2, sSigle); q.get_column(3, sName); q.get_column(4, sDesc); q.get_column(5, status); cur.id(nId); cur.version(nVersion); cur.sigle(sSigle); cur.name(sName); cur.status(status); cur.description(sDesc); } void SQLiteStatHelper::read_variable(SQLite_Statement &q, VariableType &cur) { assert(q.get_num_columns() == 12); STRINGTYPE sSigle, sName, status, sDesc, sGenre, sType; IDTYPE nId, nDatasetId; INTTYPE nVersion, nCateg; int nbModal = 0; WEIGHTYPE w = 1.0; q.get_column(0, nId); q.get_column(1, nVersion); q.get_column(2, nDatasetId); q.get_column(3, sSigle); q.get_column(4, sType); q.get_column(5, nCateg); q.get_column(6, sName); q.get_column(7, sDesc); q.get_column(8, sGenre); q.get_column(9, status); q.get_column(10, w); q.get_column(11, nbModal); bool bCateg = (nCateg != 0) ? true : false; cur.id(nId); cur.version(nVersion); cur.sigle(sSigle); cur.name(sName); cur.status(status); cur.description(sDesc); cur.is_categ(bCateg); cur.vartype(sType); cur.genre(sGenre); cur.dataset_id(nDatasetId); cur.weight(w); cur.modalites_count(nbModal); } void SQLiteStatHelper::read_indiv(SQLite_Statement &q, IndivType &cur) { assert(q.get_num_columns() == 8); STRINGTYPE sSigle, sName, status, sDesc; IDTYPE nId, nDatasetId; INTTYPE nVersion; WEIGHTYPE w = 1.0; q.get_column(0, nId); q.get_column(1, nVersion); q.get_column(2, nDatasetId); q.get_column(3, sSigle); q.get_column(4, sName); q.get_column(5, sDesc); q.get_column(6, status); q.get_column(7, w); // cur.id(nId); cur.version(nVersion); cur.sigle(sSigle); cur.name(sName); cur.status(status); cur.description(sDesc); cur.dataset_id(nDatasetId); cur.weight(w); } void SQLiteStatHelper::read_value(SQLite_Statement &q, ValueType &cur) { assert(q.get_num_columns() == 6); STRINGTYPE status, sval; IDTYPE nId, nVarId, nIndId; INTTYPE nVersion; InfoValue v; q.get_column(0, nId); q.get_column(1, nVersion); q.get_column(2, nVarId); q.get_column(3, nIndId); q.get_column(4, v); q.get_column(5, status); cur.id(nId); cur.version(nVersion); cur.status(status); cur.variable_id(nVarId); cur.indiv_id(nIndId); cur.value(v); } //////////////////////////////// SQLiteStatHelper::SQLiteStatHelper(const STRINGTYPE &sDatabaseName /*= DEFAULT_DATABASE_NAME*/) { try { this->m_intransaction = false; this->m_base.reset(new SQLite_Database(sDatabaseName)); assert(this->m_base.get() != nullptr); if (this->m_base->is_open()) { this->check_schema(); } } catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } catch (...) { #if defined(__CYGWIN__) std::cerr << "Unknown exception in open..." << std::endl; #else BOOST_LOG_TRIVIAL(error) << "Unknown exception in open..." << std::endl; #endif // __CGGWIN__ } } void SQLiteStatHelper::check_schema(void) { assert(this->is_valid()); try { int i = 0; SQLite_Database &base = *(this->m_base); while (CREATE_SQL[i] != nullptr) { const char *pszSQL = CREATE_SQL[i]; std::string sql(pszSQL); base.exec(sql); i++; }// i }// try catch (sqlite_error &err) { log_error(err); } catch (std::exception &ex) { log_error(ex); } }// check_schema bool SQLiteStatHelper::is_valid(void) { SQLite_Database *p = this->m_base.get(); return ((p != nullptr) && p->is_open()); } SQLiteStatHelper::~SQLiteStatHelper() { } /////////////////////////////////////// }// namespace info
fibonacci <- function(n) { fib <- c() x <- 0 y <- 1 for (i in 1:n){ fib <- c(fib,x) x <- x+y y <- x-y } return(fib) }
json.partial! "box_request_abuse_types/box_request_abuse_type", box_request_abuse_type: @box_request_abuse_type
import re pattern = '''^[A-Za-z0-9_@$]*$''' if(re.search(pattern,testString)): print("String does not contain special characters") else: print("string contains special characters")
#!/bin/bash echo "Making local files readable..." sudo chgrp www-data . -R #sudo chmod a+x . -R
#!/bin/bash -x # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ################################ # # Prep # ################################ WORKSPACE=$1 if [ "${WORKSPACE}" = "" ]; then echo "Specify Cassandra source directory" exit fi export PYTHONIOENCODING="utf-8" export PYTHONUNBUFFERED=true export CASS_DRIVER_NO_EXTENSIONS=true export CASS_DRIVER_NO_CYTHON=true export CCM_MAX_HEAP_SIZE="2048M" export CCM_HEAP_NEWSIZE="200M" export CCM_CONFIG_DIR=${WORKSPACE}/.ccm export NUM_TOKENS="32" export CASSANDRA_DIR=${WORKSPACE} export TESTSUITE_NAME="cqlshlib.python2.jdk8" # Loop to prevent failure due to maven-ant-tasks not downloading a jar.. for x in $(seq 1 3); do ant -buildfile ${CASSANDRA_DIR}/build.xml realclean jar RETURN="$?" if [ "${RETURN}" -eq "0" ]; then break fi done # Exit, if we didn't build successfully if [ "${RETURN}" -ne "0" ]; then echo "Build failed with exit code: ${RETURN}" exit ${RETURN} fi # Set up venv with dtest dependencies set -e # enable immediate exit if venv setup fails virtualenv --python=python2 --no-site-packages venv source venv/bin/activate pip install -r ${CASSANDRA_DIR}/pylib/requirements.txt pip freeze if [ "$cython" = "yes" ]; then TESTSUITE_NAME="${TESTSUITE_NAME}.cython" pip install "Cython>=0.20,<0.25" cd pylib/; python setup.py build_ext --inplace cd ${WORKSPACE} else TESTSUITE_NAME="${TESTSUITE_NAME}.no_cython" fi ################################ # # Main # ################################ ccm remove test || true # in case an old ccm cluster is left behind ccm create test -n 1 --install-dir=${CASSANDRA_DIR} ccm updateconf "enable_user_defined_functions: true" version_from_build=$(ccm node1 versionfrombuild) export pre_or_post_cdc=$(python -c """from distutils.version import LooseVersion print \"postcdc\" if LooseVersion(\"${version_from_build}\") >= \"3.8\" else \"precdc\" """) case "${pre_or_post_cdc}" in postcdc) ccm updateconf "cdc_enabled: true" ;; precdc) : ;; *) echo "${pre_or_post_cdc}" is an invalid value. exit 1 ;; esac ccm start --wait-for-binary-proto cd ${CASSANDRA_DIR}/pylib/cqlshlib/ set +e # disable immediate exit from this point nosetests ccm remove # hack around --xunit-prefix-with-testsuite-name not being available in nose 1.3.7 sed -i "s/testsuite name=\"nosetests\"/testsuite name=\"${TESTSUITE_NAME}\"/g" nosetests.xml sed -i "s/testcase classname=\"cqlshlib./testcase classname=\"${TESTSUITE_NAME}./g" nosetests.xml mv nosetests.xml ${WORKSPACE}/cqlshlib.xml ################################ # # Clean # ################################ # /virtualenv deactivate # Exit cleanly for usable "Unstable" status exit 0
'use strict' const run = function(generator) { //initialize the generator let gen = generator(); // call next to assign the return value to 'yield' next(); function next(error, value){ if (error) return gen.throw(error); // call next on the generator // one first execution, value will be null // on second, execution, value will be the // return value of the callback let continuable = gen.next(value); // once the generator is done, break out if (continuable.done) return; // on first pass, // the async callback is the value of the gen.next() let callback = continuable.value; // execute the callback and apply the next function // to the params (error, value) where value is the // returned value of the async callback (like data) callback(next); // when next executes again, the magic happens in this block // 'let continuable = gen.next(value);' // that is to say, yield is assigned the return value of the callback! } } module.exports = run;
#!/bin/bash -l export PORT=${PORT:-8080} export THREAD_COUNT=${THREAD_COUNT:-2} echo "................. FLASKAPP-PROM ......................" echo "" echo " Starting application via waitress-server" echo "" echo " PORT: ${PORT}" echo " THREADS: ${THREAD_COUNT}" echo " VERSION: $(cat VERSION)" echo "" echo "..........................................................." waitress-serve --port ${PORT} --threads ${THREAD_COUNT} main:app echo "Exit code is: $?" echo "" echo "Cleaning variables" unset PORT echo "-" unset THREAD_COUNT echo "-" echo "Finished, thanks for using"
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.interestrate.bond.definition; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.Validate; import com.opengamma.analytics.financial.interestrate.InstrumentDerivative; import com.opengamma.analytics.financial.interestrate.InstrumentDerivativeVisitor; /** * Describes a (Treasury) Bill transaction. */ public class BillTransaction implements InstrumentDerivative { /** * The bill underlying the transaction. * <P> The bill may not be suitable for standard price and yield calculation (incorrect settlement). */ private final BillSecurity _billPurchased; /** * The bill quantity. */ private final double _quantity; /** * The amount paid at settlement date for the bill transaction. The amount is negative for a purchase (_quantity>0) and positive for a sell (_quantity<0). */ private final double _settlementAmount; /** * The bill with standard settlement date (time). Used for yield calculation. * <P> If the standard settlement date would be after the end date, the end date should be used for settlement. */ private final BillSecurity _billStandard; /** * Constructor. * @param billPurchased The bill underlying the transaction. * @param quantity The bill quantity. * @param settlementAmount The amount paid at settlement date for the bill transaction. The amount is negative for a purchase (_quantity>0) and positive for a sell (_quantity<0). * @param billStandard The bill with standard settlement date (time). */ public BillTransaction(BillSecurity billPurchased, double quantity, double settlementAmount, BillSecurity billStandard) { Validate.notNull(billPurchased, "Bill purchased"); Validate.notNull(billStandard, "Bill standard"); Validate.isTrue(quantity * settlementAmount <= 0, "Quantity and settlement amount should have opposite signs"); _billPurchased = billPurchased; _quantity = quantity; _settlementAmount = settlementAmount; _billStandard = billStandard; } /** * Gets the bill underlying the transaction. * @return The bill. */ public BillSecurity getBillPurchased() { return _billPurchased; } /** * Gets the bill quantity. * @return The quantity. */ public double getQuantity() { return _quantity; } /** * Gets the amount paid at settlement date for the bill transaction. * @return The amount. */ public double getSettlementAmount() { return _settlementAmount; } /** * Gets the bill with standard settlement date (time). * @return The bill. */ public BillSecurity getBillStandard() { return _billStandard; } @Override public String toString() { return "Transaction: " + _quantity + " of " + _billPurchased.toString(); } @Override public <S, T> T accept(InstrumentDerivativeVisitor<S, T> visitor, S data) { return visitor.visitBillTransaction(this, data); } @Override public <T> T accept(InstrumentDerivativeVisitor<?, T> visitor) { return visitor.visitBillTransaction(this); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + _billPurchased.hashCode(); result = prime * result + _billStandard.hashCode(); long temp; temp = Double.doubleToLongBits(_quantity); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(_settlementAmount); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } BillTransaction other = (BillTransaction) obj; if (!ObjectUtils.equals(_billPurchased, other._billPurchased)) { return false; } if (!ObjectUtils.equals(_billStandard, other._billStandard)) { return false; } if (Double.doubleToLongBits(_quantity) != Double.doubleToLongBits(other._quantity)) { return false; } if (Double.doubleToLongBits(_settlementAmount) != Double.doubleToLongBits(other._settlementAmount)) { return false; } return true; } }
import unittest from factorial_module import calculate_factorial class TestFactorialCalculation(unittest.TestCase): def test_positive_integer(self): self.assertEqual(calculate_factorial(5), 120) self.assertEqual(calculate_factorial(3), 6) self.assertEqual(calculate_factorial(10), 3628800) def test_zero_and_one(self): self.assertEqual(calculate_factorial(0), 1) self.assertEqual(calculate_factorial(1), 1) def test_negative_integer(self): with self.assertRaises(ValueError): calculate_factorial(-5) def test_edge_cases(self): self.assertEqual(calculate_factorial(20), 2432902008176640000) self.assertEqual(calculate_factorial(25), 15511210043330985984000000) if __name__ == '__main__': unittest.main()
#!/bin/sh # ideas used from https://gist.github.com/motemen/8595451 # abort the script if there is a non-zero error set -e # show where we are on the machine pwd remote=$(git config remote.origin.url) siteSource="$1" if [ ! -d "$siteSource" ] then echo "Usage: $0 <site source dir>" exit 1 fi # make a directory to put the gp-pages branch mkdir gh-pages-branch cd gh-pages-branch # now lets setup a new repo so we can update the gh-pages branch git config --global user.email "$GH_EMAIL" > /dev/null 2>&1 git config --global user.name "$GH_NAME" > /dev/null 2>&1 git init git remote add --fetch origin "$remote" # switch into the the gh-pages branch if git rev-parse --verify origin/gh-pages > /dev/null 2>&1 then git checkout gh-pages # delete any old site as we are going to replace it # Note: this explodes if there aren't any, so moving it here for now git rm -rf . else git checkout --orphan gh-pages fi # copy over or recompile the new site cp -a "../${siteSource}/." . # stage any changes and new files git add -A # now commit, ignoring branch gh-pages doesn't seem to work, so trying skip git commit --allow-empty -m "Deploy to GitHub pages [ci skip]" # and push, but send any output to /dev/null to hide anything sensitive git push --force --quiet origin gh-pages > /dev/null 2>&1 # go back to where we started and remove the gh-pages git repo we made and used # for deployment cd .. rm -rf gh-pages-branch echo "Finished Deployment!"
class BankAccount: def __init__(self): self.balance = 0 self.total_transactions = 0 def deposit(self, amount): self.balance += amount self.total_transactions += 1 def withdraw(self, amount): if self.balance >= amount: self.balance -= amount self.total_transactions += 1 else: print("Insufficient funds") def get_balance(self): return self.balance def get_total_transactions(self): return self.total_transactions
find ../include ../src/compiler/include -name '*hpp' -exec clang-format -i {} \; find ../src ../include ../test ../sample ../benchmarks -name '*cpp' -exec clang-format -i {} \; python ../3rd_party/run-clang-format/run-clang-format.py -r ../include ../src ../test ../sample ../benchmarks --exclude '*asn_compiler.hpp'