text
stringlengths
1
1.05M
package fr.calamus.common.mail.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class ListeDestinataires implements Serializable { private static final long serialVersionUID = 3888626294977279852L; protected List<IDestinataireMap> liste; protected static String colId; protected static String colNom; protected static String colMail; public ListeDestinataires() { super(); liste = new ArrayList<>(); } public ListeDestinataires(List l) { this(); addAll(l); } protected void addAll(List l){ if(l!=null)for(int i=0;i<l.size();i++){ if(l.get(i)instanceof IDestinataireMap){ liste.add((IDestinataireMap) l.get(i)); } } } public static void init(ModeleTableContacts m) { colId = m.getColIdContact(); colMail = m.getColMailContact(); colNom = m.getColNomContact(); } public void add(IDestinataireMap sdb) { liste.add(sdb); } /*public Object[][] getObjectsArray(List<String> colonnesTableau) { Object[][] tto = new Object[liste.size()][]; for (int i = 0; i < liste.size(); i++) { IDestinataireMap soc = liste.get(i); Object[] to = new Object[colonnesTableau.size()]; for (int j = 0; j < colonnesTableau.size(); j++) { String col = colonnesTableau.get(j); String val; /*if(col.equalsIgnoreCase("cats")){ val=ToolBox.mergeList(soc.getCats(), " - "); }else if(col.equalsIgnoreCase("tels")){ val=soc.getTelsAffichables(); /*ArrayList<String>a=new ArrayList<>(); List<String> tels = soc.getTels(); for(int it=0;it<3;it++){ String type; switch (it) { case 0: type="Fixe"; break; case 1: type="Mobile"; break; case 2: type="Fax"; break; default: type=""; break; } if(tels.get(it)!=null){ a.add(type+" : "+tels.get(it)); } } val=ToolBox.mergeList(a, " - ");* //}else{ val = soc.getValeurAffichable(col); //} to[j] = val; } tto[i] = to; } return tto; }*/ public int size() { return liste.size(); } public List<IDestinataireMap> getListe() { return liste; } public ArrayList<Integer> getIds() { ArrayList<Integer> l = new ArrayList<Integer>(); for (int i = 0; i < liste.size(); i++) { l.add(liste.get(i).getId()); } return l; } public IDestinataireMap getDestinataireMap(int n) { return liste.get(n); } public ListeDestinataires getSousListe(int[] indices) { ListeDestinataires l = new ListeDestinataires(); for (int i = 0; i < indices.length; i++) { l.add(getDestinataireMap(indices[i])); } return l; } }
def to_compact_text(error): return f"{error['severity']}|{error['type']}|{error['loc']['file']}|{error['loc']['startLine']}|{error['loc']['startColumn']}|{error['message']}" # Test the function with the provided example error = { 'severity': 'error', 'type': 'syntax', 'loc': { 'file': 'script.py', 'startLine': 5, 'startColumn': 10 }, 'message': 'Syntax error: invalid syntax' } print(to_compact_text(error)) # Output: "error|syntax|script.py|5|10|Syntax error: invalid syntax"
<gh_stars>100-1000 /* global $, _, crossfilter, d3 */ (function(nbviz) { 'use strict'; nbviz.updateList = function(data) { var rows, cells; // Sort the winners' data by year var data = data.sort(function(a, b) { return +b.year - +a.year; }); // Bind our winners' data to the table rows rows = d3.select('#nobel-list tbody') .selectAll('tr') .data(data); // Fade out excess rows over 2 seconds rows.exit() .transition().duration(nbviz.TRANS_DURATION) .style('opacity', 0) .remove(); rows = rows.enter().append('tr') .on('click', function(d) { console.log('You clicked a row ' + JSON.stringify(d)); nbviz.displayWinner(d); }) .merge(rows) cells = rows.selectAll('td') .data(function(d) { return [d.year, d.category, d.name]; }); // Append data cells, then set their text cells.enter().append('td') .merge(cells) .text(function(d) { return d; }); // Display a random winner if data is available if(data.length){ nbviz.displayWinner(data[Math.floor(Math.random() * data.length)]); } }; nbviz.displayWinner = function(_wData) { nbviz.getDataFromAPI('winners/' + _wData._id, function(error, wData) { var nw = d3.select('#nobel-winner'); nw.select('#winner-title').text(wData.name); nw.style('border-color', nbviz.categoryFill(wData.category)); nw.selectAll('.property span') .text(function(d) { var property = d3.select(this).attr('name'); return wData[property]; }); nw.select('#biobox').html(wData.mini_bio); // Add an image if available, otherwise remove the old one if(wData.bio_image){ nw.select('#picbox img') .attr('src', 'static/images/winners/' + wData.bio_image) .style('display', 'inline'); } else{ nw.select('#picbox img').style('display', 'none'); } nw.select('#readmore a').attr('href', 'http://en.wikipedia.org/wiki/' + wData.name); }); }; }(window.nbviz = window.nbviz || {}));
const express = require('express'); const session = require('express-session'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.json()); app.use(session({ secret: 'secret-key', resave: false, saveUninitialized: false, })); let users = []; app.post('/register', (req, res) => { users.push(req.body); res.send({message: 'User registered'}); }); app.post('/login', (req, res) => { let user = users.find(user => user.username === req.body.username && user.password === req.body.password); if (user) { req.session.user = user; res.send({message: 'Logged in'}); } else { res.send({message: 'Invalid username or password'}); } }); app.get('/protected', (req, res) => { if (req.session.user) { res.send({message: 'You are authorized'}); } else { res.send({message: 'You are not authorized'}); } }); app.listen(3000, () => console.log('Server started'));
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; class Main { public static void main(String[] args) throws IOException { final var COUNT = 5; final var FILE = Paths.get("/fixtures/sample.csv"); final var OFILE = Paths.get("./sample.csv"); var sum = 0.0; System.out.println("START!!!!!"); for (var i = 0; i < COUNT; i++) { var start = System.currentTimeMillis(); try (BufferedReader br = Files.newBufferedReader(FILE); var bw = Files.newBufferedWriter(OFILE)) { String line; while ((line = br.readLine()) != null) { bw.write(line + "\n"); } } var end = System.currentTimeMillis(); var time = (double) (end - start) / 1000; sum += time; System.out.printf("Time Result: %.4f\n", time); } System.out.printf("Java Average: %.4f\n", sum / COUNT); } }
def binary_search(arr, target): left = 0 right = len(arr)-1 mid = left + (right - left)//2 while left <= right: if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 mid = left + (right - left)//2 return -1 arr = [5, 8, 10, 15, 18, 20, 25, 30] value = 18 result = binary_search(arr, value) print(result)
<gh_stars>0 import fs = require('fs'); module.exports = class Cache { private static cache: any = {}; private static logger; public static setLogger(logger: any) { this.logger = logger; } public static get(key: any) { if (Cache.cache[key] !== undefined) { const cacheItem: any = Cache.cache[key]; const expiration = cacheItem.expiration; const object = cacheItem.object; const now = new Date(); if (expiration > now.getTime()) { // object is current // this.logger.verbose("Key: " + key + " - cache hit"); return object; } else { // object expired // this.logger.verbose("Key: " + key + " - cache expired"); } } else { // this.logger.verbose("Key: " + key + " - cache miss"); } return null; } public static set(key: string, newObject: any, expirationTime: number) { const cacheItem = {expiration: expirationTime, object: newObject} Cache.cache[key] = cacheItem; } // static async saveCache() { // console.log("Saving cache."); // fs.writeFile('./cache.json', JSON.stringify(BaseballData.cache, null, 4), function(err) { // if(err) console.log(err) // }) // } }
// ensure service workers are supported if (navigator.serviceWorker) { window.addEventListener('load', () => { navigator.serviceWorker .register('sw_cached_site.js') .then(reg => console.log('Service Worker: Registered')) .catch(err => console.error(`Service Worker: Error: ${err}`)) }) }
#!/usr/bin/env bash ############################################################################### # Copyright 2017 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" source "${DIR}/apollo_base.sh" function start() { decide_task_dir $@ cd "${TASK_DIR}" # Start recording. LOG="/tmp/apollo_record.out" NUM_PROCESSES="$(pgrep -c -f "rosbag record")" if [ "${NUM_PROCESSES}" -eq 0 ]; then nohup rosbag record --split --duration=1m -b 2048 \ /apollo/sensor/camera/obstacle/front_6mm \ /apollo/sensor/conti_radar \ /apollo/sensor/delphi_esr \ /apollo/sensor/gnss/best_pose \ /apollo/sensor/gnss/corrected_imu \ /apollo/sensor/gnss/gnss_status \ /apollo/sensor/gnss/imu \ /apollo/sensor/gnss/raw_data \ /apollo/sensor/gnss/ins_stat \ /apollo/sensor/gnss/odometry \ /apollo/sensor/gnss/rtk_eph \ /apollo/sensor/gnss/rtk_obs \ /apollo/sensor/mobileye \ /apollo/canbus/chassis \ /apollo/canbus/chassis_detail \ /apollo/control \ /apollo/control/pad \ /apollo/perception/obstacles \ /apollo/perception/traffic_light \ /apollo/navigation \ /apollo/relative_map \ /apollo/planning \ /apollo/prediction \ /apollo/routing_request \ /apollo/routing_response \ /apollo/localization/pose \ /apollo/drive_event \ /tf \ /tf_static \ /apollo/monitor \ /apollo/monitor/static_info </dev/null >"${LOG}" 2>&1 & fi } function stop() { pkill -SIGKILL -f record } function help() { echo "Usage:" echo "$0 [start] Record bag to data/bag." echo "$0 [start] --portable-disk Record bag to the largest portable disk." echo "$0 stop Stop recording." echo "$0 help Show this help message." } case $1 in start) shift start $@ ;; stop) shift stop $@ ;; help) shift help $@ ;; *) start $@ ;; esac
<filename>src/main/java/org/olat/course/run/preview/PreviewSettingsForm.java /** * OLAT - Online Learning and Training<br> * http://www.olat.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> * University of Zurich, Switzerland. * <hr> * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * This file has been modified by the OpenOLAT community. Changes are licensed * under the Apache 2.0 license as the original file. */ package org.olat.course.run.preview; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.AbstractComponent; import org.olat.core.gui.components.form.flexible.FormItemContainer; import org.olat.core.gui.components.form.flexible.elements.DateChooser; import org.olat.core.gui.components.form.flexible.elements.MultipleSelectionElement; import org.olat.core.gui.components.form.flexible.elements.SingleSelection; import org.olat.core.gui.components.form.flexible.elements.TextElement; import org.olat.core.gui.components.form.flexible.impl.FormBasicController; import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.Event; import org.olat.core.gui.control.WindowControl; import org.olat.course.ICourse; import org.olat.course.groupsandrights.CourseGroupManager; import org.olat.group.BusinessGroup; import org.olat.group.area.BGArea; /** * Initial Date: 14.01.2005 <br> * * @author <NAME> */ public class PreviewSettingsForm extends FormBasicController { static final String ROLE_GLOBALAUTHOR = "role.globalauthor"; static final String ROLE_COURSEADMIN = "role.courseadmin"; static final String ROLE_COURSECOACH = "role.coursecoach"; static final String ROLE_GUEST = "role.guest"; static final String ROLE_STUDENT = "role.student"; private DateChooser sdate; private final int NUMATTR = 5; private List<TextElement> attrNames = new ArrayList<>(NUMATTR); private List<TextElement> attrValues = new ArrayList<>(NUMATTR); private SingleSelection roles; private MultipleSelectionElement groupSelector; private MultipleSelectionElement areaSelector; private final CourseGroupManager courseGroupManager; public PreviewSettingsForm(UserRequest ureq, WindowControl wControl, ICourse course) { super(ureq, wControl); courseGroupManager = course.getCourseEnvironment().getCourseGroupManager(); initForm(ureq); } /** * @return group */ public List<Long> getGroupKeys() { return getKeys(groupSelector); } /** * @return area */ public List<Long> getAreaKeys() { return getKeys(areaSelector); } /** * @return date */ public Date getDate() { return sdate.getDate(); } /** * @return attributes map */ public Map<String,String> getAttributesMap() { Map <String,String>attributesMap = new HashMap<>(); for (int i=0; i<attrNames.size(); i++) { if (!attrNames.get(i).isEmpty()) { attributesMap.put( attrNames.get(i).getValue(), attrValues.get(i).getValue() ); } } return attributesMap; } public String getRole() { return roles.getSelectedKey(); } @Override protected void formOK(UserRequest ureq) { fireEvent(ureq, Event.DONE_EVENT); } @Override protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { sdate = uifactory.addDateChooser("sdate","form.sdate" , null, formLayout); sdate.setExampleKey("form.easy.example.bdate", null); sdate.setDateChooserTimeEnabled(true); sdate.setMandatory(true); sdate.setValidDateCheck("form.sdate.invalid"); //setDate must be called after the DataChooser was configured sdate.setDate(new Date()); List<BusinessGroup> groups = courseGroupManager.getAllBusinessGroups(); String[] groupNames = new String[groups.size()]; String[] groupKeys = new String[groups.size()]; for(int i=groups.size(); i-->0; ) { groupNames[i] = groups.get(i).getName(); groupKeys[i] = groups.get(i).getKey().toString(); } groupSelector = uifactory.addCheckboxesVertical("details.groups", formLayout, groupKeys, groupNames, 1); groupSelector.setVisible(groups.size() > 0); List<BGArea> areas = courseGroupManager.getAllAreas(); String[] areaNames = new String[areas.size()]; String[] areaKeys = new String[areas.size()]; for(int i=areas.size(); i-->0; ) { areaNames[i] = areas.get(i).getName(); areaKeys[i] = areas.get(i).getKey().toString(); } areaSelector = uifactory.addCheckboxesVertical("details.areas", formLayout, areaKeys, areaNames, 1); areaSelector.setVisible(areas.size() > 0); String[] keys = { ROLE_STUDENT, ROLE_GUEST, ROLE_COURSECOACH, ROLE_COURSEADMIN, ROLE_GLOBALAUTHOR }; String[] values = new String[keys.length]; for (int i = 0; i < keys.length; i++) { values[i]=translate(keys[i]); } roles = uifactory.addRadiosVertical("roles", "form.roles", formLayout, keys, values); roles.select(ROLE_STUDENT, true); String page = velocity_root + "/attributes.html"; FormLayoutContainer attrlayout = FormLayoutContainer.createCustomFormLayout("attributes", getTranslator(), page); formLayout.add(attrlayout); attrlayout.setLabel("form.attributes", null); for (int i=0; i<NUMATTR; i++) { TextElement name = uifactory.addTextElement("attrname"+i, null, 255, "", attrlayout); ((AbstractComponent)name.getComponent()).setDomReplacementWrapperRequired(false); name.setDisplaySize(12); TextElement value = uifactory.addTextElement("attrvalue"+i, "form.equals", 255, "", attrlayout); ((AbstractComponent)value.getComponent()).setDomReplacementWrapperRequired(false); value.setDisplaySize(12); attrNames.add(name); attrValues.add(value); } uifactory.addFormSubmitButton("submit", "command.preview", formLayout); } @Override protected boolean validateFormLogic(UserRequest ureq) { return sdate.getDate()!=null; } private List<Long> getKeys(MultipleSelectionElement element) { List<Long> keys = new ArrayList<>(); if(element.isAtLeastSelected(1)) { Collection<String> selectedKeys = element.getSelectedKeys(); for(String selectedKey:selectedKeys) { keys.add(Long.parseLong(selectedKey)); } } return keys; } }
#!/bin/sh #复制文件 copyFile(){ local src=$1 local dir=$2 local name=$3 if [ ! -d $dir ] then mkdir -p $dir fi cp "$src" "$dir/$name" } #检查数组包含 containStr(){ arr=$1 for str in ${arr[@]} do if [ "$str" = "$2" ] then return 1 fi done return 0 } # 编译 build(){ local src=$1 echo "build $src" cd $WORKPATH/$src && sh build.sh echo "build $src 完成" } # TODO 添加版本号 数据库 # 可以编译的列表,用来检验参数 buildList=("account" "center" "charge_server" "cross" "game" "logserver" "gm" "coupon_server" "trade_server") # 工作目录 WORKPATH=$(pwd) echo "当前目录$WORKPATH" # 发布路径 distPath="" case "$1" in master) distPath="deploy/wanshi_master" ;; test) distPath="deploy/wanshi_test" ;; inner_test) distPath="deploy/wanshi_inner_test" ;; prod) distPath="deploy/wanshi" ;; check) distPath="deploy/wanshi_check" ;; *) echo "不支持的参数,请输入prod,test,inner_test" exit 1 esac # 需要编译的 needBuildList=() if [ "$2" = "all" ]; then needBuildList=(${buildList[@]}) else needBuildList=($@) needBuildList=(${needBuildList[@]:1}) fi # 检查参数 for needBuild in "${needBuildList[@]}" do containStr "${buildList[*]}" $needBuild ret=$? if [ $ret -eq 0 ]; then echo "输入参数[$needBuild]错误,不能构建" exit 1 fi done # 编译 for needBuild in "${needBuildList[@]}" do build $needBuild done echo "发布路径:$WORKPATH/$distPath" # 复制二进制文件 for needBuild in "${needBuildList[@]}" do echo "复制$needBuild服" copyFile "$WORKPATH/$needBuild/main" "$WORKPATH/$distPath/$needBuild" $needBuild echo "复制$needBuild服完成" done mapDir="$WORKPATH/$distPath/resources/map" templateDir="$WORKPATH/$distPath/resources/template" # 复制数据 echo "复制策划数据" if [ ! -d $mapDir ] then mkdir -p $mapDir fi # 复制地图数据 cd "$WORKPATH/resources/map" for f in *.txt do cp -rf "$f" "$mapDir/" done # 复制模板数据 if [ ! -d $templateDir ] then mkdir -p $templateDir fi cd "$WORKPATH/resources/template" for f in *.json do cp -rf "$f" "$templateDir/" done echo "复制策划数据完成"
function fibonacci(n) { if (n <= 1) { return n; } var cache = [0, 1]; for (var i = 2; i <= n; i++) { var prev = cache[i -1]; var current = cache[i - 2]; cache.push(prev + current); } return cache[n]; }
<filename>client/app/iplb/sslCertificate/iplb-ssl-certificate.service.js class IpLoadBalancerSslCertificateService { constructor ($q, OvhApiIpLoadBalancing, ServiceHelper) { this.$q = $q; this.ServiceHelper = ServiceHelper; this.Ssl = OvhApiIpLoadBalancing.Ssl().Lexi(); } getCertificates (serviceName) { return this.Ssl.query({ serviceName }) .$promise .then(sslIds => this.$q.all(sslIds.map(sslId => this.getCertificate(serviceName, sslId)))) .catch(this.ServiceHelper.errorHandler("iplb_ssl_list_error")); } getCertificate (serviceName, sslId) { return this.Ssl.get({ serviceName, sslId }) .$promise; } create (serviceName, ssl) { return this.Ssl.post({ serviceName }, ssl) .$promise .then(this.ServiceHelper.successHandler("iplb_ssl_add_success")) .catch(this.ServiceHelper.errorHandler("iplb_ssl_add_error")); } update (serviceName, sslId, ssl) { return this.Ssl.put({ serviceName, sslId }, ssl) .$promise .then(this.ServiceHelper.successHandler("iplb_ssl_update_success")) .catch(this.ServiceHelper.errorHandler("iplb_ssl_update_error")); } delete (serviceName, sslId) { return this.Ssl.delete({ serviceName, sslId }) .$promise .then(this.ServiceHelper.successHandler("iplb_ssl_delete_success")) .catch(this.ServiceHelper.errorHandler("iplb_ssl_delete_error")); } } angular.module("managerApp").service("IpLoadBalancerSslCertificateService", IpLoadBalancerSslCertificateService);
<gh_stars>1-10 """Tests for kernel connection utilities""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import json import os import re import stat import tempfile import shutil from traitlets.config import Config from jupyter_core.application import JupyterApp from jupyter_core.paths import jupyter_runtime_dir from tempfile import TemporaryDirectory from jupyter_client import connect, KernelClient from jupyter_client.consoleapp import JupyterConsoleApp from jupyter_client.session import Session from jupyter_client.connect import secure_write class TemporaryWorkingDirectory(TemporaryDirectory): """ Creates a temporary directory and sets the cwd to that directory. Automatically reverts to previous cwd upon cleanup. Usage example: with TemporaryWorkingDirectory() as tmpdir: ... """ def __enter__(self): self.old_wd = os.getcwd() os.chdir(self.name) return super().__enter__() def __exit__(self, exc, value, tb): os.chdir(self.old_wd) return super().__exit__(exc, value, tb) class DummyConsoleApp(JupyterApp, JupyterConsoleApp): def initialize(self, argv=[]): JupyterApp.initialize(self, argv=argv) self.init_connection_file() class DummyConfigurable(connect.ConnectionFileMixin): def initialize(self): pass sample_info = dict(ip='1.2.3.4', transport='ipc', shell_port=1, hb_port=2, iopub_port=3, stdin_port=4, control_port=5, key=b'abc123', signature_scheme='hmac-md5', kernel_name='python' ) sample_info_kn = dict(ip='1.2.3.4', transport='ipc', shell_port=1, hb_port=2, iopub_port=3, stdin_port=4, control_port=5, key=b'abc123', signature_scheme='hmac-md5', kernel_name='test' ) def test_write_connection_file(): with TemporaryDirectory() as d: cf = os.path.join(d, 'kernel.json') connect.write_connection_file(cf, **sample_info) assert os.path.exists(cf) with open(cf, 'r') as f: info = json.load(f) info["key"] = info["key"].encode() assert info == sample_info def test_load_connection_file_session(): """test load_connection_file() after """ session = Session() app = DummyConsoleApp(session=Session()) app.initialize(argv=[]) session = app.session with TemporaryDirectory() as d: cf = os.path.join(d, 'kernel.json') connect.write_connection_file(cf, **sample_info) app.connection_file = cf app.load_connection_file() assert session.key == sample_info['key'] assert session.signature_scheme == sample_info['signature_scheme'] def test_load_connection_file_session_with_kn(): """test load_connection_file() after """ session = Session() app = DummyConsoleApp(session=Session()) app.initialize(argv=[]) session = app.session with TemporaryDirectory() as d: cf = os.path.join(d, 'kernel.json') connect.write_connection_file(cf, **sample_info_kn) app.connection_file = cf app.load_connection_file() assert session.key == sample_info_kn['key'] assert session.signature_scheme == sample_info_kn['signature_scheme'] def test_app_load_connection_file(): """test `ipython console --existing` loads a connection file""" with TemporaryDirectory() as d: cf = os.path.join(d, 'kernel.json') connect.write_connection_file(cf, **sample_info) app = DummyConsoleApp(connection_file=cf) app.initialize(argv=[]) for attr, expected in sample_info.items(): if attr in ('key', 'signature_scheme'): continue value = getattr(app, attr) assert value == expected, "app.%s = %s != %s" % (attr, value, expected) def test_load_connection_info(): client = KernelClient() info = { 'control_port': 53702, 'hb_port': 53705, 'iopub_port': 53703, 'ip': '0.0.0.0', 'key': 'secret', 'shell_port': 53700, 'signature_scheme': 'hmac-sha256', 'stdin_port': 53701, 'transport': 'tcp', } client.load_connection_info(info) assert client.control_port == info['control_port'] assert client.session.key.decode('ascii') == info['key'] assert client.ip == info['ip'] def test_find_connection_file(): with TemporaryDirectory() as d: cf = 'kernel.json' app = DummyConsoleApp(runtime_dir=d, connection_file=cf) app.initialize() security_dir = app.runtime_dir profile_cf = os.path.join(security_dir, cf) with open(profile_cf, 'w') as f: f.write("{}") for query in ( 'kernel.json', 'kern*', '*ernel*', 'k*', ): assert connect.find_connection_file(query, path=security_dir) == profile_cf def test_find_connection_file_local(): with TemporaryWorkingDirectory() as d: cf = 'test.json' abs_cf = os.path.abspath(cf) with open(cf, 'w') as f: f.write('{}') for query in ( 'test.json', 'test', abs_cf, os.path.join('.', 'test.json'), ): assert connect.find_connection_file(query, path=['.', jupyter_runtime_dir()]) == abs_cf def test_find_connection_file_relative(): with TemporaryWorkingDirectory() as d: cf = 'test.json' os.mkdir('subdir') cf = os.path.join('subdir', 'test.json') abs_cf = os.path.abspath(cf) with open(cf, 'w') as f: f.write('{}') for query in ( os.path.join('.', 'subdir', 'test.json'), os.path.join('subdir', 'test.json'), abs_cf, ): assert connect.find_connection_file(query, path=['.', jupyter_runtime_dir()]) == abs_cf def test_find_connection_file_abspath(): with TemporaryDirectory() as d: cf = 'absolute.json' abs_cf = os.path.abspath(cf) with open(cf, 'w') as f: f.write('{}') assert connect.find_connection_file(abs_cf, path=jupyter_runtime_dir()) == abs_cf os.remove(abs_cf) def test_mixin_record_random_ports(): with TemporaryDirectory() as d: dc = DummyConfigurable(data_dir=d, kernel_name='via-tcp', transport='tcp') dc.write_connection_file() assert dc._connection_file_written assert os.path.exists(dc.connection_file) assert dc._random_port_names == connect.port_names def test_mixin_cleanup_random_ports(): with TemporaryDirectory() as d: dc = DummyConfigurable(data_dir=d, kernel_name='via-tcp', transport='tcp') dc.write_connection_file() filename = dc.connection_file dc.cleanup_random_ports() assert not os.path.exists(filename) for name in dc._random_port_names: assert getattr(dc, name) == 0
export const USER_FETCH_REQUESTED = '@task/USER_FETCH_REQUESTED' export const USER_FETCH_FAILED = '@task/USER_FETCH_FAILED' export const ADD_TASK = '@task/ADD_TASK' export const REMOVE_TASK_BY_ID = '@task/REMOVE_TASK_BY_ID'
<filename>src/ex3_js-objects-part1/task-01.js const student = {}; student.name = 'Stas'; student.surname = 'Mishin'; student.age = 25; student.access = true; delete student.surname; module.exports = student;
import matplotlib.pyplot as plt def add_color_bar(fig, color_generator, label): # Add colour bar cbaxes = fig.add_axes([0.65, 0.42, 0.01, 0.43]) # [left, bottom, width, height] color_generator.set_array([0, 0]) # array here just needs to be something iterable – norm and cmap are inherited # from color_generator cbar = fig.colorbar(color_generator, cax=cbaxes, orientation='vertical') cbar.ax.tick_params(labelsize=12) cbar.set_label(label, fontsize=16)
<reponame>Gesserok/Market<filename>AntonBabunin/src/main/java/ua/artcode/market/controllers/IReportImpl.java package ua.artcode.market.controllers; import ua.artcode.market.exclude.exception.NullArgumentException; import ua.artcode.market.interfaces.IAppDb; import ua.artcode.market.interfaces.IReport; import ua.artcode.market.models.Bill; import ua.artcode.market.models.Department; import ua.artcode.market.models.employee.Employee; import ua.artcode.market.models.employee.HeadOfSalesmen; import ua.artcode.market.models.money.Money; import java.time.LocalDateTime; import java.util.List; public class IReportImpl implements IReport { private IAppDb iAppDb; public IReportImpl(IAppDb iAppDb) { this.iAppDb = iAppDb; } @Override public Money doDepartmentReport(Department department, LocalDateTime start, LocalDateTime end) throws NullArgumentException { return doDepartmentReport(department.getEmployeeList(), 0, start, end); } @Override public Money calculateSalary(Employee employee, LocalDateTime start, LocalDateTime end) throws NullArgumentException { if (employee instanceof HeadOfSalesmen) { List<Employee> employeeList = employee.getSubordinateList(); Money empPercent = salesPercent(employee, start, end); Money subPercent = doSubordinateReport(0, employeeList, start, end). takePercent(((HeadOfSalesmen) employee). getPercentOfPercent()); return employee.getSalary().doSum(empPercent.doSum(subPercent)); } return employee.getSalary().doSum(salesPercent(employee, start, end)); } private Money doDepartmentReport(List<Employee> employeeList, int i, LocalDateTime start, LocalDateTime end) throws NullArgumentException { Money amountSalary = new Money(0,0); if (employeeList == null || employeeList.isEmpty() || i >= employeeList.size()) return amountSalary; return amountSalary.doSum(calculateSalary(employeeList.get(i), start, end)).doSum(doDepartmentReport(employeeList, i + 1, start, end)); } private Money salesPercent(Employee employee, LocalDateTime start, LocalDateTime end) throws NullArgumentException { List<Bill> bills = iAppDb.filter(employee, null, start, end, null); return billsSumm(bills, 0).takePercent(employee.getPercent()); } private Money billsSumm(List<Bill> bills, int i) { Money summ = new Money(0,0); if (bills == null || bills.isEmpty() || i >= bills.size()) return summ; return bills.get(i).getAmountPrice().doSum(billsSumm(bills, i + 1)); } private Money doSubordinateReport(int i, List<Employee> employeeList, LocalDateTime start, LocalDateTime end) throws NullArgumentException { Money summ = new Money(0,0); if (employeeList == null || employeeList.isEmpty() || i >= employeeList.size()) return summ; if (employeeList.get(i) instanceof HeadOfSalesmen) { return doSubordinateReport(0, employeeList.get(i).getSubordinateList(), start,end). doSum(billsSumm(iAppDb.filter(employeeList.get(i), null, start, end, null), 0). doSum(doSubordinateReport(i+1, employeeList, start, end))); } return billsSumm(iAppDb.filter(employeeList.get(i), null, start, end, null), 0). doSum(doSubordinateReport(i+1, employeeList, start, end)); } }
<reponame>Gesserok/Market package ua.artcode.market.controller; import org.junit.Before; import org.junit.Test; import ua.artcode.market.models.Bill; import ua.artcode.market.models.Product; import static org.junit.Assert.*; /** * Created by serhii on 19.11.17. */ public class ITerminalControllerTest { private ITerminalController terminalController; @Before public void setUp(){ this.terminalController = new ITerminalControllerImpl(new IAppDbImpl()); } @Test public void createBill() throws Exception { Bill bill = terminalController.createBill(); assertEquals(0, bill.getProductList().size()); assertEquals(0, bill.getId()); } @Test public void addProduct() throws Exception { Bill bill = terminalController.createBill(); Product product = new Product(); product.setPrice(123); product.setId(1); product.setName("Potato"); terminalController.addProduct(bill.getId(), product); product.getId(); product.getName(); product.getPrice(); assertEquals(1, bill.getProductList().size()); } @Test public void getAllBills() throws Exception { Bill bill1 = terminalController.createBill(); Bill bill2 = terminalController.createBill(); Bill bill3 = terminalController.createBill(); Bill bill4 = terminalController.createBill(); assertEquals(4, terminalController.getAllBills().size()); } @Test public void closeBill() throws Exception { Bill bill = terminalController.createBill(); Bill closed = terminalController.closeBill(bill.getId()); assertTrue(closed.isClosed()); } }
<reponame>phosphor-icons/phosphr-webcomponents /* GENERATED FILE */ import { html, svg, define } from "hybrids"; const PhAirplane = { color: "currentColor", size: "1em", weight: "regular", mirrored: false, render: ({ color, size, weight, mirrored }) => html` <svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" fill="${color}" viewBox="0 0 256 256" transform=${mirrored ? "scale(-1, 1)" : null} > ${weight === "bold" && svg`<path d="M128,224l-40,8V208l16-16V152L24,168V144l80-40,.11255-56a24,24,0,0,1,48,0l.11255,56,80,40v24l-80-16v40L168,208v24Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/>`} ${weight === "duotone" && svg`<path d="M128,224l-40,8V208l16-16V152L24,168V144l80-40,.11255-56a24,24,0,0,1,48,0l.11255,56,80,40v24l-80-16v40L168,208v24Z" opacity="0.2"/> <path d="M128,224l-40,8V208l16-16V152L24,168V144l80-40,.11255-56a24,24,0,0,1,48,0l.11255,56,80,40v24l-80-16v40L168,208v24Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/>`} ${weight === "fill" && svg`<path d="M235.80371,136.84473,160.21582,99.05078,160.1123,48a32,32,0,0,0-64-.01611l-.10253,51.06689L20.42188,136.84473A7.99967,7.99967,0,0,0,16,144v24a8.00012,8.00012,0,0,0,9.56934,7.84473L96,161.7583V188.686L82.34277,202.34326A8.00035,8.00035,0,0,0,80,208v24a8.00012,8.00012,0,0,0,9.56934,7.84473L128,232.1582l38.43066,7.68653A8.00012,8.00012,0,0,0,176,232V208a8.00119,8.00119,0,0,0-2.30273-5.6167l-13.47168-13.66357V161.7583l70.43066,14.08643A8.00013,8.00013,0,0,0,240.22559,168V144A7.99969,7.99969,0,0,0,235.80371,136.84473Z"/>`} ${weight === "light" && svg`<path d="M128,224l-40,8V208l16-16V152L24,168V144l80-40,.11255-56a24,24,0,0,1,48,0l.11255,56,80,40v24l-80-16v40L168,208v24Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="12"/>`} ${weight === "thin" && svg`<path d="M128,224l-40,8V208l16-16V152L24,168V144l80-40,.11255-56a24,24,0,0,1,48,0l.11255,56,80,40v24l-80-16v40L168,208v24Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="8"/>`} ${weight === "regular" && svg`<path d="M128,224l-40,8V208l16-16V152L24,168V144l80-40,.11255-56a24,24,0,0,1,48,0l.11255,56,80,40v24l-80-16v40L168,208v24Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/>`} </svg> `, }; define("ph-airplane", PhAirplane); export default PhAirplane;
import os def read_file(path): lines = [] with open(path, "r", encoding="utf-8") as f: lines = f.readlines() lines = [ln.strip(os.linesep) for ln in lines] return lines def write_file(path, rows, separator="\t"): with open(path, "wb") as outfile: for row in rows: line = "" if isinstance(row, list) or isinstance(row, tuple): line = separator.join(row) + os.linesep else: line = row + os.linesep outfile.write(line.encode("utf-8"))
/* * Copyright (c) 2013 Red Rainbow IT Solutions GmbH, Germany * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.jeeventstore.persistence.jpa; import java.io.Serializable; import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotNull; /** * JPA EventStore entry. */ @Cacheable @Entity @Table(name = "event_store", uniqueConstraints = { @UniqueConstraint(columnNames = {"bucket_id", "stream_id", "stream_version"}), @UniqueConstraint(columnNames = {"bucket_id", "change_set_id"}) }) public class EventStoreEntry implements Serializable { /** * Internal database ID of the entry. Can be used to enumerate all events. */ @SequenceGenerator(name="event_store_id_seq", sequenceName="event_store_id_seq", allocationSize=1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="event_store_id_seq") @Column(name = "id", updatable = false) @Id private Long id; @Column(name = "bucket_id") @NotNull private String bucketId; @Column(name = "stream_id") @NotNull private String streamId; @Column(name = "stream_version") private long streamVersion; @Column(name="persisted_at") private long persistedAt; @Column(name = "change_set_id") @NotNull private String changeSetId; /* * We cannot use @Lob, because it will cause Hibernate to map the field * in ascii-only mode when used with PostreSQL, which leads to broken * UTF8 Strings. Both parties refuse to fix this isse, see, e.g., * https://groups.google.com/forum/#!topic/pgsql.interfaces.jdbc/g4XXAL-a5tE * http://in.relation.to/15492.lace * https://hibernate.atlassian.net/browse/HHH-6127 * * We therefore fix the length at 32,672 , which is the maximum VARCHAR * size in Apache Derby, the database used for unit tests. In production * mode you are expected to manually create the table with the correct * length and field types. See src/main/sql/*.sql for table definitions. */ @Column(name = "body", length = 32672) private String body; public EventStoreEntry( String bucketId, String streamId, long streamVersion, long persistedAt, String changeSetId, String body) { if (bucketId == null || bucketId.isEmpty()) throw new IllegalArgumentException("bucketId must not be empty"); if (streamId == null || streamId.isEmpty()) throw new IllegalArgumentException("streamId must not be empty"); if (changeSetId == null || changeSetId.isEmpty()) throw new IllegalArgumentException("changeSetId must not be empty"); if (body == null || body.isEmpty()) throw new IllegalArgumentException("body must not be empty"); this.bucketId = bucketId; this.streamId = streamId; this.streamVersion = streamVersion; this.persistedAt = persistedAt; this.changeSetId = changeSetId; this.body = body; } public Long id() { return id; } public String bucketId() { return bucketId; } public String streamId() { return streamId; } public long streamVersion() { return streamVersion; } public long persistedAt() { return persistedAt; } public String changeSetId() { return changeSetId; } public String body() { return body; } /** * Required for JPA, do not use. * @deprecated */ @Deprecated protected EventStoreEntry() { } }
# # Copyright (C) 2010 OpenWrt.org # PART_NAME=firmware platform_check_image() { local board=$(board_name) local magic="$(get_magic_long "$1")" [ "$#" -gt 1 ] && return 1 case "$board" in 3g150b|\ 3g300m|\ a5-v11|\ ai-br100|\ air3gii|\ alfa-network,ac1200rm|\ alfa-network,awusfree1|\ all0239-3g|\ all0256n-4M|\ all0256n-8M|\ all5002|\ all5003|\ mediatek,ap-mt7621a-v60|\ ar725w|\ asl26555-8M|\ asl26555-16M|\ awapn2403|\ awm002-evb-4M|\ awm002-evb-8M|\ bc2|\ bocco|\ broadway|\ c108|\ carambola|\ cf-wr800n|\ cs-qr10|\ d105|\ d240|\ dap-1350|\ db-wrt01|\ dcs-930|\ dcs-930l-b1|\ dir-300-b1|\ dir-300-b7|\ dir-320-b1|\ dir-600-b1|\ dir-615-d|\ dir-615-h1|\ dir-620-a1|\ dir-620-d1|\ dir-810l|\ duzun-dm06|\ e1700|\ elecom,wrc-1167ghbk2-s|\ esr-9753|\ ew1200|\ ex2700|\ ex3700|\ f7c027|\ firewrt|\ fonera20n|\ freestation5|\ gnubee,gb-pc1|\ gnubee,gb-pc2|\ gl-mt300a|\ gl-mt300n|\ gl-mt750|\ gl-mt300n-v2|\ hc5*61|\ hc5661a|\ hg255d|\ hlk-rm04|\ hpm|\ ht-tm02|\ hw550-3g|\ iodata,wn-gx300gr|\ ip2202|\ jhr-n805r|\ jhr-n825r|\ jhr-n926r|\ k2p|\ kn|\ kn_rc|\ kn_rf|\ kng_rc|\ linkits7688|\ m2m|\ m3|\ m4-4M|\ m4-8M|\ mac1200rv2|\ microwrt|\ miniembplug|\ miniembwifi|\ miwifi-mini|\ miwifi-nano|\ mlw221|\ mlwg2|\ mofi3500-3gn|\ mpr-a1|\ mpr-a2|\ mr-102n|\ mt7628|\ mzk-750dhp|\ mzk-dp150n|\ mzk-ex300np|\ mzk-ex750np|\ mzk-w300nh2|\ mzk-wdpr|\ nbg-419n|\ nbg-419n2|\ newifi-d1|\ d-team,newifi-d2|\ nixcore-x1-8M|\ nixcore-x1-16M|\ nw718|\ omega2|\ omega2p|\ oy-0001|\ pbr-d1|\ pbr-m1|\ phicomm,k2g|\ psg1208|\ psg1218a|\ psg1218b|\ psr-680w|\ px-4885-4M|\ px-4885-8M|\ rb750gr3|\ re6500|\ rp-n53|\ rt5350f-olinuxino|\ rt5350f-olinuxino-evb|\ rt-ac51u|\ rt-g32-b1|\ rt-n10-plus|\ rt-n12p|\ rt-n13u|\ rt-n14u|\ rt-n15|\ rt-n56u|\ rut5xx|\ sap-g3200u3|\ sk-wb8|\ sl-r7205|\ tama,w06|\ tew-638apb-v2|\ tew-691gr|\ tew-692gr|\ tew-714tru|\ timecloud|\ tiny-ac|\ u25awf-h1|\ u7621-06-256M-16M|\ u7628-01-128M-16M|\ ur-326n4g|\ ur-336un|\ v22rw-2x2|\ vonets,var11n-300|\ vocore-8M|\ vocore-16M|\ vocore2|\ vocore2lite|\ vr500|\ w150m|\ w2914nsv2|\ w306r-v20|\ w502u|\ ravpower,wd03|\ wf-2881|\ whr-1166d|\ whr-300hp2|\ whr-600d|\ whr-g300n|\ widora,neo-16m|\ widora,neo-32m|\ mqmaker,witi-256m|\ mqmaker,witi-512m|\ wizfi630a|\ wl-330n|\ wl-330n3g|\ wl-341v3|\ wl-351|\ wl-wn575a3|\ wli-tx4-ag300n|\ wlr-6000|\ wmdr-143n|\ wmr-300|\ wn3000rpv3|\ wnce2001|\ wndr3700v5|\ wr512-3gn-4M|\ wr512-3gn-8M|\ wr6202|\ wrh-300cr|\ wrtnode|\ wrtnode2r |\ wrtnode2p |\ wsr-600|\ wt1520-4M|\ wt1520-8M|\ wt3020-4M|\ wt3020-8M|\ wzr-agl300nh|\ x5|\ x8|\ y1|\ y1s|\ youhua,wr1200js|\ we1026-5g-16m|\ zbt-ape522ii|\ zbt-cpe102|\ zbt-wa05|\ zbtlink,zbt-we1226|\ zbt-we1326|\ zbt-we2026|\ zbtlink,zbt-we3526|\ zbt-we826-16M|\ zbt-we826-32M|\ zbt-wg2626|\ zbt-wg3526-16M|\ zbt-wg3526-32M|\ zbt-wr8305rt|\ zorlik,zl5900v2|\ zte-q7|\ youku-yk1) [ "$magic" != "27051956" ] && { echo "Invalid image type." return 1 } return 0 ;; 3g-6200n|\ 3g-6200nl|\ br-6475nd) [ "$magic" != "43535953" ] && { echo "Invalid image type." return 1 } return 0 ;; ar670w) [ "$magic" != "6d000080" ] && { echo "Invalid image type." return 1 } return 0 ;; c20i|\ c50|\ mr200|\ tplink,c20-v1|\ tplink,c20-v4|\ tplink,c50-v3|\ tplink,tl-mr3420-v5|\ tplink,tl-wr842n-v5|\ tplink,tl-wr902ac-v3|\ tl-wr840n-v4|\ tl-wr840n-v5|\ tl-wr841n-v13) [ "$magic" != "03000000" ] && { echo "Invalid image type." return 1 } return 0 ;; cy-swr1100|\ dch-m225|\ dir-610-a1|\ dir-645|\ dir-860l-b1) [ "$magic" != "5ea3a417" ] && { echo "Invalid image type." return 1 } return 0 ;; dlink,dwr-116-a1|\ dlink,dwr-921-c1|\ dwr-512-b) [ "$magic" != "0404242b" ] && { echo "Invalid image type." return 1 } return 0 ;; hc5962|\ mir3g|\ r6220|\ ubnt-erx|\ ubnt-erx-sfp) nand_do_platform_check "$board" "$1" return $?; ;; mikrotik,rbm33g|\ re350-v1) [ "$magic" != "01000000" ] && { echo "Invalid image type." return 1 } return 0 ;; wcr-1166ds|\ wsr-1166) [ "$magic" != "48445230" ] && { echo "Invalid image type." return 1 } return 0 ;; esac echo "Sysupgrade is not yet supported on $board." return 1 } platform_pre_upgrade() { local board=$(board_name) case "$board" in mikrotik,rbm33g) [ -z "$(rootfs_type)" ] && mtd erase firmware ;; esac } platform_nand_pre_upgrade() { local board=$(board_name) case "$board" in ubnt-erx|\ ubnt-erx-sfp) platform_upgrade_ubnt_erx "$ARGV" ;; esac } platform_do_upgrade() { local board=$(board_name) case "$board" in hc5962|\ mir3g|\ r6220|\ ubnt-erx|\ ubnt-erx-sfp) nand_do_upgrade "$ARGV" ;; *) default_do_upgrade "$ARGV" ;; esac } blink_led() { . /etc/diag.sh; set_state upgrade } append sysupgrade_pre_upgrade blink_led
# # Author:: Nagalakshmi <<EMAIL>> # Cookbook Name:: nrpe # Attributes:: default # # Copyright 2015, Cloudenablers # # All rights reserved. Do not redistribute. # # nrpe package options default['nrpe']['package']['options'] = nil default['nrpe']['install_method'] = 'source' # nrpe daemon user/group default['nrpe']['user'] = 'nagios' default['nrpe']['group'] = 'nagios' # config file options default['nrpe']['allow_bash_command_substitution'] = nil default['nrpe']['server_port'] = 5666 default['nrpe']['server_address'] = nil default['nrpe']['command_prefix'] = nil default['nrpe']['log_facility'] = nil default['nrpe']['debug'] = 0 default['nrpe']['dont_blame_nrpe'] = 1 default['nrpe']['command_timeout'] = 60 default['nrpe']['connection_timeout'] = nil # Nagios plugins from source installation default['nrpe']['plugins']['version'] = '2.0.3' default['nrpe']['plugins']['url'] = 'https://region-a.geo-1.objects.hpcloudsvc.com/v1/68342917034742/Cnext/files/monitoring/plugins' # nrpe from source installation default['nrpe']['version'] = '2.15' default['nrpe']['url'] = 'https://region-a.geo-1.objects.hpcloudsvc.com/v1/68342917034742/Cnext/files/monitoring/source' # authorization options default['nrpe']['allowed_hosts'] = "172.16.17.32" default['nrpe']['multi_environment_monitoring'] = false # platform specific values case node['platform_family'] when 'debian' default['nrpe']['pid_file'] = '/var/run/nagios/nrpe.pid' default['nrpe']['home'] = '/usr/lib/nagios' default['nrpe']['plugin_dir'] = '/usr/lib/nagios/plugins' default['nrpe']['conf_dir'] = '/etc/nagios' if node['kernel']['machine'] == 'i686' default['nrpe']['ssl_lib_dir'] = '/usr/lib/i386-linux-gnu' else default['nrpe']['ssl_lib_dir'] = '/usr/lib/x86_64-linux-gnu' end if node['nrpe']['install_method'] == 'package' default['nrpe']['service_name'] = 'nagios-nrpe-server' default['nrpe']['packages'] = %w(nagios-nrpe-server nagios-plugins nagios-plugins-basic nagios-plugins-standard) else default['nrpe']['service_name'] = 'nrpe' end when 'rhel', 'fedora' default['nrpe']['pid_file'] = '/var/run/nrpe.pid' if node['kernel']['machine'] == 'i686' default['nrpe']['home'] = '/usr/lib/nagios' default['nrpe']['ssl_lib_dir'] = '/usr/lib' default['nrpe']['plugin_dir'] = '/usr/lib/nagios/plugins' else default['nrpe']['home'] = '/usr/lib64/nagios' default['nrpe']['ssl_lib_dir'] = '/usr/lib64' default['nrpe']['plugin_dir'] = '/usr/lib64/nagios/plugins' end if node['nrpe']['install_method'] == 'package' default['nrpe']['packages'] = %w(nrpe nagios-plugins-disk nagios-plugins-load nagios-plugins-procs nagios-plugins-users) end default['nrpe']['service_name'] = 'nrpe' default['nrpe']['conf_dir'] = '/etc/nagios' when 'freebsd' default['nrpe']['install_method'] = 'package' default['nrpe']['pid_file'] = '/var/run/nrpe2/nrpe2.pid' default['nrpe']['log_facility'] = 'daemon' default['nrpe']['service_name'] = 'nrpe2' default['nrpe']['conf_dir'] = '/usr/local/etc' if node['nrpe']['install_method'] == 'package' default['nrpe']['packages'] = %w(nrpe) end else default['nrpe']['pid_file'] = '/var/run/nrpe.pid' default['nrpe']['home'] = '/usr/lib/nagios' default['nrpe']['ssl_lib_dir'] = '/usr/lib' default['nrpe']['service_name'] = 'nrpe' default['nrpe']['plugin_dir'] = '/usr/lib/nagios/plugins' default['nrpe']['conf_dir'] = '/etc/nagios' end
#!/bin/sh # Copyright 1998-2019 Lawrence Livermore National Security, LLC and other # HYPRE Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) TNAME=`basename $0 .sh` RTOL=$1 ATOL=$2 #============================================================================= # compare with baseline case #============================================================================= FILES="\ ${TNAME}.out.10.lobpcg\ ${TNAME}.out.11.lobpcg\ ${TNAME}.out.18.lobpcg\ ${TNAME}.out.19.lobpcg\ " for i in $FILES do echo "# Output file: $i" tail -3 $i echo "# Output file: $i.1" tail -13 $i.1 | head -3 echo "# Output file: $i.4" tail -19 $i.4 | head -9 done > ${TNAME}.out # Make sure that the output file is reasonable RUNCOUNT=`echo $FILES | wc -w` OUTCOUNT=`grep "Iterations" ${TNAME}.out | wc -l` if [ "$OUTCOUNT" != "$RUNCOUNT" ]; then echo "Incorrect number of runs in ${TNAME}.out" >&2 fi #============================================================================= # remove temporary files #============================================================================= # rm -f ${TNAME}.testdata*
class InsufficientFundsError(Exception): pass class InvalidRecipientError(Exception): pass class User: def __init__(self, username, public_key): self.username = username self.public_key = public_key class Coin: def __init__(self, user): self.coin = {user.public_key: 100} # Initial amount of 100 for the user self.user = user self.ledger = [] def transfer(self, recipient_public_key, amount): if recipient_public_key not in self.coin: raise InvalidRecipientError("Invalid recipient public key") if self.coin[self.user.public_key] < amount: raise InsufficientFundsError("Insufficient funds for transfer") self.coin[self.user.public_key] -= amount self.coin[recipient_public_key] = self.coin.get(recipient_public_key, 0) + amount self.ledger.append((self.user.public_key, recipient_public_key, amount))
#!/bin/bash #版本信息 build_date="20200307" build_version="v1.0.0" #当前时间 格式:2020-03-12 14:36:31 NOW_DATE=$(date "+%Y-%m-%d %H:%M:%S") #当前时间 echo "=========== $(date) ===========" #定义字体颜色 color_black_start="\033[30m" color_red_start="\033[31m" color_green_start="\033[32m" color_yellow_start="\033[33m" color_blue_start="\033[34m" color_purple_start="\033[35m" color_sky_blue_start="\033[36m" color_white_start="\033[37m" color_end="\033[0m" #提示信息级别定义 message_info_tag="${color_sky_blue_start}[Info] ${NOW_DATE} ${color_end}" message_warning_tag="${color_yellow_start}[Warning] ${NOW_DATE} ${color_end}" message_error_tag="${color_red_start}[Error] ${NOW_DATE} ${color_end}" message_success_tag="${color_green_start}[Success] ${NOW_DATE} ${color_end}" message_fail_tag="${color_red_start}[Failed] ${NOW_DATE} ${color_end}" #功能、版本信息描述输出 function fun_show_version_info(){ echo -e "${color_green_start} ############################################################# # Aliyun Domain DNS Update Shell Script # # Dynamic DNS Update Using Aliyun API # # Version: ${build_version} # BuildDate: ${build_date} # Author: risfeng<risfeng@gmail.com> # GitHub: https://github.com/risfeng/aliyun-ddns-shell # # Usage: please refer to https://github.com/risfeng/aliyun-ddns-shell/blob/master/README.md # ############################################################# ${color_end}" } fun_show_version_info #全局变量定义 #操作系统发行名常量 MAC_OS_RELEASE="Darwin" CENT_OS_RELEASE="centos" UBUNTU_OS_RELEASE="ubuntu" DEBIAN_OS_RELEASE="debian" # 配置、日志文件存放目录 FILE_SAVE_DIR="" # 目录前缀 FILE_DIR_PREFIX="configs" #配置文件路径 CONFIG_FILE_PATH="" # 配置文件名 CONFIG_FILE_NAME="config.cfg" #日志储存目录 LOG_FILE_PATH="" # 日志文件名 LOG_FILE_NAME="log-info.log" #当前时间戳 var_now_timestamp="" #是否root权限执行 var_is_root_execute=false #是否支持sudo执行 var_is_support_sudo=false #是否已安装curl组件 var_is_installed_curl=false #是否已安装openssl组件 var_is_installed_openssl=false #是否已安装nslookup组件 var_is_installed_nslookup=false #当前操作系统发行版本 var_os_release=`uname -a` #当前网络是否通外网 var_is_online=false #是否存在配置文件 var_is_exist_config_file=false #检测外网是否通地址 默认:www.baidu.com var_check_online_url="" #检测外网是否通重试次数 默认:3 var_check_online_retry_times="" #阿里云Dns动态更新配置变量定义 #一级域名 例如:example.com var_first_level_domain="" #二级域名 例如:testddns var_second_level_domain="" # 域名解析类型:A、NS、MX、TXT、CNAME、SRV、AAAA、CAA、REDIRECT_URL、FORWARD_URL var_domain_record_type="" #域名生效时间,默认:600 单位:秒 var_domian_ttl="" #阿里云授权Key var_access_key_id="" #阿里云授权Key Secret var_access_key_secret="" #阿里云更新域名Api Host 默认:https://alidns.aliyuncs.com var_aliyun_ddns_api_host="https://alidns.aliyuncs.com" #获取本机外网IP的shell命令,不能带有双引号 默认:"curl -s http://members.3322.org/dyndns/getip" var_local_wan_ip="" #获取ddns域名当前的解析记录的shell命令,支持数组,不能带有双引号 默认:使用nslookup获取 var_domian_server_ip="" #域名解析记录Id var_domian_record_id="" #消息推送配置,使用阿里钉钉 #是否启用消息推送 var_enable_message_push=false #推送地址 var_push_message_api="https://oapi.dingtalk.com/robot/send" #加签密钥 var_push_message_secret="" #消息推送token var_push_message_access_token="" #==================函数==================== # ping地址是否通 function fun_ping() { if ping -c 1 $1 >/dev/null; then # ping通 echo true else # 不通 echo false fi } # 检测是否通外网 function fun_check_online(){ for((i=1;i<=$var_check_online_retry_times;i++)); do fun_wirte_log "${message_info_tag}正在尝试检测外网:ping ${var_check_online_url}${color_red_start} $i ${color_end}times......" var_is_online=$(fun_ping ${var_check_online_url}) if [[ ${var_is_online} = true ]]; then fun_wirte_log "${message_success_tag}检测外网成功!" break else fun_wirte_log "${message_fail_tag}外网不通,ping ${var_check_online_url} fail." fi done if [[ ${var_is_online} = false ]]; then fun_wirte_log "${message_error_tag}检测当前无外网环境,重试${$var_check_online_retry_times}次ping ${var_check_online_url}都失败,程序终止执行." exit 1 fi } # 检测root权限 function fun_check_root(){ if [[ "`id -u`" != "0" ]]; then var_is_root_execute=false else var_is_root_execute=true fi } # 设置配置、日志文件保存目录 function fun_setting_file_save_dir(){ fun_check_root if [ "${FILE_SAVE_DIR}" = "" ]; then # if [[ "${var_os_release}" =~ "${MAC_OS_RELEASE}" ]]; then FILE_SAVE_DIR="./${FILE_DIR_PREFIX}" # else # if [ "${var_is_root_execute}" = true ]; then # FILE_SAVE_DIR="/etc/${FILE_DIR_PREFIX}" # else # FILE_SAVE_DIR="~/${FILE_DIR_PREFIX}" # fi # fi fi if [ ! -d "$FILE_SAVE_DIR" ]; then mkdir -p ${FILE_SAVE_DIR} fi if [ "${CONFIG_FILE_PATH}" = "" ]; then CONFIG_FILE_PATH="${FILE_SAVE_DIR}/${CONFIG_FILE_NAME}" fi if [ "${LOG_FILE_PATH}" = "" ]; then LOG_FILE_PATH="${FILE_SAVE_DIR}/${LOG_FILE_NAME}" fi } # 检测运行环境 function fun_check_run_environment(){ if [[ -f "/usr/bin/sudo" ]]; then var_is_support_sudo=true else var_is_support_sudo=false fi if [[ -f "/usr/bin/curl" ]]; then var_is_installed_curl=true else var_is_installed_curl=false fi if [[ -f "/usr/bin/openssl" ]]; then var_is_installed_openssl=true else var_is_installed_openssl=false fi if [[ -f "/usr/bin/nslookup" ]]; then var_is_installed_nslookup=true else var_is_installed_nslookup=false fi if [ -f "/etc/redhat-release" ]; then var_os_release="centos" elif [ -f "/etc/lsb-release" ]; then var_os_release="ubuntu" elif [ -f "/etc/debian_version" ]; then var_os_release="debian" fi } # 获取本机外网IP function fun_get_local_wan_ip(){ fun_wirte_log "${message_info_tag}正在获取本机外网ip......" if [[ "${var_local_wan_ip}" = "" ]]; then fun_wirte_log "${message_error_tag}获取外网ip配置项为空或无效." fun_wirte_log "${message_fail_tag}程序终止执行......" exit 1 fi var_local_wan_ip=`${var_local_wan_ip}` if [[ "${var_local_wan_ip}" = "" ]]; then fun_wirte_log "${message_error_tag}获取外网ip失败,请检查var_local_wan_ip配置项命令是否正确." fun_wirte_log "${message_fail_tag}程序终止执行......" exit 1 else fun_wirte_log "${message_info_tag}本机外网ip:${var_local_wan_ip}" fi } # 获取DDNS域名当前解析记录IP function fun_get_domian_server_ip(){ fun_wirte_log "${message_info_tag}正在获取${var_second_level_domain}.${var_first_level_domain}的ip......" if [[ "${var_domian_server_ip}" = "nslookup" ]]; then var_domian_server_ip=`nslookup -sil ${var_second_level_domain}.${var_first_level_domain} 2>/dev/null | grep Address: | sed 1d | sed s/Address://g | sed 's/ //g'` else var_domian_server_ip=`${var_domian_server_ip} | sed 's/;/ /g'` fi fun_wirte_log "${message_info_tag}域名${var_second_level_domain}.${var_first_level_domain}的当前ip:${var_domian_server_ip}" } # 判断当前外网ip与域名到服务ip是否相同 function fun_is_wan_ip_and_domain_ip_same(){ if [[ "${var_domian_server_ip}" != "" ]]; then if [[ "${var_domian_server_ip}" =~ "${var_local_wan_ip}" ]]; then fun_wirte_log "${message_info_tag}当前外网ip:[${var_local_wan_ip}]与${var_second_level_domain}.${var_first_level_domain}($var_domian_server_ip)的ip相同." fun_wirte_log "${message_success_tag}本地ip与域名解析ip未发生任何变动,无需更改,程序退出." exit 1 fi fi } # 安装运行必需组件 function fun_install_run_environment(){ if [[ ${var_is_installed_curl} = false ]] || [[ ${var_is_installed_openssl} = false ]] || [[ ${var_is_installed_nslookup} = false ]]; then fun_wirte_log "${message_warning_tag}检测到缺少运行必需组件,正在尝试安装......" # 有root权限 if [[ "${var_is_root_execute}" = true ]]; then if [[ "${var_os_release}" = "${CENT_OS_RELEASE}" ]]; then fun_wirte_log "${message_info_tag}检测到当前系统发行版本为:${CENT_OS_RELEASE}" fun_wirte_log "${message_info_tag}正在安装必需组件......" yum install curl openssl bind-utils -y elif [[ "${var_os_release}" = "${UBUNTU_OS_RELEASE}" ]];then fun_wirte_log "${message_info_tag}检测到当前系统发行版本为:${UBUNTU_OS_RELEASE}" fun_wirte_log "${message_info_tag}正在安装必需组件......" apt-get install curl openssl bind-utils -y elif [[ "${var_os_release}" = "${DEBIAN_OS_RELEASE}" ]]; then fun_wirte_log "${message_info_tag}检测到当前系统发行版本为:${DEBIAN_OS_RELEASE}" fun_wirte_log "${message_info_tag}正在安装必需组件......" apt-get install curl openssl bind-utils -y else fun_wirte_log "${message_warning_tag}当前系统是:${var_os_release},不支持自动安装必需组件,建议手动安装【curl、openssl、bind-utils】" fi if [[ -f "/usr/bin/curl" ]]; then var_is_installed_curl=true else var_is_installed_curl=false fun_wirte_log "${message_error_tag}curl组件自动安装失败!可能会影响到程序运行,建议手动安装!" fi if [[ -f "/usr/bin/openssl" ]]; then var_is_installed_openssl=true else var_is_installed_openssl=false fun_wirte_log "${message_error_tag}openssl组件自动安装失败!可能会影响到程序运行,建议手动安装!" fi if [[ -f "/usr/bin/nslookup" ]]; then var_is_installed_nslookup=true else var_is_installed_nslookup=false fun_wirte_log "${message_error_tag}nslokkup组件自动安装失败!可能会影响到程序运行,建议手动安装!" fi elif [[ -f "/usr/bin/sudo" ]]; then fun_wirte_log "${message_warning_tag}当前脚本未以root权限执行,正在尝试以sudo命令安装必需组件......" if [[ "${var_os_release}" = "${CENT_OS_RELEASE}" ]]; then fun_wirte_log "${message_info_tag}检测到当前系统发行版本为:${CENT_OS_RELEASE}" fun_wirte_log "${message_info_tag}正在以sudo安装必需组件......" sudo yum install curl openssl bind-utils -y elif [[ "${var_os_release}" = "${UBUNTU_OS_RELEASE}" ]];then fun_wirte_log "${message_info_tag}检测到当前系统发行版本为:${UBUNTU_OS_RELEASE}" fun_wirte_log "${message_info_tag}正在以sudo安装必需组件......" sudo apt-get install curl openssl bind-utils -y elif ["${var_os_release}" = "${DEBIAN_OS_RELEASE}" ]; then fun_wirte_log "${message_info_tag}检测到当前系统发行版本为:${DEBIAN_OS_RELEASE}" fun_wirte_log "${message_info_tag}正在以sudo安装必需组件......" sudo apt-get install curl openssl bind-utils -y else fun_wirte_log "${message_warning_tag}当前系统是:${var_os_release},不支持自动安装必需组件,建议手动安装【curl、openssl、bind-utils】" fi else fun_wirte_log "${message_error_tag}系统缺少必需组件且无法自动安装,建议手动安装." fi fi } # 检测配置文件 function fun_check_config_file(){ fun_setting_file_save_dir if [[ -f "${CONFIG_FILE_PATH}" ]]; then fun_wirte_log "${message_info_tag}检测到配置文件,自动加载现有配置信息。可通过菜单选项【恢复出厂设置】重置." #加载配置文件 source ${CONFIG_FILE_PATH} if [[ "${var_first_level_domain}" = "" ]] || [[ "${var_second_level_domain}" = "" ]] || [[ "${var_domian_ttl}" = "" ]] \ || [[ "${var_access_key_id}" = "" ]] || [[ "${var_access_key_secret}" = "" ]] || [[ "${var_local_wan_ip}" = "" ]] \ || [[ "${var_domian_server_ip}" = "" ]] || [[ "${var_check_online_url}" = "" ]] || [[ "${var_check_online_retry_times}" = "" ]] \ || [[ "${var_aliyun_ddns_api_host}" = "" ]] \ || [[ "${var_enable_message_push}" = true && "${var_push_message_access_token}" = "" && "${var_push_message_secret}" = "" ]] \ || [[ "${var_check_online_url}" = "" ]] \ || [[ "${var_domain_record_type}" = "" ]] \ || [[ "${var_check_online_retry_times}" = "" ]] ; then fun_wirte_log "${message_error_tag}配置文件有误,请检查配置文件,建议清理后重新配置!程序退出执行." exit 1 fi var_is_exist_config_file=true else var_is_exist_config_file=fasle fi } # 设置配置文件 function fun_set_config(){ # 检测外网畅通ping等域名地址,默认:www.baidu.com if [[ "${var_check_online_url}" = "" ]]; then echo -e "\n${message_info_tag}[var_check_online_url]请输入外网检测Ping地址:" read -p "(默认:www.baidu.com,如有疑问请输入“-h”查看帮助):" var_check_online_url [[ "${var_check_online_url}" = "-h" ]] && fun_help_document "var_check_online_url" && echo -e "${message_info_tag}[var_check_online_url]请输入外网检测Ping地址:" && read -p "(默认:www.baidu.com):" var_check_online_url [[ -z "${var_check_online_url}" ]] && echo -e "${message_info_tag}输入为空值,已设置为:“www.baidu.com”" && var_check_online_url="www.baidu.com" fi # 检测外网畅通失败重试次数,默认:3 if [[ "${var_check_online_retry_times}" = "" ]]; then echo -e "\n${message_info_tag}[var_check_online_retry_times]请输入外网检测失败后重试次数:" read -p "(默认:3,如有疑问请输入“-h”查看帮助):" var_check_online_retry_times [[ "${var_check_online_retry_times}" = "-h" ]] && fun_help_document "var_check_online_retry_times" && echo -e "${message_info_tag}[var_check_online_retry_times]请输入外网检测失败后重试次数:" && read -p "(默认:3):" var_check_online_retry_times [[ -z "${var_check_online_retry_times}" ]] && echo -e "${message_info_tag}输入为空值,已设置为:“3”" && var_check_online_retry_times=3 fi # 一级域名 if [[ "${var_first_level_domain}" = "" ]]; then echo -e "\n${message_info_tag}[var_first_level_domain]请输入一级域名(示例 demo.com)${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_first_level_domain [[ "${var_first_level_domain}" = "-h" ]] && fun_help_document "var_first_level_domain" && echo -e "${message_info_tag}[var_first_level_domain]请输入一级域名 (示例 demo.com)" && read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_first_level_domain while [[ "${var_first_level_domain}" = "" || "${var_first_level_domain}" = "-h" ]] do if [[ "${var_first_level_domain}" = "" ]]; then echo -e "${message_error_tag}此项不可为空,请重新输入!" echo -e "${message_info_tag}[var_first_level_domain]请输入一级域名(示例 demo.com)${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_first_level_domain elif [[ "${var_first_level_domain}" = "-h" ]]; then fun_help_document "var_first_level_domain" echo -e "${message_info_tag}[var_first_level_domain]请输入一级域名(示例 demo.com)${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_first_level_domain fi done fi # 二级域名 if [[ "${var_second_level_domain}" = "" ]]; then echo -e "\n${message_info_tag}[var_second_level_domain]请输入二级域名(示例 test)${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_second_level_domain [[ "${var_second_level_domain}" = "-h" ]] && fun_help_document "var_second_level_domain" && echo -e "${message_info_tag}[var_second_level_domain]请输入二级域名 (示例 test)" && read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_second_level_domain while [[ "${var_second_level_domain}" = "" || "${var_second_level_domain}" = "-h" ]] do if [[ "${var_second_level_domain}" = "" ]]; then echo -e "${message_error_tag}此项不可为空,请重新输入!" echo -e "${message_info_tag}[var_second_level_domain]请输入二级域名(示例 test)${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_second_level_domain elif [[ "${var_second_level_domain}" = "-h" ]]; then fun_help_document "var_second_level_domain" echo -e "${message_info_tag}[var_second_level_domain]请输入二级域名(示例 test)${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_second_level_domain fi done fi # 域名解析类型:A、NS、MX、TXT、CNAME、SRV、AAAA、CAA、REDIRECT_URL、FORWARD_URL if [[ "${var_domain_record_type}" = "" ]]; then echo -e "\n${message_info_tag}[var_domain_record_type]请输入解析类型(示例 A)${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_domain_record_type [[ "${var_domain_record_type}" = "-h" ]] && fun_help_document "var_domain_record_type" && echo -e "${message_info_tag}[var_domain_record_type]请输入解析类型(示例 A)" && read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_domain_record_type while [[ "${var_domain_record_type}" = "" || "${var_domain_record_type}" = "-h" ]] do if [[ "${var_domain_record_type}" = "" ]]; then echo -e "${message_error_tag}此项不可为空,请重新输入!" echo -e "${message_info_tag}[var_domain_record_type]请输入解析类型(示例 A)${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_domain_record_type elif [[ "${var_domain_record_type}" = "-h" ]]; then fun_help_document "var_domain_record_type" echo -e "${message_info_tag}[var_domain_record_type]请输入解析类型(示例 A)${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_domain_record_type fi done fi # 域名生效时间,默认:600 if [[ "${var_domian_ttl}" = "" ]]; then echo -e "\n${message_info_tag}[var_domian_ttl]请输入域名解析记录生效时间(TTL Time-To-Live)秒:" read -p "(默认600,如有疑问请输入“-h”查看帮助):" var_domian_ttl [[ "${var_domian_ttl}" = "-h" ]] && fun_help_document "var_domian_ttl" && echo -e "${message_info_tag}[var_domian_ttl]请输入域名解析记录生效时间(TTL Time-To-Live)秒:" && read -p "(默认600):" var_domian_ttl [[ -z "${var_domian_ttl}" ]] && echo -e "${message_info_tag}输入为空值,已设置TTL值为:“600”" && var_domian_ttl="600" fi # 阿里云授权Key if [[ "${var_access_key_id}" = "" ]]; then echo -e "\n${message_info_tag}[var_access_key_id]请输入阿里云AccessKeyId${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_access_key_id [[ "${var_access_key_id}" = "-h" ]] && fun_help_document "var_access_key_id" && echo -e "${message_info_tag}[var_access_key_id]请输入阿里云AccessKeyId" && read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_access_key_id while [[ "${var_access_key_id}" = "" || "${var_access_key_id}" = "-h" ]] do if [[ "${var_access_key_id}" = "" ]]; then echo -e "${message_error_tag}此项不可为空,请重新输入!" echo -e "${message_info_tag}[var_access_key_id]请输入阿里云AccessKeyId${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_access_key_id elif [[ "${var_access_key_id}" = "-h" ]]; then fun_help_document "var_access_key_id" echo -e "${message_info_tag}[var_access_key_id]请输入阿里云AccessKeyId${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_access_key_id fi done fi # 阿里云授权Key Secret if [[ "${var_access_key_secret}" = "" ]]; then echo -e "\n${message_info_tag}[var_access_key_secret]请输入阿里云AccessKeySecret${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_access_key_secret [[ "${var_access_key_secret}" = "-h" ]] && fun_help_document "var_access_key_secret" && echo -e "${message_info_tag}[var_access_key_secret]请输入阿里云AccessKeySecret" && read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_access_key_secret while [[ "${var_access_key_secret}" = "" || "${var_access_key_secret}" = "-h" ]] do if [[ "${var_access_key_secret}" = "" ]]; then echo -e "${message_error_tag}此项不可为空,请重新输入!" echo -e "${message_info_tag}[var_access_key_secret]请输入阿里云AccessKeySecret${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_access_key_secret elif [[ "${var_access_key_secret}" = "-h" ]]; then fun_help_document "var_access_key_secret" echo -e "${message_info_tag}[var_access_key_secret]请输入阿里云AccessKeySecret${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_access_key_secret fi done fi # 获取本机外网IP的shell命令 if [[ "${var_local_wan_ip}" = "" ]]; then echo -e "\n${message_info_tag}[var_local_wan_ip]请输入获取本机外网IP使用的命令(默认:只支持ipv4)" read -p "(如有疑问请输入“-h”查看帮助):" var_local_wan_ip [[ "${var_local_wan_ip}" = "-h" ]] && fun_help_document "var_local_wan_ip" && echo -e "${message_info_tag}[var_local_wan_ip]请输入获取本机外网IP使用的命令(默认:只支持ipv4)" && read -p "(如有疑问请输入“-h”查看帮助):" var_local_wan_ip [[ -z "${var_local_wan_ip}" ]] && echo -e "${message_info_tag}输入为空值,已设置执行命令为:“curl -s http://members.3322.org/dyndns/getip”" && var_local_wan_ip="curl -s http://members.3322.org/dyndns/getip" fi # 获取ddns域名当前的解析记录的shell命令 if [[ "${var_domian_server_ip}" = "" ]]; then echo -e "\n${message_info_tag}[var_domian_server_ip]请输入获取域名当前解析记录的IP使用的命令(建议默认)" read -p "(如有疑问请输入“-h”查看帮助):" var_domian_server_ip [[ "${var_domian_server_ip}" = "-h" ]] && fun_help_document "var_domian_server_ip" && echo -e "${message_info_tag}[var_domian_server_ip]请输入获取域名当前解析记录的IP使用的命令(建议默认)" && read -p "(如有疑问请输入“-h”查看帮助):" var_domian_server_ip [[ -z "${var_domian_server_ip}" ]] && echo -e "${message_info_tag}输入为空值,已设置执行命令为:“nslookup“" && var_domian_server_ip="nslookup" fi # 是否启用消息推送,默认:false if [[ "${var_enable_message_push}" = false ]]; then echo -e "\n${message_info_tag}[var_enable_message_push]请输入是否启用消息通知(钉钉机器人)推送(请输入true或false):" read -p "(默认false,如有疑问请输入“-h”查看帮助):" var_enable_message_push [[ "${var_enable_message_push}" = "-h" ]] && fun_help_document "var_enable_message_push" && echo -e "${message_info_tag}[var_enable_message_push]请输入是否启用消息通知(钉钉机器人)推送(请输入true或false):" && read -p "(默认false):" var_enable_message_push [[ -z "${var_enable_message_push}" ]] && echo -e "${message_info_tag}输入为空值,已设置为:false" && var_enable_message_push=false fi # 消息通知发送token if [[ "${var_enable_message_push}" = true && "${var_push_message_access_token}" = "" ]]; then echo -e "\n${message_info_tag}[var_push_message_access_token]请输入钉钉机器人推送access_token${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_push_message_access_token [[ "${var_push_message_access_token}" = "-h" ]] && fun_help_document "var_push_message_access_token" && echo -e "${message_info_tag}[var_push_message_access_token]请输入钉钉机器人推送access_token" && read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_push_message_access_token while [[ "${var_push_message_access_token}" = "" || "${var_push_message_access_token}" = "-h" ]] do if [[ "${var_push_message_access_token}" = "" ]]; then echo -e "${message_error_tag}此项不可为空,请重新输入!" echo -e "${message_info_tag}[var_push_message_access_token]请输入钉钉机器人推送access_token${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_push_message_access_token elif [[ "${var_push_message_access_token}" = "-h" ]]; then fun_help_document "var_push_message_access_token" echo -e "${message_info_tag}[var_push_message_access_token]请输入钉钉机器人推送access_token${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_push_message_access_token fi done fi # 消息通知发送secret if [[ "${var_enable_message_push}" = true && "${var_push_message_secret}" = "" ]]; then echo -e "\n${message_info_tag}[var_push_message_secret]请输入钉钉机器人安全设置的加签(密钥)${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_push_message_secret [[ "${var_push_message_secret}" = "-h" ]] && fun_help_document "var_push_message_secret" && echo -e "${message_info_tag}[var_push_message_secret]请输入钉钉机器人安全设置的加签(密钥)" && read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_push_message_secret while [[ "${var_push_message_secret}" = "" || "${var_push_message_secret}" = "-h" ]] do if [[ "${var_push_message_secret}" = "" ]]; then echo -e "${message_error_tag}此项不可为空,请重新输入!" echo -e "${message_info_tag}[var_push_message_secret]请输入钉钉机器人安全设置的加签(密钥)${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_push_message_secret elif [[ "${var_push_message_secret}" = "-h" ]]; then fun_help_document "var_push_message_secret" echo -e "${message_info_tag}[var_push_message_secret]请输入钉钉机器人安全设置的加签(密钥)${color_red_start}(*)${color_end}" read -p "(此项为必填,如有疑问请输入“-h”查看帮助):" var_push_message_secret fi done fi } # 保存配置文件 function fun_save_config(){ # 写入配置文件 fun_wirte_log "${message_info_tag}正在保存配置文件......" fun_setting_file_save_dir rm -f ${CONFIG_FILE_PATH} cat>${CONFIG_FILE_PATH}<<EOF var_check_online_url="${var_check_online_url}" var_check_online_retry_times=${var_check_online_retry_times} var_first_level_domain="${var_first_level_domain}" var_second_level_domain="${var_second_level_domain}" var_domain_record_type="${var_domain_record_type}" var_domian_ttl="${var_domian_ttl}" var_access_key_id="${var_access_key_id}" var_access_key_secret="${var_access_key_secret}" var_local_wan_ip="${var_local_wan_ip}" var_domian_server_ip="${var_domian_server_ip}" var_enable_message_push=${var_enable_message_push} var_push_message_access_token="${var_push_message_access_token}" var_push_message_secret="${var_push_message_secret}" EOF fun_wirte_log "${message_success_tag}配置文件保存成功." fun_wirte_log "${message_info_tag}正在加载配置文件......" source ${CONFIG_FILE_PATH} fun_wirte_log "${message_success_tag}配置文件加载成功." } # 帮助文档 function fun_help_document(){ help_type="$1" case "$help_type" in "var_first_level_domain") echo -e "${message_info_tag}${color_green_start}[${help_type}]一级域名帮助-说明${color_end} 此参数决定你要修改的DDNS域名中,一级域名的名称。 请确保你要配置域名到DNS服务器已转入阿里云解析,也就是状态 必须为“正常”或者“未设置解析”,不可以为“DNS服务器错误”等错误提示。 例如:demo.com\n" var_first_level_domain="" ;; "var_second_level_domain") echo -e "${message_info_tag}${color_green_start}[${help_type}]二级域名帮助-说明${color_end} 此参数决定你要修改的DDNS域名中,二级域名的名称。 二级域名与一级域名最终拼接成:test.demo.com 例如:test\n" var_second_level_domain="" ;; # 域名解析类型:A、NS、MX、TXT、CNAME、SRV、AAAA、CAA、REDIRECT_URL、FORWARD_URL "var_domain_record_type") echo -e "${message_info_tag}${color_green_start}[${help_type}]域名解析类型帮助-说明${color_end} 此参数决定你解析域名的类型。 可选值:A、NS、MX、TXT、CNAME、SRV、AAAA、CAA、REDIRECT_URL、FORWARD_URL 每个值具体含义请移步:https://help.aliyun.com/document_detail/29805.html?spm=a2c4g.11186623.2.13.1e201cebcClxSe 例如:A\n" var_domain_record_type="" ;; "var_domian_ttl") echo -e "${message_info_tag}${color_green_start}[${help_type}]域名生效时间TTL-说明${color_end} 此参数决定你要修改的DDNS记录中,TTL(Time-To-Line)时长。 越短的TTL,DNS更新生效速度越快 (但也不是越快越好,因情况而定) 免费版产品可设置为 (600-86400) (即10分钟-1天) 收费版产品可根据所购买的云解析企业版产品配置设置为 (1-86400) (即1秒-1天) 请免费版用户不要设置TTL低于600秒,会导致运行报错!\n" var_domian_ttl="" ;; "var_access_key_id") echo -e "${message_info_tag}${color_green_start}[${help_type}]AccessKeyId-说明${color_end} 此参数决定修改DDNS记录所需要用到的阿里云API信息 (AccessKeyId)。 获取AccessKeydD和AccessKeySecret请移步:https://usercenter.console.aliyun.com/#/manage/ak ${color_red_start}注意:${color_end}请不要泄露你的AccessKeyId/AccessKeySecret给任何人! 一旦他们获取了你的AccessKeyId/AccessKeySecret,将会直接拥有控制你阿里云账号的能力!" var_access_key_id="" ;; "var_access_key_secret") echo -e "${message_info_tag}${color_green_start}[${help_type}]AccessKeySecret-说明${color_end} 此参数决定修改DDNS记录所需要用到的阿里云API信息 (AccessKeySecret)。 获取AccessKeydD和AccessKeySecret请移步:https://usercenter.console.aliyun.com/#/manage/ak ${color_red_start}注意:${color_end}请不要泄露你的AccessKeyId/AccessKeySecret给任何人! 一旦他们获取了你的AccessKeyId/AccessKeySecret,将会直接拥有控制你阿里云账号的能力!" var_access_key_secret="" ;; "var_local_wan_ip") echo -e "${message_info_tag}${color_green_start}[${help_type}]本地外网IP-说明${color_end} 此参数决定如何获取到本机的IP地址。 出于稳定性考虑,默认使用“curl -s http://members.3322.org/dyndns/getip”作为获取本地外网IP的方式, 你也可以自定义获取IP方式。输入格式为需要执行的命令且不能出现双引号(\")。" var_local_wan_ip="" ;; "var_domian_server_ip") echo -e "${message_info_tag}${color_green_start}[${help_type}]域名当前解析IP-说明${color_end} 此参数决定如何获取到DDNS域名当前的解析记录。 默认使用“nslookup”作为获取域名当前解析IP的方式,如不了解请使用默认方式。 你也可以自定义获取域名当前解析IP方式。输入格式为需要执行的命令且不能出现双引号(\")。 参考:“curl -s http://119.29.29.29/d?dn=\$var_second_level_domain.\$var_first_level_domain”" var_domian_server_ip="" ;; "var_enable_message_push") echo -e "${message_info_tag}${color_green_start}[${help_type}]是否启用消息推送-说明${color_end} 此参数决定是否启用消息通知控制。 当脚本执行失败或成功将通过钉钉机器人通知。 更多信息与配置请看https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq官方文档。" var_enable_message_push="" ;; "var_push_message_access_token") echo -e "${message_info_tag}${color_green_start}[${help_type}]消息推送密钥-说明${color_end} 此参数为钉钉机器人推送消息的access_token。 Webhook地址参数access_token=后的值。 更多信息与配置请看https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq官方文档。" var_push_message_access_token="" ;; "var_push_message_secret") echo -e "${message_info_tag}${color_green_start}[${help_type}]加签密钥-说明${color_end} 此参数为钉钉机器人安全设置中的加签密钥消息推送时签名使用 在机器人设置-安全设置-加签即可找到,以SEC开头。 更多信息与配置请看https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq官方文档。" var_push_message_secret="" ;; "var_check_online_url") echo -e "${message_info_tag}${color_green_start}[${help_type}]外网检测Ping地址-说明${color_end} 此参数为检测当前脚本运行环境与外网是否畅通ping使用的地址 如不了解,请使用默认值:www.baidu.com" var_check_online_url="" ;; "var_check_online_retry_times") echo -e "${message_info_tag}${color_green_start}[${help_type}]外网检测失败后重试次数-说明${color_end} 此参数为检测当前脚本运行环境与外网是否畅通ping失败后重试次数 如不了解,请使用默认值:3" var_check_online_retry_times="" ;; *) echo "无帮助文档" esac } # 获取当前时间戳 function fun_get_now_timestamp(){ var_now_timestamp=`date -u "+%Y-%m-%dT%H%%3A%M%%3A%SZ"` } # 获取当前时间戳 毫秒 function fun_get_current_timestamp_ms(){ echo "$((`date '+%s'`*1000+`date '+%N'`/1000000))" } # url编码 function fun_url_encode() { out="" while read -n1 c do case ${c} in [a-zA-Z0-9._-]) out="$out$c" ;; *) out="$out`printf '%%%02X' "'$c"`" ;; esac done echo -n ${out} } # url加密函数 function fun_get_url_encryption() { echo -n "$1" | fun_url_encode } #hmac-sha1 签名 usage: get_signature "签名算法" "加密串" "key" function get_signature() { echo -ne "$2" | openssl dgst -$1 -hmac "$3" -binary | base64 } # 生成uuid function fun_get_uuid(){ echo $(uuidgen | tr '[A-Z]' '[a-z]') } # json转换函数 fun_parse_json "json" "key_name" function fun_parse_json(){ echo "${1//\"/}" | sed "s/.*$2:\([^,}]*\).*/\1/" } # 发送请求 eg:fun_send_request "GET" "Action" "动态请求参数(看说明)" "控制是否打印请求响应信息:true false" fun_send_request() { local args="AccessKeyId=$var_access_key_id&Action=$2&Format=json&$3&Version=2015-01-09" local message="$1&$(fun_get_url_encryption "/")&$(fun_get_url_encryption "$args")" local key="$var_access_key_secret&" local string_to_sign=$(get_signature "sha1" "$message" "$key") local signature=$(fun_get_url_encryption "$string_to_sign") local request_url="$var_aliyun_ddns_api_host/?$args&Signature=$signature" local response=$(curl -s ${request_url}) fun_wirte_log "${message_info_tag}阿里云$2接口请求返回信息:${response},接口:${request_url}" false local code=$(fun_parse_json "$response" "Code") local message=$(fun_parse_json "$response" "Message") if [[ "$code" = "" ]]; then fun_wirte_log "${message_success_tag}阿里云$2接口请求处理成功,返回消息:${message}" else fun_wirte_log "${message_warning_tag}阿里云$2接口请求处理失败,返回代码:${code}消息:${message}" fi # 获取RecordId时需要过滤出id值 需要打印请求响应信息 if [[ "$4" != "" || "$4" = true ]]; then echo $response fi } # 获取域名解析记录Id正则 function fun_get_record_id_regx() { grep -Eo '"RecordId":"[0-9]+"' | cut -d':' -f2 | tr -d '"' } # 查询域名解析记录值请求 function fun_query_record_id_send() { local query_url="SignatureMethod=HMAC-SHA1&SignatureNonce=$(fun_get_uuid)&SignatureVersion=1.0&SubDomain=$var_second_level_domain.$var_first_level_domain&Timestamp=$var_now_timestamp" fun_send_request "GET" "DescribeSubDomainRecords" ${query_url} true } # 更新域名解析记录值请求 fun_update_record "record_id" function fun_update_record_send() { fun_send_request "GET" "UpdateDomainRecord" "RR=$var_second_level_domain&RecordId=$1&SignatureMethod=HMAC-SHA1&SignatureNonce=$(fun_get_uuid)&SignatureVersion=1.0&TTL=$var_domian_ttl&Timestamp=$var_now_timestamp&Type=$var_domain_record_type&Value=$var_local_wan_ip" } # 更新域名解析记录值 function fun_update_record(){ fun_wirte_log "${message_info_tag}正在更新域名解析记录值......" if [[ "${var_domian_record_id}" = "" ]]; then fun_wirte_log "${message_info_tag}正在获取record_id......" var_domian_record_id=`fun_query_record_id_send | fun_get_record_id_regx` if [[ "${var_domian_record_id}" = "" ]]; then fun_wirte_log "${message_warning_tag}获取record_id为空,可能没有获取到有效的解析记录(record_id=$var_domian_record_id)" else fun_wirte_log "${message_info_tag}获取到到record_id=$var_domian_record_id" fun_wirte_log "${message_info_tag}正在更新解析记录:[$var_second_level_domain.$var_first_level_domain]的ip为[$var_local_wan_ip]......" fun_update_record_send ${var_domian_record_id} fun_wirte_log "${message_info_tag}已经更新record_id=${var_domian_record_id}的记录" fi fi if [[ "${var_domian_record_id}" = "" ]]; then # 未能获取到domian_record_id fun_wirte_log "${message_fail_tag}域名解析记录更新失败!" fun_push_message "[失败]域名解析记录更新失败,获取的record_id为空,请检查域名解析记录是否存在或配置的阿里云access_key_id是否禁用或变更!" exit 1 else # 更新成功 fun_wirte_log "${message_success_tag}域名[$var_second_level_domain.$var_first_level_domain](新IP:$var_local_wan_ip)记录更新成功。" fun_push_message "[成功]域名[$var_second_level_domain.$var_first_level_domain](新IP:$var_local_wan_ip)记录更新成功。" exit 0 fi } # 写日志到文件并显示 usage:fun_wirte_log "日志内容" “是否输出到console中:true(默认) false” function fun_wirte_log(){ fun_setting_file_save_dir log_content="$1" if [[ "$2" = "" || "$2" = true ]]; then echo -e "$log_content" fi # 处理样式 todo echo "${log_content}" >> ${LOG_FILE_PATH} } # 消息推送 function fun_push_message(){ if [[ "${var_enable_message_push}" = true ]]; then fun_wirte_log "${message_info_tag}正在推送消息到钉钉......" fun_send_message_to_ding_ding "{'msgtype': 'text','text':{'content': '【域名解析服务-${NOW_DATE}】$1'}}" fi } #发送消息到钉钉 fun_send_message_to_ding_ding "内容" function fun_send_message_to_ding_ding(){ local timestamp_ms=$(fun_get_current_timestamp_ms) local str_to_sign="$timestamp_ms\n$var_push_message_secret"; local sign=$(get_signature "sha256" "$str_to_sign" "$var_push_message_secret") local encode_sign=$(fun_get_url_encryption "$sign"); local request_url="$var_push_message_api?access_token=$var_push_message_access_token&timestamp=$timestamp_ms&sign=$encode_sign" # 发送请求 local response=$(curl -s "${request_url}" -H "Content-Type: application/json" -d "$1") fun_wirte_log "${message_info_tag}钉钉接口推送返回信息:${response}" false # json解析 local errcode=$(fun_parse_json "$response" "errcode") local errmsg=$(fun_parse_json "$response" "errmsg") if [[ "$errcode" -eq "0" ]]; then fun_wirte_log "${message_success_tag}消息推送成功,返回消息:${errmsg}" else fun_wirte_log "${message_warning_tag}消息推送失败,返回消息:${errmsg}" fi } # 恢复出厂设置 function fun_restore_settings(){ fun_setting_file_save_dir rm -f ${CONFIG_FILE_PATH} var_is_root_execute=false var_is_support_sudo=false var_first_level_domain="" var_second_level_domain="" var_domian_ttl="" var_access_key_id="" var_access_key_secret="" var_local_wan_ip="" var_domian_server_ip="" var_enable_message_push=false var_push_message_access_token="" var_push_message_secret="" var_domain_record_type="" fun_wirte_log "${message_success_tag}所有配置项重置成功!" } # 清除日志文件 function fun_clearn_logs(){ fun_setting_file_save_dir rm -f ${LOG_FILE_PATH} echo -e "${message_success_tag}日志文件清理成功!" } # 主入口1 配置并运行 function main_fun_config_and_run(){ fun_check_root fun_check_run_environment fun_install_run_environment fun_check_config_file fun_set_config fun_save_config fun_check_online fun_get_local_wan_ip fun_get_domian_server_ip fun_get_now_timestamp fun_is_wan_ip_and_domain_ip_same fun_update_record exit 0 } # 主入口2 仅运行 function main_fun_only_run(){ fun_check_config_file if [[ "${var_is_exist_config_file}" != true ]]; then fun_wirte_log "${message_error_tag}未检测到配置文件,请直接运行程序配置!" exit 1 fi fun_check_run_environment fun_install_run_environment fun_check_online fun_get_local_wan_ip fun_get_domian_server_ip fun_get_now_timestamp fun_is_wan_ip_and_domain_ip_same fun_update_record exit 0 } # 主入口3 仅配置 function main_fun_only_config(){ fun_check_root fun_check_run_environment fun_install_run_environment fun_check_config_file fun_set_config fun_save_config fun_wirte_log "${message_success_tag}配置完成!" exit 0 } # 主入口4 恢复出厂设置 function main_fun_restore_settings(){ fun_wirte_log "${message_info_tag}正在恢复出厂设置......" fun_restore_settings fun_wirte_log "${message_success_tag}恢复出厂设置成功,可重新运行程序进行配置。" exit 0 } # 主入口5 清理日志文件 function main_fun_clearn_logs(){ echo -e "${message_info_tag}正在清理日志文件......" fun_clearn_logs exit 0 } # 显示程序说明和版本信息 function main_fun_show_version(){ fun_show_version_info exit 0 } CONFIG_FILE_NAME=$2 # 根据输入参数执行对应函数 case "$1" in "-config -run") main_fun_config_and_run ;; "-run") main_fun_only_run ;; "-config") main_fun_only_config ;; "-restore") main_fun_restore_settings ;; "-version") main_fun_show_version ;; "-clearn") main_fun_clearn_logs ;; *) echo -e "${color_blue_start}===阿里云域名动态IP自动解析小脚本===${color_end} 使用方法 (Usage): aliyun-ddns.sh -config -run 配置并执行脚本 aliyun-ddns.sh -run 执行脚本(前提需要有配置文件) aliyun-ddns.sh -config 仅配置信息 aliyun-ddns.sh -restore 恢复出厂设置(会清除配置文件等) aliyun-ddns.sh -clearn 清理日志文件 aliyun-ddns.sh -version 显示脚本说明及版本信息 " ;; esac echo -e "${message_info_tag}选择需要执行的功能" echo -e "\n 1.配置并执行脚本 \n 2.仅配置 \n 3.仅执行脚本 \n 4.恢复出厂设置 \n 5.清理日志文件 \n 0.退出 \n" read -p "请输入你的选择(输入数字):" run_function if [[ "${run_function}" == "1" ]]; then main_fun_config_and_run elif [[ "${run_function}" == "2" ]]; then main_fun_only_config elif [[ "${run_function}" == "3" ]]; then main_fun_only_run elif [[ "${run_function}" == "4" ]]; then main_fun_restore_settings elif [[ "${run_function}" == "5" ]]; then main_fun_clearn_logs else exit 0 fi
# Copyright 2020 TWO SIGMA OPEN SOURCE, LLC # # 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. #!/bin/bash (python -m unittest) (cd ../beakerx_tabledisplay; python -m unittest)
# The Book of Ruby - http://www.sapphiresteel.com require( "testmod.rb" )
package io.github.rcarlosdasilva.weixin.core.cache.storage.redis; import org.springframework.data.redis.core.RedisTemplate; import io.github.rcarlosdasilva.weixin.core.Registry; import io.github.rcarlosdasilva.weixin.core.exception.RedisCacheNotInitializeException; import io.github.rcarlosdasilva.weixin.core.setting.RedisSetting; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; @SuppressWarnings("rawtypes") public class RedisHandler { private static RedisTemplate redisTemplate = null; private static JedisPool pool = null; private RedisHandler() { throw new IllegalStateException("RedisHandler class"); } public static RedisTemplate getRedisTemplate() { return redisTemplate; } public static void setRedisTemplate(RedisTemplate redisTemplate) { RedisHandler.redisTemplate = redisTemplate; } private static synchronized void initSimpleRedis(RedisSetting redisSetting) { pool = new JedisPool(redisSetting.getConfig(), redisSetting.getHost(), redisSetting.getPort(), redisSetting.getTimeout(), redisSetting.getPassword(), redisSetting.getDatabase(), redisSetting.isUseSsl()); } public static synchronized Jedis getJedis() { if (pool == null) { RedisSetting redisSetting = Registry.setting().getRedisSetting(); if (redisSetting == null) { throw new RedisCacheNotInitializeException("Simple Redis缓存未配置"); } initSimpleRedis(redisSetting); } return pool.getResource(); } }
<filename>frontend/src/mixins/FieldMixin.js import { camelCase } from 'lodash-es'; import { getId, getName, attributesTable } from '@utils/helpers'; import FieldInstructions from '@components/inputs/includes/FieldInstructions.vue'; import FieldLabel from '@components/inputs/includes/FieldLabel.vue'; export default { components: { FieldInstructions, FieldLabel, }, props: { field: { type: Object, default: () => {}, }, namespace: { type: Array, default: () => { return []; }, }, namespaceSuffix: { type: Array, default: () => { return []; }, }, }, data() { return { subFields: [], }; }, methods: { attrs(field = null, handles = []) { if (field === null) { field = this.field; } return { id: this.getId(handles), name: this.getName(handles), required: field.required, placeholder: field.placeholder, value: field.defaultValue, ...attributesTable(field.inputAttributes), }; }, getId(handles = []) { const parts = [...this.namespace, this.field.handle, ...handles, ...this.namespaceSuffix]; return getId(parts); }, getName(handles = []) { const parts = [...this.namespace, this.field.handle, ...handles, ...this.namespaceSuffix]; return getName(parts); }, getSubFields() { const enabledSubFields = []; this.subFields.forEach((subFields, groupIndex) => { subFields.forEach((subField) => { if (this.field[`${subField}Enabled`]) { const subFieldOptions = {}; Object.keys(this.field).forEach((key) => { if (key.startsWith(subField)) { const newKey = camelCase(key.replace(subField, '')); subFieldOptions[newKey] = this.field[key]; } }); if (!enabledSubFields[groupIndex]) { enabledSubFields[groupIndex] = {}; } enabledSubFields[groupIndex][subField] = subFieldOptions; } }); }); return enabledSubFields; }, }, };
<reponame>humorliang/bc-cms package main import ( "flag" "github.com/gin-gonic/gin" "com/setting" "com/gmysql" "routers" "middlerware" "strconv" "fmt" ) func main() { var mode = flag.String("mode", "dev", "this is run mode options") //命令行解析 mode为*string flag.Parse() //配置文件初始化 setting.SetUp(mode) //设置模式 gin.SetMode(setting.ServerSetting.RunMode) //数据库初始化 gmysql.SetUp() //创建router对象 router := gin.New() //注册中间件 router.Use(middlerware.Logger()) router.Use(gin.Recovery()) router.Use(middlerware.NotFoundPage()) //注册路由 routers.SetUp(router) fmt.Println("Listening and serving HTTP on :",setting.ServerSetting.HttpPort) fmt.Println("-------------------------------------------") router.Run(":" + strconv.Itoa(setting.ServerSetting.HttpPort)) }
#!/usr/bin/env bash IP=ocp.datr.eu USER=justin PROJECT=tekton-example oc login https://${IP}:8443 -u $USER oc delete project $PROJECT oc new-project $PROJECT 2> /dev/null while [ $? \> 0 ]; do sleep 1 printf "." oc new-project $PROJECT 2> /dev/null done #oc apply -f git_resource.yaml # #oc apply -f image_resource.yaml # #oc apply -f build_task.yaml # #oc apply -f build_taskrun.yaml oc apply -f pipelinerun.yaml
#!/bin/bash function check_text_in_log { EXPECTED_TEXT=$1 EXPECTED_COUNT=${2:-1} echo "Checking log for '${EXPECTED_TEXT}'" EXPECTED_TEXT_COUNT=$(grep "${EXPECTED_TEXT}" ${OUTPUT_LOG_FILE} | wc -l) if [ ${EXPECTED_TEXT_COUNT} -ne ${EXPECTED_COUNT} ]; then echo "Unexpected count of '${EXPECTED_TEXT}' has not been found in output log. Expected: ${EXPECTED_COUNT} was: ${EXPECTED_TEXT_COUNT}"; exit 1 fi }
<filename>C2CRIBuildDir/projects/C2C-RI/src/RIGUI/src/org/fhwa/c2cri/gui/ConfigFileTableModel.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.fhwa.c2cri.gui; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.Date; import java.util.concurrent.Callable; import org.fhwa.c2cri.testmodel.TestConfiguration; import org.fhwa.c2cri.testmodel.TestConfigurationDescription; import org.fhwa.c2cri.testmodel.TestConfigurationList; /** * The methods in this class allow the JTable component to get and display data * about the files in a specified directly. It represents a table with 6 * columns: file name, size, modification date, plus three columns for flags: * directory, readable, writable * * @author TransCore ITS, LLC * Last Updated: 1/8/2014 */ public class ConfigFileTableModel extends javax.swing.table.AbstractTableModel { /** The directory that will be referenced by the model. */ protected File dir; /** The list of files that were found at the directory. */ protected String[] filenames; // protected String[] fileDescriptions; // protected Date[] fileDates; /** The log filter. */ private FilenameFilter logFilter; /** The config filter. */ private FilenameFilter configFilter; /** The cfg descriptions. */ private ArrayList<TestConfigurationDescription> cfgDescriptions = new ArrayList<>(); /** The Constant NTHREDS. */ private static final int NTHREDS = 10; /** The column names that will be displayed on the table. */ protected String[] columnNames = new String[]{ "Name", "Description", "Last Modified" }; /** The class types associated with the columns on the table. */ protected Class[] columnClasses = new Class[]{ String.class, String.class, Date.class }; /** The input. */ private ObjectInputStream input; // This table model works for any one given directory /** * The constructor for the ConfigTableModel. * <li> Create a config file Filter for checking for Config Files * <li> Create a log file Filter for checking for log Files * <li> set the filenames array to the list of config files * * @param dir the dir */ public ConfigFileTableModel(File dir) { this.dir = dir; // configFilter = new FilenameFilter() { // public boolean accept(File dir, String name) { //// String fileName = dir.getPath() + File.separator + name; //// System.out.println("ConfigTableModel checking file "+ name); // if (name.endsWith(".ricfg") || (name.endsWith(".RICFG"))) { //// try { //// TestConfiguration tempTest; //// ObjectInputStream input = new ObjectInputStream(new FileInputStream(fileName)); //// tempTest = (org.fhwa.c2cri.testmodel.TestConfiguration) input.readObject(); //// input.close(); //// input = null; //// if (!tempTest.isValidConfiguration()) { //// return false; //// } else { // return true; //// } //// } catch (Exception ex) { //// } // } // // // return name.endsWith(TestDefinitionCoordinator.CONFIGURATION_FILE_EXTENSION); // return false; // } // }; // // logFilter = new FilenameFilter() { // public boolean accept(File dir, String name) { // return name.contains(".rilog"); // } // }; // // System.out.println("Getting the list of config files."); // this.filenames = dir.list(configFilter); // Store a list of files in the directory // // ExecutorService executor = Executors.newFixedThreadPool(NTHREDS); // ArrayList<Future<ConfigDescription>> cfgList = new ArrayList<Future<ConfigDescription>>(); // System.out.println("Starting the config File Workers"); // for (int ii = 0; ii<this.filenames.length;ii++){ // Callable<ConfigDescription> worker = new ConfigCallable(ii,dir.getAbsolutePath(),filenames[ii]); // Future<ConfigDescription> submit = executor.submit(worker); // cfgList.add(submit); // } // // Now retrieve the result // for (Future<ConfigDescription> future : cfgList){ // try{ // ConfigDescription result = future.get(); // if (result.isValid()){ // cfgDescriptions.add(result); // } // } catch (InterruptedException e){ // e.printStackTrace(); // } catch (ExecutionException e){ // e.printStackTrace(); // } // } // executor.shutdown(); // System.out.println("Finished the config File Workers"); // //// fileDescriptions = new String[this.filenames.length]; //// fileDates = new Date[this.filenames.length]; //// for (int ii = 0; ii < this.filenames.length; ii++) { //// File f = new File(dir, filenames[ii]); //// //// String description = ""; //// try { //// input = new ObjectInputStream(new FileInputStream(f)); //// try { //// TestConfiguration testConfig = null; //// testConfig = (TestConfiguration) input.readObject(); //// if (testConfig.isValidConfiguration()) { //// description = testConfig.getTestDescription(); //// } else { //// description = "Invalid Config File"; //// } //// input.close(); //// input = null; //// testConfig = null; //// } catch (Exception e1) { //// description = "Invalid Config File"; //// } //// //// } catch (Exception e) { //// description = "Can't read file"; //// } //// fileDescriptions[ii] = description; //// fileDates[ii] = new Date(f.lastModified()); //// //// } cfgDescriptions.clear(); ArrayList<TestConfigurationDescription> cfgList = TestConfigurationList.getInstance().getList(dir); for (TestConfigurationDescription thisCfg : cfgList){ if (thisCfg.isValid()){ cfgDescriptions.add(thisCfg); } } System.out.println(" Number of files found = " + cfgDescriptions.size()); } // These are easy methods. /* (non-Javadoc) * @see javax.swing.table.TableModel#getColumnCount() */ public int getColumnCount() { return 3; } // A constant for this model /* (non-Javadoc) * @see javax.swing.table.TableModel#getRowCount() */ public int getRowCount() { // System.out.println(" Number of files found = "+ this.filenames.length); return this.cfgDescriptions.size(); } // # of files in dir // Information about each column. /* (non-Javadoc) * @see javax.swing.table.AbstractTableModel#getColumnName(int) */ @Override public String getColumnName(int col) { return columnNames[col]; } /* (non-Javadoc) * @see javax.swing.table.AbstractTableModel#getColumnClass(int) */ @Override public Class getColumnClass(int col) { return columnClasses[col]; } // The method that must actually return the value of each cell. /* (non-Javadoc) * @see javax.swing.table.TableModel#getValueAt(int, int) */ public Object getValueAt(int row, int col) { // File f = new File(dir, filenames[row]); switch (col) { case 0: return cfgDescriptions.get(row).getFilename(); case 1: return cfgDescriptions.get(row).getFileDescription(); // String description = null; // try { // input = new ObjectInputStream(new FileInputStream(f)); // try { // TestConfiguration testConfig = null; // testConfig = (TestConfiguration) input.readObject(); // if (testConfig.isValidConfiguration()) { // description = testConfig.getTestDescription(); // } else { // description = "Invalid Config File"; // } // input.close(); // input = null; // testConfig = null; // } catch (Exception e1) { // description = "Invalid Config File"; // } // // } catch (Exception e) { // description = "Can't read file"; // } // return description; case 2: return cfgDescriptions.get(row).getFileDate(); // return new Date(f.lastModified()); default: return null; } } /** * The Class ConfigDescription. * * @author TransCore ITS, LLC * Last Updated: 1/8/2014 */ class ConfigDescription { /** The id. */ private int id; /** The valid. */ private boolean valid; /** The filenames. */ private String filenames; /** The file description. */ private String fileDescription; /** The file dates. */ private Date fileDates; /** * Gets the id. * * @return the id */ public int getId() { return id; } /** * Sets the id. * * @param id the new id */ public void setId(int id) { this.id = id; } /** * Gets the filenames. * * @return the filenames */ public String getFilenames() { return filenames; } /** * Sets the filenames. * * @param filenames the new filenames */ public void setFilenames(String filenames) { this.filenames = filenames; } /** * Gets the file description. * * @return the file description */ public String getFileDescription() { return fileDescription; } /** * Sets the file description. * * @param fileDescriptions the new file description */ public void setFileDescription(String fileDescriptions) { this.fileDescription = fileDescriptions; } /** * Gets the file dates. * * @return the file dates */ public Date getFileDates() { return fileDates; } /** * Sets the file dates. * * @param fileDates the new file dates */ public void setFileDates(Date fileDates) { this.fileDates = fileDates; } /** * Checks if is valid. * * Pre-Conditions: N/A * Post-Conditions: N/A * * @return true, if is valid */ public boolean isValid() { return valid; } /** * Sets the valid. * * @param valid the new valid */ public void setValid(boolean valid) { this.valid = valid; } } /** * The Class ConfigCallable. * * @author TransCore ITS, LLC * Last Updated: 1/8/2014 */ class ConfigCallable implements Callable<ConfigDescription> { /** The index. */ private final int index; /** The dir. */ private final String dir; /** The file. */ private final String file; /** * Instantiates a new config callable. * * Pre-Conditions: N/A * Post-Conditions: N/A * * @param index the index * @param dir the dir * @param file the file */ public ConfigCallable(int index, String dir, String file) { this.index = index; this.dir = dir; this.file = file; } /* (non-Javadoc) * @see java.util.concurrent.Callable#call() */ @Override public ConfigDescription call() throws Exception { ObjectInputStream inputFile; File f = new File(dir, file); ConfigDescription cfgDescription = new ConfigDescription(); cfgDescription.setFilenames(file); cfgDescription.setId(index); cfgDescription.setFileDates(new Date(f.lastModified())); String description = ""; try { inputFile = new ObjectInputStream(new FileInputStream(f)); try { TestConfiguration testConfig = null; testConfig = (TestConfiguration) inputFile.readObject(); if (testConfig.isValidConfiguration()) { description = testConfig.getTestDescription(); cfgDescription.setValid(true); } else { description = "Invalid Config File"; cfgDescription.setValid(false); } inputFile.close(); inputFile = null; testConfig = null; } catch (Exception e1) { description = "Invalid Config File"; } } catch (Exception e) { description = "Can't read file"; } cfgDescription.setFileDescription(description); System.out.println("Index "+index + " : checking File "+file+" : valid = "+cfgDescription.isValid()); return cfgDescription; } } }
package cn.stylefeng.guns.onlineaccess.modular.mapper; import cn.stylefeng.guns.onlineaccess.modular.entity.DataType; import cn.stylefeng.guns.onlineaccess.modular.result.DataTypeResult; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface DataTypeMapper extends BaseMapper<DataType> { List<DataType> getDataTypeByProjectIdResult(Page page,Long id); }
package family.service; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * This class was generated by Apache CXF 3.2.4 * 2018-05-11T17:44:05.490+02:00 * Generated source version: 3.2.4 * */ @WebService(targetNamespace = "http://service.family/", name = "FamilyData") @XmlSeeAlso({ObjectFactory.class}) public interface FamilyData { @WebMethod(action = "urn:ReadMother") @RequestWrapper(localName = "readMother", targetNamespace = "http://service.family/", className = "family.service.ReadMother") @ResponseWrapper(localName = "readMotherResponse", targetNamespace = "http://service.family/", className = "family.service.ReadMotherResponse") @WebResult(name = "return", targetNamespace = "") public family.service.FamilyMember readMother( @WebParam(name = "surname", targetNamespace = "") java.lang.String surname ); @WebMethod(action = "urn:CreateChild") @RequestWrapper(localName = "createChild", targetNamespace = "http://service.family/", className = "family.service.CreateChild") @ResponseWrapper(localName = "createChildResponse", targetNamespace = "http://service.family/", className = "family.service.CreateChildResponse") public void createChild( @WebParam(name = "fmember_name", targetNamespace = "") java.lang.String fmemberName, @WebParam(name = "surname", targetNamespace = "") java.lang.String surname, @WebParam(name = "date_of_birth", targetNamespace = "") java.lang.String dateOfBirth ); @WebMethod(action = "urn:ReadChild") @RequestWrapper(localName = "readChild", targetNamespace = "http://service.family/", className = "family.service.ReadChild") @ResponseWrapper(localName = "readChildResponse", targetNamespace = "http://service.family/", className = "family.service.ReadChildResponse") @WebResult(name = "return", targetNamespace = "") public family.service.FamilyMember readChild( @WebParam(name = "surname", targetNamespace = "") java.lang.String surname ); @WebMethod(action = "urn:ReadFather") @RequestWrapper(localName = "readFather", targetNamespace = "http://service.family/", className = "family.service.ReadFather") @ResponseWrapper(localName = "readFatherResponse", targetNamespace = "http://service.family/", className = "family.service.ReadFatherResponse") @WebResult(name = "return", targetNamespace = "") public family.service.FamilyMember readFather( @WebParam(name = "surname", targetNamespace = "") java.lang.String surname ); @WebMethod(action = "urn:CreateFather") @RequestWrapper(localName = "createFather", targetNamespace = "http://service.family/", className = "family.service.CreateFather") @ResponseWrapper(localName = "createFatherResponse", targetNamespace = "http://service.family/", className = "family.service.CreateFatherResponse") public void createFather( @WebParam(name = "fmember_name", targetNamespace = "") java.lang.String fmemberName, @WebParam(name = "surname", targetNamespace = "") java.lang.String surname, @WebParam(name = "date_of_birth", targetNamespace = "") java.lang.String dateOfBirth ); @WebMethod(action = "urn:CreateMother") @RequestWrapper(localName = "createMother", targetNamespace = "http://service.family/", className = "family.service.CreateMother") @ResponseWrapper(localName = "createMotherResponse", targetNamespace = "http://service.family/", className = "family.service.CreateMotherResponse") public void createMother( @WebParam(name = "fmember_name", targetNamespace = "") java.lang.String fmemberName, @WebParam(name = "surname", targetNamespace = "") java.lang.String surname, @WebParam(name = "date_of_birth", targetNamespace = "") java.lang.String dateOfBirth ); }
#!/bin/bash # # Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # set -ex nvidia-smi . jenkins/version-def.sh ARTF_ROOT="$WORKSPACE/jars" MVN_GET_CMD="mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get -B \ -Dmaven.repo.local=$WORKSPACE/.m2 \ $MVN_URM_MIRROR -Ddest=$ARTF_ROOT" rm -rf $ARTF_ROOT && mkdir -p $ARTF_ROOT # maven download SNAPSHOT jars: cudf, rapids-4-spark, spark3.0 $MVN_GET_CMD -DremoteRepositories=$CUDF_REPO \ -DgroupId=ai.rapids -DartifactId=cudf -Dversion=$CUDF_VER -Dclassifier=$CUDA_CLASSIFIER $MVN_GET_CMD -DremoteRepositories=$PROJECT_REPO \ -DgroupId=com.nvidia -DartifactId=rapids-4-spark_$SCALA_BINARY_VER -Dversion=$PROJECT_VER $MVN_GET_CMD -DremoteRepositories=$PROJECT_TEST_REPO \ -DgroupId=com.nvidia -DartifactId=rapids-4-spark-udf-examples_$SCALA_BINARY_VER -Dversion=$PROJECT_TEST_VER $MVN_GET_CMD -DremoteRepositories=$PROJECT_TEST_REPO \ -DgroupId=com.nvidia -DartifactId=rapids-4-spark-integration-tests_$SCALA_BINARY_VER -Dversion=$PROJECT_TEST_VER if [ "$CUDA_CLASSIFIER"x == x ];then CUDF_JAR="$ARTF_ROOT/cudf-$CUDF_VER.jar" else CUDF_JAR="$ARTF_ROOT/cudf-$CUDF_VER-$CUDA_CLASSIFIER.jar" fi export RAPIDS_PLUGIN_JAR="$ARTF_ROOT/rapids-4-spark_${SCALA_BINARY_VER}-$PROJECT_VER.jar" RAPIDS_UDF_JAR="$ARTF_ROOT/rapids-4-spark-udf-examples_${SCALA_BINARY_VER}-$PROJECT_TEST_VER.jar" RAPIDS_TEST_JAR="$ARTF_ROOT/rapids-4-spark-integration-tests_${SCALA_BINARY_VER}-$PROJECT_TEST_VER.jar" $MVN_GET_CMD -DremoteRepositories=$PROJECT_TEST_REPO \ -DgroupId=com.nvidia -DartifactId=rapids-4-spark-integration-tests_$SCALA_BINARY_VER -Dversion=$PROJECT_TEST_VER -Dclassifier=pytest -Dpackaging=tar.gz RAPIDS_INT_TESTS_HOME="$ARTF_ROOT/integration_tests/" RAPIDS_INT_TESTS_TGZ="$ARTF_ROOT/rapids-4-spark-integration-tests_${SCALA_BINARY_VER}-$PROJECT_TEST_VER-pytest.tar.gz" tar xzf "$RAPIDS_INT_TESTS_TGZ" -C $ARTF_ROOT && rm -f "$RAPIDS_INT_TESTS_TGZ" $MVN_GET_CMD -DremoteRepositories=$SPARK_REPO \ -DgroupId=org.apache -DartifactId=spark -Dversion=$SPARK_VER -Dclassifier=bin-hadoop3.2 -Dpackaging=tgz export SPARK_HOME="$ARTF_ROOT/spark-$SPARK_VER-bin-hadoop3.2" export PATH="$SPARK_HOME/bin:$SPARK_HOME/sbin:$PATH" tar zxf $SPARK_HOME.tgz -C $ARTF_ROOT && \ rm -f $SPARK_HOME.tgz IS_SPARK_311_OR_LATER=0 [[ "$(printf '%s\n' "3.1.1" "$SPARK_VER" | sort -V | head -n1)" = "3.1.1" ]] && IS_SPARK_311_OR_LATER=1 export SPARK_TASK_MAXFAILURES=1 [[ "$IS_SPARK_311_OR_LATER" -eq "0" ]] && SPARK_TASK_MAXFAILURES=4 IS_SPARK_311=0 [[ "$SPARK_VER" == "3.1.1" ]] && IS_SPARK_311=1 export PATH="$SPARK_HOME/bin:$SPARK_HOME/sbin:$PATH" #stop and restart SPARK ETL stop-slave.sh stop-master.sh start-master.sh start-slave.sh spark://$HOSTNAME:7077 jps echo "----------------------------START TEST------------------------------------" pushd $RAPIDS_INT_TESTS_HOME export BASE_SPARK_SUBMIT_ARGS="$BASE_SPARK_SUBMIT_ARGS \ --master spark://$HOSTNAME:7077 \ --conf spark.sql.shuffle.partitions=12 \ --conf spark.task.maxFailures=$SPARK_TASK_MAXFAILURES \ --conf spark.dynamicAllocation.enabled=false \ --conf spark.driver.extraJavaOptions=-Duser.timezone=UTC \ --conf spark.executor.extraJavaOptions=-Duser.timezone=UTC \ --conf spark.sql.session.timeZone=UTC" export SEQ_CONF="--executor-memory 16G \ --total-executor-cores 6" # currently we hardcode the parallelism and configs based on our CI node's hardware specs, # we can make it dynamically generated if this script is going to be used in other scenarios in the future export PARALLEL_CONF="--executor-memory 4G \ --total-executor-cores 2 \ --conf spark.executor.cores=2 \ --conf spark.task.cpus=1 \ --conf spark.rapids.sql.concurrentGpuTasks=2 \ --conf spark.rapids.memory.gpu.allocFraction=0.15 \ --conf spark.rapids.memory.gpu.minAllocFraction=0 \ --conf spark.rapids.memory.gpu.maxAllocFraction=0.15" export CUDF_UDF_TEST_ARGS="--conf spark.rapids.memory.gpu.allocFraction=0.1 \ --conf spark.rapids.memory.gpu.minAllocFraction=0 \ --conf spark.rapids.python.memory.gpu.allocFraction=0.1 \ --conf spark.rapids.python.concurrentPythonWorkers=2 \ --conf spark.executorEnv.PYTHONPATH=${RAPIDS_PLUGIN_JAR} \ --conf spark.pyspark.python=/opt/conda/bin/python \ --py-files ${RAPIDS_PLUGIN_JAR}" export TEST_PARALLEL=0 # disable spark local parallel in run_pyspark_from_build.sh export TEST_TYPE="nightly" export LOCAL_JAR_PATH=$ARTF_ROOT export SCRIPT_PATH="$(pwd -P)" export TARGET_DIR="$SCRIPT_PATH/target" mkdir -p $TARGET_DIR run_test() { local TEST=${1//\.py/} local LOG_FILE case $TEST in all) SPARK_SUBMIT_FLAGS="$BASE_SPARK_SUBMIT_ARGS $SEQ_CONF" \ ./run_pyspark_from_build.sh ;; cudf_udf_test) SPARK_SUBMIT_FLAGS="$BASE_SPARK_SUBMIT_ARGS $SEQ_CONF $CUDF_UDF_TEST_ARGS" \ ./run_pyspark_from_build.sh -m cudf_udf --cudf_udf ;; cache_serializer) SPARK_SUBMIT_FLAGS="$BASE_SPARK_SUBMIT_ARGS $SEQ_CONF \ --conf spark.sql.cache.serializer=com.nvidia.spark.rapids.shims.spark311.ParquetCachedBatchSerializer" \ ./run_pyspark_from_build.sh -k cache_test ;; *) echo -e "\n\n>>>>> $TEST...\n" LOG_FILE="$TARGET_DIR/$TEST.log" # set dedicated RUN_DIRs here to avoid conflict between parallel tests RUN_DIR="$TARGET_DIR/run_dir_$TEST" \ SPARK_SUBMIT_FLAGS="$BASE_SPARK_SUBMIT_ARGS $PARALLEL_CONF" \ ./run_pyspark_from_build.sh -k $TEST >"$LOG_FILE" 2>&1 CODE="$?" if [[ $CODE == "0" ]]; then sed -n -e '/test session starts/,/deselected,/ p' "$LOG_FILE" || true else cat "$LOG_FILE" || true fi return $CODE ;; esac } export -f run_test # integration tests if [[ $PARALLEL_TEST == "true" ]] && [ -x "$(command -v parallel)" ]; then # put most time-consuming tests at the head of queue time_consuming_tests="join_test.py generate_expr_test.py parquet_write_test.py" tests_list=$(find "$SCRIPT_PATH"/src/main/python/ -name "*_test.py" -printf "%f ") tests=$(echo "$time_consuming_tests $tests_list" | tr ' ' '\n' | awk '!x[$0]++' | xargs) # --halt "now,fail=1": exit when the first job fail, and kill running jobs. # we can set it to "never" and print failed ones after finish running all tests if needed # --group: print stderr after test finished for better readability parallel --group --halt "now,fail=1" -j5 run_test ::: $tests else run_test all fi # cudf_udf_test run_test cudf_udf_test # Temporarily only run on Spark 3.1.1 (https://github.com/NVIDIA/spark-rapids/issues/3311) if [[ "$IS_SPARK_311" -eq "1" ]]; then run_test cache_serializer fi popd stop-slave.sh stop-master.sh
module Typus VERSION = "0.9.40" end
<filename>src/icons/legacy/LogoAds.tsx // Generated by script, don't edit it please. import createSvgIcon from '../../createSvgIcon'; import LogoAdsSvg from '@rsuite/icon-font/lib/legacy/LogoAds'; const LogoAds = createSvgIcon({ as: LogoAdsSvg, ariaLabel: 'logo ads', category: 'legacy', displayName: 'LogoAds' }); export default LogoAds;
package io.opensphere.myplaces.editor.model; import java.awt.Color; import java.awt.Font; import de.micromata.opengis.kml.v_2_2_0.ExtendedData; import de.micromata.opengis.kml.v_2_2_0.Placemark; import io.opensphere.core.util.ValidationStatus; import io.opensphere.core.util.swing.FontWrapper; import io.opensphere.core.util.swing.TextStyleModel; import io.opensphere.core.util.swing.input.model.BooleanModel; import io.opensphere.core.util.swing.input.model.ColorModel; import io.opensphere.core.util.swing.input.model.WrappedModel; import io.opensphere.myplaces.constants.Constants; import io.opensphere.myplaces.util.ExtendedDataUtils; import io.opensphere.myplaces.util.PlacemarkUtils; /** The GUI model of an annotation point. */ @SuppressWarnings("PMD.GodClass") public class AnnotationModel extends WrappedModel<Placemark> { /** Whether to animate a timed my place. */ private final BooleanModel myAnimate = new BooleanModel(); /** The border color. */ private final ColorModel myBorderColor = new ColorModel(); /** The fill color of a polygon, if applicable. */ private final ColorModel myPolygonFillColor = new ColorModel(); /** The error message. */ private String myError; /** Indicates if the model can even show headings and distances. */ private boolean myIsDistanceHeadingCapable; /** Whether the bubble is filled. */ private final BooleanModel myIsBubbleFilled = new BooleanModel(); /** Whether the polygon is filled. */ private final BooleanModel myIsPolygonFilled = new BooleanModel(false); /** Indicates if the model can even show locations. */ private boolean myIsLocationCapable; /** Whether to show the altitude. */ private final BooleanModel myShowAltitude = new BooleanModel(); /** Whether to show the decimal lat/lon. */ private final BooleanModel myShowDecimalLatLon = new BooleanModel(); /** Whether to show the description. */ private final BooleanModel myShowDescription = new BooleanModel(); /** A flag used to indicate if the model can display velocity. */ private boolean myVelocityCapable; /** The model used to store the display state of the velocity value. */ private final BooleanModel myShowVelocity = new BooleanModel(); /** A flag used to indicate if the model can display duration. */ private boolean myDurationCapable; /** The model used to store the display state of the duration value. */ private final BooleanModel myShowDuration = new BooleanModel(); /** Whether to show the distance. */ private final BooleanModel myShowDistance = new BooleanModel(); /** Whether to show the DMS lat/lon. */ private final BooleanModel myShowDMSLatLon = new BooleanModel(); /** Whether to show the heading. */ private final BooleanModel myShowHeading = new BooleanModel(); /** Whether to show a timed my place in the timeline. */ private final BooleanModel myShowInTimeline = new BooleanModel(); /** Whether to show the MGRS lat/lon. */ private final BooleanModel myShowMGRSLatLon = new BooleanModel(); /** Whether to show the title. */ private final BooleanModel myShowTitle = new BooleanModel(); /** The model in which the display state of the field titles is stored. */ private final BooleanModel myShowFieldTitles = new BooleanModel(); /** The Text style model. */ private final TextStyleModel myTextStyleModel = new TextStyleModel(); /** * Returns a new font with the given style change applied. * * @param font The font * @param style The style to apply * @param isAdd True to add the style, false to remove it * @return The new font */ private static Font changeStyle(Font font, int style, boolean isAdd) { return font.deriveFont(isAdd ? font.getStyle() | style : font.getStyle() & ~style); } /** * Count if true. * * @param value the value * @return the 1 if true 0 if false. */ private static int countIfTrue(Boolean value) { return value != null && value.booleanValue() ? 1 : 0; } /** Constructor. */ public AnnotationModel() { myShowTitle.setNameAndDescription("Title", "Whether to show the title in the bubble"); myShowFieldTitles.setNameAndDescription("Field Titles", "Whether to show the titles of each field in the bubble"); myShowDecimalLatLon.setNameAndDescription("Decimal lat/lon", "Whether to show the decimal lat/lon in the bubble"); myShowDMSLatLon.setNameAndDescription("DMS lat/lon", "Whether to show the DMS lat/lon in the bubble"); myShowMGRSLatLon.setNameAndDescription("MGRS", "Whether to show the MGRS lat/lon in the bubble"); myShowAltitude.setNameAndDescription("Altitude", "Whether to show the altitude in the bubble"); myShowDescription.setNameAndDescription("Description", "Whether to show the description lat/lon in the bubble"); myIsBubbleFilled.setNameAndDescription("Fill Bubble", "Whether to fill the bubble background"); myIsPolygonFilled.setNameAndDescription("Fill Polygon", "Whether to fill the polygon"); myBorderColor.setNameAndDescription("Color", "The border color"); myPolygonFillColor.setNameAndDescription("Fill Color", "The color with which to fill a polygon."); myShowDistance.setNameAndDescription("Distance", "Whether to show the distance in the bubble"); myShowHeading.setNameAndDescription("Heading", "Whether to show the heading in the bubble"); myShowVelocity.setNameAndDescription("Velocity", "Whether to show the velocity in the bubble"); myShowDuration.setNameAndDescription("Duration", "Whether to show duration in the bubble."); myShowInTimeline.setNameAndDescription("Show on timeline", "Whether to show a my place with a time in the timeline"); myAnimate.setNameAndDescription("Animate", "Whether to be able to animate a my place with time."); addModel(myShowTitle); addModel(myShowFieldTitles); addModel(myShowDecimalLatLon); addModel(myShowDMSLatLon); addModel(myShowMGRSLatLon); addModel(myShowAltitude); addModel(myShowDescription); addModel(myShowDistance); addModel(myShowHeading); addModel(myShowVelocity); addModel(myShowInTimeline); addModel(myAnimate); addModel(myTextStyleModel.getFont()); addModel(myTextStyleModel.getFontSize()); addModel(myTextStyleModel.getBold()); addModel(myTextStyleModel.getItalic()); addModel(myTextStyleModel.getFontColor()); addModel(myBorderColor); addModel(myPolygonFillColor); addModel(myIsBubbleFilled); addModel(myIsPolygonFilled); } /** * Gets the model that indicates if a timed my place should be animated. * * @return The animate model. */ public BooleanModel getAnimate() { return myAnimate; } /** * Gets the border color. * * @return the border color */ public ColorModel getBorderColor() { return myBorderColor; } /** * Gets the value of the {@link #myPolygonFillColor} field. * * @return the value stored in the {@link #myPolygonFillColor} field. */ public ColorModel getPolygonFillColor() { return myPolygonFillColor; } @Override public synchronized String getErrorMessage() { return myError != null ? myError : super.getErrorMessage(); } /** * Getter for isFilled. * * @return the isFilled */ public BooleanModel getBubbleFilled() { return myIsBubbleFilled; } /** * Gets the value of the {@link #myIsPolygonFilled} field. * * @return the value stored in the {@link #myIsPolygonFilled} field. */ public BooleanModel getPolygonFilled() { return myIsPolygonFilled; } /** * Gets the showAltitude. * * @return the showAltitude */ public BooleanModel getShowAltitude() { return myShowAltitude; } /** * Getter for decimalLatLon. * * @return the decimalLatLon */ public BooleanModel getShowDecimalLatLon() { return myShowDecimalLatLon; } /** * Getter for description. * * @return the description */ public BooleanModel getShowDescription() { return myShowDescription; } /** * Getter for distance.. * * @return the distance. */ public BooleanModel getShowDistance() { return myShowDistance; } /** * Getter for dMSLatLon. * * @return the dMSLatLon */ public BooleanModel getShowDMSLatLon() { return myShowDMSLatLon; } /** * Getter for heading. * * @return the heading. */ public BooleanModel getShowHeading() { return myShowHeading; } /** * Gets the value of the {@link #myShowVelocity} field. * * @return the value stored in the {@link #myShowVelocity} field. */ public BooleanModel getShowVelocity() { return myShowVelocity; } /** * Gets the value of the {@link #myShowDuration} field. * * @return the value stored in the {@link #myShowDuration} field. */ public BooleanModel getShowDuration() { return myShowDuration; } /** * Gets the model that indicates if a timed my place should show in the * timeline. * * @return The show in timeline model. */ public BooleanModel getShowInTimeline() { return myShowInTimeline; } /** * Getter for mGRSLatLon. * * @return the mGRSLatLon */ public BooleanModel getShowMGRSLatLon() { return myShowMGRSLatLon; } /** * Getter for title. * * @return the title */ public BooleanModel getShowTitle() { return myShowTitle; } /** * Gets the value of the {@link #myShowFieldTitles} field. * * @return the value stored in the {@link #myShowFieldTitles} field. */ public BooleanModel getShowFieldTitles() { return myShowFieldTitles; } /** * Gets the text style model. * * @return the text style model */ public TextStyleModel getTextStyleModel() { return myTextStyleModel; } @Override public ValidationStatus getValidationStatus() { myError = null; if (super.getValidationStatus() == ValidationStatus.VALID) { if (!isValidating()) { return ValidationStatus.VALID; } if (!bubbleCheckBoxesValid()) { myError = "You must select an item under Bubble Contents."; return ValidationStatus.ERROR; } return ValidationStatus.VALID; } return ValidationStatus.ERROR; } /** * Indicates if the model can even show a heading or a distance. * * @return True if heading and distance should be shown, false otherwise. */ public boolean isDistanceHeadingCapable() { return myIsDistanceHeadingCapable; } /** * Indicates if the model can even show a location information. * * @return True if locations should be shown, false otherwise. */ public boolean isLocationCapable() { return myIsLocationCapable; } /** * Gets the value of the {@link #myVelocityCapable} field. * * @return the value stored in the {@link #myVelocityCapable} field. */ public boolean isVelocityCapable() { return myVelocityCapable; } /** * Gets the value of the {@link #myDurationCapable} field. * * @return the value stored in the {@link #myDurationCapable} field. */ public boolean isDurationCapable() { return myDurationCapable; } /** * Saves only the changed inputs to the given point. * * @param placemark The placemark */ public void saveChangedInputs(Placemark placemark) { saveChangedAnnoSettings(placemark); saveChangedPointSettings(placemark); } /** * Saves the inputs to the given point. * * @param placemark The placemark */ public void saveInputs(Placemark placemark) { updateDomainModel(placemark); } @Override protected void updateDomainModel(Placemark placemark) { ExtendedData extendedData = placemark.getExtendedData(); ExtendedDataUtils.putBoolean(extendedData, Constants.IS_TITLE, myShowTitle.get().booleanValue()); ExtendedDataUtils.putBoolean(extendedData, Constants.IS_FIELD_TITLE, myShowFieldTitles.get().booleanValue()); ExtendedDataUtils.putBoolean(extendedData, Constants.IS_LAT_LON_ID, myShowDecimalLatLon.get().booleanValue()); ExtendedDataUtils.putBoolean(extendedData, Constants.IS_DMS_ID, myShowDMSLatLon.get().booleanValue()); ExtendedDataUtils.putBoolean(extendedData, Constants.IS_MGRS, myShowMGRSLatLon.get().booleanValue()); ExtendedDataUtils.putBoolean(extendedData, Constants.IS_SHOW_ALTITUDE, myShowAltitude.get().booleanValue()); ExtendedDataUtils.putBoolean(extendedData, Constants.IS_DESC_ID, myShowDescription.get().booleanValue()); ExtendedDataUtils.putBoolean(extendedData, Constants.IS_DISTANCE_ID, myShowDistance.get().booleanValue()); ExtendedDataUtils.putBoolean(extendedData, Constants.IS_HEADING_ID, myShowHeading.get().booleanValue()); ExtendedDataUtils.putBoolean(extendedData, Constants.IS_VELOCITY_ID, myShowVelocity.get().booleanValue()); ExtendedDataUtils.putBoolean(extendedData, Constants.IS_DURATION_ID, myShowDuration.get().booleanValue()); PlacemarkUtils.setPlacemarkFont(placemark, myTextStyleModel.getSelectedFont()); PlacemarkUtils.setPlacemarkTextColor(placemark, myTextStyleModel.getFontColor().get()); PlacemarkUtils.setPlacemarkColor(placemark, myBorderColor.get()); PlacemarkUtils.setPolygonFillColor(placemark, myPolygonFillColor.get()); ExtendedDataUtils.putBoolean(extendedData, Constants.IS_BUBBLE_FILLED_ID, myIsBubbleFilled.get().booleanValue()); ExtendedDataUtils.putBoolean(extendedData, Constants.IS_POLYGON_FILLED_ID, myIsPolygonFilled.get().booleanValue()); ExtendedDataUtils.putBoolean(extendedData, Constants.IS_ANIMATE, myAnimate.get().booleanValue()); ExtendedDataUtils.putBoolean(extendedData, Constants.IS_SHOW_IN_TIMELINE, myShowInTimeline.get().booleanValue()); } @Override protected void updateViewModel(Placemark placemark) { if (placemark != null && placemark.getExtendedData() != null) { ExtendedData extendedData = placemark.getExtendedData(); myShowTitle.set(ExtendedDataUtils.getBooleanObj(extendedData, Constants.IS_TITLE, false)); myShowFieldTitles.set(ExtendedDataUtils.getBooleanObj(extendedData, Constants.IS_FIELD_TITLE, false)); myShowDecimalLatLon.set(ExtendedDataUtils.getBooleanObj(extendedData, Constants.IS_LAT_LON_ID, false)); myShowDMSLatLon.set(ExtendedDataUtils.getBooleanObj(extendedData, Constants.IS_DMS_ID, false)); myShowMGRSLatLon.set(ExtendedDataUtils.getBooleanObj(extendedData, Constants.IS_MGRS, false)); myShowAltitude.set(ExtendedDataUtils.getBooleanObj(extendedData, Constants.IS_SHOW_ALTITUDE, false)); myShowDescription.set(ExtendedDataUtils.getBooleanObj(extendedData, Constants.IS_DESC_ID, false)); myShowDistance.set(ExtendedDataUtils.getBooleanObj(extendedData, Constants.IS_DISTANCE_ID, true)); myShowHeading.set(ExtendedDataUtils.getBooleanObj(extendedData, Constants.IS_HEADING_ID, true)); myShowVelocity.set(ExtendedDataUtils.getBooleanObj(extendedData, Constants.IS_VELOCITY_ID, true)); myShowDuration.set(ExtendedDataUtils.getBooleanObj(extendedData, Constants.IS_DURATION_ID, true)); myIsDistanceHeadingCapable = ExtendedDataUtils.getBoolean(extendedData, Constants.IS_HEADING_DISTANCE_CAPABLE, false); myIsLocationCapable = ExtendedDataUtils.getBoolean(extendedData, Constants.IS_LOCATION_CAPABLE, true); myVelocityCapable = ExtendedDataUtils.getBoolean(extendedData, Constants.IS_VELOCITY_CAPABLE, false); myDurationCapable = ExtendedDataUtils.getBoolean(extendedData, Constants.IS_DURATION_CAPABLE, false); myShowInTimeline.set(ExtendedDataUtils.getBooleanObj(extendedData, Constants.IS_SHOW_IN_TIMELINE, true)); myAnimate.set(ExtendedDataUtils.getBooleanObj(extendedData, Constants.IS_ANIMATE, true)); } else { myShowTitle.set(Boolean.FALSE); myShowFieldTitles.set(Boolean.FALSE); myShowDecimalLatLon.set(Boolean.FALSE); myShowDMSLatLon.set(Boolean.FALSE); myShowMGRSLatLon.set(Boolean.FALSE); myShowAltitude.set(Boolean.FALSE); myShowDescription.set(Boolean.FALSE); myShowDistance.set(Boolean.FALSE); myShowHeading.set(Boolean.FALSE); myShowVelocity.set(Boolean.FALSE); myShowDuration.set(Boolean.FALSE); myIsDistanceHeadingCapable = false; myIsLocationCapable = true; myVelocityCapable = false; myDurationCapable = false; myShowInTimeline.set(Boolean.TRUE); myShowInTimeline.set(Boolean.TRUE); } Font font = PlacemarkUtils.getPlacemarkFont(placemark); myTextStyleModel.getFont().set(new FontWrapper(font)); myTextStyleModel.getBold().set(Boolean.valueOf(font.isBold())); myTextStyleModel.getItalic().set(Boolean.valueOf(font.isItalic())); myTextStyleModel.getFontSize().set(Integer.valueOf(font.getSize())); if (placemark != null && placemark.getExtendedData() != null) { ExtendedData extendedData = placemark.getExtendedData(); myTextStyleModel.getFontColor().set(PlacemarkUtils.getPlacemarkTextColor(placemark)); myBorderColor.set(PlacemarkUtils.getPlacemarkColor(placemark)); myPolygonFillColor.set(PlacemarkUtils.getPolygonFillColor(placemark)); myIsBubbleFilled.set(ExtendedDataUtils.getBooleanObj(extendedData, Constants.IS_BUBBLE_FILLED_ID, true)); myIsPolygonFilled.set(ExtendedDataUtils.getBooleanObj(extendedData, Constants.IS_POLYGON_FILLED_ID, false)); } else { myTextStyleModel.getFontColor().set(Color.WHITE); myBorderColor.set(Color.WHITE); myPolygonFillColor.set(Color.WHITE); myIsBubbleFilled.set(Boolean.FALSE); myIsPolygonFilled.set(Boolean.FALSE); } setChanged(false); } /** * Bubble check boxes valid. * * @return whether they are valid */ private boolean bubbleCheckBoxesValid() { int count = 0; count += countIfTrue(getShowTitle().get()); count += countIfTrue(getShowDecimalLatLon().get()); count += countIfTrue(getShowDMSLatLon().get()); count += countIfTrue(getShowMGRSLatLon().get()); count += countIfTrue(getShowAltitude().get()); count += countIfTrue(getShowDescription().get()); count += countIfTrue(getShowDistance().get()); count += countIfTrue(getShowHeading().get()); count += countIfTrue(getShowVelocity().get()); count += countIfTrue(getShowDuration().get()); return count > 0; } /** * Saves only the changed inputs to the given point's annotation settings. * * @param placemark The placemark */ private void saveChangedAnnoSettings(Placemark placemark) { ExtendedData extendedData = placemark.getExtendedData(); saveProperty(extendedData, Constants.IS_TITLE, myShowTitle); saveProperty(extendedData, Constants.IS_FIELD_TITLE, myShowFieldTitles); saveProperty(extendedData, Constants.IS_LAT_LON_ID, myShowDecimalLatLon); saveProperty(extendedData, Constants.IS_DMS_ID, myShowDMSLatLon); saveProperty(extendedData, Constants.IS_MGRS, myShowMGRSLatLon); saveProperty(extendedData, Constants.IS_SHOW_ALTITUDE, myShowAltitude); saveProperty(extendedData, Constants.IS_DESC_ID, myShowDescription); saveProperty(extendedData, Constants.IS_DISTANCE_ID, myShowDistance); saveProperty(extendedData, Constants.IS_HEADING_ID, myShowHeading); saveProperty(extendedData, Constants.IS_VELOCITY_ID, myShowVelocity); saveProperty(extendedData, Constants.IS_DURATION_ID, myShowDuration); saveProperty(extendedData, Constants.IS_ANIMATE, myAnimate); saveProperty(extendedData, Constants.IS_SHOW_IN_TIMELINE, myShowInTimeline); } /** * Saves only the changed inputs to the given point's non-annotation * settings. * * @param placemark The placemark */ private void saveChangedPointSettings(Placemark placemark) { if (myTextStyleModel.getFont().isChanged()) { Font existingFont = PlacemarkUtils.getPlacemarkFont(placemark); Font newFont = myTextStyleModel.getFont().get().getFont().deriveFont(existingFont.getStyle(), existingFont.getSize()); PlacemarkUtils.setPlacemarkFont(placemark, newFont); } if (myTextStyleModel.getFontSize().isChanged()) { Font existingFont = PlacemarkUtils.getPlacemarkFont(placemark); Font newFont = existingFont.deriveFont(myTextStyleModel.getFontSize().get().floatValue()); PlacemarkUtils.setPlacemarkFont(placemark, newFont); } if (myTextStyleModel.getBold().isChanged()) { Font existingFont = PlacemarkUtils.getPlacemarkFont(placemark); Font newFont = changeStyle(existingFont, Font.BOLD, myTextStyleModel.getBold().get().booleanValue()); PlacemarkUtils.setPlacemarkFont(placemark, newFont); } if (myTextStyleModel.getItalic().isChanged()) { Font existingFont = PlacemarkUtils.getPlacemarkFont(placemark); Font newFont = changeStyle(existingFont, Font.ITALIC, myTextStyleModel.getItalic().get().booleanValue()); PlacemarkUtils.setPlacemarkFont(placemark, newFont); } if (myTextStyleModel.getFontColor().isChanged()) { PlacemarkUtils.setPlacemarkTextColor(placemark, myTextStyleModel.getFontColor().get()); } if (myBorderColor.isChanged()) { PlacemarkUtils.setPlacemarkColor(placemark, myBorderColor.get()); } if (myPolygonFillColor.isChanged()) { PlacemarkUtils.setPolygonFillColor(placemark, myPolygonFillColor.get()); } saveProperty(placemark.getExtendedData(), Constants.IS_BUBBLE_FILLED_ID, myIsBubbleFilled); saveProperty(placemark.getExtendedData(), Constants.IS_POLYGON_FILLED_ID, myIsPolygonFilled); } /** * Saves the property to the extended data. * * @param extendedData the extended data * @param propertyName the property name * @param property the property */ private static void saveProperty(ExtendedData extendedData, String propertyName, BooleanModel property) { if (property.isChanged()) { ExtendedDataUtils.putBoolean(extendedData, propertyName, property.get().booleanValue()); } } }
import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import cookie from '../libs/cookie/client'; export default class Protected extends React.Component<any,any> { redirectUrl = '/login'; constructor(props: any) { super(props); this.state = { initialized: false, allow: false, }; } componentDidMount() { // Add your custom validation const isLoggedIn = cookie.getItem('secretKey') === 'allowmein'; if (!isLoggedIn) { this.setState({ initialized: true, allow: false, }); } else { this.setState({ initialized: true, allow: true, }); } } render() { const { initialized, allow } = this.state; // eslint-disable-next-line const { children } = this.props; if (!initialized) { return null; } if (allow) { return children; } return ( <Route render={({ staticContext }: any) => { // eslint-disable-next-line if (staticContext) staticContext.status = 403; return <Redirect to={this.redirectUrl} />; }} /> ); } }
def is_prime(num): #handle edge case when num is 1 if num == 1: return False #check every number from 2 to n-1 to see if its a factor for i in range(2,num): if num % i == 0: return False #if we don't find any factor, then num is prime return True
package chylex.hee.world.feature.stronghold.rooms.decorative; import java.util.Random; import net.minecraft.init.Blocks; import chylex.hee.system.abstractions.Meta; import chylex.hee.system.abstractions.Pos.PosMutable; import chylex.hee.system.abstractions.facing.Facing4; import chylex.hee.world.feature.stronghold.rooms.StrongholdRoom; import chylex.hee.world.structure.StructureWorld; import chylex.hee.world.structure.dungeon.StructureDungeonPieceInst; import chylex.hee.world.structure.util.IBlockPicker; import chylex.hee.world.util.Size; public class StrongholdRoomLowerCorners extends StrongholdRoom{ public StrongholdRoomLowerCorners(){ super(new Size(9, 8, 9)); } @Override public void generate(StructureDungeonPieceInst inst, StructureWorld world, Random rand, int x, int y, int z){ super.generate(inst, world, rand, x, y, z); // corners for(int cornerX = 0; cornerX < 2; cornerX++){ for(int cornerZ = 0; cornerZ < 2; cornerZ++){ int px = x+2+4*cornerX, pz = z+2+4*cornerZ; placeBlock(world, rand, IBlockPicker.basic(Blocks.stone_slab, Meta.slabStoneSmoothBottom), px, y, pz); placeStairOutline(world, rand, Blocks.stone_brick_stairs, px, y, pz, 1, false, false); } } // ceiling final int centerX = x+maxX/2, centerZ = z+maxZ/2, topY = y+maxY-1; placeBlock(world, rand, placeStoneBrickPlain, centerX, topY, centerZ); for(Facing4 facing:Facing4.list){ placeLine(world, rand, placeStoneBrickPlain, centerX+facing.getX(), topY, centerZ+facing.getZ(), centerX+3*facing.getX(), topY, centerZ+3*facing.getZ()); } PosMutable mpos = new PosMutable(); for(Facing4 facing:Facing4.list){ mpos.set(centerX, 0, centerZ).move(facing, 3).move(facing = facing.rotateRight()); facing = facing.rotateRight(); placeLine(world, rand, placeStoneBrickStairs(facing.rotateRight(), true), mpos.x, topY, mpos.z, mpos.x+2*facing.getX(), topY, mpos.z+2*facing.getZ()); mpos.move(facing, 2).move(facing = facing.rotateLeft()); placeLine(world, rand, placeStoneBrickStairs(facing.rotateRight(), true), mpos.x, topY, mpos.z, mpos.x+facing.getX(), topY, mpos.z+facing.getZ()); } } }
from ...Core.commands import Commands def object_val_def(compiler, node): value_type = node.value.compile_asm(compiler) prop_var = compiler.environment.add_local_var(value_type, node.name.name, object_namespace=compiler.environment.object_list[-1][0]) compiler.code.add(Commands.POP, prop_var)
#!/bin/bash RESOURCES=$(echo "deploy/neutron-server" \ "ds/nova-compute-default" \ "job/neutron-db-init" \ "job/neutron-db-sync") NAMESPACE=${NAMESPACE:-openstack} mkdir resources pushd resources for resource in $RESOURCES; do echo "Fetching resource $resource...." rtype=$(dirname $resource) rname=$(basename $resource) kubectl -n $NAMESPACE get $resource --export -o yaml > $rtype-$rname.yaml done popd
<reponame>smagill/opensphere-desktop package io.opensphere.core.pipeline.processor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.jogamp.opengl.util.texture.TextureCoords; import com.vividsolutions.jts.geom.Polygon; import io.opensphere.core.geometry.TileGeometry; import io.opensphere.core.math.Matrix3d; import io.opensphere.core.math.Vector2d; import io.opensphere.core.math.Vector3d; import io.opensphere.core.model.GeoScreenBoundingBox; import io.opensphere.core.model.GeographicBoundingBox; import io.opensphere.core.model.GeographicBoxAnchor; import io.opensphere.core.model.GeographicConvexQuadrilateral; import io.opensphere.core.model.GeographicPosition; import io.opensphere.core.model.LatLonAlt; import io.opensphere.core.model.ModelBoundingBox; import io.opensphere.core.model.Quadrilateral; import io.opensphere.core.model.ScreenBoundingBox; import io.opensphere.core.model.ScreenPosition; import io.opensphere.core.model.TesseraList; import io.opensphere.core.pipeline.cache.CacheProvider; import io.opensphere.core.pipeline.processor.TileData.TileMeshData; import io.opensphere.core.projection.AbstractGeographicProjection.GeographicProjectedTesseraVertex; import io.opensphere.core.projection.Projection; import io.opensphere.core.util.MathUtil; import io.opensphere.core.util.Utilities; import io.opensphere.core.util.collections.ConcurrentLazyMap; import io.opensphere.core.util.collections.LazyMap; import io.opensphere.core.util.collections.New; import io.opensphere.core.util.jts.JTSUtilities; import io.opensphere.core.util.lang.HashCodeHelper; import io.opensphere.core.viewer.impl.PositionConverter; /** Utility class to build the TileData. */ public final class TileDataBuilder { /** Texture coordinates that cover a full quad. */ private static final List<Vector2d> FULL_TEXTURE_COORDS = Collections.unmodifiableList( Arrays.asList(new Vector2d(0d, 1d), new Vector2d(0d, 0d), new Vector2d(1d, 0d), new Vector2d(1d, 1d))); /** * Polygon meshes which come from petrified tessera blocks. These meshes may * span multiple projection snapshots; using a weak map ensures that they * will not be removed until all associated projection snapshots are no * longer in use. */ private static final Map<TesseraList.TesseraBlock<?>, PolygonMeshData> ourPetrifiedMeshes = New.weakMap(); /** Lock for modification of the tile data map. */ private static final Lock ourTileDataLock = new ReentrantLock(); /** * Keep track of the tile data which has been produced for a particular * bounding box and a particular projection. */ private static final Map<Projection, LazyMap<TileDataKey, TileData>> ourTileDataMap = LazyMap.create( New.<Projection, LazyMap<TileDataKey, TileData>>map(), Projection.class, key -> new ConcurrentLazyMap<>( Collections.<TileDataKey, TileData>synchronizedMap(New.<TileDataKey, TileData>map()), TileDataKey.class)); /** * Build the tile data for a geometry. * * @param geom The tile geometry. * @param imageTexCoords The image texture coordinates which describe the * portion of the image used by the tile. * @param projection Projection which is current for the geometry. * @param converter Utility class for converting positions between * coordinate systems. * @param cache The cache for the associated processor. * @param modelCenter The model coordinate origin of the processor * associated with the given tile. * @return The tile data for rendering. */ public static TileData buildTileData(TileGeometry geom, TextureCoords imageTexCoords, final Projection projection, final PositionConverter converter, final CacheProvider cache, final Vector3d modelCenter) { Utilities.checkNull(imageTexCoords, "imageTexCoords"); if (geom.getBounds() instanceof GeoScreenBoundingBox) { return buildGeoScreenTileData(imageTexCoords, projection, converter, (GeoScreenBoundingBox)geom.getBounds()); } else if (geom.getBounds() instanceof ScreenBoundingBox) { return buildTileData(imageTexCoords, converter, (ScreenBoundingBox)geom.getBounds()); } else if (geom.getBounds() instanceof ModelBoundingBox) { return buildModelTileData(imageTexCoords, converter, (ModelBoundingBox)geom.getBounds()); } else if (geom.getBounds() instanceof GeographicConvexQuadrilateral) { return buildGeoQuadTileData(imageTexCoords, projection, (GeographicConvexQuadrilateral)geom.getBounds(), modelCenter); } // TODO what about Screen and model quads? else { LazyMap<TileDataKey, TileData> projectionMap; ourTileDataLock.lock(); try { projectionMap = ourTileDataMap.get(projection); } finally { ourTileDataLock.unlock(); } LazyMap.Factory<TileDataKey, TileData> factory = tdk -> { Quadrilateral<?> bbox = tdk.getBoundingBox(); TextureCoords keyTexCoords = tdk.getImageTextureCoords(); if (bbox instanceof GeographicBoundingBox) { return buildTileData(keyTexCoords, projection, (GeographicBoundingBox)bbox, cache, modelCenter); } return null; }; return projectionMap.get(new TileDataKey(geom.getBounds(), imageTexCoords), factory); } } /** * Get the cached {@link TileData} if it's available for a certain bounding * box and image texture coordinates. * * @param bbox The bounding box. * @param imageTexCoords The image texture coordinates. * @param projection The projection. * @return The cached {@link TileData}, or {@code null}. */ public static TileData getCachedTileData(Quadrilateral<?> bbox, TextureCoords imageTexCoords, final Projection projection) { if (bbox instanceof GeoScreenBoundingBox) { return null; } LazyMap<TileDataKey, TileData> projectionMap; ourTileDataLock.lock(); try { projectionMap = ourTileDataMap.get(projection); } finally { ourTileDataLock.unlock(); } return projectionMap.getIfExists(new TileDataKey(bbox, imageTexCoords)); } /** * When a projection becomes the active projection, processors should begin * requesting data for the new projection. Remove old map entries for * generated TileData. * * @param projection The projection which is now the latest */ public static void setActiveProjection(Projection projection) { if (projection == null) { return; } ourTileDataLock.lock(); try { Iterator<Projection> iter = ourTileDataMap.keySet().iterator(); while (iter.hasNext()) { Projection pj = iter.next(); if (pj != null && pj.getActivationTimestamp() < projection.getActivationTimestamp()) { iter.remove(); } } } finally { ourTileDataLock.unlock(); } } /** * Build the tile data for a geographic quadrilateral. * * @param imageTexCoords The image texture coordinates. * @param projection The projection used to generate the mesh which backs * the image. * @param quad The quad which defines the bounds of the image. * @param modelCenter The model coordinate origin of the processor * associated with the given tile. * @return The tile data for rendering. */ private static TileData buildGeoQuadTileData(TextureCoords imageTexCoords, Projection projection, GeographicConvexQuadrilateral quad, Vector3d modelCenter) { Polygon poly = JTSUtilities.createJTSPolygon(quad.getVertices(), null); TesseraList<? extends GeographicProjectedTesseraVertex> tesserae = projection.convertPolygonToModelMesh(poly, projection.getModelCenter()); List<TileMeshData> meshes = New.list(); if (tesserae != null) { for (TesseraList.TesseraBlock<? extends GeographicProjectedTesseraVertex> block : tesserae.getTesseraBlocks()) { List<? extends GeographicProjectedTesseraVertex> vertices = block.getVertices(); List<Vector2d> textureCoords = new ArrayList<>(vertices.size()); handleImageTexCoords(imageTexCoords, quad, vertices, textureCoords); List<Vector3d> modelCoords = New.list(vertices.size()); for (GeographicProjectedTesseraVertex vertex : vertices) { modelCoords.add(vertex.getModelCoordinates()); } PolygonMeshData meshData = new PolygonMeshData(modelCoords, null, block.getIndices(), null, null, block.getTesseraVertexCount(), false); TileMeshData data = new TileMeshData(meshData, textureCoords); meshes.add(data); } } return new TileData(imageTexCoords, meshes, projection.hashCode()); } /** * Build the tile data for a geographically attached, screen coordinate * located geometry. * * @param imageTexCoords The image texture coordinates. * @param projection Projection which is current for the geometry. * @param gsbb The bounding box. * @param converter Utility class for converting positions between * coordinate systems. * @return The tile data for rendering. */ private static TileData buildGeoScreenTileData(TextureCoords imageTexCoords, Projection projection, PositionConverter converter, GeoScreenBoundingBox gsbb) { GeographicBoxAnchor anchor = gsbb.getAnchor(); Vector3d windowOffset = converter.convertPositionToWindow(anchor.getGeographicAnchor(), projection); double offsetX = windowOffset.getX() - gsbb.getWidth() * anchor.getHorizontalAlignment(); double offsetY = windowOffset.getY() + gsbb.getHeight() * (1. - anchor.getVerticalAlignment()); // Text which is not set on an integer pixel renders poorly, so // round. int anchorOffsetX = anchor.getAnchorOffset() == null ? 0 : anchor.getAnchorOffset().getX(); int anchorOffsetY = anchor.getAnchorOffset() == null ? 0 : anchor.getAnchorOffset().getY(); windowOffset = new Vector3d(Math.round(offsetX) + anchorOffsetX, -Math.round(offsetY) + anchorOffsetY, 0.); ScreenPosition ul = gsbb.getUpperLeft(); ScreenPosition ll = gsbb.getLowerLeft(); ScreenPosition lr = gsbb.getLowerRight(); ScreenPosition ur = gsbb.getUpperRight(); // Do not use the position converter since it will adjust negative // values to wrap based on the viewport size. List<Vector3d> modelCoords = new ArrayList<>(4); modelCoords.add(new Vector3d(windowOffset.getX() + ul.getX(), -windowOffset.getY() - ul.getY(), 0.)); modelCoords.add(new Vector3d(windowOffset.getX() + ll.getX(), -windowOffset.getY() - ll.getY(), 0.)); modelCoords.add(new Vector3d(windowOffset.getX() + lr.getX(), -windowOffset.getY() - lr.getY(), 0.)); modelCoords.add(new Vector3d(windowOffset.getX() + ur.getX(), -windowOffset.getY() - ur.getY(), 0.)); List<Vector2d> textureCoords = new ArrayList<>(4); textureCoords.add(new Vector2d(imageTexCoords.left(), imageTexCoords.top())); textureCoords.add(new Vector2d(imageTexCoords.left(), imageTexCoords.bottom())); textureCoords.add(new Vector2d(imageTexCoords.right(), imageTexCoords.bottom())); textureCoords.add(new Vector2d(imageTexCoords.right(), imageTexCoords.top())); return new TileData(imageTexCoords, modelCoords, textureCoords, null, 4, projection.hashCode()); } /** * Build the tile data for a model coordinate located geometry. * * @param imageTexCoords The image texture coordinates. * @param bb The bounding box. * @param converter Utility class for converting positions between * coordinate systems. * @return The tile data for rendering. */ // TODO if we want model coordinate based geometries to have a movable model // center, they will have to be projection sensitive and use the projection // snapshot here. private static TileData buildModelTileData(TextureCoords imageTexCoords, PositionConverter converter, ModelBoundingBox bb) { List<Vector3d> modelCoords = new ArrayList<>(4); modelCoords.add(converter.convertPositionToModel(bb.getUpperLeft(), null, Vector3d.ORIGIN)); modelCoords.add(converter.convertPositionToModel(bb.getLowerLeft(), null, Vector3d.ORIGIN)); modelCoords.add(converter.convertPositionToModel(bb.getLowerRight(), null, Vector3d.ORIGIN)); modelCoords.add(converter.convertPositionToModel(bb.getUpperRight(), null, Vector3d.ORIGIN)); List<Vector2d> textureCoords; if (imageTexCoords == null) { textureCoords = FULL_TEXTURE_COORDS; } else { textureCoords = new ArrayList<>(4); textureCoords.add(new Vector2d(imageTexCoords.left(), imageTexCoords.bottom())); textureCoords.add(new Vector2d(imageTexCoords.right(), imageTexCoords.bottom())); textureCoords.add(new Vector2d(imageTexCoords.right(), imageTexCoords.top())); textureCoords.add(new Vector2d(imageTexCoords.left(), imageTexCoords.top())); } return new TileData(imageTexCoords, modelCoords, textureCoords, null, 4, -1); } /** * Build the tile data for a screen coordinate located geometry. * * @param imageTexCoords The image texture coordinates. * @param converter Utility class for converting positions between * coordinate systems. * @param sbb The bounding box. * @return The tile data for rendering. */ private static TileData buildTileData(TextureCoords imageTexCoords, PositionConverter converter, ScreenBoundingBox sbb) { List<Vector3d> modelCoords = new ArrayList<>(4); if (sbb != null) { modelCoords.add(converter.convertPositionToModel(sbb.getUpperLeft(), Vector3d.ORIGIN)); modelCoords.add(converter.convertPositionToModel(sbb.getLowerLeft(), Vector3d.ORIGIN)); modelCoords.add(converter.convertPositionToModel(sbb.getLowerRight(), Vector3d.ORIGIN)); modelCoords.add(converter.convertPositionToModel(sbb.getUpperRight(), Vector3d.ORIGIN)); } List<Vector2d> textureCoords = new ArrayList<>(4); if (imageTexCoords != null) { textureCoords.add(new Vector2d(imageTexCoords.left(), imageTexCoords.top())); textureCoords.add(new Vector2d(imageTexCoords.left(), imageTexCoords.bottom())); textureCoords.add(new Vector2d(imageTexCoords.right(), imageTexCoords.bottom())); textureCoords.add(new Vector2d(imageTexCoords.right(), imageTexCoords.top())); } return new TileData(imageTexCoords, modelCoords, textureCoords, null, 4, -1); } /** * Build the tile data for a geometry. * * @param imageTexCoords The image texture coordinates. * @param gbb The bounding box. * @param projection Projection which is current for the geometry. * @param cache The cache for the associated processor. * @param modelCenter The model coordinate origin of the processor * associated with the given tile. * @return The tile data for rendering. */ private static TileData buildTileData(TextureCoords imageTexCoords, Projection projection, GeographicBoundingBox gbb, CacheProvider cache, Vector3d modelCenter) { GeographicPosition lowerLeft = gbb.getLowerLeft(); GeographicPosition upperRight = gbb.getUpperRight(); GeographicPosition lowerRight = gbb.getLowerRight(); GeographicPosition upperLeft = gbb.getUpperLeft(); TesseraList<? extends GeographicProjectedTesseraVertex> tesserae = projection.convertQuadToModel(lowerLeft, lowerRight, upperRight, upperLeft, modelCenter == null ? Vector3d.ORIGIN : modelCenter); List<TileMeshData> meshes = new ArrayList<>(); for (TesseraList.TesseraBlock<? extends GeographicProjectedTesseraVertex> block : tesserae.getTesseraBlocks()) { PolygonMeshData meshData = null; if (block.isPetrified()) { meshData = ourPetrifiedMeshes.get(block); } List<? extends GeographicProjectedTesseraVertex> vertices = block.getVertices(); List<Vector2d> textureCoords = new ArrayList<>(vertices.size()); handleImageTexCoords(imageTexCoords, gbb, vertices, textureCoords); if (meshData == null) { List<Vector3d> modelCoords = new ArrayList<>(vertices.size()); for (GeographicProjectedTesseraVertex vertex : vertices) { modelCoords.add(vertex.getModelCoordinates()); } meshData = new PolygonMeshData(modelCoords, null, block.getIndices(), null, null, block.getTesseraVertexCount(), false); } if (block.isPetrified()) { ourPetrifiedMeshes.put(block, meshData); } TileMeshData data = new TileMeshData(meshData, textureCoords); meshes.add(data); } return new TileData(imageTexCoords, meshes, projection.hashCode()); } /** * Generate the texture coordinates which map to the given vertices. * * @param imageTexCoords The image texture coordinates. * @param gbb The geographic bounding box for the tile. * @param vertices The vertices which are within the tile. * @param textureCoords The texture coordinate list to populate. */ private static void handleImageTexCoords(TextureCoords imageTexCoords, GeographicBoundingBox gbb, List<? extends GeographicProjectedTesseraVertex> vertices, List<Vector2d> textureCoords) { LatLonAlt lowerLeft = gbb.getLowerLeft().getLatLonAlt(); LatLonAlt upperRight = gbb.getUpperRight().getLatLonAlt(); double geoLeft = lowerLeft.getLonD(); double geoRight = upperRight.getLonD(); double geoBottom = lowerLeft.getLatD(); double geoTop = upperRight.getLatD(); double imageXmin = imageTexCoords.left(); double imageXmax = imageTexCoords.right(); // The image may be flipped. double imageYmin = Math.min(imageTexCoords.top(), imageTexCoords.bottom()); double imageYmax = Math.max(imageTexCoords.top(), imageTexCoords.bottom()); // To find the position in texture coordinates, we divide the geographic // offset by the geographic width to get the percentage into the tile, // then we multiply by the texture coordinate width to get the texture // coordinate offset. double xScale = (imageXmax - imageXmin) / (geoRight - geoLeft); double yScale = (imageYmax - imageYmin) / (geoTop - geoBottom); for (GeographicProjectedTesseraVertex vertex : vertices) { LatLonAlt lla = vertex.getCoordinates().getLatLonAlt(); double x = (lla.getLonD() - geoLeft) * xScale + imageXmin; double y = (geoTop - lla.getLatD()) * yScale + imageYmin; Vector2d texCoords = new Vector2d(x, y); textureCoords.add(texCoords); } } /** * Generate the texture coordinates which map to the given vertices. * * @param imageTexCoords The image texture coordinates. * @param quad The geographic bounds for the tile. * @param vertices The vertices which are within the tile. * @param textureCoords The texture coordinate list to populate. */ private static void handleImageTexCoords(TextureCoords imageTexCoords, Quadrilateral<GeographicPosition> quad, List<? extends GeographicProjectedTesseraVertex> vertices, List<Vector2d> textureCoords) { Vector2d ll = quad.getVertices().get(0).getLatLonAlt().asVec2d(); Vector2d lr = quad.getVertices().get(1).getLatLonAlt().asVec2d(); Vector2d ur = quad.getVertices().get(2).getLatLonAlt().asVec2d(); Vector2d ul = quad.getVertices().get(3).getLatLonAlt().asVec2d(); Matrix3d trans = Matrix3d.getQuadToSquareTransform(ll, lr, ur, ul); for (GeographicProjectedTesseraVertex vertex : vertices) { Vector2d lonLat = vertex.getCoordinates().getLatLonAlt().asVec2d(); Vector2d transformed = trans.applyPerspectiveTransform(lonLat); textureCoords.add(transformed); } } /** Disallow instantiation. */ private TileDataBuilder() { } /** * A key for uniquely determining a tile data to use for one or more * geometries. */ private static class TileDataKey { /** The bounding box. */ private final Quadrilateral<?> myBoundingBox; /** The image texture coordinates. */ private final TextureCoords myImageTextureCoords; /** * Constructor. * * @param boundingBox The bounding box. * @param imageTexCoords The image texture coordinates. */ public TileDataKey(Quadrilateral<?> boundingBox, TextureCoords imageTexCoords) { myBoundingBox = boundingBox; myImageTextureCoords = imageTexCoords; } @Override public boolean equals(Object obj) { if (!(obj instanceof TileDataKey)) { return false; } TileDataKey otherKey = (TileDataKey)obj; if (!myBoundingBox.equals(otherKey.getBoundingBox())) { return false; } TextureCoords otherTexCoords = otherKey.getImageTextureCoords(); return MathUtil.isZero(myImageTextureCoords.left() - otherTexCoords.left()) && MathUtil.isZero(myImageTextureCoords.right() - otherTexCoords.right()) && MathUtil.isZero(myImageTextureCoords.top() - otherTexCoords.top()) && MathUtil.isZero(myImageTextureCoords.bottom() - otherTexCoords.bottom()); } /** * Get the boundingBox. * * @return the boundingBox */ public Quadrilateral<?> getBoundingBox() { return myBoundingBox; } /** * Get the imageTextureCoords. * * @return the imageTextureCoords */ public TextureCoords getImageTextureCoords() { return myImageTextureCoords; } @Override public int hashCode() { if (myImageTextureCoords == null) { return myBoundingBox.hashCode(); } return myBoundingBox.hashCode() + HashCodeHelper.getHashCode(myImageTextureCoords.left()) + HashCodeHelper.getHashCode(myImageTextureCoords.right()) + HashCodeHelper.getHashCode(myImageTextureCoords.top()) + HashCodeHelper.getHashCode(myImageTextureCoords.bottom()); } } }
export CODAR_CHEETAH_EXPERIMENT_DIR="/gpfs/alpine/csc299/proj-shared/iyakushin/test_cs/1/local/iyakushin" export CODAR_CHEETAH_MACHINE_CONFIG="/autofs/nccs-svm1_home1/iyakushin/.conda/envs/Test10/lib/python3.8/site-packages/cheetah-0.5.1-py3.8.egg/codar/cheetah/data/machine_config/local/submit-env.sh" export CODAR_CHEETAH_APP_CONFIG="" export CODAR_WORKFLOW_SCRIPT="/autofs/nccs-svm1_home1/iyakushin/.conda/envs/Test10/lib/python3.8/site-packages/cheetah-0.5.1-py3.8.egg/codar/savanna/main.py" export CODAR_WORKFLOW_RUNNER="mpiexec" export CODAR_CHEETAH_WORKFLOW_LOG_LEVEL="DEBUG" export CODAR_CHEETAH_UMASK="027" export CODAR_PYTHON="/ccs/home/iyakushin/.conda/envs/Test10/bin/python"
<gh_stars>1-10 package discovery import ( "errors" "net/http" "net/http/httptest" "testing" "github.com/paulormart/assert" ) func TestNewConsulDefault(t *testing.T) { cd := newConsulDefault() assert.Equal(t, "localhost:8500", cd.cfg.Addr) assert.Equal(t, "http://localhost:8500", cd.cfg.URL()) assert.Equal(t, Services{}, cd.cfg.Services) assert.Equal(t, Checks{}, cd.cfg.Checks) } func TestIsAvailable(t *testing.T) { var tests = []struct { hf http.HandlerFunc expectedResp bool expectedErr error }{ { hf: func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write([]byte(`"10.1.10.12:8300"`)) }, expectedResp: true, expectedErr: nil, }, { hf: func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write([]byte(`""`)) }, expectedResp: false, expectedErr: nil, }, { hf: func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write([]byte(`[]`)) }, expectedResp: false, expectedErr: errors.New("Error querying Consul API: json: cannot unmarshal array into Go value of type string"), }, } for _, test := range tests { ts := httptest.NewServer(http.HandlerFunc(test.hf)) cd := newConsulDefault(Addr(ts.Listener.Addr().String())) resp, err := cd.IsAvailable() assert.Equal(t, test.expectedResp, resp) assert.Equal(t, test.expectedErr, err) ts.Close() } } func TestService(t *testing.T) { var tests = []struct { hf http.HandlerFunc expectedResp []string expectedErr error }{ { hf: func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write([]byte(`[{"Node": "foobar","Address": "10.1.10.12","ServiceID": "redis","ServiceName": "redis","ServiceTags": null,"ServiceAddress": "","ServicePort": 8000}]`)) }, expectedResp: []string{"10.1.10.12:8000"}, expectedErr: nil, }, { hf: func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write([]byte(`[]`)) }, expectedResp: nil, expectedErr: errors.New("Error service: redis is not available in any of the nodes"), }, } for _, test := range tests { ts := httptest.NewServer(http.HandlerFunc(test.hf)) cd := newConsulDefault(Addr(ts.Listener.Addr().String())) resp, err := cd.Service("redis") assert.Equal(t, test.expectedResp, resp) assert.Equal(t, test.expectedErr, err) ts.Close() } } func TestRegister(t *testing.T) { var tests = []struct { hf http.HandlerFunc expectedResp Service expectedErr error }{ { hf: func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write([]byte(`{"ID": "redis","Name": "redis","Address": "","Port": 8000}`)) }, expectedErr: nil, }, { hf: func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write([]byte(`{"ID": "service:redis","Name": "Service 'redis' check","Status": "passing","Notes": "","Output": "","ServiceID": "redis","ServiceName": "redis"}`)) }, expectedErr: nil, }, { hf: func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write([]byte(`{}`)) }, expectedErr: nil, // expectedErr: errors.New("Error service: redis is not available in any of the nodes"), }, } for _, test := range tests { ts := httptest.NewServer(http.HandlerFunc(test.hf)) s := Service{ ID: "redis", Service: "redis", Port: 8000, } c := Check{ ID: "test_check", Name: "TCP check", Notes: "Ensure the server is listening on the specific port", DeregisterCriticalServiceAfter: "1m", TCP: ":60500", Interval: "10s", Timeout: "1s", ServiceID: "test", } cd := NewDiscovery(Addr(ts.Listener.Addr().String())) err := cd.Register(ServicesCfg(s), ChecksCfg(c)) assert.Equal(t, test.expectedErr, err) err = cd.Unregister() assert.Equal(t, test.expectedErr, err) ts.Close() } }
export const environment = { production: false, api_url: 'http://192.168.127.12:81/api/', host_url: 'http://192.168.127.12:81', apiKey: '<KEY>', };
<reponame>baart1989/gatsby-starter-elemental import React from "react" import { useStaticQuery, graphql, Link } from "gatsby" import { Logo } from "./utils" import Navlinks from "./navigation-list" export default function() { const query = useStaticQuery(graphql` query { site { siteMetadata { title footerLinks { name url } } } } `) const footerLinks = query.site.siteMetadata.footerLinks.map((item, _) => ( <ListItem data={item} className="nav-links" key={`footer-n-l-${_}`} /> )) return ( <footer className="footer bg-bgalt py-12"> <div className="container mx-auto text-center"> <div className="flex justify-center my-3 mb-6"> <Link to="/" title={query.site.siteMetadata.title}> <Logo className="w-12"/> </Link> </div> <div className="text-color-2 my-3 footer-links animated-link-parent"> <Navlinks className="flex items-center justify-center flex-wrap" withThemeSwitch={false}/> </div> <div className="text-color-2 my-3" > <ul> {footerLinks} </ul> </div> <p className="text-color-default text-lg"> Copyright &copy; {query.site.siteMetadata.title}{" "} {new Date().getFullYear()} </p> </div> </footer> ) } const ListItem = ({ data }) => { return ( <li className="inline-block mx-3 animated-link-parent"> <Link to={data.url} title={data.name}> <span>{data.name}</span> </Link> </li> ) }
#!/bin/bash sed $'s/,/\\\n/g' <names.csv >names.txt sed -i '' 's/\"//g' names.txt
function akill() { adb shell ps | grep $1 | grep -Eo " [0-9]+ " | head -1 | xargs adb shell kill } function javaDiff() { diff <(git diff "$@" -G "^import ") <(git diff "$@") | sed "s/^> //" | vim - }
#!/bin/bash -e . /var/cache/build/packages-manual/common.sh # Install R packages. #d XXX: This is unverifiable and thus may compromise the whole image. # XXX: Use notary (https://github.com/ropenscilabs/notary) when ready. sed -e 's/^#.*$//g' -e '/^$/d' /var/cache/build/packages-r.txt | \ Rscript --slave --no-save --no-restore-history \ -e "install.packages(readLines('stdin'), repos='https://cloud.r-project.org')" # XXX: This is unverifiable and in WITHOUT HTTPS and thus may compromise the whole image. # XXX: Use notary (https://github.com/ropenscilabs/notary) when ready. sed -e 's/^#.*$//g' -e '/^$/d' /var/cache/build/packages-r-bioconductor.txt | \ Rscript --slave --no-save --no-restore-history \ -e "BiocManager::install(readLines('stdin'))"
<reponame>despo/apply-for-teacher-training module SupportInterface class ProviderUsersFilter attr_reader :applied_filters def initialize(params:) @applied_filters = params end def filters [ { type: :checkboxes, heading: 'Use of service', name: 'use_of_service', options: [ { value: 'has_signed_in', label: 'Has signed in', checked: applied_filters[:use_of_service]&.include?('has_signed_in'), }, { value: 'never_signed_in', label: 'Never signed in', checked: applied_filters[:use_of_service]&.include?('never_signed_in'), }, ], }, { type: :search, heading: 'Name or email', value: applied_filters[:q], name: 'q', }, ] end end end
#ifndef STRING_UTILITIES_H #define STRING_UTILITIES_H #include <string> #include <vector> #include <iostream> std::string characterToString(char ch); int toInt(const std::string & str); double toDouble(const std::string & str); std::string escapeUnderscore(const std::string & str); std::string toString(double f, unsigned int fracDigits, unsigned int width); std::string stringToUpper(std::string & str); std::string stringToLower(std::string & str); void removeDotsFromString(std::string & str); bool removeFirstDotFromString(std::string & str); std::vector<std::string> splitStringOnFirstChar(const std::string & str, char ch); std::vector<std::string> splitStringOnFirstChar(const std::string & str, const std::string & substr); std::vector<std::string> splitStringOnChar(std::vector<std::string> & v, char ch); std::vector<std::string> splitStringOnChar(const std::string & str, char ch); std::vector<std::string> splitStringOnString(const std::string & str, const std::string & substr); std::string readStringUpTo(std::istream & istr, char ch); int readIntUpTo(std::istream & istr, char ch); double readDoubleUpTo(std::istream & istr, char ch); void replaceAllOddByEven(std::string & str, const std::string & oddEven); void replaceAll(std::string & str, char oldCh, char newCh); bool replace(std::string & str, char oldCh, char newCh); void parseWhiteSpace(std::istream & istr); void parseWhiteSpaceAndOneLineCComment(std::istream & istr); bool ifCanReadFromWriteTo(const std::string & fileName, std::ostream & ostr); #endif // STRING_UTILITIES_H
function celToFah(arr) { let result = []; for (let temp of arr) { let fah = (temp * 9/5) + 32; result.push(fah); } return result; } let celsiusArray = [28, 15, -2]; let fahrenheitArray = celToFah(celsiusArray); console.log(fahrenheitArray);
<filename>translations/strings/security/zh.ts export const zh = { 'security': { /** * Rooted device warning screen */ 'modified-device': '设备已改良', 'modified-device-subtitle': '您正在使用的是已ROOT过的设备或越狱设备。', 'modified-device-intro1': '这对您的助记词和密码存在安全风险,并可能危及您的资金。', 'modified-device-intro2': '您可以卸载此应用程序,也可以继续使用它,但您现在已经意识到潜在的风险。', 'modified-device-accept': '我已了解风险,继续' } };
#!/bin/bash echo "/gen/challenge" echo "/gen/libc.so"
import React from 'react'; export interface IconUsersProps extends React.SVGAttributes<SVGElement> { color?: string; size?: string | number; className?: string; style?: React.CSSProperties; } export const IconUsers: React.SFC<IconUsersProps> = ( props: IconUsersProps ): 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-users" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ verticalAlign: 'middle', ...style }} {...restProps} > <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" /> <circle cx="9" cy="7" r="4" /> <path d="M23 21v-2a4 4 0 0 0-3-3.87" /> <path d="M16 3.13a4 4 0 0 1 0 7.75" /> </svg> ); }; IconUsers.defaultProps = { color: 'currentColor', size: '1em', }; export default IconUsers;
import tensorflow as tf from tensorflow.keras.layers import * from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam # Create the model inputs = Input(shape=(256, 256, 3)) conv1 = Conv2D(64, (3,3), activation="relu", padding="same")(inputs) conv2 = Conv2D(64, (3,3), activation="relu", padding="same")(conv1) pool1 = MaxPooling2D(pool_size=(2,2))(conv2) conv3 = Conv2D(128, (3,3), activation="relu", padding="same")(pool1) conv4 = Conv2D(128, (3,3), activation="relu", padding="same")(conv3) pool2 = MaxPooling2D(pool_size=(2,2))(conv4) conv5 = Conv2D(256, (3,3), activation="relu", padding="same")(pool2) conv6 = Conv2D(256, (3,3), activation="relu", padding="same")(conv5) conv7 = Conv2D(2, (3,3), activation="relu", padding="same")(conv6) model = Model(inputs=inputs, outputs=conv7) # Compile the model model.compile(optimizer=Adam(lr=0.0001), loss="binary_crossentropy", metrics=["accuracy"]) # Train the model model.fit_generator(dataset, epochs=10, steps_per_epoch=200) # Test the model model.evaluate(test_dataset)
#!/bin/bash # Copyright 2019 The Kubernetes 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. if [ -n "$DEBUG" ]; then set -x fi set -o errexit set -o nounset set -o pipefail DIR=$(cd $(dirname "${BASH_SOURCE}") && pwd -P) AWS_FILE="${DIR}/images/nginx/aws.tfvars" ENV_FILE="${DIR}/images/nginx/env.tfvars" if [ ! -f "${AWS_FILE}" ]; then echo "File $AWS_FILE does not exist. Please create this file with keys access_key an secret_key" exit 1 fi if [ ! -f "${ENV_FILE}" ]; then echo "File $ENV_FILE does not exist. Please create this file with keys docker_username and docker_password" exit 1 fi # build local terraform image to build nginx docker build \ --tag build-ingress-controller-terraform $DIR/images/ingress-controller # build nginx and publish docker images to quay.io. # this can take up to two hours. docker run --rm -it \ --volume $DIR/images/ingress-controller:/tf \ -w /tf \ -v ${AWS_FILE}:/root/aws.tfvars:ro \ -v ${ENV_FILE}:/root/env.tfvars:ro \ build-ingress-controller-terraform docker rmi -f build-ingress-controller-terraform
package goscope import ( "fmt" "net/http" "os" "strings" "github.com/gin-gonic/gin" "github.com/shirou/gopsutil/cpu" "github.com/shirou/gopsutil/disk" "github.com/shirou/gopsutil/host" "github.com/shirou/gopsutil/mem" ) func getAppName(c *gin.Context) { c.Header("Access-Control-Allow-Origin", "*") c.JSON(http.StatusOK, gin.H{ "applicationName": Config.ApplicationName, }) } // getSystemInfoHandler is the controller to show system information of the current host in GoScope API. func getSystemInfoHandler(c *gin.Context) { responseBody := getSystemInfo() c.Header("Access-Control-Allow-Origin", "*") c.JSON(http.StatusOK, responseBody) } func getSystemInfo() systemInformationResponse { cpuStatus, _ := cpu.Info() firstCPU := cpuStatus[0] memoryStatus, _ := mem.VirtualMemory() swapStatus, _ := mem.SwapMemory() hostStatus, _ := host.Info() diskStatus, _ := disk.Usage("/") environment := make(map[string]string) env := os.Environ() for i := range env { variable := strings.SplitN(env[i], "=", 2) environment[variable[0]] = variable[1] } return systemInformationResponse{ ApplicationName: Config.ApplicationName, CPU: systemInformationResponseCPU{ CoreCount: fmt.Sprintf("%d Cores", firstCPU.Cores), ModelName: firstCPU.ModelName, }, Memory: systemInformationResponseMemory{ Available: fmt.Sprintf("%.2f GB", float64(memoryStatus.Available)/BytesInOneGigabyte), Total: fmt.Sprintf("%.2f GB", float64(memoryStatus.Total)/BytesInOneGigabyte), UsedSwap: fmt.Sprintf("%.2f%%", swapStatus.UsedPercent), }, Host: systemInformationResponseHost{ HostOS: hostStatus.OS, HostPlatform: hostStatus.Platform, Hostname: hostStatus.Hostname, KernelArch: hostStatus.KernelArch, KernelVersion: hostStatus.KernelVersion, Uptime: fmt.Sprintf("%.2f hours", float64(hostStatus.Uptime)/SecondsInOneMinute/SecondsInOneMinute), }, Disk: systemInformationResponseDisk{ FreeSpace: fmt.Sprintf("%.2f GB", float64(diskStatus.Free)/BytesInOneGigabyte), MountPath: diskStatus.Path, PartitionType: diskStatus.Fstype, TotalSpace: fmt.Sprintf("%.2f GB", float64(diskStatus.Total)/BytesInOneGigabyte), }, Environment: environment, } }
package y2020.day11 import org.scalatest.flatspec.AnyFlatSpec class SeatingSystemSpec extends AnyFlatSpec{ val ferry = new Ferry("y2020/11_test.txt") val ferry2 = new Ferry("y2020/11_test.txt") ferry.relax ferry2.relax2 "Ferry with simple seating rules" should "have 37 occupied seats" in { assert(ferry.numOccupied == 37) } "Ferry with extended seating rules" should "have 26 occupied seats" in { assert(ferry2.numOccupied == 26) } }
/* * Licensed to Cloudera, Inc. under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Cloudera, Inc. 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 com.cloudera.hue.livy.server.interactive import java.net.URL import java.util.concurrent.atomic.AtomicInteger import com.cloudera.hue.livy.msgs.ExecuteRequest import com.cloudera.hue.livy.sessions._ import org.json4s.JsonAST.{JArray, JObject} import org.json4s.jackson.JsonMethods._ import org.scalatest.FunSpecLike import org.scalatra.test.scalatest.ScalatraSuite import scala.concurrent.Future class InteractiveSessionServletSpec extends ScalatraSuite with FunSpecLike { class MockInteractiveSession(val id: Int) extends InteractiveSession { var _state: State = Idle() var _idCounter = new AtomicInteger() var _statements = IndexedSeq[Statement]() override def kind: Kind = Spark() override def logLines() = IndexedSeq() override def state = _state override def stop(): Future[Unit] = ??? override def url_=(url: URL): Unit = ??? override def lastActivity: Long = ??? override def executeStatement(executeRequest: ExecuteRequest): Statement = { val id = _idCounter.getAndIncrement val statement = new Statement( id, executeRequest, Future.successful(JObject())) _statements :+= statement statement } override def proxyUser: Option[String] = None override def url: Option[URL] = ??? override def statements: IndexedSeq[Statement] = _statements override def interrupt(): Future[Unit] = ??? } class MockInteractiveSessionFactory() extends InteractiveSessionFactory { override def createSession(id: Int, createInteractiveRequest: CreateInteractiveRequest): Future[InteractiveSession] = { Future.successful(new MockInteractiveSession(id)) } } val sessionManager = new SessionManager(new MockInteractiveSessionFactory()) val servlet = new InteractiveSessionServlet(sessionManager) addServlet(servlet, "/*") describe("For /sessions") { it("GET / should return the sessions") { get("/") { status should equal (200) header("Content-Type") should include("application/json") val parsedBody = parse(body) parsedBody \ "sessions" should equal (JArray(List())) } } } }
/* * Copyright (c) Open Source Strategies, Inc. * * Opentaps is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Opentaps is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Opentaps. If not, see <http://www.gnu.org/licenses/>. */ package org.opentaps.tests.financials; import java.math.BigDecimal; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import com.ibm.icu.util.Calendar; import javolution.util.FastList; import org.ofbiz.base.util.GeneralException; import org.ofbiz.base.util.UtilDateTime; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.condition.EntityCondition; import org.ofbiz.entity.condition.EntityOperator; import org.opentaps.common.agreement.UtilAgreement; import org.opentaps.common.util.UtilCommon; import org.opentaps.tests.OpentapsTestCase; public class AgreementTests extends OpentapsTestCase { public static final String module = AgreementTests.class.getName(); GenericValue demofinadmin = null; GenericValue DemoSalesManager = null; GenericValue demowarehouse1 = null; GenericValue demopurch1 = null; String organizationPartyId = "Company"; TimeZone timeZone = TimeZone.getDefault(); Locale locale = Locale.getDefault(); public class InvoiceAction { private List<InvoiceItemAction> items; private boolean expectFailure = false; @SuppressWarnings("unchecked") public InvoiceAction(boolean expectFailure) { items = FastList.newInstance(); this.expectFailure = expectFailure; } public List<InvoiceItemAction> getItems() { return items; } public void addItem(InvoiceItemAction item) { items.add(item); } public boolean hasExpectFailure() { return expectFailure; } } public class InvoiceItemAction { private String invoiceItemTypeId; private String productId; private Double quantity; private Double amount; public InvoiceItemAction(String invoiceItemTypeId, String productId, Double quantity, Double amount) { this.invoiceItemTypeId = invoiceItemTypeId; this.quantity = quantity; this.amount = amount; this.productId = productId; } public String getInvoiceItemTypeId() { return invoiceItemTypeId; } public String getProductId() { return productId; } public Double getQuantity() { return quantity; } public Double getAmount() { return amount; } } public class PaymentAction { private Double amount; private boolean inAdvance = false; public PaymentAction(Double amount) { this.amount = amount; } public PaymentAction(Double amount, boolean inAdvance) { this.amount = amount; this.inAdvance = inAdvance; } public Double getAmount() { return amount; } public boolean hasInAdvance() { return inAdvance; } } @Override public void setUp() throws Exception { super.setUp(); demofinadmin = delegator.findByPrimaryKeyCache("UserLogin", UtilMisc.toMap("userLoginId", "demofinadmin")); DemoSalesManager = delegator.findByPrimaryKeyCache("UserLogin", UtilMisc.toMap("userLoginId", "DemoSalesManager")); demowarehouse1 = delegator.findByPrimaryKeyCache("UserLogin", UtilMisc.toMap("userLoginId", "demowarehouse1")); demopurch1 = delegator.findByPrimaryKeyCache("UserLogin", UtilMisc.toMap("userLoginId", "demopurch1")); } @Override public void tearDown() throws Exception { super.tearDown(); demofinadmin = null; DemoSalesManager = null; demowarehouse1 = null; demopurch1 = null; } public void testTermTypeFields() { assertTrue("Fields for FIN_PAYMENT_TERM are correct", UtilCommon.isEquivalent(UtilMisc.toList("termDays"), UtilAgreement.getValidFields("FIN_PAYMENT_TERM", delegator))); assertTrue("Fields for PROD_CAT_COMMISSION are correct", UtilCommon.isEquivalent(UtilMisc.toList("termValue", "productCategoryId", "description", "minQuantity", "maxQuantity"), UtilAgreement.getValidFields("PROD_CAT_COMMISSION", delegator))); assertTrue("Fields for PARTNER_SVC_PROD are correct", UtilCommon.isEquivalent(UtilMisc.toList("productId", "valueEnumId"), UtilAgreement.getValidFields("PARTNER_SVC_PROD", delegator))); } /** * This test checks if a party classification group plus net days agreement is working or not. * @throws GeneralException if an error occurs */ public void testSalesAgreementNetDaysToGroup() throws GeneralException { FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin); // create sales invoice to democlass2 String invoiceId = fa.createInvoice("democlass2", "SALES_INVOICE"); // verify that due date on the new invoice is at the end (ie, 23:59:59) of 30 days from today GenericValue invoice = delegator.findByPrimaryKey("Invoice", UtilMisc.toMap("invoiceId", invoiceId)); Calendar invoiceDate = UtilDateTime.toCalendar(invoice.getTimestamp("invoiceDate"), timeZone, locale); Calendar dueDate = UtilDateTime.toCalendar(invoice.getTimestamp("dueDate")); Calendar expectedDate = (Calendar) invoiceDate.clone(); expectedDate.add(Calendar.DATE, 30); expectedDate.set(Calendar.HOUR_OF_DAY, 23); expectedDate.set(Calendar.MINUTE, 59); expectedDate.set(Calendar.SECOND, 59); expectedDate.set(Calendar.MILLISECOND, 999); assertDatesEqual(String.format("Invoice %1$s: Due Date is not set at the end of 30 days from today (ie, 23:59:59).", invoiceId), expectedDate, dueDate); } /** * This test checks if a sales agreement for a day of the month due date is correct or not. * @throws GeneralException if an error occurs */ public void testSalesAgreementOnDayOfMonthToGroup() throws GeneralException { // set AgreementTerm.minQuantity=31 for agreementTermId=AGRTRM_DUE_10TH so that it is always greater than today Map<String, Object> callCtxt = new HashMap<String, Object>(); callCtxt.put("userLogin", demofinadmin); callCtxt.put("agreementTermId", "AGRTRM_DUE_10TH"); callCtxt.put("minQuantity", new Double(31.0)); runAndAssertServiceSuccess("updateAgreementTerm", callCtxt); // create sales invoice for democlass1 FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin); String invoiceId = fa.createInvoice("democlass1", "SALES_INVOICE"); // verify that the sales invoice's due date is at the end of the 10th day of the next month, ie if today is 2007-12-05, the invoice is due 2008-01-10 GenericValue invoice = delegator.findByPrimaryKey("Invoice", UtilMisc.toMap("invoiceId", invoiceId)); Calendar invoiceDate = UtilDateTime.toCalendar(invoice.getTimestamp("invoiceDate")); Calendar dueDate = UtilDateTime.toCalendar(invoice.getTimestamp("dueDate")); Calendar expectedDate = (Calendar) invoiceDate.clone(); expectedDate.add(Calendar.MONTH, 1); expectedDate.set(Calendar.DAY_OF_MONTH, 10); expectedDate.set(Calendar.HOUR_OF_DAY, 23); expectedDate.set(Calendar.MINUTE, 59); expectedDate.set(Calendar.SECOND, 59); expectedDate.set(Calendar.MILLISECOND, 999); assertDatesEqual(String.format("Invoice %1$s: Due Date is not set at the end of the 10th day of the next month, ie if today is 2007-12-05, the invoice is due 2008-01-10", invoiceId), expectedDate, dueDate); // set AgreementTerm.minQuantity=0 for agreementTermId=AGRTRM_DUE_10TH so that it is always greater than today callCtxt = new HashMap<String, Object>(); callCtxt.put("userLogin", demofinadmin); callCtxt.put("agreementTermId", "AGRTRM_DUE_10TH"); callCtxt.put("minQuantity", new Double(0.0)); runAndAssertServiceSuccess("updateAgreementTerm", callCtxt); // create sales invoice for democlass1 invoiceId = fa.createInvoice("democlass1", "SALES_INVOICE"); // verify that the sales invoice's due date is at the end of the 10th day of the two months later, ie if today is 2007-12-05, the invoice is due 2008-02-10 invoice = delegator.findByPrimaryKey("Invoice", UtilMisc.toMap("invoiceId", invoiceId)); invoiceDate = UtilDateTime.toCalendar(invoice.getTimestamp("invoiceDate")); dueDate = UtilDateTime.toCalendar(invoice.getTimestamp("dueDate")); expectedDate = (Calendar) invoiceDate.clone(); expectedDate.add(Calendar.MONTH, 2); expectedDate.set(Calendar.DAY_OF_MONTH, 10); expectedDate.set(Calendar.HOUR_OF_DAY, 23); expectedDate.set(Calendar.MINUTE, 59); expectedDate.set(Calendar.SECOND, 59); expectedDate.set(Calendar.MILLISECOND, 999); assertDatesEqual(String.format("Invoice %1$s: Due Date is not set at the end of the 10th day of the two months later, ie if today is 2007-12-05, the invoice is due 2008-02-10", invoiceId), expectedDate, dueDate); } /** * This test verifies if a sales agreement for a particular party is working. * @throws GeneralException if an error occurs */ public void testSalesAgreementNetDaysToParty() throws GeneralException { performSalesAgreementNetDaysToPartyTest("democlass3", 60); } /** * This test verifies that purchasing agreements work. * @throws GeneralException if an error occurs */ public void testPurchaseAgreementNetDaysAndTermsToParty() throws GeneralException { // create purchase invoice from DemoSupplier to Company FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin); String invoiceId = fa.createInvoice("DemoSupplier", "PURCHASE_INVOICE"); // verify that the invoice due date is at the end of 30 days from today GenericValue invoice = delegator.findByPrimaryKey("Invoice", UtilMisc.toMap("invoiceId", invoiceId)); assertNotNull(invoice.get("dueDate")); Calendar invoiceDate = UtilDateTime.toCalendar(invoice.getTimestamp("invoiceDate")); Calendar dueDate = UtilDateTime.toCalendar(invoice.getTimestamp("dueDate")); invoiceDate.add(Calendar.DATE, 30); assertEquals("Difference between invoiceDate and dueDate is 30 days.", invoiceDate.get(Calendar.DATE), dueDate.get(Calendar.DATE)); // verify that the invoice has invoiceTerm.termTypeId=PURCH_VENDOR_ID and PURCH_FREIGHT whose text value equals those of AgreementTerm id "1003" and "1004" EntityCondition conditions = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, invoiceId), EntityCondition.makeCondition("termTypeId", EntityOperator.IN, Arrays.asList("PURCH_VENDOR_ID", "PURCH_FREIGHT"))); List<GenericValue> invoiceTerms = delegator.findByCondition("InvoiceTerm", conditions, null, null); String agreementTermId = null; for (GenericValue term : invoiceTerms) { agreementTermId = "PURCH_VENDOR_ID".equals(term.getString("termTypeId")) ? "1003" : "PURCH_FREIGHT".equals(term.getString("termTypeId")) ? "1004" : null; if (UtilValidate.isEmpty(agreementTermId)) { break; } GenericValue agreementTerm = delegator.findByPrimaryKey("AgreementTerm", UtilMisc.toMap("agreementTermId", agreementTermId)); String agreementTextValue = agreementTerm.getString("textValue"); String invoiceTextValue = term.getString("textValue"); assertEquals(String.format("Text values of agreement term (\"%1$s\") and corresponding invoice term (\"%2$s\") aren't equals.", agreementTextValue, invoiceTextValue), agreementTextValue, invoiceTextValue); } assertEquals(String.format("Error. Both PURCH_VENDOR_ID and PURCH_FREIGHT terms should be assigned to invoice %1$s.", invoiceId), true, UtilValidate.isNotEmpty(agreementTermId)); } /** * This test checks the following: * 1. A credit limit is enforced so that customer invoices cannot be made READY above it * 2. By making a payment and reducing the limit, the customer invoice can be made READY again * 3. Receiving a customer payment in advance will cause the invoice to pass successfully as well * @throws GeneralException if an error occurs */ public void testCreditLimit() throws GeneralException { performCreditLimitTest("accountlimit100"); } /** * The method performs credit limit test. Actually it creates invoices and payments in sequence * specified by actions argument. * * <strong>Important note!</strong> Payments are always applied to last invoice. * * @param partyId <code>partyIdTo</code> for invoices created. * @throws GeneralException if an error occurs * @see org.opentaps.tests.financials.AgreementTests.InvoiceAction * @see org.opentaps.tests.financials.AgreementTests.InvoiceItemAction * @see org.opentaps.tests.financials.AgreementTests.PaymentAction */ public void performCreditLimitTest(String partyId) throws GeneralException { // create sales invoice from Company to specified party with one invoice item for $50 FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin); String invoiceId1 = fa.createInvoice(partyId, "SALES_INVOICE"); fa.createInvoiceItem(invoiceId1, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("50.0")); // set invoice status to READY is successful fa.updateInvoiceStatus(invoiceId1, "INVOICE_READY"); // create a second sales invoice from Company to accountlimit100 with one invoice item for $49 String invoiceId2 = fa.createInvoice(partyId, "SALES_INVOICE"); fa.createInvoiceItem(invoiceId2, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("49.0")); // set invoice status to READY is successful fa.updateInvoiceStatus(invoiceId2, "INVOICE_READY"); // create a third sales invoice from Company to accountlimit100 with one invoice item for $5 String invoiceId3 = fa.createInvoice(partyId, "SALES_INVOICE"); fa.createInvoiceItem(invoiceId3, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("5.0")); // set invoice status to READY should fail. (The message is "Cannot mark invoice as ready. Customer credit limit exceeded.") Map<String, Object> callCtxt = new HashMap<String, Object>(); callCtxt.put("userLogin", demofinadmin); callCtxt.put("invoiceId", invoiceId3); callCtxt.put("statusId", "INVOICE_READY"); callCtxt.put("statusDate", UtilDateTime.nowTimestamp()); runAndAssertServiceError("setInvoiceStatus", callCtxt); // create payment of type CUSTOMER_PAYMENT from accountlimit100 to Company of $5 and apply to the first sales invoice, set its status to RECEIVED fa.createPaymentAndApplication(new BigDecimal("5.0"), partyId, organizationPartyId, "CUSTOMER_PAYMENT", "CREDIT_CARD", null, invoiceId1, "PMNT_RECEIVED"); // set the third invoice status to READY again and this time it should succeed because the payment has brought the balance down fa.updateInvoiceStatus(invoiceId3, "INVOICE_READY"); // receive a payment of type CUSTOMER_DEPOSIT from accountlimit100 to Company of $100 and set its status to RECEIVED, but do not apply it to any invoice fa.createPayment(new BigDecimal("100.0"), partyId, "CUSTOMER_DEPOSIT", "CREDIT_CARD", "PMNT_RECEIVED"); // create a fourth sales invoice to accountlimit100 with one item for $100 String invoiceId4 = fa.createInvoice(partyId, "SALES_INVOICE"); fa.createInvoiceItem(invoiceId4, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("100.0")); // set it to READY and it should succeed because there is a payment already fa.updateInvoiceStatus(invoiceId4, "INVOICE_READY"); } /** * This method is implementation of the test to verify if a sales agreement for a particular * party and net payments days term is working. * * @param partyId <code>partyIdTo</code> for invoices created. * @param netPaymentDays Net payments days term value. * @throws GeneralException if an error occurs */ public void performSalesAgreementNetDaysToPartyTest(String partyId, int netPaymentDays) throws GeneralException { // create sales invoice for specified partyId FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin); String invoiceId = fa.createInvoice(partyId, "SALES_INVOICE"); // verify that the invoice due date is the invoice date plus the specified netPaymentDays GenericValue invoice = delegator.findByPrimaryKey("Invoice", UtilMisc.toMap("invoiceId", invoiceId)); Calendar invoiceDate = UtilDateTime.toCalendar(invoice.getTimestamp("invoiceDate")); Calendar dueDate = UtilDateTime.toCalendar(invoice.getTimestamp("dueDate")); invoiceDate.add(Calendar.DATE, netPaymentDays); assertEquals("Difference between invoiceDate and dueDate isn't equals " + Integer.valueOf(netPaymentDays).toString() + " days.", invoiceDate.get(Calendar.DATE), dueDate.get(Calendar.DATE)); } }
import path from 'path'; async function loadModules(modulePaths) { const results = {}; for (const modulePath of modulePaths) { const moduleName = path.basename(modulePath, '.js'); const module = require(modulePath); if (moduleName.includes('sendMsgToAll')) { results[moduleName] = await module.sendMsgToAll(); } else if (moduleName.includes('secret')) { results[moduleName] = await module.secret(); } else if (moduleName.includes('canBeNull')) { results[moduleName] = await module.canBeNull(); } else if (moduleName.includes('stringValidation')) { results[moduleName] = await module.stringValidation(); } else if (moduleName.includes('anyOfValidation')) { results[moduleName] = await module.anyOfValidation(); } else if (moduleName.includes('objectValidation')) { results[moduleName] = await module.objectValidation(); } else if (moduleName.includes('objectClassValidation')) { results[moduleName] = await module.objectClassValidation(); } } return results; }
#!/bin/bash # 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. workload_folder=`dirname "$0"` workload_folder=`cd "$workload_folder"; pwd` workload_root=${workload_folder}/../../.. . "${workload_root}/../../bin/functions/load-bench-config.sh" enter_bench ScalaSparkDFSIOE ${workload_root} ${workload_folder} show_bannar start echo -e "${On_Blue}Spark DFSIOE not implemented yet, nothing to do.${Color_Off}" show_bannar finish leave_bench
#!/bin/bash # Sets up a venv suitable for running samples. # Recommend getting default 'python' to be python 3. For example on Debian: # sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 1 # Or launch with python=/some/path TD="$(cd $(dirname $0) && pwd)" VENV_DIR="$TD/iree-samples.venv" if [ -z "$PYTHON" ]; then PYTHON="$(which python)" fi echo "Setting up venv dir: $VENV_DIR" echo "Python: $PYTHON" echo "Python version: $("$PYTHON" --version)" function die() { echo "Error executing command: $*" exit 1 } $PYTHON -m venv "$VENV_DIR" || die "Could not create venv." source "$VENV_DIR/bin/activate" || die "Could not activate venv" # Upgrade pip and install requirements. 'python' is used here in order to # reference to the python executable from the venv. python -m pip install --upgrade pip || die "Could not upgrade pip" python -m pip install --upgrade -r "$TD/requirements.txt" echo "Activate venv with:" echo " source $VENV_DIR/bin/activate"
#!/bin/sh DOTFILES_BOOTSTRAP=false . ./bootstrap.sh package="git" # TODO: should we overwrite system git on macOS? install_packages_if_necessary "${package}" || die "Installing ${package} failed" source_config_dir="$DOTFILES_DIR/config/$package" # TODO: rely on $HOME being set? # TODO: support XDG... dest_config_dir=$HOME/.config/$package configure_single_package "$source_config_dir" "$dest_config_dir"
<filename>C2CRIBuildDir/projects/C2C-RI/src/jameleon-test-suite-3_3-RC1-C2CRI/jameleon-core/src/java/net/sf/jameleon/reporting/AbstractTestRunReporter.java<gh_stars>0 /* Jameleon - An automation testing tool.. Copyright (C) 2007 <NAME> (<EMAIL>) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package net.sf.jameleon.reporting; import java.io.IOException; import java.io.Writer; public abstract class AbstractTestRunReporter implements TestRunReporter { private Writer writer; public void cleanUp() { try{ if (writer != null){ writer.flush(); writer.close(); writer = null; } }catch(IOException ioe){ ioe.printStackTrace(); } } public Writer getWriter() { return writer; } public void setWriter(Writer writer) { this.writer = writer; } }
/* * 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. */ // THIS IS A GENERATED FILE. DO NOT MODIFY MANUALLY. @see scripts/compile-icons.js import * as React from 'react'; interface SVGRProps { title?: string; titleId?: string; } const EuiIconLogoCodesandbox = ({ title, titleId, ...props }: React.SVGProps<SVGSVGElement> & SVGRProps) => ( <svg xmlns="http://www.w3.org/2000/svg" width={32} height={32} viewBox="0 0 32 32" aria-labelledby={titleId} {...props} > {title ? <title id={titleId}>{title}</title> : null} <path d="M14.738 28.044V16.681L3.172 10.919v6.46l5.32 2.67v4.889l6.246 3.106zm2.344.066l6.357-3.17v-5.002l5.353-2.686V10.87l-11.71 5.854V28.11zM27.306 8.993l-6.003-3.012-5.286 2.656-5.325-2.659L4.637 9.03l11.317 5.638 11.352-5.675zM.828 23.744V8.324L15.981.689l15.155 7.604V23.72L15.98 31.28.828 23.743z" /> </svg> ); export const icon = EuiIconLogoCodesandbox;
def get_room_details(buildings_data, room_id): for building in buildings_data["buildings"]: for room in building["rooms"]: if room["id"] == room_id: details = { "Window": room["window"], "Door": room["door"], "AC": room["ac"], "Indoor": room["indoor"], "Outdoor": room["outdoor"] } return "Room Details:\n" + "\n".join(f"{key}: {value}" for key, value in details.items()) return "Room not found"
#! /bin/bash ANSWER=0 if [[ $1 =~ force-* ]]; then FORCED=1; else FORCED=0; fi if [ -d "/usr/local/include/eosio" ] || [ -d "$HOME/opt/eosio" ] || [ $FORCED == 1 ]; then # use force for running the script directly printf "\nEOSIO installation (AND DEPENDENCIES) already found...\n" if [ $1 == 0 ]; then read -p "Do you wish to remove them? (this includes dependencies)? (y/n) " ANSWER elif [ $1 == 1 ] || [ $FORCED == 1 ]; then ANSWER=1 fi echo "Uninstalling..." case $ANSWER in 1 | [Yy]* ) if [ -d "$HOME/opt/eosio" ] || [[ $1 == "force-new" ]]; then if [ $( uname ) == "Darwin" ]; then # gettext and other brew packages are not modified as they can be dependencies for things other than eosio if [ $ANSWER != 1 ]; then read -p "Do you wish to uninstall and unlink all brew installed llvm@4 versions? (y/n) " ANSWER; fi case $ANSWER in 1 | [Yy]* ) brew uninstall llvm@4 --force brew cleanup -s llvm@4 ;; [Nn]* ) ;; * ) echo "Please type 'y' for yes or 'n' for no."; exit;; esac if [ $ANSWER != 1 ]; then read -p "Do you wish to uninstall and unlink all brew installed doxygen versions? (y/n) " ANSWER; fi case $ANSWER in 1 | [Yy]* ) brew uninstall doxygen --force brew cleanup -s doxygen ;; [Nn]* ) ;; * ) echo "Please type 'y' for yes or 'n' for no."; exit;; esac if [ $ANSWER != 1 ]; then read -p "Do you wish to uninstall and unlink all brew installed graphviz versions? (y/n) " ANSWER; fi case $ANSWER in 1 | [Yy]* ) brew uninstall graphviz --force brew cleanup -s graphviz ;; [Nn]* ) ;; * ) echo "Please type 'y' for yes or 'n' for no."; exit;; esac if [ $ANSWER != 1 ]; then read -p "Do you wish to uninstall and unlink all brew installed libusb versions? (y/n) " ANSWER; fi case $ANSWER in 1 | [Yy]* ) brew uninstall libusb --force brew cleanup -s libusb ;; [Nn]* ) ;; * ) echo "Please type 'y' for yes or 'n' for no."; exit;; esac fi rm -rf $HOME/opt/eosio rm -f $HOME/bin/eosio-launcher rm -rf $HOME/lib/cmake/eosios rm -rf $HOME/opt/llvm rm -f $HOME/opt/boost rm -rf $HOME/src/boost_* rm -rf $HOME/src/cmake-* rm -rf $HOME/share/cmake-* rm -rf $HOME/share/aclocal/cmake* rm -rf $HOME/doc/cmake* rm -f $HOME/bin/nodeos $HOME/bin/keosd $HOME/bin/cleos $HOME/bin/ctest $HOME/bin/*cmake* $HOME/bin/cpack rm -rf $HOME/src/mongo* fi if [ -d "/usr/local/include/eosio" ] || [[ $1 == "force-old" ]]; then if [ "$(id -u)" -ne 0 ]; then printf "\nCleanup requires sudo... Please manually run ./scripts/clean_old_install.sh with sudo.\n" exit -1 fi pushd /usr/local &> /dev/null rm -rf wasm pushd include &> /dev/null rm -rf libbson-1.0 libmongoc-1.0 mongocxx bsoncxx appbase chainbase eosio.system eosiolib fc libc++ musl secp256k* 2>/dev/null rm -rf eosio 2>/dev/null popd &> /dev/null pushd bin &> /dev/null rm cleos eosio-abigen eosio-applesedemo eosio-launcher eosio-s2wasm eosio-wast2wasm eosiocpp keosd nodeos 2>/dev/null popd &> /dev/null libraries=( libeosio_testing libpose_chain libfc libbinaryen libWAST libWASM libRuntime libPlatform libIR libLogging libsoftfloat libchainbase libappbase libbuiltins libbson-1.0 libbson-static-1.0.a libbsoncxx-static libmongoc-1.0 libmongoc-static-1.0.a libmongocxx-static libsecp256k* ) pushd lib &> /dev/null for lib in ${libraries[@]}; do rm ${lib}.a ${lib}.dylib ${lib}.so 2>/dev/null rm pkgconfig/${lib}.pc 2>/dev/null rm cmake/${lib} 2>/dev/null done popd &> /dev/null pushd etc &> /dev/null rm eosio 2>/dev/null popd &> /dev/null pushd share &> /dev/null rm eosio 2>/dev/null popd &> /dev/null pushd usr/share &> /dev/null rm eosio 2>/dev/null popd &> /dev/null pushd var/lib &> /dev/null rm eosio 2>/dev/null popd &> /dev/null pushd var/log &> /dev/null rm eosio 2>/dev/null popd &> /dev/null fi ;; [Nn]* ) printf "Skipping\n\n" exit 0 ;; esac fi
def shortest_path(start, end): # create the graph graph = createGraph(matrix) # find all possible paths paths = findAllPaths(start, end, graph) # find the shortest shortest = reduce(lambda a, b: a if len(a)< len(b) else b, paths) # returning the shortest path return shortest def createGraph(matrix): # creates a graph object graph = Graph() # add edges to the graph for row in range(len(matrix)): for col in range(len(matrix[0])): if row+1 < len(matrix): graph.addEdge((row, col), (row+1, col)) if col+1 < len(matrix[0]): graph.addEdge((row, col), (row, col+1)) # returning the graph object return graph def findAllPaths(start, end, graph): # use the BFS algorithm to find all the paths paths = graph.bfs(start, end) # returning the paths return paths
<filename>src/main/java/org/olat/course/nodes/sp/SPPeekviewController.java /** * OLAT - Online Learning and Training<br> * http://www.olat.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> * University of Zurich, Switzerland. * <hr> * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * This file has been modified by the OpenOLAT community. Changes are licensed * under the Apache 2.0 license as the original file. */ package org.olat.course.nodes.sp; import org.olat.core.commons.modules.singlepage.SinglePageController; import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.Component; import org.olat.core.gui.components.download.DownloadComponent; import org.olat.core.gui.components.panel.Panel; import org.olat.core.gui.components.velocity.VelocityContainer; import org.olat.core.gui.control.Event; import org.olat.core.gui.control.WindowControl; import org.olat.core.gui.control.controller.BasicController; import org.olat.core.gui.control.generic.iframe.DeliveryOptions; import org.olat.core.id.OLATResourceable; import org.olat.core.util.vfs.VFSContainer; import org.olat.core.util.vfs.VFSItem; import org.olat.core.util.vfs.VFSLeaf; import org.olat.course.run.userview.UserCourseEnvironment; import org.olat.modules.ModuleConfiguration; /** * Description:<br> * This is the implementatino of the peekview for the sp course node. Files of * type html, htm or xhtml are displayed in the peekview with a 75% scaling. For * other types only a download link is displayed. * * <P> * Initial Date: 09.12.2009 <br> * * @author gnaegi */ public class SPPeekviewController extends BasicController { /** * Constructor for the sp peek view * @param ureq * @param wControl * @param userCourseEnv * @param config * @param ores */ public SPPeekviewController(UserRequest ureq, WindowControl wControl, UserCourseEnvironment userCourseEnv, ModuleConfiguration config, OLATResourceable ores) { super(ureq, wControl); // just display the page String file = config.getStringValue(SPEditController.CONFIG_KEY_FILE); DeliveryOptions deliveryOptions = (DeliveryOptions)config.get(SPEditController.CONFIG_KEY_DELIVERYOPTIONS); Component resPanel = new Panel("empty"); // empty panel to use if no file could be found if (file != null) { String fileLC = file.toLowerCase(); if (fileLC.endsWith(".html") || fileLC.endsWith(".htm") || fileLC.endsWith(".xhtml")) { // Render normal view but scaled down to 75% boolean allowRelativeLinks = config.getBooleanSafe(SPEditController.CONFIG_KEY_ALLOW_RELATIVE_LINKS); // in preview, randomize the mapper of the html page SinglePageController spController = new SinglePageController(ureq, wControl, userCourseEnv.getCourseEnvironment().getCourseFolderContainer(), file, allowRelativeLinks, null, ores, deliveryOptions, userCourseEnv.getCourseEnvironment().isPreview()); // but add scaling to fit preview into minimized space spController.setScaleFactorAndHeight(0.75f, 400, true); listenTo(spController); resPanel = spController.getInitialComponent(); } else { // Render a download link for file VFSContainer courseFolder = userCourseEnv.getCourseEnvironment().getCourseFolderContainer(); VFSItem downloadItem = courseFolder.resolve(file); if (file != null && downloadItem instanceof VFSLeaf) { DownloadComponent downloadComp = new DownloadComponent("downloadComp", (VFSLeaf) downloadItem); VelocityContainer peekviewVC = createVelocityContainer("peekview"); peekviewVC.put("downloadComp", downloadComp); resPanel = peekviewVC; } } } putInitialPanel(resPanel); } @Override protected void event(UserRequest ureq, Component source, Event event) { // no events to catch } }
The first snippet is more efficient than the second snippet because it uses a for loop, which allows the loop counter (i) to be initialized, tested, and updated in a single statement. In the second snippet, the counter has to be manually incremented each time through the loop, and that requires an extra statement, which increases the amount of time needed to execute the loop.
<filename>pirates/piratesgui/LootPopupPanel.py<gh_stars>1-10 # File: L (Python 2.4) from direct.showbase import DirectObject from direct.gui.DirectGui import * from pandac.PandaModules import * from pirates.piratesbase import PLocalizer from pirates.piratesbase import Freebooter from pirates.piratesgui import PiratesGuiGlobals from pirates.piratesgui import GuiButton from pirates.piratesbase import PiratesGlobals from pirates.ai import HolidayGlobals from pirates.makeapirate import ClothingGlobals from direct.interval.IntervalGlobal import * from pirates.piratesgui import RadialMenu from pirates.battle import WeaponGlobals from pirates.piratesbase import CollectionMap from pirates.piratesgui.MessageStackPanel import StackMessage from pirates.minigame import PlayingCardGlobals from pirates.minigame import PotionGlobals from pirates.uberdog.UberDogGlobals import InventoryType from pirates.economy.EconomyGlobals import * from pirates.audio import SoundGlobals from pirates.audio.SoundGlobals import loadSfx class LootPopupPanel(StackMessage, DirectObject.DirectObject): width = 0.80000000000000004 height = 0.20000000000000001 lootSfx = None BountyTex = None CoinTex = None CrateTex = None ChestTex = None RoyalChestTex = None TreasureGui = None TailorGui = None JewelerIconsA = None JewelerIconsB = None TattooIcons = None WeaponIcons = None def __init__(self, background = 1, extraArgs = []): panelName = PLocalizer.LootPlundered StackMessage.__init__(self, text = '', text_wordwrap = 14, time = PiratesGuiGlobals.LootPopupTime, frameSize = (0, self.width, 0, -(self.height), 0)) self.initialiseoptions(LootPopupPanel) self.loot = [] self.titleLabel = DirectLabel(parent = self, relief = None, text = panelName, text_align = TextNode.ALeft, text_scale = PiratesGuiGlobals.TextScaleMed, text_fg = PiratesGuiGlobals.TextFG1, text_shadow = PiratesGuiGlobals.TextShadow, text_font = PiratesGlobals.getInterfaceOutlineFont(), textMayChange = 1, text_wordwrap = 14, sortOrder = 21) if not LootPopupPanel.lootSfx: LootPopupPanel.lootSfx = loadSfx(SoundGlobals.SFX_GUI_LOOT) LootPopupPanel.lootSfx.setVolume(0.75) card = loader.loadModel('models/textureCards/icons') topgui = loader.loadModel('models/gui/toplevel_gui') inventoryGui = loader.loadModel('models/gui/gui_icons_inventory') LootPopupPanel.BountyTex = loader.loadModel('models/gui/avatar_chooser_rope').find('**/avatar_c_B_delete') LootPopupPanel.CoinTex = topgui.find('**/treasure_w_coin*') LootPopupPanel.CrateTex = topgui.find('**/icon_crate*') LootPopupPanel.ChestTex = card.find('**/icon_chest') LootPopupPanel.RoyalChestTex = card.find('**/topgui_icon_ship_chest03*') LootPopupPanel.LootSacTex = inventoryGui.find('**/pir_t_ico_trs_sack*') LootPopupPanel.LootChestTex = inventoryGui.find('**/pir_t_ico_trs_chest_01*') LootPopupPanel.LootSkullChestTex = inventoryGui.find('**/pir_t_ico_trs_chest_02*') LootPopupPanel.TreasureGui = loader.loadModel('models/gui/treasure_gui') LootPopupPanel.TailorGui = loader.loadModel('models/textureCards/tailorIcons') LootPopupPanel.JewelerIconsA = loader.loadModel('models/gui/char_gui') LootPopupPanel.JewelerIconsB = loader.loadModel('models/textureCards/shopIcons') LootPopupPanel.TattooIcons = loader.loadModel('models/textureCards/tattooIcons') LootPopupPanel.WeaponIcons = loader.loadModel('models/gui/gui_icons_weapon') if not background: self.frameParent.hide() self['relief'] = None self.titleLabel['relief'] = None self.icons = { ItemId.CARGO_CRATE: (LootPopupPanel.CrateTex, PLocalizer.Crate), ItemId.CARGO_CHEST: (LootPopupPanel.ChestTex, PLocalizer.Chest), ItemId.CARGO_SKCHEST: (LootPopupPanel.RoyalChestTex, PLocalizer.SkChest), ItemId.CARGO_LOOTSAC: (LootPopupPanel.LootSacTex, PLocalizer.Crate), ItemId.CARGO_LOOTCHEST: (LootPopupPanel.LootChestTex, PLocalizer.Chest), ItemId.CARGO_LOOTSKCHEST: (LootPopupPanel.LootSkullChestTex, PLocalizer.SkChest), ItemId.CARGO_SHIPUPGRADECHEST: (LootPopupPanel.LootChestTex, PLocalizer.Chest), ItemId.CARGO_SHIPUPGRADESKCHEST: (LootPopupPanel.LootSkullChestTex, PLocalizer.SkChest), ItemId.GOLD: (LootPopupPanel.CoinTex, PLocalizer.MoneyName), ItemId.BOUNTY: (LootPopupPanel.BountyTex, PLocalizer.PVPInfamySpendable) } self.titleLabel['text_scale'] = PiratesGuiGlobals.TextScaleLarge self.repackPanels() def showLoot(self, plunder = [], gold = 0, collect = 0, card = 0, cloth = 0, color = 0, jewel = None, tattoo = None, weapon = None, bounty = 0): for loot in self.loot: loot.destroy() del loot self.loot = [] gender = localAvatar.style.getGender() self.show() self.setAlphaScale(1.0) treasure = [] for itemId in self.icons.iterkeys(): count = 0 for item in plunder: if item == itemId: count += 1 continue if count > 0: treasure.append([ itemId, count]) continue plunder = treasure if gold: plunder.append([ ItemId.GOLD, gold]) LootPopupPanel.lootSfx.play() if bounty: plunder.append([ ItemId.BOUNTY, bounty]) LootPopupPanel.lootSfx.play() if collect: plunder.append([ ItemId.COLLECT, collect]) LootPopupPanel.lootSfx.play() if card: plunder.append([ ItemId.CARD, card]) LootPopupPanel.lootSfx.play() if cloth: plunder.append([ ItemId.CLOTHING, (cloth, color)]) LootPopupPanel.lootSfx.play() if jewel is not None: plunder.append([ ItemId.QUEST_DROP_JEWEL, jewel]) LootPopupPanel.lootSfx.play() if tattoo is not None: plunder.append([ ItemId.QUEST_DROP_TATTOO, tattoo]) LootPopupPanel.lootSfx.play() if weapon is not None: plunder.append([ ItemId.QUEST_DROP_WEAPON, weapon]) LootPopupPanel.lootSfx.play() for item in plunder: (itemType, quantity) = item if itemType == ItemId.COLLECT: itemId = quantity howRare = CollectionMap.Collection_Rarity.get(itemId, 0) rarityText = PLocalizer.CollectionRarities.get(howRare) value = CollectionValues.get(howRare, 0) itemName = PLocalizer.Collections[itemId] howManyDoIHave = localAvatar.getInventory().getStackQuantity(itemId) howManyINeed = CollectionMap.Collection_Needed.get(itemId, 1) if howManyDoIHave < howManyINeed: textInfo = PLocalizer.CollectionPopupNewText % (itemName, rarityText, value) else: textInfo = PLocalizer.CollectionPopupDuplicateText % (itemName, rarityText, value) pic_name = CollectionMap.Assets[itemId] lootIcon = LootPopupPanel.TreasureGui.find('**/%s*' % pic_name) iconScale = 0.34999999999999998 elif itemType == ItemId.CLOTHING: (clothingId, colorId) = quantity if clothingId in ClothingGlobals.quest_items: textInfo = PLocalizer.getItemName(clothingId) else: textInfo = PLocalizer.TailorColorStrings.get(colorId) textInfo = textInfo + ' ' + ClothingGlobals.getClothingTypeName(ItemGlobals.getType(clothingId)) clothingType = ItemGlobals.getType(clothingId) iconScale = 0.13 if clothingType == 0: lootIcon = LootPopupPanel.TailorGui.find('**/icon_shop_tailor_hat') elif clothingType == 1: lootIcon = loader.loadModel('models/gui/char_gui').find('**/chargui_cloth') iconScale = 0.29999999999999999 elif clothingType == 2: lootIcon = LootPopupPanel.TailorGui.find('**/icon_shop_tailor_vest') elif clothingType == 3: lootIcon = LootPopupPanel.TailorGui.find('**/icon_shop_tailor_coat') elif clothingType == 4: lootIcon = LootPopupPanel.TailorGui.find('**/icon_shop_tailor_pants') elif clothingType == 5: lootIcon = LootPopupPanel.TailorGui.find('**/icon_shop_tailor_belt') elif clothingType == 6: lootIcon = LootPopupPanel.TailorGui.find('**/icon_shop_tailor_sock') else: lootIcon = LootPopupPanel.TailorGui.find('**/icon_shop_tailor_booths') elif itemType == ItemId.CARD: textInfo = PLocalizer.InventoryTypeNames.get(quantity) pic_name = '' lootIcon = PlayingCardGlobals.getImage('standard', PlayingCardGlobals.getSuit(quantity), PlayingCardGlobals.getRank(quantity)) iconScale = 0.20000000000000001 elif itemType == ItemId.GOLD: textInfo = PLocalizer.LootGold % str(quantity) potionPercent = PotionGlobals.getGoldBoostEffectPercent(localAvatar) potionGold = 0 textInfo = PLocalizer.LootGold % str(quantity) if base.cr.newsManager: if base.cr.newsManager.getHoliday(HolidayGlobals.DOUBLEGOLDHOLIDAYPAID) or Freebooter.getPaidStatus(base.localAvatar.getDoId()) or base.cr.newsManager.getHoliday(HolidayGlobals.DOUBLEGOLDHOLIDAY): textInfo = PLocalizer.LootGold % str(quantity / 2) + '\n + ' + PLocalizer.LootGoldDouble % str(quantity / 2) if potionGold > 0: textInfo += '\n + ' + PLocalizer.LootGoldPotionBoost % str(potionGold) lootIcon = self.icons.get(itemType)[0] iconScale = 0.27000000000000002 elif itemType == ItemId.BOUNTY: textInfo = PLocalizer.LootBounty % str(quantity) lootIcon = self.icons.get(itemType)[0] iconScale = 0.27000000000000002 elif itemType == ItemId.CARGO_CRATE: if quantity == 1: textInfo = PLocalizer.CargoCrate % quantity else: textInfo = PLocalizer.CargoCrateP % quantity lootIcon = self.icons.get(itemType)[0] iconScale = 0.089999999999999997 elif itemType == ItemId.CARGO_CHEST: if quantity == 1: textInfo = PLocalizer.CargoChest % quantity else: textInfo = PLocalizer.CargoChestP % quantity lootIcon = self.icons.get(itemType)[0] iconScale = 0.089999999999999997 elif itemType == ItemId.CARGO_SKCHEST: if quantity == 1: textInfo = PLocalizer.CargoSkChest % quantity else: textInfo = PLocalizer.CargoSkChestP % quantity lootIcon = self.icons.get(itemType)[0] iconScale = 0.089999999999999997 elif itemType == ItemId.CARGO_LOOTSAC: if quantity == 1: textInfo = PLocalizer.LootSac % quantity else: textInfo = PLocalizer.LootSacP % quantity lootIcon = self.icons.get(itemType)[0] iconScale = 0.089999999999999997 elif itemType == ItemId.CARGO_LOOTCHEST: if quantity == 1: textInfo = PLocalizer.LootChest % quantity else: textInfo = PLocalizer.LootChestP % quantity lootIcon = self.icons.get(itemType)[0] iconScale = 0.089999999999999997 elif itemType == ItemId.CARGO_LOOTSKCHEST: if quantity == 1: textInfo = PLocalizer.LootSkChest % quantity else: textInfo = PLocalizer.LootSkChestP % quantity lootIcon = self.icons.get(itemType)[0] iconScale = 0.089999999999999997 elif itemType == ItemId.CARGO_SHIPUPGRADECHEST: if quantity == 1: textInfo = PLocalizer.LootUpgradeChest % quantity else: textInfo = PLocalizer.LootUpgradeChestP % quantity lootIcon = self.icons.get(itemType)[0] iconScale = 0.089999999999999997 elif itemType == ItemId.CARGO_SHIPUPGRADESKCHEST: if quantity == 1: textInfo = PLocalizer.LootRareUpgradeChest % quantity else: textInfo = PLocalizer.LootRareUpgradeChestP % quantity lootIcon = self.icons.get(itemType)[0] iconScale = 0.089999999999999997 elif itemType == ItemId.QUEST_DROP_JEWEL: textInfo = None type = None lootIcon = None iconScale = 1.0 type = ItemGlobals.getType(quantity) textInfo = PLocalizer.getItemName(quantity) if type == ItemGlobals.BROW: lootIcon = LootPopupPanel.JewelerIconsB.find('**/icon_shop_tailor_brow') iconScale = (-0.14000000000000001, 0.14000000000000001, 0.14000000000000001) elif type == ItemGlobals.EAR: lootIcon = LootPopupPanel.JewelerIconsA.find('**/chargui_ears') iconScale = (-0.34999999999999998, 0.34999999999999998, 0.34999999999999998) elif type == ItemGlobals.NOSE: lootIcon = LootPopupPanel.JewelerIconsA.find('**/chargui_nose') iconScale = (0.34999999999999998, 0.34999999999999998, 0.34999999999999998) elif type == ItemGlobals.MOUTH: lootIcon = LootPopupPanel.JewelerIconsA.find('**/chargui_mouth') iconScale = (0.32500000000000001, 0.32500000000000001, 0.32500000000000001) elif type == ItemGlobals.HAND: lootIcon = LootPopupPanel.JewelerIconsB.find('**/icon_shop_tailor_hand') iconScale = (0.125, 0.125, 0.125) else: lootIcon = None elif itemType == ItemId.QUEST_DROP_TATTOO: textInfo = None type = None lootIcon = None iconScale = 1.0 type = ItemGlobals.getType(quantity) textInfo = PLocalizer.getItemName(quantity) if type == ItemGlobals.CHEST: lootIcon = LootPopupPanel.TattooIcons.find('**/icon_shop_tailor_chest_male') iconScale = 0.10000000000000001 elif type == ItemGlobals.ARM: lootIcon = LootPopupPanel.TattooIcons.find('**/icon_shop_tailor_arm') iconScale = 0.10000000000000001 elif type == ItemGlobals.FACE: lootIcon = LootPopupPanel.TattooIcons.find('**/icon_shop_tailor_face_male') iconScale = 0.10000000000000001 else: lootIcon = None elif itemType == ItemId.QUEST_DROP_WEAPON: weaponId = quantity iconScale = 0.10000000000000001 textInfo = None lootIcon = None iconName = getItemIcons(weaponId) if iconName is not None: lootIcon = LootPopupPanel.WeaponIcons.find('**/' + iconName) textInfo = PLocalizer.InventoryTypeNames.get(weaponId) entry = DirectFrame(parent = self, relief = None, geom = lootIcon, geom_scale = iconScale, text = textInfo, text_scale = PiratesGuiGlobals.TextScaleSmall, text_align = TextNode.ALeft, text_fg = PiratesGuiGlobals.TextFG0, text_pos = (0.070000000000000007, 0.01), text_font = PiratesGlobals.getInterfaceFont()) entry.setTransparency(1) self.loot.append(entry) self.repackPanels() def repackPanels(self): invHeight = len(self.loot) i = 0 z = 0.10000000000000001 iconXOffset = 0.089999999999999997 addHeight = (invHeight - 1) * z for i in xrange(invHeight): iconZOffset = z * (i + 1) - 0.01 - self.height - addHeight self.loot[i].setPos(iconXOffset, 0, iconZOffset) self.titleLabel.setPos(0.040000000000000001, 0, -0.059999999999999998) self['frameSize'] = (0, self.width, -(self.height) - addHeight, 0) self.cornerGeom.setPos(0.068000000000000005, 0, -0.066000000000000003) self.resetFrameSize() def destroy(self, autoDestroy = 1): taskMgr.remove('selfHideTask' + str(self.getParent())) self.ignoreAll() StackMessage.destroy(self, autoDestroy)
app.get('/users', (req, res) => { try { const users = db.getUsers(); res.send(users); } catch (err) { console.error(err); res.status(500).send({error: 'Internal Server Error'}); } });
/** * Copyright 2020 <NAME>. * * 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. */ import type Label from '../Label'; import type { Flow } from './flows'; import { MessageVisibleKind } from './kinds'; /** * @internal */ export class Edge { constructor( readonly id: string, readonly bpmnElement: Flow, readonly waypoints?: Waypoint[], readonly label?: Label, readonly messageVisibleKind: MessageVisibleKind = MessageVisibleKind.NONE, ) {} } /** * @internal */ export class Waypoint { constructor(readonly x: number, readonly y: number) {} }
__all__ = [ "IPAnylast", ]
package pl.gda.pg.eti.kio.malicious.event; import pl.gda.pg.eti.kio.malicious.entity.BaseMalice; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author szkol_000 */ public class MaliciousRemoteEvent extends MaliciousEvent{ private BaseMalice malice; public MaliciousRemoteEvent(String desc, BaseMalice malice) { super(desc); this.malice = malice; } public BaseMalice getMalice() { return malice; } public void setMalice(BaseMalice malice) { this.malice = malice; } }
<filename>PeshOS.Poll/scripts/peshos.poll.edit.js "use strict"; var PeshOS = PeshOS || {}; PeshOS.Poll = PeshOS.Poll || {}; PeshOS.Poll.Edit = (function () { var resources = PeshOS.Poll.Resources.getLocaleStrings(), PreviewButtonsModel = function () { var self = this; self.save = function () { PeshOS.Poll.SP.saveConfiguration(PeshOS.Common.queryString('pollId')).then( function () { $('#alertSaved').show(); }, function () { $('#alertError').show(); }); }; self.close = function () { document.location.href = PeshOS.Common.removeURLParameter( document.location.href.replace('peshos.poll.edit', 'peshos.poll.landing'), 'pollId'); }; self.reset = function () { if (confirm(resources.Message_DeleteData)) { PeshOS.Poll.SP.deleteListItems([PeshOS.Poll.constants.VotesList, '_', PeshOS.Common.queryString('pollId')].join('')).then( function (totalItems) { $('#alertTotalItems').text(totalItems); $('#alertItemsDeleted').show(); }, function () { $('#alertError').show(); }); } }; }, EditModel = function () { var self = this; self.helpInfo = function () { $('#pollDesign').hide(); $('#pollPreviewSave').hide(); $('#pollConfiguration').hide(); $('#pollHelp').show(); }; self.configuration = function () { $('#pollDesign').hide(); $('#pollPreviewSave').hide(); $('#pollHelp').hide(); $('#pollConfiguration').show(); PeshOS.Poll.Configuration.configure(); }; self.design = function () { $('#pollConfiguration').hide(); $('#pollPreviewSave').hide(); $('#pollHelp').hide(); $('#pollDesign').show(); PeshOS.Poll.Designer.configure(); }; self.previewSave = function () { $('#pollConfiguration').hide(); $('#pollDesign').hide(); $('#pollHelp').hide(); $('#pollPreviewSave').show(); ko.cleanNode(document.getElementById('pollPreviewButtons')); ko.applyBindings(new PreviewButtonsModel(), document.getElementById('pollPreviewButtons')); ko.cleanNode(document.getElementById('pollPollPreview')); ko.applyBindings(PeshOS.Poll.configObj.poll, document.getElementById('pollPollPreview')); $('#pollChartPreview').empty(); $.jqplot('pollChartPreview', [self.getChartData()], PeshOS.Poll.configObj.chartConfiguration); }; self.getChartData = function () { var data = [['Heavy Industry', 25], ['Retail', 9], ['Light Industry', 14], ['Out of home', 16], ['Commuting', 7], ['Orientation', 9]], i = 0, maxI = PeshOS.Poll.configObj.poll.questions.length; switch (PeshOS.Poll.configObj.design.chartType) { case "pie": case "funnel": data = []; for (i; i < maxI; ++i) { data.push([PeshOS.Poll.configObj.poll.questions[i].chartText, Math.floor(Math.random() * 100)]); } break; case "barHorizontal": data = []; PeshOS.Poll.configObj.chartConfiguration.axes.yaxis.ticks = []; for (i; i < maxI; ++i) { PeshOS.Poll.configObj.chartConfiguration.axes.yaxis.ticks.push(PeshOS.Poll.configObj.poll.questions[i].chartText); data.push(Math.floor(Math.random() * 100)); } break; case "barVertical": data = []; PeshOS.Poll.configObj.chartConfiguration.axes.xaxis.ticks = []; for (i; i < maxI; ++i) { PeshOS.Poll.configObj.chartConfiguration.axes.xaxis.ticks.push(PeshOS.Poll.configObj.poll.questions[i].chartText); data.push(Math.floor(Math.random() * 100)); } break; default: break; } return data; }; } function configure() { ko.cleanNode(document.getElementById('pollTopMenu')); ko.applyBindings(new EditModel(), document.getElementById('pollTopMenu')); }; return { configure: configure }; }());
package main import ( "bufio" "fmt" "os" ) func main() { scanner := bufio.NewScanner(os.Stdin) for { fmt.Print("Enter command: ") if scanner.Scan() { command := scanner.Text() if command == "quit" { break } fmt.Println("\nYou entered: " + command) } } }
<gh_stars>0 package provider import ( "errors" "k8s.io/apimachinery/pkg/util/wait" "sync" "time" "github.com/lterrac/system-autoscaler/pkg/metrics-exposer/pkg/metrics" apierr "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/dynamic" "k8s.io/metrics/pkg/apis/custom_metrics" "github.com/kubernetes-sigs/custom-metrics-apiserver/pkg/provider" "github.com/kubernetes-sigs/custom-metrics-apiserver/pkg/provider/helpers" "github.com/lterrac/system-autoscaler/pkg/informers" ) // CustomMetricResource wraps provider.CustomMetricInfo in a struct which stores the Name and Namespace of the resource // So that we can accurately store and retrieve the metric as if this were an actual metrics server. type CustomMetricResource struct { provider.CustomMetricInfo types.NamespacedName } type metricValue struct { labels labels.Set value resource.Quantity } // responseTimeMetricsProvider is a sample implementation of provider.MetricsProvider which stores a map of fake metrics type responseTimeMetricsProvider struct { client dynamic.Interface mapper apimeta.RESTMapper metricClient *metrics.Client informers informers.Informers cacheLock sync.RWMutex cache map[CustomMetricResource]metricValue } // NewResponseTimeMetricsProvider returns an instance of responseTimeMetricsProvider func NewResponseTimeMetricsProvider(client dynamic.Interface, mapper apimeta.RESTMapper, informers informers.Informers, stopCh <-chan struct{}) provider.CustomMetricsProvider { p := &responseTimeMetricsProvider{ client: client, mapper: mapper, metricClient: metrics.NewClient(), informers: informers, cache: make(map[CustomMetricResource]metricValue), } go wait.Until(p.updateMetrics, time.Second, stopCh) return p } // valueFor is a helper function to get just the value of a specific metric func (p *responseTimeMetricsProvider) valueFor(info provider.CustomMetricInfo, namespacedName types.NamespacedName, metricSelector labels.Selector) (resource.Quantity, error) { info, _, err := info.Normalized(p.mapper) if err != nil { return resource.Quantity{}, err } metricInfo := CustomMetricResource{ CustomMetricInfo: info, NamespacedName: namespacedName, } value, ok := p.cache[metricInfo] if !ok { return resource.Quantity{}, errors.New("metric not in cache, failed to retrieve metrics") } return value.value, nil } // metricFor is a helper function which formats a value, metric, and object info into a MetricValue which can be returned by the metrics API func (p *responseTimeMetricsProvider) metricFor(value resource.Quantity, name types.NamespacedName, selector labels.Selector, info provider.CustomMetricInfo, metricSelector labels.Selector) (*custom_metrics.MetricValue, error) { objRef, err := helpers.ReferenceFor(p.mapper, name, info) if err != nil { return nil, err } metric := &custom_metrics.MetricValue{ DescribedObject: objRef, Metric: custom_metrics.MetricIdentifier{ Name: info.Metric, }, Timestamp: metav1.Time{Time: time.Now()}, Value: value, } if len(metricSelector.String()) > 0 { sel, err := metav1.ParseToLabelSelector(metricSelector.String()) if err != nil { return nil, err } metric.Metric.Selector = sel } return metric, nil } // metricsFor is a wrapper used by GetMetricBySelector to format several metrics which match a resource selector func (p *responseTimeMetricsProvider) metricsFor(namespace string, selector labels.Selector, info provider.CustomMetricInfo, metricSelector labels.Selector) (*custom_metrics.MetricValueList, error) { names, err := helpers.ListObjectNames(p.mapper, p.client, namespace, selector, info) if err != nil { return nil, err } res := make([]custom_metrics.MetricValue, 0, len(names)) for _, name := range names { namespacedName := types.NamespacedName{Name: name, Namespace: namespace} value, err := p.valueFor(info, namespacedName, metricSelector) if err != nil { if apierr.IsNotFound(err) { continue } return nil, err } metric, err := p.metricFor(value, namespacedName, selector, info, metricSelector) if err != nil { return nil, err } res = append(res, *metric) } return &custom_metrics.MetricValueList{ Items: res, }, nil } func (p *responseTimeMetricsProvider) GetMetricByName(name types.NamespacedName, info provider.CustomMetricInfo, metricSelector labels.Selector) (*custom_metrics.MetricValue, error) { p.cacheLock.RLock() defer p.cacheLock.RUnlock() value, err := p.valueFor(info, name, metricSelector) if err != nil { return nil, err } return p.metricFor(value, name, labels.Everything(), info, metricSelector) } func (p *responseTimeMetricsProvider) GetMetricBySelector(namespace string, selector labels.Selector, info provider.CustomMetricInfo, metricSelector labels.Selector) (*custom_metrics.MetricValueList, error) { p.cacheLock.RLock() defer p.cacheLock.RUnlock() return p.metricsFor(namespace, selector, info, metricSelector) } func (p *responseTimeMetricsProvider) ListAllMetrics() []provider.CustomMetricInfo { p.cacheLock.RLock() defer p.cacheLock.RUnlock() // Get unique CustomMetricInfos from wrapper CustomMetricResources infos := make(map[provider.CustomMetricInfo]struct{}) for r := range p.cache { infos[r.CustomMetricInfo] = struct{}{} } // Build slice of CustomMetricInfos to be returns metrics := make([]provider.CustomMetricInfo, 0, len(infos)) for info := range infos { metrics = append(metrics, info) } return metrics }
<reponame>khaled-11/Botai<filename>local_modules/database/update_current_page.js // Function to update the Messenger user Data // const _ = require("lodash"); const AWS = require("aws-sdk"); var ddb = new AWS.DynamoDB(); var docClient = new AWS.DynamoDB.DocumentClient(); module.exports = async (id, field, data, field2, data2) => { if(field2){ params = { TableName: 'wit_clients', Key: { "clientID" : id, }, UpdateExpression: `set ${field} = :ss, ${field2} = :ss2`, ExpressionAttributeValues:{ ":ss":`${data}`, ":ss2":`${data2}` }, }; } else { params = { TableName: 'wit_clients', Key: { "clientID" : id, }, UpdateExpression: `set ${field} = :ss`, ExpressionAttributeValues:{ ":ss":`${data}` }, }; } const request = docClient.update(params); const result = await request.promise(); return result; };
<reponame>KevinMellott91/jibo-philips-hue<filename>src/lighting/lighting-controller.js<gh_stars>1-10 'use strict'; const Hue = require('node-hue-api'); const _ = require('lodash'); const fs = require('fs'); const nconf = require('nconf'); const moment = require('moment'); /** * Main class that allows the program to interact with the Philips Hue API, which * in turn controls lights within the home. */ class LightingController { /** * Initializes the variables within the lighting controller. * @param {EventEmitter} emitter The emitter that should be used when * publishing or consuming events. * @param {Logger} logger The object that should be used to log messages * (informational, trace, error, etc). */ init(emitter, logger) { const _self = this; if (!_self.initialized) { _self.initialized = true; _self.connectionEstablished = false; _self.connectionInProgress = false; _self.connectionRetryAttempts = 0; _self.emitter = emitter; _self.logger = logger; // Attempt to load the Hue bridge name. nconf.use('file', { file: 'config.json' }); _self.hueBridgeUsername = nconf.get('hue:bridgeUsername'); } } /** * Retrieves the username that was generated when the application paired with * the Hue bridge for the first time. * @return {string} Username that should be used when connecting to the Hue bridge. */ getBridgeUsername() { const _self = this; return _self.hueBridgeUsername; } /** * Sets the username that should be used when communicating with the Hue bridge. * This value will be stored, so that the application only needs to be registered once. * @param {string} username Username that was generated when initially connecting * to the Hue bridge. */ setBridgeUsername(username) { const _self = this; // Update the values stored in the config file, so that this is remembered next time around. nconf.use('file', { file: 'config.json' }); nconf.set('hue:bridgeUsername', username); nconf.save(() => { fs.readFile('config.json', (err, data) => { _self.logger.error(JSON.parse(data.toString())); }); }); _self.hueBridgeUsername = username; } /** * Initializes the event handlers for the lighting controls, primarily around * connection retry logic. */ configureEvents() { const _self = this; _self.logger.trace('Configuring lighting-controller events.'); // Attempt to connect to the Hue bridge. _self.emitter.on('bridgeRetry', () => { _self.logger.info(`Retry attempt ${_self.connectionRetryAttempts} to ` + 'establish bridge connection.'); _self.setupHueApi(); }); // Connection to the Hue bridge timed out. _self.emitter.on('bridgeTimeout', () => { _self.logger.info(`Retry timed out after ${_self.connectionRetryAttempts} attempts.`); _self.connectionInProgress = false; _self.publishMessage('bridgeTimeout'); }); // Hue bridge was not detected on the network. _self.emitter.on('errorNoBridge', () => { if (_self.connectionRetryAttempts === 0) { _self.publishMessage('errorNoBridge'); } _self.attemptConnection(); }); // Hue bridge was detected, but this application is not registered. _self.emitter.on('errorNotRegistered', () => { if (_self.connectionRetryAttempts === 0) { _self.publishMessage('errorNotRegistered'); } _self.attemptConnection(); }); // Successful connection to the Hue bridge. _self.emitter.on('bridgeConnected', () => { _self.logger.info('Connection to bridge has been established.'); _self.publishMessage('bridgeConnected'); // Update the tracking information. _self.connectionEstablished = true; _self.connectionRetryAttempts = 0; }); } /** * Tracks the number of times a connection has been attempted, and triggers * the event to try again. * Also determines when it is time to give up and trigger the timeout event. */ attemptConnection() { const _self = this; // Update the tracking information. _self.connectionEstablished = false; _self.connectionRetryAttempts += 1; // If we haven't reached the retry limit, then try again after waiting a few seconds. if (_self.connectionRetryAttempts < 10) { setTimeout(() => { _self.emitter.emit('bridgeRetry'); }, 6000); } else { _self.emitter.emit('bridgeTimeout'); } } /** * Emits a message representing a given condition, which is meant to be communicated to the user. * @param {string} eventType The type of event that has occurred. */ publishMessage(eventType) { const _self = this; let message = ''; switch (eventType) { case 'errorNoBridge': message = _self.errorNoBridgePublished === true ? 'Just a minute while I connect to your lighting system.' : 'I can\'t find your Philips Hue bridge. Can you ' + 'make sure it is powered on and connected to your network?'; _self.errorNoBridgePublished = true; break; case 'errorNotRegistered': message = _self.errorNotRegisteredPublished === true ? 'Just a minute while I connect to your lighting system.' : 'Press the button on your Philips Hue bridge and I\'ll let you know ' + 'when I\'m connected.'; _self.errorNotRegisteredPublished = true; break; case 'bridgeConnected': message = 'I am connected to your lighting system. How can I help you today?'; break; case 'bridgeTimeout': message = 'I can\'t seem to connect to your bridge and am going to take ' + 'a break. Let me know when you\'d like me to try again.'; break; case 'invalidCommand': message = 'Sorry I didn\'t understand that. Perhaps you\'d like me to ' + 'turn the lights on or off, or to dim them?'; break; case 'connectionInProgress': message = 'Just a minute while I connect to your lighting system.'; break; case 'sleepPrompt': message = 'Would you like me to turn off the lights in five minutes?'; break; case 'nightPrompt': message = 'Would you like me to turn on the lights?'; break; case 'nightConfirmation': message = 'Oh, that\'s much better!'; break; case 'invalidRoom': message = 'I don\'t recognize that room.'; break; default: _self.logger.error(`Encountered an unsupported message type "${eventType}".`); break; } _self.emitter.emit('userMessage', message); } /** * Creates a stub connection, which can be used when there are no Philips Hue * bridges available to use. */ setupFakeBridge() { const _self = this; _self.logger.trace('setting up fake bridge connection.'); _self.connectionInProgress = true; _self.authenticatedApi = Hue.api('192.168.1.8', 'newdeveloper'); _self.emitter.emit('bridgeConnected'); } /** * Creates an actual connection to a Philips Hue bridge, and triggers the * necessary events for failure modes. */ setupActualBridge() { const _self = this; _self.connectionInProgress = true; // Detect the Hue bridges within range. _self.logger.trace('setting up actual bridge connection.'); Hue.nupnpSearch() .then((bridges) => { // Example response: // Hue Bridges Found: [{"id":"001788fffe096103","ipaddress":"192.168.2.129", // "name":"Philips Hue","mac":"00:00:00:00:00"}] _self.logger.trace('Hue Bridges Found: %s', JSON.stringify(bridges)); // Ensure that we found bridges. if (bridges.length === 0) { throw new Error('Did not detect any Hue bridges.'); } // Just use the first bridge that was discovered. // TODO: This should be updated to allow the user to choose the correct Hue bridge. const bridge = _.head(bridges); // Check to see if our application is already registered with this bridge. if (_self.getBridgeUsername()) { _self.authenticatedApi = new Hue.HueApi(bridge.ipaddress, _self.getBridgeUsername()); _self.validateBridgeConnection(); } else { // Otherwise, attempt to register the application. _self.registerApplication(bridge.ipaddress); } }) .fail((error) => { // Could not communicate with the bridge. _self.logger.error(error); _self.emitter.emit('errorNoBridge'); }) .done(); } /** * Connects to the Hue bridge using the established instance, to retrieve * basic configuration information. If the connection succeeds, then the * "bridgeConnected" event will be emitted. */ validateBridgeConnection() { const _self = this; // Validate the connection by accessing basic information. _self.authenticatedApi.fullState() .then(() => { _self.emitter.emit('bridgeConnected'); }) .fail((error) => { // Clear out the stored username. _self.logger.error(error); _self.authenticatedApi = undefined; _self.setBridgeUsername(undefined); _self.emitter.emit('errorNotRegistered'); }) .done(); } /** * Establishes a username for the Jibo application on the Hue bridge. This * username will be stored for future use, to prevent re-registering. * @param {string} ipAddress The IP address of the Hue bridge. */ registerApplication(ipAddress) { const _self = this; const tempApi = new Hue.HueApi(); tempApi.registerUser(ipAddress, 'jibo-philips-hue') .then((username) => { // Example response: // Existing device user found: 51780342fd7746f2fb4e65c30b91d7 _self.logger.trace('Device user found: %s', username); // Store the authenticated API. _self.setBridgeUsername(username); _self.authenticatedApi = new Hue.HueApi(ipAddress, _self.getBridgeUsername()); _self.validateBridgeConnection(); }) .fail((error) => { // User is not registered with the device. _self.logger.error(error); _self.emitter.emit('errorNotRegistered'); }) .done(); } /** * Establishes a connection to the Hue bridge, which can be a fake one (to support testing). */ setupHueApi() { const _self = this; // _self.setupFakeBridge(); _self.setupActualBridge(); } /** * Triggers behavior within the Hue API, based on the provided action. * @param {string} action The type of action to take (turn on lights, turn off lights, etc). * @param {object} params Additional options to be used when invoking the action. */ takeAction(action, params) { const _self = this; // Clear out any pending actions. These are used for advanced interactions (confirmations, etc). _self.request = { action, time: params.time, room: params.room, color: params.color, state: {}, }; // If there is not a valid connection, then do not process the command. if (!_self.connectionEstablished) { // Trigger the retry workflow if it isn't already running. if (!_self.connectionInProgress) { _self.logger.trace('Attempting connection to the Hue bridge.'); _self.connectionRetryAttempts = 0; _self.setupHueApi(); } else { _self.publishMessage('connectionInProgress'); } return; } // Call the appropriate method, based on the incoming request. _self.logger.info('Received request for action: %s.', action); switch (action) { case 'on': _self.turnOnLights(); break; case 'off': _self.turnOffLights(); break; case 'color': _self.colorLights(); break; case 'dim': _self.dimLights(); break; case 'night': _self.nighttimeBehavior(); break; case 'sleep': _self.bedtimeBehavior(); break; case 'connect': _self.setupHueApi(); break; default: _self.publishMessage('invalidCommand'); break; } } /** * Confirms an action that is already in progress, triggering the next steps in the process. */ confirmAction() { const _self = this; // Call the appropriate method, based on the incoming request. _self.logger.info('Confirming action: %s.', _self.request.pendingAction); switch (_self.request.pendingAction) { case 'night': // Turn on all of the lights and provide a confirmation message. _self.turnOnLights(); _self.publishMessage('nightConfirmation'); break; case 'sleep': // Turn off all of the lights in five minutes. _self.request.time = moment().add(5, 'minutes'); _self.turnOffLights(); break; default: _self.publishMessage('invalidCommand'); break; } } /** * Clears any pending action information. */ cancelAction() { const _self = this; // Cancel the request. _self.logger.trace('Cancelling request of type "%s"', _self.request.pendingAction); _self.request = {}; // Send an acknowledgment back to the user, to let them know that a change is coming. _self.emitter.emit('acknowledgeRequest'); } /** * Uses the Hue API to turn off all lights within range. */ turnOffLights() { const _self = this; _self.request.state = Hue.lightState.create().off(); _self.logger.trace('Turning off the lights'); _self.changeLightsState(); } /** * Uses the Hue API to change the color of all lights within range. */ colorLights() { const _self = this; const xColor = _self.request.color; let nHue = 32767; // default: white switch (xColor) { case 'red': nHue = 0; break; case 'orange': nHue = 5000; break; case 'yellow': nHue = 18000; break; case 'green': nHue = 25500; break; case 'cyan': nHue = 36207; break; case 'blue': nHue = 46920; break; case 'pink': nHue = 56100; break; case 'indigo': nHue = 48500; break; case 'violet': nHue = 46000; break; default: _self.logger.error(`Unsupported color requested: ${xColor}`); } _self.request.state = Hue.lightState.create().on().hue(nHue).sat(255); _self.logger.trace(`Setting the lights to color ${xColor}.`); _self.changeLightsState(); } /** * Uses the Hue API to turn on all lights within range. */ turnOnLights() { const _self = this; _self.request.state = Hue.lightState.create().on().brightness(100); _self.logger.trace('Turning on the lights'); _self.changeLightsState(); } /** * Uses the Hue API to dim all lights within range. This is essentially changing the brightness of * each light to a mid-range value. */ dimLights() { const _self = this; // Available range is 0 - 100. _self.request.state = Hue.lightState.create().on().brightness(30); _self.logger.trace('Dimming the lights'); _self.changeLightsState(); } /** * Triggers the nighttime use case, with Jibo confirming that the user would like to * turn off all lights in the home. */ nighttimeBehavior() { const _self = this; _self.logger.trace('Invoking nighttime behavior.'); // If this action is not already pending, then kick off the interaction. if (_self.request.pendingAction !== 'night') { // Ask if they want the lights turned on. _self.publishMessage('nightPrompt'); // Mark this as a pending action. _self.request.pendingAction = 'night'; } } /** * Triggers the bedtime use case, with Jibo confirming that the user would like to * turn off all lights in the home in 5 minutes. */ bedtimeBehavior() { const _self = this; _self.logger.trace('Invoking bedtime behavior.'); // If this action is not already pending, then kick off the interaction. if (_self.request.pendingAction !== 'sleep') { // Ask if they want the lights turned off. _self.publishMessage('sleepPrompt'); // Mark this as a pending action. _self.request.pendingAction = 'sleep'; } } /** * If all of the lights have been processed, then this will publish a * notification message for the main application. * @param {integer} lightsProcessed Total number of lights that have already been processed. * @param {integer} totalLights Number of lights that require processing. */ updateLightsStatusCheck(lightsProcessed, totalLights) { const _self = this; if (lightsProcessed === totalLights) { // Determine which action was taken (on/off/dim) if (_self.request && _self.request.action) { // Parse the human-readable action. let action = _self.request.action; if (action !== 'on' && action !== 'off' && action !== 'dim') { // Determine the inferred action, if necessary. if (action === 'night') { action = 'on'; } else if (action === 'sleep') { action = 'off'; } } // Emit the room-specific message. if (_self.request.room) { if (action === 'dim') { _self.emitter.emit('userMessage', `I\'ve dimmed the lights in the ${_self.request.room}.`); } else { // on/off _self.emitter.emit('userMessage', `I\'ve turned ${action} the lights in the ${_self.request.room}.`); } } else if (_self.request.schedule && _self.request.schedule.localtime) { // Emit the schedule-specific message. const displayTime = moment(_self.request.schedule.localtime).format('h:mma'); if (action === 'dim') { _self.emitter.emit('userMessage', `Certainly, I\'ll dim them at ${displayTime}.`); } else { // on/off _self.emitter.emit('userMessage', `Certainly, I\'ll turn them ${action} at ${displayTime}.`); } } } else if (_self.request.time) { // Also notify with a message if an action was scheduled for the future. const message = 'Certainly, I\'ll turn them <on/off> at <5:00 PM>'; _self.emitter.emit('userMessage', message); } // Notify the general completion message. _self.logger.trace(`Processed all ${lightsProcessed} light(s), publishing ` + '"acknowledgeRequest" notification message.'); _self.emitter.emit('acknowledgeRequest'); } } /** * Updates each of the lights matching the filter (if supplied), using the provided * update action. */ updateLights() { const _self = this; // Access the connected lights. _self.authenticatedApi.lights() .then((result) => { // Track the number of lights processed, so that we know when we are done. const totalLights = _.size(result.lights); let lightsProcessed = 0; _self.logger.trace(`All lights: ${JSON.stringify(result.lights)}.`); _self.logger.trace(`Filtered lights: ${JSON.stringify(_self.request.filteredLightIds)}.`); // Loop through each light that was detected. _.forEach(result.lights, (light) => { // Leave this light alone if it is not in the specified room (if a // room filter was supplied). if (_self.request.filteredLightIds && _.size(_self.request.filteredLightIds) > 0 && !_.some(_self.request.filteredLightIds, (id) => id === light.id.toString())) { _self.logger.info(`skipping light ${light.id} because it is not in ` + `the ${_self.request.room}.`); // Notify if we have processed all of the lights. ++lightsProcessed; _self.updateLightsStatusCheck(lightsProcessed, totalLights); return; } // If a schedule was provided, then apply the changes using it. if (_self.request.schedule) { // Set the bulb information and setup the schedule. _self.request.schedule.command.address = `/api/${_self.hueBridgeUsername}/lights/${light.id}/state`; _self.logger.info(`Changing state of light #${light.id} to ` + `${JSON.stringify(_self.request.state._values)} at ${_self.request.schedule.time}.`); _self.authenticatedApi.scheduleEvent(_self.request.schedule) .then(() => { _self.logger.info(`Attempted to schedule change for light #${light.id} ` + `with result of "${JSON.stringify(result, null, 2)}".`); }) .fail((error) => { _self.logger.error(error); }) .done(() => { // Notify if we have processed all of the lights. ++lightsProcessed; _self.updateLightsStatusCheck(lightsProcessed, totalLights); }); } else { // Otherwise, make the change immediately. _self.logger.info(`Changing state of light #${light.id} to ` + `${JSON.stringify(_self.request.state._values)}.`); _self.authenticatedApi.setLightState(light.id, _self.request.state) .then(() => { _self.logger.info(`Attempted to change state of light #${light.id} ` + `with result of "${JSON.stringify(result, null, 2)}"`); }) .fail((error) => { _self.logger.error(error); }) .done(() => { // Notify if we have processed all of the lights. ++lightsProcessed; _self.updateLightsStatusCheck(lightsProcessed, totalLights); }); } }); }) .fail((error) => { _self.logger.error(error); }); } /** * Modifies the state of all lights that are accessible to the authenticated Hue bridge. * The light state object contains information about the change (brightness, on/off, etc.). */ changeLightsState() { const _self = this; // Create a schedule that represents the users request, if one was provided. if (_self.request.time) { const time = moment(_self.request.time, 'hh:mmA'); _self.request.schedule = { name: 'Jibo Schedule', description: 'This schedule was created by the jibo-philips-hue application.', time: time.format('YYYY-MM-DDTHH:mm:ss'), localtime: time.format('YYYY-MM-DDTHH:mm:ss'), command: { method: 'PUT', body: _self.request.state._values, }, }; } // If a room filter was provided, then identify all lights that should be altered. if (_self.request.room) { // This array will restrict the lights being altered. _self.request.filteredLightIds = []; // Get information from light groups. _self.authenticatedApi.groups() .then((groups) => { // Capture the results of this API invocation. _self.logger.trace(`Located ${_.size(groups)} light group(s). ` + `Details: ${JSON.stringify(groups)}.`); // Locate the group that matches the specified room. const group = _.find(groups, (g) => _.toLower(g.name) === _.toLower(_self.request.room) ); if (group) { _self.logger.trace('Found a group that matched requested room. ' + `Details: ${JSON.stringify(group)}.`); // Locate the lights in the matching group. _self.authenticatedApi.getGroup(group.id) .then((groupDetails) => { // Use the lights in this room as our filter. _self.request.filteredLightIds = groupDetails.lights; _self.updateLights(); }) .fail((error) => { _self.logger.error(error); }) .done(); } else { _self.logger.warn('No matching groups were found for room "%s".', _self.request.room); _self.publishMessage('invalidRoom'); } }) .fail((error) => { _self.logger.error(error); }) .done(); } else { _self.updateLights(); } } } module.exports = LightingController;
#!/usr/bin/env bash function _wrap_build() { local start_time=$(date +"%s") local start_ns=$(date +"%N") "$@" local ret=$? local end_ns=$(date +"%N") ((start_ns=10#$start_ns)) ((end_ns=10#$end_ns)) local end_time=$(date +"%s") if [ $start_ns -gt $end_ns ] ; then end_time=$(($end_time-1)) end_ns=$(($end_ns+1000000000)) fi local tdiff=$(($end_time-$start_time)) local nsdiff=$((($end_ns-${start_ns}) / 10000000)) local hours=$(($tdiff / 3600 )) local mins=$((($tdiff % 3600) / 60)) local secs=$(($tdiff % 60)) local ncolors=$(tput colors 2>/dev/null) if [ -n "$ncolors" ] && [ $ncolors -ge 8 ]; then color_failed=$'\E'"[0;31m" color_success=$'\E'"[0;32m" color_reset=$'\E'"[00m" else color_failed="" color_success="" color_reset="" fi echo if [ $ret -eq 0 ] ; then echo -n "${color_success}--- sync completed successfully " else echo -n "${color_failed}--- failed to sync some targets " fi if [ $hours -gt 0 ] ; then printf "(%02g:%02g:%02g)" $hours $mins $secs elif [ $mins -gt 0 ] ; then printf "(%02g:%02g)" $mins $secs elif [[ $secs -ne 0 || $nsdiff -ne 0 ]] ; then printf "(%s.%02g seconds)" $secs $nsdiff fi echo " ---${color_reset}" echo return $ret } function reposync() { # 当前 repo sync 进程的 pid PID= kill_prog() { # kill 当前repo sync子进程 echo "kill : $PID" [[ -n $PID ]] && kill $PID } start_sync() { # 启动子进程(使用coproc) coproc syncproc { repo sync; } PID=$syncproc_PID } restart_sync() { kill_prog start_sync } # 如果网络流量在retry_delay时间内小于min_speed, 则认为repo sync已经卡住了 min_speed="50" retry_delay=300 ((counter=0)) ((n_retries=0)) restart_sync while true; do # 用ifstat检测网速 speed=$(ifstat 1 1 | tail -n 1 | awk '{print $1}') result=$(echo "$speed < $min_speed" | bc) if [[ $result == "1" ]]; then ((counter++)) else ((counter=0)) fi if [[ `ps -p $PID| wc -l` == "1" ]]; then # 检测到子进程已经退出(ps已经查不到它了) # 用wait取得子进程返回值 wait $PID if [[ $? -eq 0 ]]; then echo "sync successful" break else echo "sync failed" ((counter=0)) ((n_retries++)) restart_sync continue fi fi if ((counter > retry_delay)); then ((counter=0)) echo "netspeed low. restart!" ((n_retries++)) restart_sync fi done } _wrap_build reposync "$@"
<reponame>souza-eti-br/souza-crypto package br.eti.souza.crypto; import br.eti.souza.exception.SystemException; /** * Classe utilitária para criptografia usando Base64. * @author <NAME>. */ public final class Base64 { /** * Codificar texto para base64. * @param text Texto. * @return Codificação base64. */ public static String encode(String text) { return java.util.Base64.getEncoder().encodeToString(text.getBytes()); } /** * Decodificar base64 para texto. * @param base64 Base64. * @return Texto decodificados. * @throws SystemException Caso o argumento não seja um esquema Base64 válido. */ public static String decode(String base64) throws SystemException { try { return new String(java.util.Base64.getDecoder().decode(base64)); } catch (IllegalArgumentException e) { throw new SystemException("invalid.scheme.base64", e); } } }
<reponame>icokk/react-native-braintree-xplat<gh_stars>0 package com.pw.droplet.braintree; import android.content.Intent; import android.content.Context; import android.app.Activity; import com.braintreepayments.api.PayPal; import com.braintreepayments.api.PaymentRequest; import com.braintreepayments.api.ThreeDSecure; import com.braintreepayments.api.interfaces.BraintreeErrorListener; import com.braintreepayments.api.models.PayPalRequest; import com.braintreepayments.api.models.PaymentMethodNonce; import com.braintreepayments.api.BraintreePaymentActivity; import com.braintreepayments.api.BraintreeFragment; import com.braintreepayments.api.exceptions.InvalidArgumentException; import com.braintreepayments.api.models.CardBuilder; import com.braintreepayments.api.Card; import com.braintreepayments.api.interfaces.PaymentMethodNonceCreatedListener; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ActivityEventListener; import java.util.Locale; public class Braintree extends ReactContextBaseJavaModule implements ActivityEventListener { private static final int PAYMENT_REQUEST = 1; private String token; private Callback nonceCreatedCallback; private Callback errorCallback; private Context mActivityContext; private BraintreeFragment mBraintreeFragment; public Braintree(ReactApplicationContext reactContext) { super(reactContext); reactContext.addActivityEventListener(this); } @Override public String getName() { return "Braintree"; } public String getToken() { return this.token; } public void setToken(String token) { this.token = token; } @ReactMethod public void setup(final String token, final Callback successCallback, final Callback errorCallback) { try { this.mBraintreeFragment = BraintreeFragment.newInstance(getCurrentActivity(), token); this.mBraintreeFragment.addListener(new PaymentMethodNonceCreatedListener() { @Override public void onPaymentMethodNonceCreated(PaymentMethodNonce paymentMethodNonce) { nonceCreatedHandler(paymentMethodNonce.getNonce()); } }); this.mBraintreeFragment.addListener(new BraintreeErrorListener() { @Override public void onError(Exception error) { errorHandler(error.getMessage()); } }); this.setToken(token); successCallback.invoke(this.getToken()); } catch (InvalidArgumentException e) { errorCallback.invoke(e.getMessage()); } } private void nonceCreatedHandler(String nonce) { if ( this.nonceCreatedCallback != null ) this.nonceCreatedCallback.invoke(nonce); } private void errorHandler(Object errorMessage) { if ( this.errorCallback != null ) this.errorCallback.invoke(errorMessage); } @ReactMethod public void getCardNonce(final String cardNumber, final String expirationMonth, final String expirationYear, final Callback successCallback, final Callback errorCallback) { try { this.nonceCreatedCallback = successCallback; this.errorCallback = errorCallback; CardBuilder cardBuilder = new CardBuilder() .cardNumber(cardNumber) .expirationMonth(expirationMonth) .expirationYear(expirationYear); Card.tokenize(this.mBraintreeFragment, cardBuilder); } catch (Exception e) { errorCallback.invoke(e.getMessage()); } } @ReactMethod public void paymentRequest(final Callback successCallback, final Callback errorCallback) { try { this.nonceCreatedCallback = successCallback; this.errorCallback = errorCallback; PaymentRequest paymentRequest = new PaymentRequest() .clientToken(this.getToken()); Activity currentActivity = getCurrentActivity(); if ( currentActivity != null ) { currentActivity.startActivityForResult( paymentRequest.getIntent(currentActivity), PAYMENT_REQUEST ); } } catch (Exception e) { errorCallback.invoke(e.getMessage()); } } @Override public void onActivityResult(Activity activity, final int requestCode, final int resultCode, final Intent data) { if (requestCode == PAYMENT_REQUEST) { switch (resultCode) { case Activity.RESULT_OK: PaymentMethodNonce paymentMethodNonce = data.getParcelableExtra( BraintreePaymentActivity.EXTRA_PAYMENT_METHOD_NONCE ); this.nonceCreatedHandler(paymentMethodNonce.getNonce()); break; case BraintreePaymentActivity.BRAINTREE_RESULT_DEVELOPER_ERROR: case BraintreePaymentActivity.BRAINTREE_RESULT_SERVER_ERROR: case BraintreePaymentActivity.BRAINTREE_RESULT_SERVER_UNAVAILABLE: this.errorHandler( data.getSerializableExtra(BraintreePaymentActivity.EXTRA_ERROR_MESSAGE) ); break; default: break; } } } // necessary for react-native 0.31 public void onNewIntent(Intent intent) { } @ReactMethod public void verify3DSecure(String paymentNonce, double amount, final Callback successCallback, final Callback errorCallback) { try { this.nonceCreatedCallback = successCallback; this.errorCallback = errorCallback; String amountStr = String.format(Locale.US, "%.2f", amount); ThreeDSecure.performVerification(mBraintreeFragment, paymentNonce, amountStr); } catch (Exception e) { errorCallback.invoke(e.getMessage()); } } @ReactMethod public void tokenizeCardAndVerify(String cardNumber, String expirationMonth, String expirationYear, String cvv, double amount, boolean verify, final Callback successCallback, final Callback errorCallback) { try { this.nonceCreatedCallback = successCallback; this.errorCallback = errorCallback; CardBuilder cardBuilder = new CardBuilder() .cardNumber(cardNumber) .expirationMonth(expirationMonth) .expirationYear(expirationYear) .cvv(cvv); if ( verify ) { String amountStr = String.format(Locale.US, "%.2f", amount); ThreeDSecure.performVerification(this.mBraintreeFragment, cardBuilder, amountStr); } else { Card.tokenize(this.mBraintreeFragment, cardBuilder); } } catch (Exception e) { errorCallback.invoke(e.getMessage()); } } @ReactMethod public void payWithPayPal(double amount, String currency, final Callback successCallback, final Callback errorCallback) { try { this.nonceCreatedCallback = successCallback; this.errorCallback = errorCallback; String amountStr = String.format(Locale.US, "%.2f", amount); PayPalRequest request = new PayPalRequest(amountStr) .currencyCode(currency); PayPal.requestOneTimePayment(mBraintreeFragment, request); } catch (Exception e) { errorCallback.invoke(e.getMessage()); } } }
class Item { public $item; public function __construct($item) { $this->item = $item; } public function searchDatabase() { $db = new mysqli('localhost', 'my_user', 'my_password', 'my_db'); if (mysqli_connect_errno()) { return 'Connection failed.'; } $sql = "SELECT * FROM items WHERE item = '$this->item'"; $result = $db->query($sql); if ($result->num_rows > 0) { return 'Item found.' } else { return 'Item not found.'; } } } $item = new Item("Jeans"); echo $item->searchDatabase();
#!/bin/bash unameOut="$(uname -s)" platform="" case "${unameOut}" in Linux*) platform=Linux;; Darwin*) platform=Mac;; *) platform="UNSUPPORTED:${unameOut}" esac echo "Attempting to mount EFI folder..." read -p "Enter the disk identifier for EFI partition (e.g. disk0s1, sdb1, etc): " disk_id esp_path="" if [ "$platform" == "Linux" ]; then esp_path="/mnt/ESP" elif [ "$platform" == "Mac" ]; then esp_path="/Volumes/ESP" else echo "Unsupported platform! Use a Mac or Linux machine!" exit 1 fi mkdir -p "${esp_path}" mount -t msdos "/dev/${disk_id}" "${esp_path}" rsync -avz --progress EFI "${esp_path}/"
<filename>python/modules/kivydd/widgets/light_button.py # The MIT license: # # Copyright 2017 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and # to permit persons to whom the Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or substantial portions of # the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO # THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # Note: The DeepDriving project on this repository is derived from the DeepDriving project devloped by the princeton # university (http://deepdriving.cs.princeton.edu/). The above license only applies to the parts of the code, which # were not a derivative of the original DeepDriving project. For the derived parts, the original license and # copyright is still valid. Keep this in mind, when using code from this project. import kivy from kivy.uix.button import Button from kivy.lang import Builder from kivy.properties import StringProperty import os _CURRENT_SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__)) kivy.resources.resource_add_path(_CURRENT_SCRIPT_PATH) Builder.load_string(""" <LightButton>: Image: source: self.parent._CurrentImage size: (14, 14) y: self.parent.y + self.parent.height / 2 - self.height / 2 x: self.parent.x + self.width / 2 """) class LightButton(Button): _IsOn = False _CurrentImage = StringProperty("light_off.png") def __init__(self, **kwargs): self.register_event_type('on_enable') self.register_event_type('on_disable') super().__init__(**kwargs) self.bind(on_press=self.onPressed) self._updateLight(self._IsOn) kivy.clock.Clock.schedule_once(self._updateLight, 0) def onPressed(self, Instance): self._IsOn = not self._IsOn self._updateLight(self._IsOn) def _updateLight(self, *args): if self._IsOn: self._CurrentImage = "light_on.png" self.dispatch('on_enable', self._IsOn) else: self._CurrentImage = "light_off.png" self.dispatch('on_disable', self._IsOn) def on_enable(self, *args): pass def on_disable(self, *args): pass
<filename>arbidex-more-info.js function showHideMoreInfo() { if (typeof window.ABXnodesAdded !== 'undefined') { // If script was executed, clean previous work window.ABXnodesAdded.forEach(node => node.remove()); delete window.ABXnodesAdded; return } window.ABXnodesAdded = [] // Global variable to store added nodes to DOM function createTextNode(text) { let result = document.createElement("span"); result.appendChild(document.createTextNode(text)); window.ABXnodesAdded.push(result); return result } //First, open arbitrage table if is not visible in UI const arbitrageSection = document.querySelector( "main > div > div:nth-child(5)" ); if (arbitrageSection.children.length < 2) { // Lets open table clicking the button arbitrageSection.children[0].click(); } let tables = document.querySelectorAll(".rt-table"); // Overview table const btcRow = tables[0].querySelector(".rt-tbody .rt-tr-group:nth-child(2)"); const ehtRow = tables[0].querySelector(".rt-tbody .rt-tr-group:nth-child(3)"); const btcInArb = Number(btcRow.querySelector(".rt-ar:nth-child(4)").innerText); const ehtInArb = Number(ehtRow.querySelector(".rt-ar:nth-child(4)").innerText); // Arbitrage History table (last one) const arbHistoryTable = tables[tables.length - 1]; // Add table header row title const siblin = arbHistoryTable.querySelector(".rt-thead .rt-th:nth-child(2)"); siblin.insertAdjacentElement("afterend", createTextNode("Total (%)")); const rows = arbHistoryTable.querySelectorAll(".rt-tbody .rt-tr"); // Calculate and add new cell values let currTotal; let ethTotal = ehtInArb; let btcTotal = btcInArb; rows.forEach(row => { let symbol = row.querySelector(":nth-child(2) > span").innerText; let ammount = Number(row.querySelector(":nth-child(3) > span").innerText); let type = row.querySelector(":nth-child(4) > span").innerText; let cellToAppendSiblin = row.querySelector(":nth-child(2)"); currTotal = getCurrentTotal(symbol); if (type === "To Deposit") { ammount *= -1; // Page shows withdraw to deposit as positive numbers, fixing. } let percentage = (ammount / (currTotal - ammount)) * 100; let node = createTextNode(`${currTotal.toFixed(4)} (${percentage.toFixed(4)} %)`) cellToAppendSiblin.insertAdjacentElement("afterend", node); setCurrentTotal(symbol, currTotal - ammount); }); function getCurrentTotal(symbol) { if (symbol == "BTC") { return btcTotal; } return ethTotal; } function setCurrentTotal(symbol, newTotal) { if (symbol == "BTC") { btcTotal = newTotal; } else { ethTotal = newTotal; } } } showHideMoreInfo();
package com.createchance.imageeditor.shaders; import android.opengl.GLES20; /** * Butterfly Wave Scrawler transition shader. * * @author createchance * @date 2018/12/31 */ public class ButterflyWaveScrawlerTransShader extends TransitionMainFragmentShader { private final String TRANS_SHADER = "ButterflyWaveScrawler.glsl"; private final String U_AMPLITUDE = "amplitude"; private final String U_WAVES = "waves"; private final String U_COLOR_SEPARATION = "colorSeparation"; public ButterflyWaveScrawlerTransShader() { initShader(new String[]{TRANSITION_FOLDER + BASE_SHADER, TRANSITION_FOLDER + TRANS_SHADER}, GLES20.GL_FRAGMENT_SHADER); } @Override public void initLocation(int programId) { super.initLocation(programId); addLocation(U_AMPLITUDE, true); addLocation(U_WAVES, true); addLocation(U_COLOR_SEPARATION, true); loadLocation(programId); } public void setUAmplitude(float amplitude) { setUniform(U_AMPLITUDE, amplitude); } public void setUWaves(float waves) { setUniform(U_WAVES, waves); } public void setUColorSeparation(float colorSeparation) { setUniform(U_COLOR_SEPARATION, colorSeparation); } }
export XDK_TARGET_PLATFORM=linux export XDK_TARGET_CPU=x86 if [[ ! "$_ELASTOS64" == "" ]]; then export XDK_TARGET_CPU_ARCH=64 else export XDK_TARGET_CPU_ARCH=32 fi export XDK_COMPILER=gnu #export XDK_TARGET_BOARD=pc #export XDK_TARGET_PRODUCT=devtools export THIRDPART_DEPENDED=$XDK_ROOT/ToolChains/$XDK_TARGET_PLATFORM/Thirdlibrary export XDK_TARGET_FORMAT=elf export LD_LIBRARY_PATH=.:$THIRDPART_DEPENDED/lib
<filename>src/blocks/RecipeCarousel/RecipeCarousel.tsx import React, { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { LazyLoadImage } from 'react-lazy-load-image-component'; import { Link } from 'react-router-dom'; import Box from '@mui/material/Box'; import Typography from '@mui/material/Typography'; import useMediaQuery from '@mui/material/useMediaQuery'; import Button from '@mui/material/Button'; import Skeleton from '@mui/material/Skeleton'; import { useTheme } from '@mui/material/styles'; import Carousel from 'react-multi-carousel'; import 'react-multi-carousel/lib/styles.css'; import './dotClass.css'; import Container from 'components/Container'; import { fetchRecipeList, selectAllRecipes, selectChosenRecipeTitle, selectRecipeListLoading, } from 'redux-toolkit/slices/recipeSlice'; import { RECIPE_SLICE } from 'utils/constants'; const responsive = { desktop: { breakpoint: { max: 3000, min: 900 }, items: 3, slidesToSlide: 3, // optional, default to 1. partialVisibilityGutter: 30, }, tablet: { breakpoint: { max: 900, min: 600 }, items: 2, slidesToSlide: 2, // optional, default to 1. partialVisibilityGutter: 20, }, mobile: { breakpoint: { max: 600, min: 0 }, items: 1, slidesToSlide: 1, // optional, default to 1. partialVisibilityGutter: 40, }, }; interface Props { // eslint-disable-next-line @typescript-eslint/ban-types isHome: boolean; } const RecipeCarousel = ({ isHome }: Props): JSX.Element => { const theme = useTheme(); const dispatch = useDispatch(); const recipes = useSelector(selectAllRecipes); const recipeListLoading = useSelector(selectRecipeListLoading); const chosenRecipeTitle = useSelector(selectChosenRecipeTitle); useEffect(() => { if (recipeListLoading === 'idle') { dispatch(fetchRecipeList()); } }, []); const isMd = useMediaQuery(theme.breakpoints.up('md'), { defaultMatches: true, }); const isSm = useMediaQuery(theme.breakpoints.up('sm'), { defaultMatches: true, }); const recipeFilter = recipes.filter( (item) => item.title !== chosenRecipeTitle, ); function carouselLogic(command: string) { if (command === 'recipes') { return recipeListLoading === 'fulfilled' ? recipes : Array.from(new Array(3)); } else { return recipeListLoading === 'fulfilled' ? recipeFilter : Array.from(new Array(3)); } } return ( <Container> <Box marginBottom={4}> {isHome && ( <Typography variant="h6" data-aos={isMd ? 'fade-up' : 'none'} color="text.primary" align={'center'} gutterBottom sx={{ fontFamily: 'Inter', fontWeight: 500, textTransform: 'uppercase', }} > Recipes </Typography> )} <Typography variant="h3" data-aos={isMd ? 'fade-up' : 'none'} color="text.primary" align={'center'} gutterBottom sx={{ fontWeight: 600, }} > {isHome ? 'Go try this recent recipes!' : 'Try another recipes!'} </Typography> </Box> <Carousel showDots={isSm ? true : false} responsive={responsive} removeArrowOnDeviceType={['tablet', 'mobile']} infinite={true} partialVisible={true} transitionDuration={600} containerClass="react-multi-carousel-list" > {(isHome ? carouselLogic('recipes').slice(0, RECIPE_SLICE) : carouselLogic('recipeFilter').slice(0, RECIPE_SLICE) ).map((item, i) => ( <Box key={i} flexDirection={'column'} m={2}> {item ? ( <Link to={{ pathname: `/recipes/${item.title .toLowerCase() .replaceAll(' ', '-')}`, }} style={{ textDecoration: 'none', color: 'inherit' }} > <Box component={LazyLoadImage} height={1} width={1} src={item.image} alt="..." effect="blur" sx={{ objectFit: 'cover', height: { sm: 330, md: 350, lg: 480, }, borderRadius: 2, }} /> </Link> ) : ( <Skeleton variant={'rectangular'} sx={{ height: { sm: 330, md: 350, lg: 480, }, borderRadius: 2, }} /> )} {item ? ( <Link to={{ pathname: `/recipes/${item.title .toLowerCase() .replaceAll(' ', '-')}`, }} style={{ textDecoration: 'none', color: 'inherit' }} > <Typography color="text.primary" fontWeight={700} variant="h5" sx={{ marginTop: 2, '&:hover': { textDecoration: 'underline', cursor: 'pointer', }, }} > {item.title} </Typography> </Link> ) : ( <Skeleton sx={{ marginTop: 2 }} /> )} </Box> ))} </Carousel> <Box sx={{ display: 'flex', justifyContent: 'center' }}> <Button variant="outlined" color="primary" sx={{ borderRadius: 10, border: 2, borderColor: 'primary.main', my: 2, px: 2, '&:hover': { border: 2, }, }} href="/recipes" > <Typography variant="button" color="text.primary" sx={{ fontFamily: 'Inter', textTransform: 'uppercase', letterSpacing: 1.2, fontWeight: 400, fontSize: { xs: 12, md: 14 }, }} > View All Recipes </Typography> </Button> </Box> </Container> ); }; export default RecipeCarousel;
#!/bin/bash set -e source /home/venv/bin/activate mypy -p autorop
from typing import Any, Optional, Union import jwt from fastapi import Depends, Header from sqlalchemy.orm import Session from app.api.api_v1.router.auth import crud from app.api.api_v1.router.auth import schemas from app.api.db.session import get_db from app.api.models.auth import AdminUser from app.api.utils import customExc from app.config import settings from app.security import security def check_jwt_token( token: Optional[str] = Header(None) ) -> Union[str, Any]: """ 只解析验证token :param token: :return: """ try: payload = jwt.decode( token, settings.SECRET_KEY, algorithms=[security.ALGORITHM] ) return schemas.TokenPayload(**payload) except BaseException: raise customExc.UserTokenError(err_desc="Token 验证失败") def get_current_user( db: Session = Depends(get_db), token: Optional[str] = Header(None) ) -> AdminUser: """ 根据header中token 获取当前用户 :param db: :param token: :return: """ print("这就是Token:", token) if not token: raise customExc.UserTokenError(err_desc='Token 未定义') token_data = check_jwt_token(token) user = crud.curd_user.get(db, id=token_data.sub) if not user: raise customExc.UserNotFound(err_desc="用户未存在") return user # def get_current_active_user( # current_user: models.User = Depends(get_current_user), # ) -> models.User: # if not crud.user.is_active(current_user): # raise HTTPException(status_code=400, detail="Inactive user") # return current_user # # # def get_current_active_superuser( # current_user: models.User = Depends(get_current_user), # ) -> models.User: # if not crud.user.is_superuser(current_user): # raise HTTPException( # status_code=400, detail="The user doesn't have enough privileges" # ) # return current_user
<reponame>songningbo/jdk8source<filename>javafx-src/com/sun/webkit/Utilities.java<gh_stars>1-10 /* * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.webkit; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.HashMap; import java.util.Map; import sun.reflect.misc.MethodUtil; public abstract class Utilities { private static Utilities instance; public static synchronized void setUtilities(Utilities util) { instance = util; } public static synchronized Utilities getUtilities() { return instance; } protected abstract Pasteboard createPasteboard(); protected abstract PopupMenu createPopupMenu(); protected abstract ContextMenu createContextMenu(); private static String fwkGetMIMETypeForExtension(String ext) { return MimeTypeMapHolder.MIME_TYPE_MAP.get(ext); } private static final class MimeTypeMapHolder { private static final Map<String, String> MIME_TYPE_MAP = createMimeTypeMap(); private static Map<String,String> createMimeTypeMap() { Map<String, String> mimeTypeMap = new HashMap<String, String>(21); mimeTypeMap.put("txt", "text/plain"); mimeTypeMap.put("html", "text/html"); mimeTypeMap.put("htm", "text/html"); mimeTypeMap.put("css", "text/css"); mimeTypeMap.put("xml", "text/xml"); mimeTypeMap.put("xsl", "text/xsl"); mimeTypeMap.put("js", "application/x-javascript"); mimeTypeMap.put("xhtml", "application/xhtml+xml"); mimeTypeMap.put("svg", "image/svg+xml"); mimeTypeMap.put("svgz", "image/svg+xml"); mimeTypeMap.put("gif", "image/gif"); mimeTypeMap.put("jpg", "image/jpeg"); mimeTypeMap.put("jpeg", "image/jpeg"); mimeTypeMap.put("png", "image/png"); mimeTypeMap.put("tif", "image/tiff"); mimeTypeMap.put("tiff", "image/tiff"); mimeTypeMap.put("ico", "image/ico"); mimeTypeMap.put("cur", "image/ico"); mimeTypeMap.put("bmp", "image/bmp"); mimeTypeMap.put("mp3", "audio/mpeg"); return mimeTypeMap; } } private static Object fwkInvokeWithContext(final Method method, final Object instance, final Object[] args, AccessControlContext acc) throws Throwable { try { return AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> MethodUtil.invoke(method, instance, args), acc); } catch (PrivilegedActionException ex) { Throwable cause = ex.getCause(); if (cause == null) cause = ex; else if (cause instanceof InvocationTargetException && cause.getCause() != null) cause = cause.getCause(); throw cause; } } }