text
stringlengths
1
1.05M
#!/bin/bash set -e set -x until [ -f /var/lib/docker/certs/client/ca.pem ] do echo "Waiting for /var/lib/docker/certs/client/ca.pem to be available from dind volume" sleep 1 done START_TIME=`date +"%d-%m-%yT%H-%M-%S"` mkdir -pv ~/.docker cp -v /var/lib/docker/certs/client/* ~/.docker touch ./builder-started.txt bash ./scripts/setup_helm.sh bash ./scripts/setup_aws.sh $AWS_ACCESS_KEY $AWS_SECRET $AWS_REGION $CLUSTER_NAME npm run install-projects bash ./scripts/build_docker.sh $RELEASE_NAME $DOCKER_LABEL $PRIVATE_ECR $AWS_REGION npm install -g cli aws-sdk bash ./scripts/publish_ecr.sh $RELEASE_NAME ${TAG}__${START_TIME} $DOCKER_LABEL $PRIVATE_ECR $AWS_REGION bash ./scripts/deploy.sh $RELEASE_NAME ${TAG}__${START_TIME} DEPLOY_TIME=`date +"%d-%m-%yT%H-%M-%S"` if [ $PUBLISH_DOCKERHUB == 'true' ] then bash ./scripts/publish_dockerhub.sh ${TAG}__${START_TIME} $DOCKER_LABEL fi bash ./scripts/cleanup_builder.sh ${TAG}__${START_TIME} $DOCKER_LABEL END_TIME=`date +"%d-%m-%yT%H-%M-%S"` echo "Started build at $START_TIME, deployed image to K8s at $DEPLOY_TIME, ended at $END_TIME" sleep infinity
#!/bin/bash declare -a Containers=( "registry.dev.proneer.co/fastapi:nvidia-11.1-cudnn8-runtime-ubuntu20.04-py39" ) for image in ${Containers[@]}; do echo "------------------------" echo "image: $image" sudo docker container run -p 8000:8000 --rm --gpus all $image done
#!/bin/sh pnpx ncu -iu --packageFile ./package.json pnpx ncu -iu --packageFile ./packages/create/package.json pnpx ncu -iu --packageFile ./packages/web-widget-web-server-utils/package.json pnpx ncu -iu --packageFile ./packages/web-widget-welcome/package.json pnpx ncu -iu --packageFile ./packages/ts-config-web-widget/package.json pnpx ncu -iu --packageFile ./packages/webpack-config-web-widget/package.json pnpx ncu -iu --packageFile ./packages/webpack-config-web-widget-react/package.json pnpx ncu -iu --packageFile ./packages/webpack-config-web-widget-react-ts/package.json pnpx ncu -iu --packageFile ./packages/webpack-config-web-widget-ts/package.json # generator-web-widget has a bunch of nested package jsons pnpx ncu -iu --packageFile ./packages/generator-web-widget/package.json pnpx ncu -iu --packageFile ./packages/generator-web-widget/src/common-templates/typescript/react.package.json pnpx ncu -iu --packageFile ./packages/generator-web-widget/src/common-templates/typescript/typescript.package.json pnpx ncu -iu --packageFile ./packages/generator-web-widget/src/react/templates/react.package.json pnpx ncu -iu --packageFile ./packages/generator-web-widget/src/react/templates/typescript/typescript-react.package.json pnpx ncu -iu --packageFile ./packages/generator-web-widget/src/root-config/templates/root-config.package.json pnpx ncu -iu --packageFile ./packages/generator-web-widget/src/root-config/templates/root-config-layout.package.json pnpx ncu -iu --packageFile ./packages/generator-web-widget/src/svelte/templates/svelte.package.json pnpx ncu -iu --packageFile ./packages/generator-web-widget/src/util-module/templates/util-module.package.json
#! /bin/csh rm -f varying/flows* varying/tmp* varying/dropRate* varying/data* ns red-pd.tcl one netMix Varying testUnresp 0 period 1 plotq 0 time 360 verbose 5 > tmp.Off mv one.netMix.Varying.1.flows flows.Off awk '{if ($4==10) {bw = 8*($6 - old)/1000000; print $2, bw; old=$6}}' flows.Off > bw.Off grep curr tmp.Off | awk '{if ($2=="(0)") print $1, $4*100, $6*100}' > dropRate.Off ns red-pd.tcl one netMix Varying period 1 plotq 0 time 360 verbose 5 > tmp.On mv one.netMix.Varying.1.flows flows.On awk '{if ($4==10) {bw = 8*($6 - old)/1000000; print $2, bw; old=$6}}' flows.On > bw.On grep curr tmp.On | awk '{if ($2=="(0)") print $1, $4*100, $6*100}' > dropRate.On grep curr tmp.On | awk '{if ($2=="(0)") { sum1+=$11; sum2+=$13}} END {dr=sum1/sum2; frp = sqrt(1.5)/(0.040*sqrt(dr)); sendrate=(8000*frp)/1000000; print 0, sendrate; print 400, sendrate;}' > dropRate.overall mv flows.* tmp.* bw.* dropRate.* varying cd varying gnuplot varying.gp gv varying.ps & gv varying_On.ps & gv varying-dropRate-On.ps & gv varying-dropRate-Off.ps & cd ..
#!/bin/bash echo "Running 5 runs, no learning rate" sh scripts/downstream_cnn/outcomes/pg5/no_lr_schedule/pod8/run1.sh sh scripts/downstream_cnn/outcomes/pg5/no_lr_schedule/pod8/run2.sh sh scripts/downstream_cnn/outcomes/pg5/no_lr_schedule/pod8/run3.sh sh scripts/downstream_cnn/outcomes/pg5/no_lr_schedule/pod8/run4.sh sh scripts/downstream_cnn/outcomes/pg5/no_lr_schedule/pod8/run5.sh python scripts/downstream_cnn/outcomes/pg5/no_lr_schedule/pod8/collect_results.py
package io.github.rcarlosdasilva.weixin.api.weixin; import java.util.List; import io.github.rcarlosdasilva.weixin.common.dictionary.Language; import io.github.rcarlosdasilva.weixin.model.response.user.BlackListQueryResponse; import io.github.rcarlosdasilva.weixin.model.response.user.UserOpenIdListResponse; import io.github.rcarlosdasilva.weixin.model.response.user.UserResponse; import io.github.rcarlosdasilva.weixin.model.response.user.bean.User; /** * 公众号用户相关API * * @author <a href="mailto:<EMAIL>"><NAME></a> */ public interface UserApi { /** * 设置用户备注名. * * <p> * 开发者可以通过该接口对指定用户设置备注名,该接口暂时开放给微信认证的服务号 * * @param openId * OpenId * @param name * 新的备注名,长度必须小于30字符 * @return 是否成功 * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140838&token=&lang=zh_CN" * >设置用户备注名</a> */ boolean remarkName(String openId, String name); /** * 获取用户信息. * * @param openId * OpenId * @return {@link UserResponse} 用户信息 * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839&token=&lang=zh_CN" * >获取用户基本信息(UnionID机制)</a> */ User getUserInfo(String openId); /** * 批量获取用户信息. * * @param openIds * OpenId列表 * @return {@link UserResponse} 用户信息列表 * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839&token=&lang=zh_CN" * >获取用户基本信息(UnionID机制)</a> */ List<User> getUsersInfo(List<String> openIds); /** * 获取用户信息. * * @param openId * OpenId * @param language * 语言 * @return {@link UserResponse} 用户信息 * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839&token=&lang=zh_CN" * >获取用户基本信息(UnionID机制)</a> */ User getUserInfo(String openId, Language language); /** * 批量获取用户信息. * * @param openIds * OpenId列表 * @param language * 语言 * @return {@link UserResponse} 用户信息列表 * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839&token=&lang=zh_CN" * >获取用户基本信息(UnionID机制)</a> */ List<User> getUsersInfo(List<String> openIds, Language language); /** * 获取公众号的关注者列表. * * <p> * 关注者列表由一串OpenID(加密后的微信号,每个用户对每个公众号的OpenID是唯一的)组成。 * 一次拉取调用最多拉取10000个关注者的OpenID,可以通过多次拉取的方式来满足需求。 * * @return {@link UserOpenIdListResponse} 列表信息 * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140840&token=&lang=zh_CN" * >获取用户列表</a> */ UserOpenIdListResponse listAllUsersOpenId(); /** * 获取公众号的关注者列表. * * <p> * 关注者列表由一串OpenID(加密后的微信号,每个用户对每个公众号的OpenID是唯一的)组成。 * 一次拉取调用最多拉取10000个关注者的OpenID,可以通过多次拉取的方式来满足需求。 * * @param nextOpenId * 第一个拉取的OPENID,不填默认从头开始拉取 * @return {@link UserOpenIdListResponse} 列表信息 * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140840&token=&lang=zh_CN" * >获取用户列表</a> */ UserOpenIdListResponse listAllUsersOpenId(String nextOpenId); /** * 网页授权,拉取用户信息(需scope为 snsapi_userinfo). * * <p> * 通过网页授权获取的access_token,获取用户信息(用户不需要关注公众号,只要授权即可) * * @param accessToken * 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同 * @param openId * OpenId * @return {@link UserResponse} 用户信息 * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842&token=&lang=zh_CN" * >拉取用户信息</a> */ User getUserInfoByWebAuthorize(String accessToken, String openId); /** * 获取标签下粉丝列表. * * @param tagId * 标签id * @return {@link UserOpenIdListResponse} 列表信息 * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp<PASSWORD>&token=&lang=zh_CN" * >用户标签管理</a> */ UserOpenIdListResponse listUsersOpenIdWithTag(int tagId); /** * 获取标签下粉丝列表. * * @param tagId * 标签id * @param nextOpenId * 第一个拉取的OPENID,不填默认从头开始拉取 * @return {@link UserOpenIdListResponse} 列表信息 * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN" * >用户标签管理</a> */ UserOpenIdListResponse listUsersOpenIdWithTag(int tagId, String nextOpenId); /** * 获取黑名单中的用户列表. * * <p> * 公众号可通过该接口来获取帐号的黑名单列表,黑名单列表由一串 OpenID(加密后的微信号,每个用户对每个公众号的OpenID是唯一的)组成。 * 该接口每次调用最多可拉取 10000 个OpenID,当列表数较多时,可以通过多次拉取的方式来满足需求。 * * @return {@link BlackListQueryResponse} * @deprecated use {@link #listUsersInBlack()} * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1471422259_pJMWA&token=&lang=zh_CN">黑名单管理</a> */ @Deprecated BlackListQueryResponse listUsersInBlackList(); /** * 获取黑名单中的用户列表. * * <p> * 公众号可通过该接口来获取帐号的黑名单列表,黑名单列表由一串 OpenID(加密后的微信号,每个用户对每个公众号的OpenID是唯一的)组成。 * 该接口每次调用最多可拉取 10000 个OpenID,当列表数较多时,可以通过多次拉取的方式来满足需求。 * * @return {@link BlackListQueryResponse} * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1471422259_pJMWA&token=&lang=zh_CN">黑名单管理</a> */ BlackListQueryResponse listUsersInBlack(); /** * 获取黑名单中的用户列表. * * <p> * 公众号可通过该接口来获取帐号的黑名单列表,黑名单列表由一串 OpenID(加密后的微信号,每个用户对每个公众号的OpenID是唯一的)组成。 * 该接口每次调用最多可拉取 10000 个OpenID,当列表数较多时,可以通过多次拉取的方式来满足需求。 * * @param beginOpenId * 当 begin_openid 为空时,默认从开头拉取 * @return {@link BlackListQueryResponse} * @deprecated user {@link #listUsersInBlack(String)} * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1471422259_pJMWA&token=&lang=zh_CN">黑名单管理</a> */ @Deprecated BlackListQueryResponse listUsersInBlackList(String beginOpenId); /** * 获取黑名单中的用户列表. * * <p> * 公众号可通过该接口来获取帐号的黑名单列表,黑名单列表由一串 OpenID(加密后的微信号,每个用户对每个公众号的OpenID是唯一的)组成。 * 该接口每次调用最多可拉取 10000 个OpenID,当列表数较多时,可以通过多次拉取的方式来满足需求。 * * @param beginOpenId * 当 begin_openid 为空时,默认从开头拉取 * @return {@link BlackListQueryResponse} * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1471422259_pJMWA&token=&lang=zh_CN">黑名单管理</a> */ BlackListQueryResponse listUsersInBlack(String beginOpenId); /** * 把用户拉黑. * * @param openIds * 需要拉入黑名单的用户的openid,一次拉黑最多允许20个 * @return 成功 * @deprecated user {@link #appendUsersToBlack(List)} * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1471422259_pJMWA&token=&lang=zh_CN">黑名单管理</a> */ @Deprecated boolean appendUsersToBlackList(List<String> openIds); /** * 把用户拉黑. * * @param openIds * 需要拉入黑名单的用户的openid,一次拉黑最多允许20个 * @return 成功 * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1471422259_pJMWA&token=&lang=zh_CN">黑名单管理</a> */ boolean appendUsersToBlack(List<String> openIds); /** * 取消拉黑用户. * * @param openIds * 需要取消拉黑名单的用户的openid,一次拉黑最多允许20个 * @return 成功 * @deprecated use {@link #cancelUsersFromBlack(List)} * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1471422259_pJMWA&token=&lang=zh_CN">黑名单管理</a> */ @Deprecated boolean cancelUsersFromBlackList(List<String> openIds); /** * 取消拉黑用户. * * @param openIds * 需要取消拉黑名单的用户的openid,一次拉黑最多允许20个 * @return 成功 * @see <a href= * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1471422259_pJMWA&token=&lang=zh_CN">黑名单管理</a> */ boolean cancelUsersFromBlack(List<String> openIds); }
package net.woaf.jono.phonehome import akka.actor.{ Props, ActorSystem } import com.typesafe.scalalogging.StrictLogging final case class Config(firebaseUrl: String = "", nestToken: String = "", hosts: Seq[String] = Seq(), interface: String = "") object Main extends App with StrictLogging { val parser = new scopt.OptionParser[Config]("phone-is-home") { head("phone-is-home", "0.1") opt[String]('f', "firebase") required () valueName "<url>" action { (x, c) => c.copy(firebaseUrl = x) } text "firebase URL" opt[String]('t', "token") required () valueName "<token>" action { (x, c) => c.copy(nestToken = x) } text "nest API token" opt[Seq[String]]('h', "hosts") valueName "<host>,<host>..." action { (x, c) => c.copy(hosts = x) } text "hosts to monitor" opt[String]('i', "interface") valueName "<interface>" action { (x, c) => c.copy(interface = x) } text "Linux network interface to ping from" help("help") } // parser.parse returns Option[C] parser.parse(args, Config()) match { case Some(config) => // create a top level actor to connect the Nest API with the Twitter REST and Streaming APIs logger.info("Starting up actor system") val system = ActorSystem("mySystem") system.actorOf(Props(new AwayMonitoringActor(config.nestToken, config.firebaseUrl, config.hosts, config.interface))) case None => // arguments are bad, error message will have been displayed } }
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+512+512-N-VB-fill/13-model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+512+512-N-VB-fill/13-1024+0+512-STWS-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function shuffle_trigrams_within_sentences_first_two_thirds_sixth --eval_function last_sixth_eval
<gh_stars>0 import { PlaylistCompact, VideoCompact, Channel } from "."; import { YoutubeRawData } from "../common"; interface VideoAttributes { id: string; title: string; duration: number | null; thumbnail: string; description: string; channel: Channel; uploadDate: string; viewCount: number | null; likeCount: number | null; dislikeCount: number | null; isLiveContent: boolean; tags: string[]; upNext: VideoCompact | PlaylistCompact; related: (VideoCompact | PlaylistCompact)[]; } /** * Represent a Video */ export default class Video implements VideoAttributes { id: string; title: string; duration: number | null; thumbnail: string; description: string; channel: Channel; uploadDate: string; viewCount: number | null; likeCount: number | null; dislikeCount: number | null; isLiveContent: boolean; tags: string[]; upNext: VideoCompact | PlaylistCompact; related: (VideoCompact | PlaylistCompact)[]; constructor(video?: Partial<VideoAttributes>); /** * Load instance attributes from youtube raw data * * @param youtubeRawData raw object from youtubei */ load(youtubeRawData: YoutubeRawData): Video; } export {};
<reponame>CesarRamosA/restaurantdb_and_sololearn_mysql<filename>restaurantdb/restaurant.sql -- ------------------------------------------------------------- -- TablePlus 2.3(222) -- -- https://tableplus.com/ -- -- Database: restaurant -- Generation Time: 2019-05-06 12:51:15.3060 -- ------------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; DROP TABLE IF EXISTS `categoria`; CREATE TABLE `categoria` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nombre` varchar(60) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; DROP TABLE IF EXISTS `platillos`; CREATE TABLE `platillos` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nombre` varchar(60) DEFAULT NULL, `precio` float DEFAULT NULL, `disponible` tinyint(1) DEFAULT NULL, `categoriaId` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`), KEY `categoriaId` (`categoriaId`), CONSTRAINT `platillos_ibfk_1` FOREIGN KEY (`categoriaId`) REFERENCES `categoria` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; DROP TABLE IF EXISTS `reservaciones`; CREATE TABLE `reservaciones` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nombre` varchar(60) NOT NULL, `apellido` varchar(60) NOT NULL, `hora` time DEFAULT NULL, `fecha` date DEFAULT NULL, `cantidadmesa` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; INSERT INTO `categoria` (`id`, `nombre`) VALUES ('1', 'Desayunos'), ('2', 'Comida'), ('3', 'Bebidas'), ('4', 'Bebidas con Alcohol'), ('5', 'Postres'), ('6', 'Ensaladas'); INSERT INTO `platillos` (`id`, `nombre`, `precio`, `disponible`, `categoriaId`) VALUES ('1', 'Pastel de Chocolate', '89', '1', '5'), ('2', '400g de Rib Eye', '199', '1', '2'), ('3', 'Refresco', '25', '1', '3'), ('4', 'Café Americano', '35', '1', '3'), ('5', 'Tequila', '89', '1', '4'), ('6', 'Vodka con Jugo', '119', '1', '4'), ('7', 'Hot Cakes (3)', '119', '1', '1'), ('8', 'Omellete', '89', '0', '1'), ('9', 'Pastel de Zanahoria', '89', '0', '5'), ('10', 'Rol de Canela', '69', '1', '5'), ('11', 'A<NAME> Naranja', '79', '1', '3'), ('12', 'Chuletas de Cerdo', '179', '1', '2'), ('13', 'Costillas BBQ', '189', '1', '2'), ('14', 'Huevo al Gusto', '49', '1', '1'), ('15', 'Omellete <NAME> y <NAME>', '79', '1', '1'), ('16', '<NAME>', '49', '0', '3'), ('17', '<NAME>', '49', '1', '3'), ('18', '<NAME>', '49', '1', '3'), ('19', 'Ensalada Violeta', '89', '1', '6'), ('20', 'Ensalada de Higo', '89', '1', '6'), ('21', 'Ensalada Cesar', '89', '0', '6'), ('22', 'Club Sandwich', '99', '1', '1'), ('23', 'Sandwich Salami', '119', '1', '1'), ('24', 'Filete de Pescado Róbalo', '179', '0', '2'), ('25', 'Filete de Atún ', '179', '1', '2'), ('26', 'Milanesa de Pollo', '149', '1', '2'), ('27', '<NAME>', '199', '1', '2'), ('28', '<NAME>', '45', '1', '3'), ('29', 'C<NAME>', '50', '1', '3'), ('30', 'Café Expresso', '25', '1', '3'), ('31', 'Vino Tinto Francia', '89', '0', '4'), ('32', 'Vino Tinto Chile', '89', '1', '4'), ('33', 'Vino Tinto México', '89', '1', '4'), ('34', 'Vino Tinto España', '89', '0', '4'), ('35', 'Vino Tinto Argentina', '89', '1', '4'); INSERT INTO `reservaciones` (`id`, `nombre`, `apellido`, `hora`, `fecha`, `cantidadmesa`) VALUES ('1', 'Juan', 'De la torre', '10:30:00', '2019-06-28', '3'), ('2', 'Antonio', 'Hernandez', '14:00:00', '2019-07-30', '2'), ('3', 'Pedro', 'Juarez', '20:00:00', '2019-06-25', '5'), ('4', 'Mireya', 'Perez', '19:00:00', '2019-06-25', '2'), ('5', 'Jose', 'Castillo', '14:00:00', '2019-07-30', '3'), ('6', 'Maria', 'Diaz', '14:30:00', '2019-06-25', '2'), ('7', 'Clara', 'Duran', '10:00:00', '2019-07-01', '3'), ('8', 'Miriam', 'Ibañez', '09:00:00', '2019-07-01', '3'), ('9', 'Samuel ', 'Reyes', '10:00:00', '2019-07-02', '2'), ('10', 'Joaquin', 'Muñoz', '19:00:00', '2019-06-28', '3'), ('11', 'Julia', 'Lopez', '08:00:00', '2019-06-25', '3'), ('12', 'Carmen', 'Ruiz', '20:00:00', '2019-07-01', '4'), ('13', 'Isaac', 'Sala', '09:00:00', '2019-07-30', '3'), ('14', 'Ana', 'Preciado', '14:30:00', '2019-06-28', '4'), ('15', 'Sergio', 'Iglesias', '10:00:00', '2019-07-02', '2'), ('16', 'Aina', 'Acosta', '14:00:00', '2019-07-30', '3'), ('17', 'Carlos', 'Ortiz', '20:00:00', '2019-06-25', '2'), ('18', 'Roberto', 'Serrano', '10:00:00', '2019-07-30', '4'), ('19', 'Carlota', 'Perez', '14:00:00', '2019-07-01', '2'), ('20', '<NAME>', 'Igleias', '14:00:00', '2019-07-02', '2'), ('21', 'Jaime', 'Jimenez', '14:00:00', '2019-07-01', '4'), ('22', 'Roberto ', 'Torres', '10:00:00', '2019-07-02', '3'), ('23', 'Juan', 'Cano', '09:00:00', '2019-07-02', '5'), ('24', 'Santiago', 'Hernandez', '19:00:00', '2019-06-28', '5'), ('25', 'Berta', 'Gomez', '09:00:00', '2019-07-01', '3'), ('26', 'Miriam', 'Dominguez', '19:00:00', '2019-06-28', '3'), ('27', 'Antonio', 'Castro', '14:30:00', '2019-07-02', '2'), ('28', 'Hugo', 'Alonso', '09:00:00', '2019-06-28', '2'), ('29', 'Victoria', 'Perez', '10:00:00', '2019-07-02', '1'), ('30', 'Jimena', 'Leon', '10:30:00', '2019-07-30', '2'), ('31', 'Raquel ', 'Peña', '20:30:00', '2019-06-25', '3'); /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
let facade = require('gamecloud') let {EntityType} = facade.const /** * 聊天接口类 * updated by liub 2017.5.17 */ class chat extends facade.Control { constructor(core){ super(core); } /** * @brief 报文编号 102001:聊天室操作相关报文 * * @date 2016.10.12 * * @param {UserEntity} user * @param : * 名称 | 类型 | 描述 * ------------|----------|-------------------- * n | int | 接收者ID * c | string | 聊天内容 * * @return * 名称 | 类型 | 描述 * ------------|----------|---------------------- * .msg | object | 消息体 * ..mid | int | 消息编号 * ..s | string | 发送者名称 * ..sid | int | 发送者ID * ..n | string | 接收者名称 * ..nid | int | 接收者ID * ..c | string | 聊天内容 * * @note */ async sendChat(user, objData) { if(!!objData.oemInfo){ delete objData.oemInfo; } //填充源用户信息 objData.sid = user.id; objData.s = user.name; if (!!objData.nid) { //判断是私聊 let simUser = this.core.GetObject(EntityType.User, objData.nid); //获取缓存对象 if (!!simUser) { objData.nid = simUser.id; objData.n = simUser.name; simUser.privateChatMgr.Record(objData); user.privateChatMgr.Record(objData); } } else { if(!!objData.system){ this.core.service.chat.Record(objData); } else {//公聊 if (objData.c != '') { this.core.service.chat.Record(objData); } } } } } exports = module.exports = chat;
// Use the shorthand character class \W to count the number of non-alphanumeric // characters in various quotes and strings. // (1) Your regex should use the global flag. // (2) Your regex should find 6 non-alphanumeric characters // in "The five boxing wizards jump quickly.". // (3) Your regex should use the shorthand character to match characters which // are non-alphanumeric. // (4) Your regex should find 8 non-alphanumeric characters // in "Pack my box with five dozen liquor jugs." // (5) Your regex should find 6 non-alphanumeric characters // in "How vexingly quick daft zebras jump!" // (6) Your regex should find 12 non-alphanumeric characters // in "123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ." let firstQuoteSample = "The five boxing wizards jump quickly."; let secondQuoteSample = "Pack my box with five dozen liquor jugs."; let thirdQuoteSample = "How vexingly quick daft zebras jump!"; let forthQuoteSample = "123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ."; let nonAlphabetRegex = /\W+/g; // Change this line console.log(firstQuoteSample.match(nonAlphabetRegex).length); // 6 console.log(secondQuoteSample.match(nonAlphabetRegex).length); // 8 console.log(thirdQuoteSample.match(nonAlphabetRegex).length); // 6 console.log(forthQuoteSample.match(nonAlphabetRegex).length); // 12
<gh_stars>0 """Tests for TAPQueryRunner.""" from __future__ import annotations from typing import TYPE_CHECKING from unittest.mock import ANY, patch import pytest import pyvo from tests.support.gafaelfawr import mock_gafaelfawr from tests.support.util import wait_for_business if TYPE_CHECKING: from aioresponses import aioresponses from httpx import AsyncClient from tests.support.slack import MockSlack @pytest.mark.asyncio async def test_run( client: AsyncClient, mock_aioresponses: aioresponses ) -> None: mock_gafaelfawr(mock_aioresponses) with patch.object(pyvo.dal, "TAPService"): r = await client.put( "/mobu/flocks", json={ "name": "test", "count": 1, "user_spec": { "username_prefix": "testuser", "uid_start": 1000, }, "scopes": ["exec:notebook"], "business": "TAPQueryRunner", }, ) assert r.status_code == 201 # Wait until we've finished at least one loop and check the results. data = await wait_for_business(client, "testuser1") assert data == { "name": "testuser1", "business": { "failure_count": 0, "name": "TAPQueryRunner", "success_count": 1, "timings": ANY, }, "restart": False, "state": "RUNNING", "user": { "scopes": ["exec:notebook"], "token": ANY, "uidnumber": 1000, "username": "testuser1", }, } # Get the log and check that we logged the query. r = await client.get("/mobu/flocks/test/monkeys/testuser1/log") assert r.status_code == 200 assert "Running: " in r.text assert "Query finished after " in r.text @pytest.mark.asyncio async def test_alert( client: AsyncClient, slack: MockSlack, mock_aioresponses: aioresponses ) -> None: mock_gafaelfawr(mock_aioresponses) with patch.object(pyvo.dal, "TAPService") as mock: mock.return_value.search.side_effect = [Exception("some error")] r = await client.put( "/mobu/flocks", json={ "name": "test", "count": 1, "user_spec": { "username_prefix": "testuser", "uid_start": 1000, }, "scopes": ["exec:notebook"], "business": "TAPQueryRunner", }, ) assert r.status_code == 201 # Wait until we've finished at least one loop and check the results. data = await wait_for_business(client, "testuser1") assert data["business"]["failure_count"] == 1 assert slack.alerts == [ { "blocks": [ { "type": "section", "text": { "type": "mrkdwn", "text": "Error while running TAP query", }, }, { "type": "section", "fields": [ {"type": "mrkdwn", "text": ANY}, {"type": "mrkdwn", "text": ANY}, {"type": "mrkdwn", "text": "*User*\ntestuser1"}, {"type": "mrkdwn", "text": "*Event*\nexecute_query"}, ], }, ], "attachments": [ { "blocks": [ { "type": "section", "text": { "type": "mrkdwn", "text": ( "*Error*\n" "```\nException: some error\n```" ), "verbatim": True, }, }, { "type": "section", "text": { "type": "mrkdwn", "text": ANY, "verbatim": True, }, }, ] } ], } ]
sudo wget -O calendar_50.csv.gz "http://data.insideairbnb.com/united-states/ny/new-york-city/2019-05-03/data/calendar.csv.gz" gunzip calendar_50.csv.gz aws s3 cp calendar_50.csv s3://edenbucket rm calendar_50.csv sudo wget -O calendar_51.csv.gz "http://data.insideairbnb.com/united-states/ny/new-york-city/2019-06-02/data/calendar.csv.gz" gunzip calendar_51.csv.gz aws s3 cp calendar_51.csv s3://edenbucket rm calendar_51.csv sudo wget -O calendar_52.csv.gz "http://data.insideairbnb.com/united-states/ny/new-york-city/2019-07-08/data/calendar.csv.gz" gunzip calendar_52.csv.gz aws s3 cp calendar_52.csv s3://edenbucket rm calendar_52.csv sudo wget -O calendar_53.csv.gz "http://data.insideairbnb.com/united-states/ny/new-york-city/2019-08-06/data/calendar.csv.gz" gunzip calendar_53.csv.gz aws s3 cp calendar_53.csv s3://edenbucket rm calendar_53.csv sudo wget -O calendar_54.csv.gz "http://data.insideairbnb.com/united-states/ny/new-york-city/2019-09-12/data/calendar.csv.gz" gunzip calendar_54.csv.gz aws s3 cp calendar_54.csv s3://edenbucket rm calendar_54.csv sudo wget -O calendar_55.csv.gz "http://data.insideairbnb.com/united-states/ny/new-york-city/2019-10-14/data/calendar.csv.gz" gunzip calendar_55.csv.gz aws s3 cp calendar_55.csv s3://edenbucket rm calendar_55.csv sudo wget -O calendar_56.csv.gz "http://data.insideairbnb.com/united-states/ny/new-york-city/2019-11-01/data/calendar.csv.gz" gunzip calendar_56.csv.gz aws s3 cp calendar_56.csv s3://edenbucket rm calendar_56.csv sudo wget -O calendar_57.csv.gz "http://data.insideairbnb.com/united-states/ny/new-york-city/2019-12-04/data/calendar.csv.gz" gunzip calendar_57.csv.gz aws s3 cp calendar_57.csv s3://edenbucket rm calendar_57.csv sudo wget -O calendar_58.csv.gz "http://data.insideairbnb.com/united-states/ny/new-york-city/2020-01-03/data/calendar.csv.gz" gunzip calendar_58.csv.gz aws s3 cp calendar_58.csv s3://edenbucket rm calendar_58.csv sudo wget -O calendar_59.csv.gz "http://data.insideairbnb.com/united-states/ny/new-york-city/2020-02-12/data/calendar.csv.gz" gunzip calendar_59.csv.gz aws s3 cp calendar_59.csv s3://edenbucket rm calendar_59.csv
import numpy as np def heaviside(x, a=0): return 1 if x >= a else 0 def higham_polynomial(eigs, lambda_val): n = len(eigs) result = 0 for j in range(n): result += (lambda_val - eigs[j]) ** j return result
#!/bin/sh set -e echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # use filter instead of exclude so missing patterns dont' throw errors echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements \"$1\"" /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements "$1" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current file archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" stripped="" for arch in $archs; do if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "Pods/Bolts.framework" install_framework "Pods/Flurry_iOS_SDK.framework" install_framework "Pods/Parse.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "Pods/Bolts.framework" install_framework "Pods/Flurry_iOS_SDK.framework" install_framework "Pods/Parse.framework" fi
/* Description: The ANSI C code of the PRVNS approach Programmer: <NAME> E-mail: <EMAIL> Date: 04/11/2014 Lisence: Free Note: The system was developed using Linux. To compile: Type: make To run: ./algorithm input.in */ #ifndef max #define max(x, y) ((x) > (y) ? (x) : (y)) #endif #ifndef abss #define abss(a) (a<0 ? (-a) : a) #endif typedef int bool; #define true 1 #define false 0 #define FAIL 0 #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include "mersenne.h" #include "functions.c" #include <fcntl.h> #include <unistd.h> #include <pthread.h> #include <unistd.h> /* sleep() */ #include <string.h> typedef struct _AG { int P; /*The metric used, l1,l2,l_inf */ int FUNCTION; //Problem definitions int DIM; //number of problem variables int RUN; /*Algorithm can run many times in order to see its robustness*/ double *best; //[DIM]; //best solution found double bestfo; //best fo value double LB; //lower bound of the variables double UB; //upper bound of the variables int KMAX,TMAX,AVAL_MAX; int RADII_T_FLAG; int know; double Q,RADII,RHO,EPSILON; double *r; int METHOD; int ECO_STEP; int EVO_STEP; int VNS_POP; int POP_INDEX; double DELTA_MUTATION; int G_MAX; double PC; //probabilidade de crossover }pAG; int getParametersAG(FILE *file, pAG *ag) { int *P,*ECO_STEP,*EVO_STEP,*VNS_POP,*G_MAX,*FUNCTION,*DIM,*RUN; int *KMAX,*TMAX,*AVAL_MAX,*METHOD; int *RADII_T_FLAG; double *Q,*RADII,*RHO,*EPSILON,*PC; FUNCTION = (int*) malloc(sizeof(int)); DIM = (int*) malloc(sizeof(int)); RUN = (int*) malloc(sizeof(int)); ECO_STEP = (int*) malloc(sizeof(int)); EVO_STEP = (int*) malloc(sizeof(int)); VNS_POP = (int*) malloc(sizeof(int)); KMAX = (int*) malloc(sizeof(int)); TMAX = (int*) malloc(sizeof(int)); METHOD = (int*) malloc(sizeof(int)); AVAL_MAX = (int*) malloc(sizeof(int)); RADII_T_FLAG = (int*) malloc(sizeof(int)); Q = (double*) malloc(sizeof(double)); RADII = (double*) malloc(sizeof(double)); RHO = (double*) malloc(sizeof(double)); EPSILON = (double*) malloc(sizeof(double)); P = (int*) malloc(sizeof(int)); G_MAX = (int*) malloc(sizeof(int)); PC = (double*) malloc(sizeof(double)); if (file == 0) { printf( "Could not open ini file! Usage ./<exec> <file.in>\n" ); return -1; } else { ffscanf("RUN", file, "%d", &RUN); ffscanf("DIM", file, "%d", &DIM); ffscanf("FUNCTION",file, "%d", &FUNCTION); ffscanf("KMAX", file, "%d", &KMAX); ffscanf("TMAX", file, "%d", &TMAX); ffscanf("Q", file, "%lf", &Q); ffscanf("RADII", file, "%lf", &RADII); ffscanf("RADII_T_FLAG", file, "%d", &RADII_T_FLAG); ffscanf("AVAL_MAX", file, "%d", &AVAL_MAX); ffscanf("RHO", file, "%lf", &RHO); ffscanf("EPSILON", file, "%lf", &EPSILON); ffscanf("METHOD", file, "%d", &METHOD); ffscanf("P", file, "%d", &P); ffscanf("VNS_POP", file, "%d", &VNS_POP); ffscanf("ECO_STEP", file, "%d", &ECO_STEP); ffscanf("EVO_STEP", file, "%d", &EVO_STEP); ffscanf("G_MAX", file, "%d", &G_MAX); ffscanf("PC", file, "%lf", &PC); vns->RUN = *RUN; vns->DIM = *DIM; vns->FUNCTION = *FUNCTION; vns->KMAX = *KMAX; vns->TMAX = *TMAX; vns->Q = *Q; vns->RADII = *RADII; vns->RADII_T_FLAG = *RADII_T_FLAG; vns->AVAL_MAX = *AVAL_MAX; vns->RHO = *RHO; vns->EPSILON = *EPSILON; vns->METHOD = *METHOD; vns->P = *P; vns->VNS_POP = *VNS_POP; vns->ECO_STEP = *ECO_STEP; vns->EVO_STEP = *EVO_STEP; vns->G_MAX = *G_MAX; vns->PC = *PC; return 1; } } /*Main program of the search algorithm*/ int main(int argc, char **argv) { srand(time(NULL)); MT_seed(); }
#!/bin/bash # Configuring Timezone cd /scripts echo "Updating..." apt update 2>&1 1>/dev/null if [ $? -ne 0 ]; then echo "Updating failed." else echo "Updating succeded." fi echo "Upgrading..." apt upgrade -y 2>&1 1>/dev/null if [ $? -ne 0 ]; then echo "Upgrading failed." else echo "Updating succeeded." fi echo "Stargin qBittorrent and PIA..." ./run_setup.sh
<filename>packages/chakra-app/src/components/Inputs/ControllerPlus.tsx import { Input } from "@chakra-ui/input"; import React from "react"; import { Controller } from "react-hook-form"; export const ControllerPlus = ({ control, transform, name, }: { name: string; transform: any; control: any; }) => ( <Controller control={control} name={name} render={({ field }) => ( <Input borderColor="purple.500" color="purple.500" placeholder="Enter Address" onChange={(e) => field.onChange(transform.output(e))} value={transform.input(field.value)} /> )} /> );
<filename>Problem Solving/Data Structures/Linked Lists/Reverse a linked list/solution.java // Solution public static SinglyLinkedListNode reverse(SinglyLinkedListNode head) { if (head == null) { return null; } SinglyLinkedListNode currentNode = head; SinglyLinkedListNode nextNode = head.next; SinglyLinkedListNode previousNode = null; while (currentNode != null) { nextNode = currentNode.next; // store next currentNode.next = previousNode; // change next of current previousNode = currentNode; // set previous as current currentNode = nextNode; // set current as previous } return previousNode; // previous = head }
# ----------------------------------------------------------------------------- # # Package : generify # Version : 4.1.0 # Source repo : https://github.com/mcollina/generify # Tested on : RHEL 8.3 # Script License: Apache License, Version 2 or later # Maintainer : BulkPackageSearch Automation <sethp@us.ibm.com> # # Disclaimer: This script has been tested in root mode on given # ========== platform using the mentioned version of the package. # It may not work as expected with newer versions of the # package and/or distribution. In such case, please # contact "Maintainer" of this script. # # ---------------------------------------------------------------------------- PACKAGE_NAME=generify PACKAGE_VERSION=4.1.0 PACKAGE_URL=https://github.com/mcollina/generify yum -y update && yum install -y yum-utils nodejs nodejs-devel nodejs-packaging npm python38 python38-devel ncurses git gcc gcc-c++ libffi libffi-devel ncurses git jq make cmake yum-config-manager --add-repo http://rhn.pbm.ihost.com/rhn/latest/8.3Server/ppc64le/appstream/ yum-config-manager --add-repo http://rhn.pbm.ihost.com/rhn/latest/8.3Server/ppc64le/baseos/ yum-config-manager --add-repo http://rhn.pbm.ihost.com/rhn/latest/7Server/ppc64le/optional/ yum install -y firefox liberation-fonts xdg-utils && npm install n -g && n latest && npm install -g npm@latest && export PATH="$PATH" && npm install --global yarn grunt-bump xo testem acorn OS_NAME=`python3 -c "os_file_data=open('/etc/os-release').readlines();os_info = [i.replace('PRETTY_NAME=','').strip() for i in os_file_data if i.startswith('PRETTY_NAME')];print(os_info[0])"` HOME_DIR=`pwd` if ! git clone $PACKAGE_URL $PACKAGE_NAME; then echo "------------------$PACKAGE_NAME:clone_fails---------------------------------------" echo "$PACKAGE_URL $PACKAGE_NAME" > /home/tester/output/clone_fails echo "$PACKAGE_NAME | $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail | Clone_Fails" > /home/tester/output/version_tracker exit 0 fi cd $HOME_DIR/$PACKAGE_NAME git checkout $PACKAGE_VERSION PACKAGE_VERSION=$(jq -r ".version" package.json) # run the test command from test.sh if ! npm install && npm audit fix && npm audit fix --force; then echo "------------------$PACKAGE_NAME:install_fails-------------------------------------" echo "$PACKAGE_URL $PACKAGE_NAME" echo "$PACKAGE_NAME | $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail | Install_Fails" exit 0 fi cd $HOME_DIR/$PACKAGE_NAME if ! npm test; then echo "------------------$PACKAGE_NAME:install_success_but_test_fails---------------------" echo "$PACKAGE_URL $PACKAGE_NAME" echo "$PACKAGE_NAME | $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail | Install_success_but_test_Fails" exit 0 else echo "------------------$PACKAGE_NAME:install_&_test_both_success-------------------------" echo "$PACKAGE_URL $PACKAGE_NAME" echo "$PACKAGE_NAME | $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Pass | Both_Install_and_Test_Success" exit 0 fi
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flinkx.connector.cassandra.conf; import com.dtstack.flinkx.conf.FlinkxCommonConf; import org.apache.flink.configuration.ReadableConfig; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.CLUSTER_NAME; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.CONNECT_TIMEOUT_MILLISECONDS; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.CONSISTENCY; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.CORE_CONNECTIONS_PER_HOST; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.HOST; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.HOST_DISTANCE; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.KEY_SPACES; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.MAX_CONNECTIONS__PER_HOST; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.MAX_QUEUE_SIZE; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.MAX_REQUESTS_PER_CONNECTION; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.PASSWORD; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.POOL_TIMEOUT_MILLISECONDS; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.PORT; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.READ_TIME_OUT_MILLISECONDS; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.TABLE_NAME; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.USER_NAME; import static com.dtstack.flinkx.connector.cassandra.optinos.CassandraCommonOptions.USE_SSL; /** * @author tiezhu * @since 2021/6/21 星期一 */ public class CassandraCommonConf extends FlinkxCommonConf { protected String host; protected Integer port; protected String userName; protected String password; protected String tableName; protected String keyspaces; protected String hostDistance = "LOCAL"; protected boolean useSSL = false; protected String clusterName = "flinkx-cluster"; protected String consistency = "LOCAL_QUORUM"; protected Integer coreConnectionsPerHost = 8; protected Integer maxConnectionsPerHost = 32768; protected Integer maxRequestsPerConnection = 1; protected Integer maxQueueSize = 10 * 1000; protected Integer readTimeoutMillis = 60 * 1000; protected Integer connectTimeoutMillis = 60 * 1000; protected Integer poolTimeoutMillis = 60 * 1000; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public String getKeyspaces() { return keyspaces; } public void setKeyspaces(String keyspaces) { this.keyspaces = keyspaces; } public String getHostDistance() { return hostDistance; } public void setHostDistance(String hostDistance) { this.hostDistance = hostDistance; } public boolean isUseSSL() { return useSSL; } public void setUseSSL(boolean useSSL) { this.useSSL = useSSL; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getConsistency() { return consistency; } public void setConsistency(String consistency) { this.consistency = consistency; } public Integer getMaxRequestsPerConnection() { return maxRequestsPerConnection; } public void setMaxRequestsPerConnection(Integer maxRequestsPerConnection) { this.maxRequestsPerConnection = maxRequestsPerConnection; } public Integer getCoreConnectionsPerHost() { return coreConnectionsPerHost; } public void setCoreConnectionsPerHost(Integer coreConnectionsPerHost) { this.coreConnectionsPerHost = coreConnectionsPerHost; } public Integer getMaxConnectionsPerHost() { return maxConnectionsPerHost; } public void setMaxConnectionsPerHost(Integer maxConnectionsPerHost) { this.maxConnectionsPerHost = maxConnectionsPerHost; } public Integer getMaxQueueSize() { return maxQueueSize; } public void setMaxQueueSize(Integer maxQueueSize) { this.maxQueueSize = maxQueueSize; } public Integer getReadTimeoutMillis() { return readTimeoutMillis; } public void setReadTimeoutMillis(Integer readTimeoutMillis) { this.readTimeoutMillis = readTimeoutMillis; } public Integer getConnectTimeoutMillis() { return connectTimeoutMillis; } public void setConnectTimeoutMillis(Integer connectTimeoutMillis) { this.connectTimeoutMillis = connectTimeoutMillis; } public Integer getPoolTimeoutMillis() { return poolTimeoutMillis; } public void setPoolTimeoutMillis(Integer poolTimeoutMillis) { this.poolTimeoutMillis = poolTimeoutMillis; } public static CassandraCommonConf from( ReadableConfig readableConfig, CassandraCommonConf conf) { conf.setHost(readableConfig.get(HOST)); conf.setPort(readableConfig.get(PORT)); conf.setUserName(readableConfig.get(USER_NAME)); conf.setPassword(readableConfig.get(PASSWORD)); conf.setUseSSL(readableConfig.get(USE_SSL)); conf.setTableName(readableConfig.get(TABLE_NAME)); conf.setKeyspaces(readableConfig.get(KEY_SPACES)); conf.setHostDistance(readableConfig.get(HOST_DISTANCE)); conf.setClusterName(readableConfig.get(CLUSTER_NAME)); conf.setConsistency(readableConfig.get(CONSISTENCY)); conf.setCoreConnectionsPerHost(readableConfig.get(CORE_CONNECTIONS_PER_HOST)); conf.setMaxConnectionsPerHost(readableConfig.get(MAX_CONNECTIONS__PER_HOST)); conf.setMaxQueueSize(readableConfig.get(MAX_QUEUE_SIZE)); conf.setMaxRequestsPerConnection(readableConfig.get(MAX_REQUESTS_PER_CONNECTION)); conf.setReadTimeoutMillis(readableConfig.get(READ_TIME_OUT_MILLISECONDS)); conf.setConnectTimeoutMillis(readableConfig.get(CONNECT_TIMEOUT_MILLISECONDS)); conf.setPoolTimeoutMillis(readableConfig.get(POOL_TIMEOUT_MILLISECONDS)); return conf; } @Override public String toString() { ToStringBuilder toStringBuilder = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append("host", host) .append("port", port) .append("userName", userName) .append("tableName", tableName) .append("keyspaces", keyspaces) .append("hostDistance", hostDistance) .append("useSSL", useSSL) .append("clusterName", clusterName) .append("consistency", consistency) .append("coreConnectionsPerHost", coreConnectionsPerHost) .append("maxConnectionsPerHost", maxConnectionsPerHost) .append("maxRequestPerConnection", maxRequestsPerConnection) .append("readTimeoutMillis", readTimeoutMillis) .append("connectTimeoutMillis", connectTimeoutMillis) .append("poolTimeoutMillis", poolTimeoutMillis); return toStringBuilder.toString(); } }
<filename>pre-processing-source/restaurant_filter/rest_filter.py<gh_stars>1-10 import pandas as pd import numpy as np import json df = pd.read_csv('langtest.csv') for index,row in df.iterrows(): print (index) flag = 0 fileobj = open('rest_ids.txt'); for line in fileobj: line = line.rstrip('\n') print (line) print (df.iloc[index,0]) if (df.iloc[index,0] == line): flag = 1 if (flag == 0): df.drop(index, inplace=True) df.to_csv('out.csv', sep='\t')
#include <getopt.h> #include <stdio.h> #include <stdlib.h> #include "daemon/log.h" #include "daemon/supervisor.h" static _Noreturn void usage(const int status) { // clang-format off printf( "covend: naive service supervisor\n" "Usage:\n" " covend [SVDIR]\n" " covend [--help]\n" "Options:\n" " -h, --help: display this screen and exit\n" "\n" "SVDIR is the folder with the compiled service entries\n" ); // clang-format on exit(status); } int main(int argc, char **argv) { struct daemon_supervisor sv; int opt, opt_idx; static struct option opts[] = { {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}, }; while ((opt = getopt_long(argc, argv, "h", opts, &opt_idx)) != -1) { switch (opt) { case 'h': usage(EXIT_SUCCESS); case '?': __attribute__((fallthrough)); default: usage(EXIT_FAILURE); } } if (daemon_log_init() != 0) { exit(EXIT_FAILURE); } if (daemon_supervisor_init(&sv) != 0) { daemon_log_fail("supervisor initialize"); exit(EXIT_FAILURE); } while (sv.running == 1) { daemon_supervisor_loop(&sv); } daemon_supervisor_deinit(&sv); return 0; }
#!/usr/bin/env bash HUB=gcr.io/istio-testing VERSION=$(date +%Y-%m-%d) docker build --no-cache -t $HUB/website-builder:$VERSION . docker push $HUB/website-builder:$VERSION
#! /bin/sh rm -rf dist mkdir dist/ mkdir dist/rules babel -q index.js -o dist/index.js for file in `echo rules/*.js`; do babel $file -o dist/${file} done
#!/bin/bash set -e cecho(){ RED="\033[0;31m" GREEN='\033[0;32m' YELLOW='\033[1;33m' # ... ADD MORE COLORS NC='\033[0m' # No Color printf "${!1}${2} ${NC}\n" } if [ -z $1 ]; then echo "NAMESPACE argument not set. You need to inform a NAMESPACE as an argument." echo "Example: ./accounts.sh lemonade-dev" exit 1 fi NAMESPACE=$1 export NAMESPACE # Path for kubectl program KUBECTL=kubectl cecho "GREEN" "Creating namespace ${NAMESPACE} in Kubernetes" envsubst < ./k8s/namespace.yaml | $KUBECTL apply -f - cecho "GREEN" "Creating accounts" kubectl create serviceaccount jumppod -n $NAMESPACE kubectl create rolebinding jumppod-rb --clusterrole=admin --serviceaccount=$NAMESPACE:jumppod -n $NAMESPACE kubectl create serviceaccount spark-sa -n $NAMESPACE kubectl create rolebinding spark-sa-rb --clusterrole=edit --serviceaccount=$NAMESPACE:spark-sa -n $NAMESPACE kubectl create clusterrolebinding spark-sa-ra --clusterrole=edit --serviceaccount=$NAMESPACE:spark-sa -n $NAMESPACE
#!/bin/bash set -e inkscape -D ./orbital-motion-real.svg -o ../../latex/fig-orbital-motion-real.pdf --export-latex
import express from 'express'; import { checkIfAuthenticated } from './utils'; const router = express.Router(); // Get list of items from database router.get('/', (req, res) => { ItemModel.find((err, items) => { if (err) res.send(err); res.send(items); }); }); // Create new item router.post('/', checkIfAuthenticated, (req, res) => { ItemModel.create({ name: req.body.name, description: req.body.description, price: req.body.price }, (err, item) => { if (err) res.send(err); res.send(item); }); }); // Edit existing item router.put('/:id', checkIfAuthenticated, (req, res) => { ItemModel.findByIdAndUpdate(req.params.id, { name: req.body.name, description: req.body.description, price: req.body.price }, (err, item) => { if (err) res.send(err); res.send(item); }); }); // Delete item router.delete('/:id', checkIfAuthenticated, (req, res) => { ItemModel.findByIdAndDelete(req.params.id, (err, item) => { if (err) res.send(err); res.send(item); }); }); export default router;
#!/bin/bash python -m twine upload dist/*
package server /* * mimi * * Copyright (c) 2018 beito * * This software is released under the MIT License. * http://opensource.org/licenses/mit-license.php **/ import ( "errors" "time" "github.com/beito123/mimi" "github.com/beito123/mimi/pks" ) type ServerSession struct { mimi.BaseSession console *Console tracker *LogTracker } func (session *ServerSession) Update(handlers []mimi.PacketHandler) { session.Update(handlers) if session.State() != mimi.StateConnected { return } if session.console == nil { return } session.SendPacket(&pks.ConsoleMessages{ Messages: session.console.Lines(session.tracker), }) } func (session *ServerSession) HasJoined() bool { return session.console != nil } func (session *ServerSession) JoinConsole(con *Console) error { if con.Closed() { return errors.New("already closed the console") } session.console = con session.tracker = NewLogTracker() logger.Debugf("Session(%s) joins a console(%s)", session.Addr().String(), con.UUID.String()) return nil } func (session *ServerSession) QuitConsole() error { if !session.HasJoined() { return errors.New("not joined a console") } session.console = nil session.tracker = nil return nil } type ServerSessionHandler struct { ProgramManager *ProgramManager ConsoleManager *ConsoleManager Console *Console IngoreProtocol bool } func (sp *ServerSessionHandler) HandlePacket(session mimi.Session, pk pks.Packet) { switch npk := pk.(type) { case *pks.ConnectionRequest: logger.Debugf("Received a ConnectionRequest packet from %s\n", session.Addr().String()) if session.State() != mimi.StateConnecting { logger.Debugf("Received a ConnectionRequest packet, but already connected\n") // TODO: implements to reconnect return } if npk.ClientProtocol != mimi.ProtocolVersion && !sp.IngoreProtocol { session.SendPacket(&pks.IncompatibleProtocol{ Protocol: mimi.ProtocolVersion, }) session.Close() return } session.SetClientUUID(npk.ClientUUID) session.SetState(mimi.StateConnected) session.SendPacket(&pks.ConnectionResponse{ Time: time.Now().Unix(), }) logger.Debugf("Established new connection IP: %s CID: %s\n", session.Addr().String(), session.ClientUUID().String()) case *pks.RequestProgramList: logger.Debugf("Received a RequestProgramList packet\n") rpk := &pks.ResponseProgramList{} for _, p := range sp.ProgramManager.Programs { rpk.Programs = append(rpk.Programs, &pks.Program{ Name: p.Name, LoaderName: p.Loader.Name(), }) } session.SendPacket(rpk) case *pks.StartProgram: logger.Debugf("Received a StartProgram packet\n") program, ok := sp.ProgramManager.Get(npk.ProgramName) if !ok { session.SendPacket(&pks.ErrorMessage{ Error: mimi.ErrIDProgramNotFound, }) return } con, err := sp.ConsoleManager.NewConsole(program.Loader) if err != nil { logger.Errorln(err) session.SendPacket(&pks.ErrorMessage{ Error: mimi.ErrIDInternalError, }) return } session.SendPacket(&pks.ProgramStatus{ ProgramName: program.Name, ConsoleUUID: con.UUID, Running: true, }) case *pks.JoinConsole: logger.Debugf("Received a JoinConsole packet\n") con, ok := sp.ConsoleManager.Get(npk.ConsoleUUID) if !ok { session.SendPacket(&pks.ErrorMessage{ Error: mimi.ErrIDConsoleNotFound, }) return } serSession, ok := session.(*ServerSession) if !ok { mimi.Error("couldn't convert to *ServerSession") session.SendPacket(&pks.ErrorMessage{ Error: mimi.ErrIDInternalError, }) return } if con.Closed() { session.SendPacket(&pks.ErrorMessage{ Error: mimi.ErrIDConsoleAlreadyClosed, }) return } err := serSession.JoinConsole(con) if err != nil { mimi.Error("couldn't join a console error: %s", err.Error()) session.SendPacket(&pks.ErrorMessage{ Error: mimi.ErrIDInternalError, }) } case *pks.QuitConsole: logger.Debugf("Received a QuitConsole packet\n") serSession, ok := session.(*ServerSession) if !ok { mimi.Error("couldn't convert to *ServerSession") session.SendPacket(&pks.ErrorMessage{ Error: mimi.ErrIDInternalError, }) return } if !serSession.HasJoined() { session.SendPacket(&pks.ErrorMessage{ Error: mimi.ErrIDSessionNotJoinedConsole, }) return } err := serSession.QuitConsole() if err != nil { mimi.Error("couldn't join a console error: %s", err.Error()) session.SendPacket(&pks.ErrorMessage{ Error: mimi.ErrIDInternalError, }) } case *pks.DisconnectionNotification: logger.Debugf("Received disconnection packet IP: %s CID: %s\n", session.Addr().String(), session.ClientUUID().String()) if session.State() != mimi.StateDisconnected { session.Close() } default: logger.Debugf("Received unknown packet ID:%d\n", npk.ID()) } }
#pragma strict class PieceEV { public static var PIECE_NEL : int = 1; public static var PIECE_SITKEL : int = 2; public static var PIECE_ELEPHANT : int = 3; public static var PIECE_HORSE : int = 4; public static var PIECE_CASTLE : int = 5; public static var PIECE_KING : int = 6; public var type : int; public var PieceActionValue : int; public var PieceValue : int; public var DefendedValue : int; public var AttackedValue : int; public var Black : boolean; public var ValidMoves : System.Collections.Generic.Stack.<byte>; public var Moved : boolean; function PieceEV() { } // copy piece function PieceEV(cp_piece : PieceEV) { type = cp_piece.type; PieceActionValue = PieceActionValue; PieceValue = cp_piece.PieceValue; Black = cp_piece.Black; Moved = cp_piece.Moved; } }
<gh_stars>0 // 如果没有明确的指定类型,那么 TypeScript 会依照类型推论(Type Inference)的规则推断出一个类型 let seven = 'seven'; // seven = 3 报错,初始赋值时有类型,则推断为初始值类型 seven = 'hello'
package com.tracy.competition.config import com.alibaba.druid.pool.DruidDataSource import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.context.annotation.{Bean, Configuration, PropertySource} /** * @author Tracy * @date 2021/2/9 0:45 */ @Configuration @PropertySource(Array("classpath:db-config.properties")) class DruidConfig { /** * 在容器中注入Druid数据源 * * @return 数据源 */ @ConfigurationProperties(prefix = "spring.datasource") @Bean def druid = new DruidDataSource }
<reponame>donfyy/AndroidCrowds package com.donfyy.willremove.intercept.innerintercept; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.ListView; public class InnerListView extends ListView { private static final String TAG = "InnerListView"; // 分别记录上次滑动的坐标 private int mLastX = 0; private int mLastY = 0; public InnerListView(Context context) { super(context); } public InnerListView(Context context, AttributeSet attrs) { super(context, attrs); } public InnerListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } //Solution 1 @Override public boolean dispatchTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { getParent().getParent().requestDisallowInterceptTouchEvent(true); break; } case MotionEvent.ACTION_MOVE: { int deltaX = x - mLastX; int deltaY = y - mLastY; Log.d(TAG, "dx:" + deltaX + " dy:" + deltaY); if (Math.abs(deltaX) > Math.abs(deltaY)) { getParent().getParent().requestDisallowInterceptTouchEvent(false); } break; } } mLastX = x; mLastY = y; return super.dispatchTouchEvent(event); } // Solution 2, onInterceptTouchEvent is called only if mFirstTouchTarget is not null for ACTION_MOVE touch event. // InnerListView must have child to accept ACTION_DOWN touch event, // thus InnerListView's mFirstTouchTarget will not be null. Then latter // ACTION_MOVE touch events will pass to onInterceptTouchEvent method // // // Check for interception. // final boolean intercepted; // if (actionMasked == MotionEvent.ACTION_DOWN // || mFirstTouchTarget != null) { // final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0; // if (!disallowIntercept) { // intercepted = onInterceptTouchEvent(ev); // ev.setAction(action); // restore action in case it was changed // } else { // intercepted = false; // } // } // /* @Override public boolean onInterceptTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { getParent().getParent().requestDisallowInterceptTouchEvent(true); break; } case MotionEvent.ACTION_MOVE: { int deltaX = x - mLastX; int deltaY = y - mLastY; Log.d(TAG, "dx:" + deltaX + " dy:" + deltaY); if (Math.abs(deltaX) > Math.abs(deltaY)) { getParent().getParent().requestDisallowInterceptTouchEvent(false); } break; } } mLastX = x; mLastY = y; return super.onInterceptTouchEvent(event); }*/ }
<filename>integration/tasks.py """ Tasks module for use within the integration tests. """ from invoke import task @task def print_foo(c): print("foo") @task def print_name(c, name): print(name) @task def print_config(c): print(c.foo)
# Static parameters WORKSPACE=./ BOX_PLAYBOOK=$WORKSPACE/box.yml BOX_NAME=seventeen BOX_ADDRESS=192.168.0.20 BOX_USER=slavko BOX_PWD= prudentia ssh <<EOF unregister $BOX_NAME register $BOX_PLAYBOOK $BOX_NAME $BOX_ADDRESS $BOX_USER $BOX_PWD verbose 4 set box_address $BOX_ADDRESS provision $BOX_NAME EOF
#!/usr/bin/env bash ./gradlew updateBuildPackageJsonFile
#!/bin/bash set -e set -o pipefail umask 0002 #### SET THE STAGE SCRATCH_DIR=/scratch/BWA_Reseq_low_251_300_on_A_2020-04-23--12-47-03_285_temp$$ GSTORE_DIR=/srv/gstore/projects INPUT_DATASET=/srv/gstore/projects/p1634/BWA_Reseq_low_251_300_on_A_2020-04-23--12-47-03/input_dataset.tsv LAST_JOB=FALSE echo "Job runs on `hostname`" echo "at $SCRATCH_DIR" mkdir $SCRATCH_DIR || exit 1 cd $SCRATCH_DIR || exit 1 source /usr/local/ngseq/etc/lmod_profile module add Tools/samtools/1.10 Aligner/BWA/0.7.17 QC/Flexbar/3.0.3 QC/fastp/0.20.0 Dev/R/3.6.1 Tools/sambamba/0.6.7 #### NOW THE ACTUAL JOBS STARTS R --vanilla --slave<< EOT EZ_GLOBAL_VARIABLES <<- '/usr/local/ngseq/opt/EZ_GLOBAL_VARIABLES.txt' library(ezRun) param = list() param[['cores']] = '8' param[['ram']] = '16' param[['scratch']] = '100' param[['node']] = 'fgcz-c-048,fgcz-h-004,fgcz-h-006,fgcz-h-007,fgcz-h-008,fgcz-h-009,fgcz-h-010,fgcz-h-011,fgcz-h-012,fgcz-h-013,fgcz-h-014,fgcz-h-015,fgcz-h-016,fgcz-h-017,fgcz-h-018,fgcz-h-019' param[['process_mode']] = 'SAMPLE' param[['samples']] = '251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300' param[['refBuild']] = 'Finger_millet/KEN/DENOVO_v2.0_A_subgenome/Annotation/Release_01-2019-02-04' param[['paired']] = 'true' param[['algorithm']] = 'mem' param[['cmdOptions']] = '-M' param[['trimAdapter']] = 'true' param[['trim_front1']] = '0' param[['trim_tail1']] = '0' param[['cut_front']] = 'false' param[['cut_front_window_size']] = '4' param[['cut_front_mean_quality']] = '20' param[['cut_tail']] = 'false' param[['cut_tail_window_size']] = '4' param[['cut_tail_mean_quality']] = '20' param[['cut_right']] = 'false' param[['cut_right_window_size']] = '4' param[['cut_right_mean_quality']] = '20' param[['average_qual']] = '0' param[['max_len1']] = '0' param[['max_len2']] = '0' param[['poly_x_min_len']] = '10' param[['length_required']] = '18' param[['cmdOptionsFastp']] = '' param[['mail']] = '' param[['dataRoot']] = '/srv/gstore/projects' param[['resultDir']] = 'p1634/BWA_Reseq_low_251_300_on_A_2020-04-23--12-47-03' param[['isLastJob']] = FALSE output = list() output[['Name']] = '285' output[['BAM [File]']] = 'p1634/BWA_Reseq_low_251_300_on_A_2020-04-23--12-47-03/285.bam' output[['BAI [File]']] = 'p1634/BWA_Reseq_low_251_300_on_A_2020-04-23--12-47-03/285.bam.bai' output[['IGV Starter [Link]']] = 'p1634/BWA_Reseq_low_251_300_on_A_2020-04-23--12-47-03/285-igv.jnlp' output[['Species']] = 'n/a' output[['refBuild']] = 'Finger_millet/KEN/DENOVO_v2.0_A_subgenome/Annotation/Release_01-2019-02-04' output[['paired']] = 'true' output[['refFeatureFile']] = '' output[['strandMode']] = '' output[['Read Count']] = '26356933' output[['IGV Starter [File]']] = 'p1634/BWA_Reseq_low_251_300_on_A_2020-04-23--12-47-03/285-igv.jnlp' output[['IGV Session [File]']] = 'p1634/BWA_Reseq_low_251_300_on_A_2020-04-23--12-47-03/285-igv.xml' output[['PreprocessingLog [File]']] = 'p1634/BWA_Reseq_low_251_300_on_A_2020-04-23--12-47-03/285_preprocessing.log' output[['Condition [Factor]']] = '' output[['Extract Id [B-Fabric]']] = 'bfe_41437' output[['FragmentSize [Characteristic]']] = '0' output[['SampleConc [Characteristic]']] = '25' output[['Tube [Characteristic]']] = 'p1634_3646/285' output[['Index [Characteristic]']] = 'AGCGATAG-AGGCGAAG' output[['PlatePosition [Characteristic]']] = 'SA_150817_1_E12' output[['LibConc_100_800bp [Characteristic]']] = '65.2' output[['LibConc_qPCR [Characteristic]']] = '0' output[['InputAmount [Characteristic]']] = '100' input = list() input[['Name']] = '285' input[['Condition']] = '' input[['Read1']] = 'p1634/HiSeq4000_20170906_RUN374_o3646/20170906.A-285_R1.fastq.gz' input[['Read2']] = 'p1634/HiSeq4000_20170906_RUN374_o3646/20170906.A-285_R2.fastq.gz' input[['Species']] = 'n/a' input[['FragmentSize']] = '0' input[['SampleConc']] = '25' input[['Tube']] = 'p1634_3646/285' input[['Extract Id']] = 'bfe_41437' input[['Index']] = 'AGCGATAG-AGGCGAAG' input[['PlatePosition']] = 'SA_150817_1_E12' input[['LibConc_100_800bp']] = '65.2' input[['LibConc_qPCR']] = '0' input[['Adapter1']] = 'GATCGGAAGAGCACACGTCTGAACTCCAGTCAC' input[['Adapter2']] = 'AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGT' input[['strandMode']] = 'both' input[['LibraryPrepKit']] = 'TruSeq DNA Nano' input[['EnrichmentMethod']] = 'None' input[['InputAmount']] = '100' input[['Read Count']] = '26356933' EzAppBWA\$new()\$run(input=input, output=output, param=param) EOT #### JOB IS DONE WE PUT THINGS IN PLACE AND CLEAN AUP g-req -w copy 285.bam /srv/gstore/projects/p1634/BWA_Reseq_low_251_300_on_A_2020-04-23--12-47-03 g-req -w copy 285.bam.bai /srv/gstore/projects/p1634/BWA_Reseq_low_251_300_on_A_2020-04-23--12-47-03 g-req -w copy 285-igv.jnlp /srv/gstore/projects/p1634/BWA_Reseq_low_251_300_on_A_2020-04-23--12-47-03 g-req -w copy 285-igv.xml /srv/gstore/projects/p1634/BWA_Reseq_low_251_300_on_A_2020-04-23--12-47-03 g-req -w copy 285_preprocessing.log /srv/gstore/projects/p1634/BWA_Reseq_low_251_300_on_A_2020-04-23--12-47-03 cd /scratch rm -rf /scratch/BWA_Reseq_low_251_300_on_A_2020-04-23--12-47-03_285_temp$$ || exit 1
SCRIPT_NAME=alphavms OUTPUT_FORMAT="vms-alpha" ARCH=alpha EXTRA_EM_FILE=vms
/** * This program and the accompanying materials * are made available under the terms of the License * which accompanies this distribution in the file LICENSE.txt */ package com.archimatetool.canvas.model; import com.archimatetool.model.IDiagramModelConnection; import com.archimatetool.model.ILockable; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Model Connection</b></em>'. * <!-- end-user-doc --> * * * @see com.archimatetool.canvas.model.ICanvasPackage#getCanvasModelConnection() * @model * @generated */ public interface ICanvasModelConnection extends IDiagramModelConnection, ILockable { } // ICanvasModelConnection
package com.honyum.elevatorMan.net; import com.honyum.elevatorMan.data.ContartInfo; import com.honyum.elevatorMan.data.ContractElevator; import com.honyum.elevatorMan.data.ContractFile; import com.honyum.elevatorMan.data.ContractPayment; import com.honyum.elevatorMan.data.ResultMapInfo; import com.honyum.elevatorMan.net.base.Response; import com.honyum.elevatorMan.net.base.ResponseBody; import java.io.Serializable; import java.util.List; public class ContractInfoDetailResponse extends Response implements Serializable{ private ContractDetailBody body; public void setBody(ContractDetailBody body) { this.body = body; } public ContractDetailBody getBody() { return body; } public static class ContractDetailBody extends ResponseBody{ private ResultMapInfo _process_resultMap; private ContartInfo contract; private List<ContractElevator> listContractElevator; private List<ContractFile> listContractFile; private List<ContractPayment> listContractPayment; public void setContract(ContartInfo contract) { this.contract = contract; } public ContartInfo getContract() { return contract; } public void setListContractElevator(List<ContractElevator> listContractElevator) { this.listContractElevator = listContractElevator; } public List<ContractElevator> getListContractElevator() { return listContractElevator; } public List<ContractFile> getListContractFile() { return listContractFile; } public void setListContractFile(List<ContractFile> listContractFile) { this.listContractFile = listContractFile; } public List<ContractPayment> getListContractPayment() { return listContractPayment; } public void setListContractPayment(List<ContractPayment> listContractPayment) { this.listContractPayment = listContractPayment; } public ResultMapInfo get_process_resultMap() { return _process_resultMap; } public void set_process_resultMap(ResultMapInfo _process_resultMap) { this._process_resultMap = _process_resultMap; } } /** * 根据json生成对象 * @param json * @return */ public static ContractInfoDetailResponse getContratInfoResponse(String json) { return (ContractInfoDetailResponse) parseFromJson(ContractInfoDetailResponse.class, json); } }
#!/usr/bin/env shellspec set -euo pipefail Describe 'services' Include resource/lib/cf-functions.sh setup() { org=$(generate_test_name_with_spaces) space=$(generate_test_name_with_spaces) service_instance=$(generate_test_name_with_spaces) service_key=$(generate_test_name_with_spaces) source=$(get_source_config "$org" "$space") || error_and_exit "[ERROR] error loading source json config" test::login test::create_org_and_space "$org" "$space" } teardown() { test::delete_org_and_space "$org" "$space" test::logout } BeforeAll 'setup' AfterAll 'teardown' It 'can create a service' create_service() { local config=$( %text:expand #|$source #|params: #| command: create-service #| service: bookstore #| plan: standard #| service_instance: $service_instance ) put "$config" } When call create_service The status should be success The output should json '.version | keys == ["timestamp"]' The error should include "Creating service instance $service_instance" Assert test::service_exists "$service_instance" "$org" "$space" End It 'can create a service key' create_service_key() { local config=$( %text:expand #|$source #|params: #| command: create-service-key #| service_instance: $service_instance #| service_key: $service_key ) if cf::is_cf8; then config=$( %text:expand #|$config #| wait: true ) fi put "$config" } When call create_service_key The status should be success The output should json '.version | keys == ["timestamp"]' The error should include "Creating service key $service_key for service instance $service_instance" if cf::is_cf8; then The error should include 'Waiting for the operation to complete' fi Assert test::service_key_exists "$service_instance" "$service_key" "$org" "$space" End It 'can delete a service key' delete_service_key() { local config=$( %text:expand #|$source #|params: #| command: delete-service-key #| service_instance: $service_instance #| service_key: $service_key ) if cf::is_cf8; then config=$( %text:expand #|$config #| wait: true ) fi put "$config" } When call delete_service_key The status should be success The output should json '.version | keys == ["timestamp"]' The error should include "Deleting key $service_key for service instance $service_instance" if cf::is_cf8; then The error should include 'Waiting for the operation to complete' fi Assert not test::service_key_exists "$service_instance" "$service_key" "$org" "$space" End It 'can delete a service' delete_service() { local config=$( %text:expand #|$source #|params: #| command: delete-service #| service_instance: $service_instance ) put "$config" } When call delete_service The status should be success The output should json '.version | keys == ["timestamp"]' The error should include "Deleting service" Assert not test::service_exists "$service_instance" "$org" "$space" End End
#!/bin/bash if [[ $# -ne 0 ]]; then echo "$0 does not accept parameters" exit 2 fi docker run \ -e GOOGLE_APPLICATION_CREDENTIALS=/root/.config/gcloud/legacy_credentials/${USER}@private.com/adc.json \ -e USER=${USER} \ -v ~/.config/gcloud:/root/.config/gcloud \ --rm -i -t serenade-dd \ gs://my-google-cloud-project-shared/train_full/csv/part-00000-2ec72272-c01e-4e80-bf3a-45b18fdbfff4-c000.csv \ gs://my-google-cloud-project-shared/test_full/csv/part-00000-f3c1634a-3c41-4c78-ba2c-435fb52254dd-c000.csv \ gs://my-google-cloud-project-shared/results/dd_1m_vsknn_predictions.txt \ gs://my-google-cloud-project-shared/results/dd_1m_latencies.txt
package colliders; import java.awt.geom.Point2D.Double; public class ColliderTriangle extends Collider { double minX; double maxX; double minY; double maxY; double rc; boolean left; public ColliderTriangle(double xMin, double yMin, double xMax, double yMax, boolean openLeft) { minX = xMin; minY = yMin; maxX = xMax; maxY = yMax; left = openLeft; rc = (maxY - minY) / (maxX - minX); } @Override public double minX() { return minX; } @Override public double minY() { return minY; } @Override public double maxX() { return maxX; } @Override public double maxY() { return maxY; } @Override public boolean hit(Collider other) { if(other instanceof ColliderBox){ ColliderBox box = (ColliderBox) other; if(box.minX <= maxX && box.maxX >= minX && box.minY <= maxY && box.maxY >= minY){ if(isInCollider(new Double(box.minX, box.minY)) || isInCollider(new Double(box.minX, box.maxY)) || isInCollider(new Double(box.maxX, box.minY)) || isInCollider(new Double(box.maxX, box.maxY))) return true; if(left){ double x = minX; if(box.minX > minX) x = box.minX; double y = minY; if(box.minY > minY) y = box.minY; if(isInCollider(new Double(x, y))) return true; } else { double x = maxX; if(box.maxX < maxX) x = box.maxX; double y = minY; if(box.minY > minY) y = box.minY; if(isInCollider(new Double(x, y))) return true; } } return false; } if(other instanceof ColliderCircle){ ColliderCircle circle = (ColliderCircle) other; if(circle.minX() <= maxX && circle.maxX() >= minX && circle.minY() <= maxY && circle.maxY() >= minY){ if(circle.isInCollider(new Double(minX, minY)) || circle.isInCollider(new Double(maxX, minY)) || circle.isInCollider(new Double(left ? maxX : minX, maxY))) return true; double rotation = Math.atan2(minY - circle.center.y, left ? maxX - circle.center.x : minX - circle.center.x); double x = circle.center.x + Math.cos(rotation) * circle.radius; double y = circle.center.y + Math.sin(rotation) * circle.radius; if(isInCollider(new Double(x, y))) return true; x = left ? maxX : minX; y = circle.center.y; if(y > maxY) y = maxY; if(y < minY) y = minY; if(circle.isInCollider(new Double(x, y))) return true; } return false; } if(other instanceof ColliderTriangle){ ColliderTriangle tri = (ColliderTriangle) other; if(tri.minX <= maxX && tri.maxX >= minX && tri.minY <= maxY && tri.maxY >= minY){ if(isInCollider(new Double(tri.minX, tri.minY)) || isInCollider(new Double(tri.maxX, tri.minY)) || isInCollider(new Double(tri.left ? tri.maxX : tri.minX, tri.maxY))) return true; if(left){ double x = minX; if(tri.minX > minX) x = tri.minX; double y = minY; if(tri.minY > minY) y = tri.minY; if(isInCollider(new Double(x, y)) && tri.isInCollider(new Double(x, y))) return true; } else { double x = maxX; if(tri.maxX < maxX) x = tri.maxX; double y = minY; if(tri.minY > minY) y = tri.minY; if(isInCollider(new Double(x, y)) && tri.isInCollider(new Double(x, y))) return true; } } } if(other instanceof ColliderNull) return false; if(other instanceof ColliderList) return other.hit(this); throw new Collider.CollissionException(); } @Override public boolean equals(Collider other) { if(other instanceof ColliderTriangle){ ColliderTriangle triangle = (ColliderTriangle) other; return triangle.minX == minX && triangle.minY == minY && triangle.maxX == maxX && triangle.maxY == maxY && triangle.left == left; } return false; } @Override public double distanceTo(Collider other) { if(hit(other)) return 0; if(other instanceof ColliderNull) return java.lang.Double.NaN; if(other instanceof ColliderList) return other.distanceTo(this); if(other instanceof ColliderBox){ ColliderBox box = (ColliderBox) other; double distance; double d; double y1 = maxY; if(y1 > box.maxY && box.maxY >= minY) y1 = box.maxY; else if(y1 > box.maxY) y1 = minY; double x = left ? maxX : minX; if(x > box.maxX) x = box.maxX; if(x < box.minX) x = box.minX; double y = y1; if(y > box.maxY) y = box.maxY; if(y < box.minY) y = box.minY; distance = new Double(x, y).distance(new Double(left ? maxX : minX, y1)); double x1 = maxX; if(x1 > box.maxX && box.maxX >= minX) x1 = box.maxX; else if(x1 > box.maxX) x1 = minX; x = x1; if(x > box.maxX) x = box.maxX; if(x < box.minX) x = box.minX; d = new Double(x, y).distance(new Double(x1, minY)); if(d < distance) distance = d; if(box.minX > minX && box.maxX < maxX && box.minY > minY){ if(left){ // box.minX = 22 en box.maxX = 27 en box.minY = 52 && box.maxY = 56 en minX = 20 en maxX = 35 en minY = 30 en maxY = 45 // rc = (45 - 30) / (35 - 20) = 15 / 15 = 1 // angle = atan(rc) + 1.5PI = 6.27 // startY = 30 + (27 - 20) * 1 = 30 + 7 * 1 = 37 // d = (37 - 52) / (sin(6.27) - sin(1.56)) = (-15) / (-1.01) = 14.81 double angle = Math.atan(rc) + 1.5 * Math.PI; //5.76 double startY = minY + (box.maxX - minX) * rc; // 18.66 //box.minY + sin(angle) * l = startY + sin(angle - 1.5PI) * l //sin(angle) * l - sin(angle - 1.5PI) * l = startY - box.minY //l * (sin(angle) - sin(angle - 1.5PI)) = startY - box.minY //l = (startY - box.minY) / (sin(angle) - sin(angle - 1.5PI)) d = (startY - box.minY) / (Math.sin(angle) - Math.sin(angle - 1.5 * Math.PI)); } else { double angle = Math.atan(rc) + 1.5 * Math.PI; double startY = (maxX - box.minX) * rc; d = (startY - box.minY) / (Math.sin(angle) - Math.sin(angle - 1.5 * Math.PI)); } if(d < distance) distance = d; } return distance; } if(other instanceof ColliderCircle){ //TODO finish this! } if(other instanceof ColliderTriangle){ //TODO finish this! } throw new Collider.CollissionException(); } @Override public boolean isInCollider(Double position) { if(position.x < minX || position.x > maxX || position.y < minY || position.y > maxX) return false; double x = left ? position.x - minX : maxX - position.x; double y = minY + rc * x; return position.y < y; } public double distanceToCollider(){ return 0; } }
package Adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import de.httptandooripalace.restaurantorderprinter.R; import entities.Bill; import helpers.Rounder; /** * Created by uiz on 27/04/2017. */ public class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.MyViewHolder> { private Context context; private List<Bill> bills; public HistoryAdapter(Context c, List<Bill> bills) { context = c; this.bills = new ArrayList<>(); this.bills = bills; } @Override public long getItemId(int position) { return position; } @Override public int getItemCount() { return bills.size(); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { Bill bill = bills.get(position); holder.tvId.setText(bill.getId() + ""); holder.tvDate.setText(bill.getDate().toString().substring(4, 10)); holder.tvTable.setText(bill.getTableNr() + ""); holder.tvWaiter.setText(bill.getWaiter() + ""); holder.tvPrice.setText(Rounder.round(bill.getTotal_price_excl()) + " €"); } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.history_list_item, parent, false); return new MyViewHolder(itemView); } public class MyViewHolder extends RecyclerView.ViewHolder { public TextView tvId; public TextView tvDate; public TextView tvTable; public TextView tvWaiter; public TextView tvPrice; public MyViewHolder(View itemView) { super(itemView); tvDate = (TextView) itemView.findViewById(R.id.date); tvId = (TextView) itemView.findViewById(R.id.id); tvTable = (TextView) itemView.findViewById(R.id.table); tvWaiter = (TextView) itemView.findViewById(R.id.waiter); tvPrice = (TextView) itemView.findViewById(R.id.price); } } }
#!/bin/sh # first install cli for yuml (https://github.com/wandernauta/yuml) class_list='' usecase_list='use-case-back-end use-case-arbitrageur use-case-lender use-case-borrower use-case-lp use-case-fee use-case-yield-farming use-case-borrower-repay' while getopts ":c:u:" opt; do case $opt in c) class_list="$OPTARG" ;; u) usecase_list="$OPTARG" ;; \?) printf "***************************\n" printf "* Error: Invalid argument.*\n" printf "***************************\n" exit 1 ;; esac done for i in $class_list; do yuml -i $i.yuml -t class -s nofunky -f svg -o $i.svg done for i in $usecase_list; do yuml -i $i.yuml -t usecase -s nofunky -f png -o $i.png done
import numpy as np def calculate_metrics_mean(metric_list, video_number): if video_number > 0 and video_number <= len(metric_list): video_metrics = [x for x in metric_list if metric_list.index(x) + 1 == video_number] if video_metrics: metrics_mean = tuple(np.mean(np.array(video_metrics), axis=0)) return metrics_mean else: return "Video number not found in the metric list" else: return "Invalid video number" # Test the function metric_list = [ (0.75, 0.82, 0.63, 0.91, 0.78), (0.68, 0.75, 0.59, 0.88, 0.72), (0.82, 0.88, 0.71, 0.94, 0.81) ] print(calculate_metrics_mean(metric_list, 2)) # Output: (0.75, 0.82, 0.63, 0.91, 0.78)
""" Torrent Search Plugin for Userbot. //torrentdownloads.me cmd: .search search_string Note: Number of results are currently limited to 30 By:-@Zero_cool7870 """ from bs4 import BeautifulSoup as bs import requests from telethon import events from uniborg.util import admin_cmd import asyncio from telegraph import Telegraph telegraph = Telegraph() telegraph.create_account(short_name='{}'.format(borg.me.username)) @borg.on(admin_cmd(pattern="search ?(.*)", allow_sudo=True)) async def tor_search(event): if event.fwd_from: return headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'} search_str = event.pattern_match.group(1) print(search_str) await event.edit("Searching for "+search_str+".....") if " " in search_str: search_str = search_str.replace(" ","+") print(search_str) res = requests.get("https://www.torrentdownloads.me/search/?new=1&s_cat=0&search="+search_str,headers) else: res = requests.get("https://www.torrentdownloads.me/search/?search="+search_str,headers) source = bs(res.text,'lxml') with open("source.html",'w') as f: f.write(str(source)) urls = [] magnets = [] counter = 0 for a in source.find_all('a',{'class':'cloud'}): # print("https://www.torrentdownloads.me"+a['href']) try: urls.append("https://www.torrentdownloads.me"+a['href']) except: pass if counter == 30: break counter = counter + 1 if not urls: await event.edit("Either the Keyword was restricted or not found..") return print("Found URLS....") for url in urls: res = requests.get(url,headers) # print("URl: "+url) source = bs(res.text,'lxml') with open("source2.html",'w') as f: f.write(str(source)) for div in source.find_all('div',{'class':'grey_bar1 back_none'}): try: mg = div.p.a['href'] # print(str(mg)) magnets.append("<b>URL: </b>"+str(url)+"<br/><b>\nMagnet: </b>{}\n<br/>".format(str(mg))) except: pass print("Found Magnets...") msg = "" try: search_str = search_str.replace("+"," ") except: pass for i in magnets: msg = msg + i response = telegraph.create_page( search_str, html_content = msg ) await event.edit('Magnet Links for {}:\nhttps://telegra.ph/{}'.format(search_str,response['path']))
import React, { useState } from "react" import PropTypes from "prop-types" import styled from "styled-components" import { DesktopNav } from "./desktopNav" import { MobileMenu } from "./mobileMenu" import Hamburger from "./hamburger" import { Link } from "gatsby" const Nav = styled.nav` display: flex; width: 100vw; justify-content: space-evenly; align-items: center; height: 15vh; font-family: sans-serif; background-color: #1a042b; opacity: 85%; color: white; z-index: 1000; position: fixed; overflow: visible; top: 0; box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23); ` const Title = styled(Link)` color: white; width: 50%; text-align: center; font-size: 2rem; ` export const Navbar = () => { const [open, setOpen] = useState(false) return ( <Nav className="navbar"> <Title to="/">Atole Tech</Title> <DesktopNav /> <MobileMenu open={open} setOpen={setOpen} /> <Hamburger open={open} setOpen={setOpen} /> </Nav> ) } Navbar.propTypes = { siteTitle: PropTypes.string, } Navbar.defaultProps = { siteTitle: ``, }
#! /bin/bash ########### ## Input ## ########### dir=${1:-"benchmarks"} suite=${2:-"forPR"} # which set of benchmarks to run: full, forPR, forConf useARCH=${3:-0} ################### ## Configuration ## ################### source xeon_scripts/common-variables.sh ${suite} ${useARCH} source xeon_scripts/init-env.sh ###################################### ## Move Compute Performance Results ## ###################################### # Move subroutine build benchmarks builddir="Benchmarks" mkdir -p ${dir}/${builddir} mkdir -p ${dir}/${builddir}/logx for ben_arch in "${arch_array[@]}" do for benchmark in TH VU do oBase=${ben_arch}_${sample}_${benchmark} mv ${oBase}_"time".png ${dir}/${builddir} mv ${oBase}_"speedup".png ${dir}/${builddir} mv ${oBase}_"time_logx".png ${dir}/${builddir}/logx mv ${oBase}_"speedup_logx".png ${dir}/${builddir}/logx done done # Move multiple events in flight plots meifdir="MultEvInFlight" mkdir -p ${dir}/${meifdir} mkdir -p ${dir}/${meifdir}/logx for ben_arch in "${arch_array[@]}" do for build in "${meif_builds[@]}" do echo ${!build} | while read -r bN bO do oBase=${ben_arch}_${sample}_${bN}_"MEIF" mv ${oBase}_"time".png ${dir}/${meifdir} mv ${oBase}_"speedup".png ${dir}/${meifdir} mv ${oBase}_"time_logx".png ${dir}/${meifdir}/logx mv ${oBase}_"speedup_logx".png ${dir}/${meifdir}/logx done done done # Move plots from text dump dumpdir="PlotsFromDump" mkdir -p ${dir}/${dumpdir} mkdir -p ${dir}/${dumpdir}/diffs for build in "${text_builds[@]}" do echo ${!build} | while read -r bN bO do for var in nHits pt eta phi do mv ${sample}_${bN}_${var}.png ${dir}/${dumpdir} mv ${sample}_${bN}_"d"${var}.png ${dir}/${dumpdir}/diffs done done done ###################################### ## Move Physics Performance Results ## ###################################### # Make SimTrack Validation directories simdir=("SIMVAL_MTV" "SIMVAL_MTV_SEED") simval=("SIMVAL" "SIMVALSEED") for((i=0;i<${#simdir[@]};++i));do mkdir -p ${dir}/${simdir[i]} mkdir -p ${dir}/${simdir[i]}/logx mkdir -p ${dir}/${simdir[i]}/diffs mkdir -p ${dir}/${simdir[i]}/nHits mkdir -p ${dir}/${simdir[i]}/score # Move text file dumps for SimTrack Validation for build in "${val_builds[@]}" do echo ${!build} | while read -r bN bO do vBase=${val_arch}_${sample}_${bN} mv "validation"_${vBase}_${simval[i]}/"totals_validation"_${vBase}_${simval[i]}.txt ${dir}/${simdir[i]} done done # Move dummy CMSSW text file (SimTrack Validation) vBase=${val_arch}_${sample}_CMSSW mv validation_${vBase}_${simval[i]}/totals_validation_${vBase}_${simval[i]}.txt ${dir}/${simdir[i]} # Move rate plots for SimTrack Validation for rate in eff ineff_brl ineff_trans ineff_ec dr fr do for pt in 0p0 0p9 2p0 do for var in phi eta nLayers do mv ${val_arch}_${sample}_${rate}_${var}_"build"_"pt"${pt}_${simval[i]}.png ${dir}/${simdir[i]} done done # only copy pt > 0 for pt rate plots for var in pt pt_zoom do mv ${val_arch}_${sample}_${rate}_${var}_"build"_"pt0p0"_${simval[i]}.png ${dir}/${simdir[i]} done mv ${val_arch}_${sample}_${rate}_"pt_logx"_"build"_"pt0p0"_${simval[i]}.png ${dir}/${simdir[i]}/logx done # Move kinematic diff plots for SimTrack Validation for coll in bestmatch allmatch do for var in nHits invpt phi eta do for pt in 0p0 0p9 2p0 do mv ${val_arch}_${sample}_${coll}_"d"${var}_"build"_"pt"${pt}_${simval[i]}.png ${dir}/${simdir[i]}/diffs done done done # Move track quality plots for SimTrack Validation (nHits,score) for coll in allreco fake bestmatch allmatch do for pt in 0p0 0p9 2p0 do for qual in nHits score do mv ${val_arch}_${sample}_${coll}_${qual}_"build"_"pt"${pt}_${simval[i]}.png ${dir}/${simdir[i]}/${qual} done done done done # Final message echo "Finished collecting benchmark plots into ${dir}!"
#!/bin/bash # setup-git-hooks.sh # Copyright (c) 2013-2019 Pablo Acosta-Serafini # See LICENSE for details # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # * Neither the name of the <organization> nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### Functions # Find directory where script is # from http://stackoverflow.com/questions/59895/ # can-a-bash-script-tell-what-directory-its-stored-in) # BASH_SOURCE[0] is the pathname of the currently executing function or script # -h True if file exists and is a symbolic link # cd -P does not follow symbolic links current_dir() { local sdir="$1" local udir="" # Resolve ${sdir} until the file is no longer a symlink while [ -h "${sdir}" ]; do udir="$(cd -P "$(dirname "${sdir}")" && pwd)" sdir="$(readlink "${sdir}")" # If ${sdir} was a relative symlink, we need to resolve it # relative to the path where the symlink file was located [[ "${sdir}" != /* ]] && sdir="${udir}/${sdir}" done udir="$(cd -P "$(dirname "${sdir}")" && pwd)" echo "${udir}" } ### Unofficial strict mode set -euo pipefail IFS=$'\n\t' ### Processing cwd=${PWD} print_banner=0 finish() { if [ "${print_banner}" == 0 ]; then echo "Cleaning up..." print_banner=1 fi cd "${cwd}" || exit 1 exit "${1:-1}" } sdir=$(current_dir "${BASH_SOURCE[0]}") # Configure Git user name and email email=0 personal_repo=0 cfg_fname="${sdir}/repo-cfg.sh" if [ -f "${cfg_fname}" ]; then # shellcheck disable=SC1090,SC1091 source "${sdir}/repo-cfg.sh" else echo "Using default repo config" fi if [ "${email}" == 1 ]; then if [ "${personal_repo}" == 1 ]; then if [ "${PERSONAL_NAME}" != "" ] && [ "${PERSONAL_EMAIL}" != "" ]; then echo "Configuring personal Git author information" git config user.name "${PERSONAL_NAME}" git config user.email "${PERSONAL_EMAIL}" fi else if [ "${WORK_NAME}" != "" ] && [ "${WORK_EMAIL}" != "" ]; then echo "Configuring work Git author information" git config user.name "${WORK_NAME}" git config user.email "${WORK_EMAIL}" fi fi fi repo_dir=$(dirname "${sdir}") # Use pre-commit framework if possible hooks=('pre-commit') if [ -f "${repo_dir}/.pre-commit-config.yaml" ]; then if which pre-commit &> /dev/null; then cd "${repo_dir}" || exit 1 echo "Setting up pre-commit framework" pre-commit install fi hooks=() fi gname="$(basename "$(git rev-parse --show-toplevel)")" if [ "${gname}" == "pypkg" ]; then hooks+=('post-merge') fi if [ "${#hooks[@]}" != 0 ]; then echo "Setting up shell hooks" git_hooks_dir="$(git rev-parse --git-dir)"/hooks cd "${git_hooks_dir}" || exit 1 for hook in ${hooks[*]}; do echo "Setting ${hook} hook" ln -s -f "${sdir}/${hook}" "${hook}" done fi
import tensorflow as tf class ClusterDistanceCalculator(tf.keras.layers.Layer): def __init__(self, feature_dim, num_clusters, **kwargs): super(ClusterDistanceCalculator, self).__init__(**kwargs) self.cluster_centers = self.add_weight( shape=(num_clusters, feature_dim), initializer=tf.random_normal_initializer(stddev=1.0 / math.sqrt(feature_dim)), trainable=True, name="cluster_centers" + str(num_clusters) ) self.feature_dim = feature_dim def calculate_distances(self, frames): # Calculate the Euclidean distances between frames and cluster centers expanded_frames = tf.expand_dims(frames, axis=1) # Add a new axis for broadcasting expanded_centers = tf.expand_dims(self.cluster_centers, axis=0) # Add a new axis for broadcasting squared_diff = tf.square(expanded_frames - expanded_centers) # Calculate squared differences distances = tf.sqrt(tf.reduce_sum(squared_diff, axis=-1)) # Sum across feature dimensions and take square root return distances
#!/bin/sh ## https://www.tensorflow.org/lite/guide/build_cmake #$ ln -s ../../tflite_build/tools/ #GRAPH=tflite_graphs/detect_f.tflite #GRAPH=/media/shin/Linux-Ext/TFseg/models/research/deeplab/tflite_graphs/seg_graph_f.tflite #GRAPH=/media/shin/Linux-Ext/TFseg/models/research/deeplab/tflite_graphs/seg_graph_q.tflite #INPUT=ImageTensor #INPUTSHAPE=1,513,513,3 #GRAPH=tflite_model_mb2/model.tflite #INPUT=serving_default_input:0 #INPUTSHAPE=1,300,300,3 #GRAPH=tflite_model_mb2/model.tflite GRAPH=tflite_model_mb2/model_q.tflite INPUT=serving_default_input:0 INPUTSHAPE=1,300,300,3 /home/shin/app5th/TF/tflite_build/tools/benchmark/benchmark_model \ --graph=$GRAPH \ --benchmark_name=test\ --output_prefix=ttt\ --enable_op_profiling=true\ --verbose=true \ --use_xnnpack=false \ --input_layer=$INPUT \ --input_layer_shape=$INPUTSHAPE \
<gh_stars>1-10 /** * * Events generator for Stock tools * * (c) 2009-2019 <NAME> * * License: www.highcharts.com/license * * */ /** * A config object for bindings in Stock Tools module. * * @interface Highcharts.StockToolsBindingsObject *//** * ClassName of the element for a binding. * @name Highcharts.StockToolsBindingsObject#className * @type {string|undefined} *//** * Last event to be fired after last step event. * @name Highcharts.StockToolsBindingsObject#end * @type {Function|undefined} *//** * Initial event, fired on a button click. * @name Highcharts.StockToolsBindingsObject#init * @type {Function|undefined} *//** * Event fired on first click on a chart. * @name Highcharts.StockToolsBindingsObject#start * @type {Function|undefined} *//** * Last event to be fired after last step event. Array of step events to be * called sequentially after each user click. * @name Highcharts.StockToolsBindingsObject#steps * @type {Array<Function>|undefined} */ 'use strict'; import H from '../parts/Globals.js'; import U from '../parts/Utilities.js'; var defined = U.defined, isNumber = U.isNumber; var fireEvent = H.fireEvent, pick = H.pick, extend = H.extend, merge = H.merge, correctFloat = H.correctFloat, bindingsUtils = H.NavigationBindings.prototype.utils, PREFIX = 'highcharts-'; /** * Generates function which will add a flag series using modal in GUI. * Method fires an event "showPopup" with config: * `{type, options, callback}`. * * Example: NavigationBindings.utils.addFlagFromForm('url(...)') - will * generate function that shows modal in GUI. * * @private * @function bindingsUtils.addFlagFromForm * * @param {string} type * Type of flag series, e.g. "squarepin" * * @return {Function} * Callback to be used in `start` callback */ bindingsUtils.addFlagFromForm = function (type) { return function (e) { var navigation = this, chart = navigation.chart, toolbar = chart.stockTools, getFieldType = bindingsUtils.getFieldType, point = bindingsUtils.attractToPoint(e, chart), pointConfig = { x: point.x, y: point.y }, seriesOptions = { type: 'flags', onSeries: point.series.id, shape: type, data: [pointConfig], point: { events: { click: function () { var point = this, options = point.options; fireEvent( navigation, 'showPopup', { point: point, formType: 'annotation-toolbar', options: { langKey: 'flags', type: 'flags', title: [ options.title, getFieldType( options.title ) ], name: [ options.name, getFieldType( options.name ) ] }, onSubmit: function (updated) { if (updated.actionType === 'remove') { point.remove(); } else { point.update( navigation.fieldsToOptions( updated.fields, {} ) ); } } } ); } } } }; if (!toolbar || !toolbar.guiEnabled) { chart.addSeries(seriesOptions); } fireEvent( navigation, 'showPopup', { formType: 'flag', // Enabled options: options: { langKey: 'flags', type: 'flags', title: ['A', getFieldType('A')], name: ['Flag A', getFieldType('Flag A')] }, // Callback on submit: onSubmit: function (data) { navigation.fieldsToOptions( data.fields, seriesOptions.data[0] ); chart.addSeries(seriesOptions); } } ); }; }; bindingsUtils.manageIndicators = function (data) { var navigation = this, chart = navigation.chart, seriesConfig = { linkedTo: data.linkedTo, type: data.type }, indicatorsWithVolume = [ 'ad', 'cmf', 'mfi', 'vbp', 'vwap' ], indicatorsWithAxes = [ 'ad', 'atr', 'cci', 'cmf', 'macd', 'mfi', 'roc', 'rsi', 'vwap', 'ao', 'aroon', 'aroonoscillator', 'trix', 'apo', 'dpo', 'ppo', 'natr', 'williamsr', 'stochastic', 'linearRegression', 'linearRegressionSlope', 'linearRegressionIntercept', 'linearRegressionAngle' ], yAxis, series; if (data.actionType === 'edit') { navigation.fieldsToOptions(data.fields, seriesConfig); series = chart.get(data.seriesId); if (series) { series.update(seriesConfig, false); } } else if (data.actionType === 'remove') { series = chart.get(data.seriesId); if (series) { yAxis = series.yAxis; if (series.linkedSeries) { series.linkedSeries.forEach(function (linkedSeries) { linkedSeries.remove(false); }); } series.remove(false); if (indicatorsWithAxes.indexOf(series.type) >= 0) { yAxis.remove(false); navigation.resizeYAxes(); } } } else { seriesConfig.id = H.uniqueKey(); navigation.fieldsToOptions(data.fields, seriesConfig); if (indicatorsWithAxes.indexOf(data.type) >= 0) { yAxis = chart.addAxis({ id: H.uniqueKey(), offset: 0, opposite: true, title: { text: '' }, tickPixelInterval: 40, showLastLabel: false, labels: { align: 'left', y: -2 } }, false, false); seriesConfig.yAxis = yAxis.options.id; navigation.resizeYAxes(); } else { seriesConfig.yAxis = chart.get(data.linkedTo).options.yAxis; } if (indicatorsWithVolume.indexOf(data.type) >= 0) { seriesConfig.params.volumeSeriesID = chart.series.filter( function (series) { return series.options.type === 'column'; } )[0].options.id; } chart.addSeries(seriesConfig, false); } fireEvent( navigation, 'deselectButton', { button: navigation.selectedButtonElement } ); chart.redraw(); }; /** * Update height for an annotation. Height is calculated as a difference * between last point in `typeOptions` and current position. It's a value, * not pixels height. * * @private * @function bindingsUtils.updateHeight * * @param {global.Event} e * normalized browser event * * @param {Highcharts.Annotation} annotation * Annotation to be updated */ bindingsUtils.updateHeight = function (e, annotation) { annotation.update({ typeOptions: { height: this.chart.pointer.getCoordinates(e).yAxis[0].value - annotation.options.typeOptions.points[1].y } }); }; // @todo // Consider using getHoverData(), but always kdTree (columns?) bindingsUtils.attractToPoint = function (e, chart) { var coords = chart.pointer.getCoordinates(e), x = coords.xAxis[0].value, y = coords.yAxis[0].value, distX = Number.MAX_VALUE, closestPoint; chart.series.forEach(function (series) { series.points.forEach(function (point) { if (point && distX > Math.abs(point.x - x)) { distX = Math.abs(point.x - x); closestPoint = point; } }); }); return { x: closestPoint.x, y: closestPoint.y, below: y < closestPoint.y, series: closestPoint.series, xAxis: closestPoint.series.xAxis.index || 0, yAxis: closestPoint.series.yAxis.index || 0 }; }; /** * Shorthand to check if given yAxis comes from navigator. * * @private * @function bindingsUtils.isNotNavigatorYAxis * * @param {Highcharts.Axis} axis * Axis * * @return {boolean} */ bindingsUtils.isNotNavigatorYAxis = function (axis) { return axis.userOptions.className !== PREFIX + 'navigator-yaxis'; }; /** * Update each point after specified index, most of the annotations use * this. For example crooked line: logic behind updating each point is the * same, only index changes when adding an annotation. * * Example: NavigationBindings.utils.updateNthPoint(1) - will generate * function that updates all consecutive points except point with index=0. * * @private * @function bindingsUtils.updateNthPoint * * @param {number} startIndex * Index from each point should udpated * * @return {Function} * Callback to be used in steps array */ bindingsUtils.updateNthPoint = function (startIndex) { return function (e, annotation) { var options = annotation.options.typeOptions, coords = this.chart.pointer.getCoordinates(e), x = coords.xAxis[0].value, y = coords.yAxis[0].value; options.points.forEach(function (point, index) { if (index >= startIndex) { point.x = x; point.y = y; } }); annotation.update({ typeOptions: { points: options.points } }); }; }; // Extends NavigationBindigs to support indicators and resizers: extend(H.NavigationBindings.prototype, { /** * Get current positions for all yAxes. If new axis does not have position, * returned is default height and last available top place. * * @private * @function Highcharts.NavigationBindings#getYAxisPositions * * @param {Array<Highcharts.Axis>} yAxes * Array of yAxes available in the chart. * * @param {number} plotHeight * Available height in the chart. * * @param {number} defaultHeight * Default height in percents. * * @return {Array} * An array of calculated positions in percentages. * Format: `{top: Number, height: Number}` */ getYAxisPositions: function (yAxes, plotHeight, defaultHeight) { var positions, allAxesHeight = 0; function isPercentage(prop) { return defined(prop) && !isNumber(prop) && prop.match('%'); } positions = yAxes.map(function (yAxis) { var height = isPercentage(yAxis.options.height) ? parseFloat(yAxis.options.height) / 100 : yAxis.height / plotHeight, top = isPercentage(yAxis.options.top) ? parseFloat(yAxis.options.top) / 100 : correctFloat( yAxis.top - yAxis.chart.plotTop ) / plotHeight; // New yAxis does not contain "height" info yet if (!isNumber(height)) { height = defaultHeight / 100; } allAxesHeight = correctFloat(allAxesHeight + height); return { height: height * 100, top: top * 100 }; }); positions.allAxesHeight = allAxesHeight; return positions; }, /** * Get current resize options for each yAxis. Note that each resize is * linked to the next axis, except the last one which shouldn't affect * axes in the navigator. Because indicator can be removed with it's yAxis * in the middle of yAxis array, we need to bind closest yAxes back. * * @private * @function Highcharts.NavigationBindings#getYAxisResizers * * @param {Array<Highcharts.Axis>} yAxes * Array of yAxes available in the chart * * @return {Array<object>} * An array of resizer options. * Format: `{enabled: Boolean, controlledAxis: { next: [String]}}` */ getYAxisResizers: function (yAxes) { var resizers = []; yAxes.forEach(function (yAxis, index) { var nextYAxis = yAxes[index + 1]; // We have next axis, bind them: if (nextYAxis) { resizers[index] = { enabled: true, controlledAxis: { next: [ pick( nextYAxis.options.id, nextYAxis.options.index ) ] } }; } else { // Remove binding: resizers[index] = { enabled: false }; } }); return resizers; }, /** * Resize all yAxes (except navigator) to fit the plotting height. Method * checks if new axis is added, then shrinks other main axis up to 5 panes. * If added is more thatn 5 panes, it rescales all other axes to fit new * yAxis. * * If axis is removed, and we have more than 5 panes, rescales all other * axes. If chart has less than 5 panes, first pane receives all extra * space. * * @private * @function Highcharts.NavigationBindings#resizeYAxes * * @param {number} defaultHeight * Default height for yAxis */ resizeYAxes: function (defaultHeight) { defaultHeight = defaultHeight || 20; // in %, but as a number var chart = this.chart, // Only non-navigator axes yAxes = chart.yAxis.filter(this.utils.isNotNavigatorYAxis), plotHeight = chart.plotHeight, allAxesLength = yAxes.length, // Gather current heights (in %) positions = this.getYAxisPositions( yAxes, plotHeight, defaultHeight ), resizers = this.getYAxisResizers(yAxes), allAxesHeight = positions.allAxesHeight, changedSpace = defaultHeight; // More than 100% if (allAxesHeight > 1) { // Simple case, add new panes up to 5 if (allAxesLength < 6) { // Added axis, decrease first pane's height: positions[0].height = correctFloat( positions[0].height - changedSpace ); // And update all other "top" positions: positions = this.recalculateYAxisPositions( positions, changedSpace ); } else { // We have more panes, rescale all others to gain some space, // This is new height for upcoming yAxis: defaultHeight = 100 / allAxesLength; // This is how much we need to take from each other yAxis: changedSpace = defaultHeight / (allAxesLength - 1); // Now update all positions: positions = this.recalculateYAxisPositions( positions, changedSpace, true, -1 ); } // Set last position manually: positions[allAxesLength - 1] = { top: correctFloat(100 - defaultHeight), height: defaultHeight }; } else { // Less than 100% changedSpace = correctFloat(1 - allAxesHeight) * 100; // Simple case, return first pane it's space: if (allAxesLength < 5) { positions[0].height = correctFloat( positions[0].height + changedSpace ); positions = this.recalculateYAxisPositions( positions, changedSpace ); } else { // There were more panes, return to each pane a bit of space: changedSpace /= allAxesLength; // Removed axis, add extra space to the first pane: // And update all other positions: positions = this.recalculateYAxisPositions( positions, changedSpace, true, 1 ); } } positions.forEach(function (position, index) { // if (index === 0) debugger; yAxes[index].update({ height: position.height + '%', top: position.top + '%', resize: resizers[index] }, false); }); }, /** * Utility to modify calculated positions according to the remaining/needed * space. Later, these positions are used in `yAxis.update({ top, height })` * * @private * @function Highcharts.NavigationBindings#recalculateYAxisPositions * * @param {Array<object>} positions * Default positions of all yAxes. * * @param {number} changedSpace * How much space should be added or removed. * @param {number} adder * `-1` or `1`, to determine whether we should add or remove space. * * @param {boolean} modifyHeight * Update only `top` or both `top` and `height`. * * @return {Array<object>} * Modified positions, */ recalculateYAxisPositions: function ( positions, changedSpace, modifyHeight, adder ) { positions.forEach(function (position, index) { var prevPosition = positions[index - 1]; position.top = !prevPosition ? 0 : correctFloat(prevPosition.height + prevPosition.top); if (modifyHeight) { position.height = correctFloat( position.height + adder * changedSpace ); } }); return positions; } }); /** * @type {Highcharts.Dictionary<Highcharts.StockToolsBindingsObject>|*} * @since 7.0.0 * @optionparent navigation.bindings */ var stockToolsBindings = { // Line type annotations: /** * A segment annotation bindings. Includes `start` and one event in `steps` * array. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-segment", "start": function() {}, "steps": [function() {}], "annotationsOptions": {}} */ segment: { /** @ignore */ className: 'highcharts-segment', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'segment', type: 'crookedLine', typeOptions: { points: [{ x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }] } }, navigation.annotationsOptions, navigation.bindings.segment.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateNthPoint(1) ] }, /** * A segment with an arrow annotation bindings. Includes `start` and one * event in `steps` array. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-arrow-segment", "start": function() {}, "steps": [function() {}], "annotationsOptions": {}} */ arrowSegment: { /** @ignore */ className: 'highcharts-arrow-segment', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'arrowSegment', type: 'crookedLine', typeOptions: { line: { markerEnd: 'arrow' }, points: [{ x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }] } }, navigation.annotationsOptions, navigation.bindings.arrowSegment.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateNthPoint(1) ] }, /** * A ray annotation bindings. Includes `start` and one event in `steps` * array. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-ray", "start": function() {}, "steps": [function() {}], "annotationsOptions": {}} */ ray: { /** @ignore */ className: 'highcharts-ray', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'ray', type: 'crookedLine', typeOptions: { type: 'ray', points: [{ x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }] } }, navigation.annotationsOptions, navigation.bindings.ray.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateNthPoint(1) ] }, /** * A ray with an arrow annotation bindings. Includes `start` and one event * in `steps` array. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-arrow-ray", "start": function() {}, "steps": [function() {}], "annotationsOptions": {}} */ arrowRay: { /** @ignore */ className: 'highcharts-arrow-ray', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'arrowRay', type: 'infinityLine', typeOptions: { type: 'ray', line: { markerEnd: 'arrow' }, points: [{ x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }] } }, navigation.annotationsOptions, navigation.bindings.arrowRay.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateNthPoint(1) ] }, /** * A line annotation. Includes `start` and one event in `steps` array. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-infinity-line", "start": function() {}, "steps": [function() {}], "annotationsOptions": {}} */ infinityLine: { /** @ignore */ className: 'highcharts-infinity-line', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'infinityLine', type: 'infinityLine', typeOptions: { type: 'line', points: [{ x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }] } }, navigation.annotationsOptions, navigation.bindings.infinityLine.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateNthPoint(1) ] }, /** * A line with arrow annotation. Includes `start` and one event in `steps` * array. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-arrow-infinity-line", "start": function() {}, "steps": [function() {}], "annotationsOptions": {}} */ arrowInfinityLine: { /** @ignore */ className: 'highcharts-arrow-infinity-line', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'arrowInfinityLine', type: 'infinityLine', typeOptions: { type: 'line', line: { markerEnd: 'arrow' }, points: [{ x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }] } }, navigation.annotationsOptions, navigation.bindings.arrowInfinityLine.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateNthPoint(1) ] }, /** * A horizontal line annotation. Includes `start` event. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-horizontal-line", "start": function() {}, "annotationsOptions": {}} */ horizontalLine: { /** @ignore */ className: 'highcharts-horizontal-line', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'horizontalLine', type: 'infinityLine', draggable: 'y', typeOptions: { type: 'horizontalLine', points: [{ x: coords.xAxis[0].value, y: coords.yAxis[0].value }] } }, navigation.annotationsOptions, navigation.bindings.horizontalLine.annotationsOptions ); this.chart.addAnnotation(options); } }, /** * A vertical line annotation. Includes `start` event. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-vertical-line", "start": function() {}, "annotationsOptions": {}} */ verticalLine: { /** @ignore */ className: 'highcharts-vertical-line', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'verticalLine', type: 'infinityLine', draggable: 'x', typeOptions: { type: 'verticalLine', points: [{ x: coords.xAxis[0].value, y: coords.yAxis[0].value }] } }, navigation.annotationsOptions, navigation.bindings.verticalLine.annotationsOptions ); this.chart.addAnnotation(options); } }, /** * Crooked line (three points) annotation bindings. Includes `start` and two * events in `steps` (for second and third points in crooked line) array. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-crooked3", "start": function() {}, "steps": [function() {}, function() {}], "annotationsOptions": {}} */ // Crooked Line type annotations: crooked3: { /** @ignore */ className: 'highcharts-crooked3', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'crooked3', type: 'crookedLine', typeOptions: { points: [{ x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }] } }, navigation.annotationsOptions, navigation.bindings.crooked3.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateNthPoint(1), bindingsUtils.updateNthPoint(2) ] }, /** * Crooked line (five points) annotation bindings. Includes `start` and four * events in `steps` (for all consequent points in crooked line) array. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-crooked3", "start": function() {}, "steps": [function() {}, function() {}, function() {}, function() {}], "annotationsOptions": {}} */ crooked5: { /** @ignore */ className: 'highcharts-crooked5', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'crookedLine', type: 'crookedLine', typeOptions: { points: [{ x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }] } }, navigation.annotationsOptions, navigation.bindings.crooked5.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateNthPoint(1), bindingsUtils.updateNthPoint(2), bindingsUtils.updateNthPoint(3), bindingsUtils.updateNthPoint(4) ] }, /** * Elliott wave (three points) annotation bindings. Includes `start` and two * events in `steps` (for second and third points) array. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-elliott3", "start": function() {}, "steps": [function() {}, function() {}], "annotationsOptions": {}} */ elliott3: { /** @ignore */ className: 'highcharts-elliott3', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'elliott3', type: 'elliottWave', typeOptions: { points: [{ x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }] }, labelOptions: { style: { color: '#666666' } } }, navigation.annotationsOptions, navigation.bindings.elliott3.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateNthPoint(1), bindingsUtils.updateNthPoint(2), bindingsUtils.updateNthPoint(3) ] }, /** * Elliott wave (five points) annotation bindings. Includes `start` and four * event in `steps` (for all consequent points in Elliott wave) array. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-elliott3", "start": function() {}, "steps": [function() {}, function() {}, function() {}, function() {}], "annotationsOptions": {}} */ elliott5: { /** @ignore */ className: 'highcharts-elliott5', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'elliott5', type: 'elliottWave', typeOptions: { points: [{ x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }] }, labelOptions: { style: { color: '#666666' } } }, navigation.annotationsOptions, navigation.bindings.elliott5.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateNthPoint(1), bindingsUtils.updateNthPoint(2), bindingsUtils.updateNthPoint(3), bindingsUtils.updateNthPoint(4), bindingsUtils.updateNthPoint(5) ] }, /** * A measure (x-dimension) annotation bindings. Includes `start` and one * event in `steps` array. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-measure-x", "start": function() {}, "steps": [function() {}], "annotationsOptions": {}} */ measureX: { /** @ignore */ className: 'highcharts-measure-x', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'measure', type: 'measure', typeOptions: { selectType: 'x', point: { x: coords.xAxis[0].value, y: coords.yAxis[0].value, xAxis: 0, yAxis: 0 }, crosshairX: { strokeWidth: 1, stroke: '#000000' }, crosshairY: { enabled: false, strokeWidth: 0, stroke: '#000000' }, background: { width: 0, height: 0, strokeWidth: 0, stroke: '#ffffff' } }, labelOptions: { style: { color: '#666666' } } }, navigation.annotationsOptions, navigation.bindings.measureX.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateRectSize ] }, /** * A measure (y-dimension) annotation bindings. Includes `start` and one * event in `steps` array. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-measure-y", "start": function() {}, "steps": [function() {}], "annotationsOptions": {}} */ measureY: { /** @ignore */ className: 'highcharts-measure-y', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'measure', type: 'measure', typeOptions: { selectType: 'y', point: { x: coords.xAxis[0].value, y: coords.yAxis[0].value, xAxis: 0, yAxis: 0 }, crosshairX: { enabled: false, strokeWidth: 0, stroke: '#000000' }, crosshairY: { strokeWidth: 1, stroke: '#000000' }, background: { width: 0, height: 0, strokeWidth: 0, stroke: '#ffffff' } }, labelOptions: { style: { color: '#666666' } } }, navigation.annotationsOptions, navigation.bindings.measureY.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateRectSize ] }, /** * A measure (xy-dimension) annotation bindings. Includes `start` and one * event in `steps` array. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-measure-xy", "start": function() {}, "steps": [function() {}], "annotationsOptions": {}} */ measureXY: { /** @ignore */ className: 'highcharts-measure-xy', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'measure', type: 'measure', typeOptions: { selectType: 'xy', point: { x: coords.xAxis[0].value, y: coords.yAxis[0].value, xAxis: 0, yAxis: 0 }, background: { width: 0, height: 0, strokeWidth: 10 }, crosshairX: { strokeWidth: 1, stroke: '#000000' }, crosshairY: { strokeWidth: 1, stroke: '#000000' } }, labelOptions: { style: { color: '#666666' } } }, navigation.annotationsOptions, navigation.bindings.measureXY.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateRectSize ] }, // Advanced type annotations: /** * A fibonacci annotation bindings. Includes `start` and two events in * `steps` array (updates second point, then height). * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-fibonacci", "start": function() {}, "steps": [function() {}, function() {}], "annotationsOptions": {}} */ fibonacci: { /** @ignore */ className: 'highcharts-fibonacci', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'fibonacci', type: 'fibonacci', typeOptions: { points: [{ x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }] }, labelOptions: { style: { color: '#666666' } } }, navigation.annotationsOptions, navigation.bindings.fibonacci.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateNthPoint(1), bindingsUtils.updateHeight ] }, /** * A parallel channel (tunnel) annotation bindings. Includes `start` and * two events in `steps` array (updates second point, then height). * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-parallel-channel", "start": function() {}, "steps": [function() {}, function() {}], "annotationsOptions": {}} */ parallelChannel: { /** @ignore */ className: 'highcharts-parallel-channel', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'parallelChannel', type: 'tunnel', typeOptions: { points: [{ x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }] } }, navigation.annotationsOptions, navigation.bindings.parallelChannel.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateNthPoint(1), bindingsUtils.updateHeight ] }, /** * An Andrew's pitchfork annotation bindings. Includes `start` and two * events in `steps` array (sets second and third control points). * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-pitchfork", "start": function() {}, "steps": [function() {}, function() {}], "annotationsOptions": {}} */ pitchfork: { /** @ignore */ className: 'highcharts-pitchfork', /** @ignore */ start: function (e) { var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, options = merge( { langKey: 'pitchfork', type: 'pitchfork', typeOptions: { points: [{ x: coords.xAxis[0].value, y: coords.yAxis[0].value, controlPoint: { style: { fill: 'red' } } }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }, { x: coords.xAxis[0].value, y: coords.yAxis[0].value }], innerBackground: { fill: 'rgba(100, 170, 255, 0.8)' } }, shapeOptions: { strokeWidth: 2 } }, navigation.annotationsOptions, navigation.bindings.pitchfork.annotationsOptions ); return this.chart.addAnnotation(options); }, /** @ignore */ steps: [ bindingsUtils.updateNthPoint(1), bindingsUtils.updateNthPoint(2) ] }, // Labels with arrow and auto increments /** * A vertical counter annotation bindings. Includes `start` event. On click, * finds the closest point and marks it with a numeric annotation - * incrementing counter on each add. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-vertical-counter", "start": function() {}, "annotationsOptions": {}} */ verticalCounter: { /** @ignore */ className: 'highcharts-vertical-counter', /** @ignore */ start: function (e) { var closestPoint = bindingsUtils.attractToPoint(e, this.chart), navigation = this.chart.options.navigation, verticalCounter = !defined(this.verticalCounter) ? 0 : this.verticalCounter, options = merge( { langKey: 'verticalCounter', type: 'verticalLine', typeOptions: { point: { x: closestPoint.x, y: closestPoint.y, xAxis: closestPoint.xAxis, yAxis: closestPoint.yAxis }, label: { offset: closestPoint.below ? 40 : -40, text: verticalCounter.toString() } }, labelOptions: { style: { color: '#666666', fontSize: '11px' } }, shapeOptions: { stroke: 'rgba(0, 0, 0, 0.75)', strokeWidth: 1 } }, navigation.annotationsOptions, navigation.bindings.verticalCounter.annotationsOptions ), annotation; annotation = this.chart.addAnnotation(options); verticalCounter++; annotation.options.events.click.call(annotation, {}); } }, /** * A vertical arrow annotation bindings. Includes `start` event. On click, * finds the closest point and marks it with an arrow and a label with * value. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-vertical-label", "start": function() {}, "annotationsOptions": {}} */ verticalLabel: { /** @ignore */ className: 'highcharts-vertical-label', /** @ignore */ start: function (e) { var closestPoint = bindingsUtils.attractToPoint(e, this.chart), navigation = this.chart.options.navigation, options = merge( { langKey: 'verticalLabel', type: 'verticalLine', typeOptions: { point: { x: closestPoint.x, y: closestPoint.y, xAxis: closestPoint.xAxis, yAxis: closestPoint.yAxis }, label: { offset: closestPoint.below ? 40 : -40 } }, labelOptions: { style: { color: '#666666', fontSize: '11px' } }, shapeOptions: { stroke: 'rgba(0, 0, 0, 0.75)', strokeWidth: 1 } }, navigation.annotationsOptions, navigation.bindings.verticalLabel.annotationsOptions ), annotation; annotation = this.chart.addAnnotation(options); annotation.options.events.click.call(annotation, {}); } }, /** * A vertical arrow annotation bindings. Includes `start` event. On click, * finds the closest point and marks it with an arrow. Green arrow when * pointing from above, red when pointing from below the point. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-vertical-arrow", "start": function() {}, "annotationsOptions": {}} */ verticalArrow: { /** @ignore */ className: 'highcharts-vertical-arrow', /** @ignore */ start: function (e) { var closestPoint = bindingsUtils.attractToPoint(e, this.chart), navigation = this.chart.options.navigation, options = merge( { langKey: 'verticalArrow', type: 'verticalLine', typeOptions: { point: { x: closestPoint.x, y: closestPoint.y, xAxis: closestPoint.xAxis, yAxis: closestPoint.yAxis }, label: { offset: closestPoint.below ? 40 : -40, format: ' ' }, connector: { fill: 'none', stroke: closestPoint.below ? 'red' : 'green' } }, shapeOptions: { stroke: 'rgba(0, 0, 0, 0.75)', strokeWidth: 1 } }, navigation.annotationsOptions, navigation.bindings.verticalArrow.annotationsOptions ), annotation; annotation = this.chart.addAnnotation(options); annotation.options.events.click.call(annotation, {}); } }, // Flag types: /** * A flag series bindings. Includes `start` event. On click, finds the * closest point and marks it with a flag with `'circlepin'` shape. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-flag-circlepin", "start": function() {}} */ flagCirclepin: { /** @ignore */ className: 'highcharts-flag-circlepin', /** @ignore */ start: bindingsUtils .addFlagFromForm('circlepin') }, /** * A flag series bindings. Includes `start` event. On click, finds the * closest point and marks it with a flag with `'diamondpin'` shape. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-flag-diamondpin", "start": function() {}} */ flagDiamondpin: { /** @ignore */ className: 'highcharts-flag-diamondpin', /** @ignore */ start: bindingsUtils .addFlagFromForm('flag') }, /** * A flag series bindings. Includes `start` event. * On click, finds the closest point and marks it with a flag with * `'squarepin'` shape. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-flag-squarepin", "start": function() {}} */ flagSquarepin: { /** @ignore */ className: 'highcharts-flag-squarepin', /** @ignore */ start: bindingsUtils .addFlagFromForm('squarepin') }, /** * A flag series bindings. Includes `start` event. * On click, finds the closest point and marks it with a flag without pin * shape. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-flag-simplepin", "start": function() {}} */ flagSimplepin: { /** @ignore */ className: 'highcharts-flag-simplepin', /** @ignore */ start: bindingsUtils .addFlagFromForm('nopin') }, // Other tools: /** * Enables zooming in xAxis on a chart. Includes `start` event which * changes [chart.zoomType](#chart.zoomType). * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-zoom-x", "init": function() {}} */ zoomX: { /** @ignore */ className: 'highcharts-zoom-x', /** @ignore */ init: function (button) { this.chart.update({ chart: { zoomType: 'x' } }); fireEvent( this, 'deselectButton', { button: button } ); } }, /** * Enables zooming in yAxis on a chart. Includes `start` event which * changes [chart.zoomType](#chart.zoomType). * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-zoom-y", "init": function() {}} */ zoomY: { /** @ignore */ className: 'highcharts-zoom-y', /** @ignore */ init: function (button) { this.chart.update({ chart: { zoomType: 'y' } }); fireEvent( this, 'deselectButton', { button: button } ); } }, /** * Enables zooming in xAxis and yAxis on a chart. Includes `start` event * which changes [chart.zoomType](#chart.zoomType). * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-zoom-xy", "init": function() {}} */ zoomXY: { /** @ignore */ className: 'highcharts-zoom-xy', /** @ignore */ init: function (button) { this.chart.update({ chart: { zoomType: 'xy' } }); fireEvent( this, 'deselectButton', { button: button } ); } }, /** * Changes main series to `'line'` type. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-series-type-line", "init": function() {}} */ seriesTypeLine: { /** @ignore */ className: 'highcharts-series-type-line', /** @ignore */ init: function (button) { this.chart.series[0].update({ type: 'line', useOhlcData: true }); fireEvent( this, 'deselectButton', { button: button } ); } }, /** * Changes main series to `'ohlc'` type. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-series-type-ohlc", "init": function() {}} */ seriesTypeOhlc: { /** @ignore */ className: 'highcharts-series-type-ohlc', /** @ignore */ init: function (button) { this.chart.series[0].update({ type: 'ohlc' }); fireEvent( this, 'deselectButton', { button: button } ); } }, /** * Changes main series to `'candlestick'` type. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-series-type-candlestick", "init": function() {}} */ seriesTypeCandlestick: { /** @ignore */ className: 'highcharts-series-type-candlestick', /** @ignore */ init: function (button) { this.chart.series[0].update({ type: 'candlestick' }); fireEvent( this, 'deselectButton', { button: button } ); } }, /** * Displays chart in fullscreen. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-full-screen", "init": function() {}} */ fullScreen: { /** @ignore */ className: 'highcharts-full-screen', /** @ignore */ init: function (button) { var chart = this.chart; chart.fullScreen = new H.FullScreen(chart.container); fireEvent( this, 'deselectButton', { button: button } ); } }, /** * Hides/shows two price indicators: * - last price in the dataset * - last price in the selected range * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-current-price-indicator", "init": function() {}} */ currentPriceIndicator: { /** @ignore */ className: 'highcharts-current-price-indicator', /** @ignore */ init: function (button) { var chart = this.chart, series = chart.series[0], options = series.options, lastVisiblePrice = options.lastVisiblePrice && options.lastVisiblePrice.enabled, lastPrice = options.lastPrice && options.lastPrice.enabled, gui = chart.stockTools, iconsURL = gui.getIconsURL(); if (gui && gui.guiEnabled) { if (lastPrice) { button.firstChild.style['background-image'] = 'url("' + iconsURL + 'current-price-show.svg")'; } else { button.firstChild.style['background-image'] = 'url("' + iconsURL + 'current-price-hide.svg")'; } } series.update({ // line lastPrice: { enabled: !lastPrice, color: 'red' }, // label lastVisiblePrice: { enabled: !lastVisiblePrice, label: { enabled: true } } }); fireEvent( this, 'deselectButton', { button: button } ); } }, /** * Indicators bindings. Includes `init` event to show a popup. * * Note: In order to show base series from the chart in the popup's * dropdown each series requires * [series.id](https://api.highcharts.com/highstock/series.line.id) to be * defined. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-indicators", "init": function() {}} */ indicators: { /** @ignore */ className: 'highcharts-indicators', /** @ignore */ init: function () { var navigation = this; fireEvent( navigation, 'showPopup', { formType: 'indicators', options: {}, // Callback on submit: onSubmit: function (data) { navigation.utils.manageIndicators.call( navigation, data ); } } ); } }, /** * Hides/shows all annotations on a chart. * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-toggle-annotations", "init": function() {}} */ toggleAnnotations: { /** @ignore */ className: 'highcharts-toggle-annotations', /** @ignore */ init: function (button) { var chart = this.chart, gui = chart.stockTools, iconsURL = gui.getIconsURL(); this.toggledAnnotations = !this.toggledAnnotations; (chart.annotations || []).forEach(function (annotation) { annotation.setVisibility(!this.toggledAnnotations); }, this); if (gui && gui.guiEnabled) { if (this.toggledAnnotations) { button.firstChild.style['background-image'] = 'url("' + iconsURL + 'annotations-hidden.svg")'; } else { button.firstChild.style['background-image'] = 'url("' + iconsURL + 'annotations-visible.svg")'; } } fireEvent( this, 'deselectButton', { button: button } ); } }, /** * Save a chart in localStorage under `highcharts-chart` key. * Stored items: * - annotations * - indicators (with yAxes) * - flags * * @type {Highcharts.StockToolsBindingsObject} * @product highstock * @default {"className": "highcharts-save-chart", "init": function() {}} */ saveChart: { /** @ignore */ className: 'highcharts-save-chart', /** @ignore */ init: function (button) { var navigation = this, chart = navigation.chart, annotations = [], indicators = [], flags = [], yAxes = []; chart.annotations.forEach(function (annotation, index) { annotations[index] = annotation.userOptions; }); chart.series.forEach(function (series) { if (series instanceof H.seriesTypes.sma) { indicators.push(series.userOptions); } else if (series.type === 'flags') { flags.push(series.userOptions); } }); chart.yAxis.forEach(function (yAxis) { if (navigation.utils.isNotNavigatorYAxis(yAxis)) { yAxes.push(yAxis.options); } }); H.win.localStorage.setItem( PREFIX + 'chart', JSON.stringify({ annotations: annotations, indicators: indicators, flags: flags, yAxes: yAxes }) ); fireEvent( this, 'deselectButton', { button: button } ); } } }; H.setOptions({ navigation: { bindings: stockToolsBindings } });
<filename>javascript/es2017-async-await/async-await.js const fs = require('fs') const util = require('util') // utilitário transforma o método nativo em callback-style em promise-style const readFile = util.promisify(fs.readFile) const run = async () => { // Promise version - método convencional readFile('./resources/scientists1.json') .then(scientistsJson => { try { console.log(JSON.parse(scientistsJson)[0]) } catch (err) { console.error('Não foi possível fazer o parse do arquivo', err) } }) .catch(err => console.error('Ocorreu um erro inesperado', err)) // Async-Await version try { const scientistsJson = await readFile('./resources/scientists1.json') console.log(JSON.parse(scientistsJson)[0]) } catch (err) { // trata erros como o reject de uma Promise // também já trata erros do método parse do JSON console.error('Ocorreu um erro inesperado', err) } } run();
# Define the base class Model for the language model class Model: def __init__(self): pass # Add methods and attributes as needed for the base class # Define a subclass FilteringWordModel inheriting from Model class FilteringWordModel(Model): def __init__(self): super().__init__() # Implement specific functionality for FilteringWordModel # Define a subclass WordModel inheriting from Model class WordModel(Model): def __init__(self): super().__init__() # Implement specific functionality for WordModel # Implement any necessary utilities for the top-level functionality # Add any additional classes, functions, or constants required for the language model challenge
<reponame>maven-nar/cpptasks-parallel<filename>src/main/java/com/github/maven_nar/cpptasks/compiler/LinkerConfiguration.java /* * * Copyright 2002-2004 The Ant-Contrib project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.maven_nar.cpptasks.compiler; import org.apache.tools.ant.BuildException; import com.github.maven_nar.cpptasks.CCTask; import com.github.maven_nar.cpptasks.LinkerParam; import com.github.maven_nar.cpptasks.TargetInfo; /** * A configuration for a linker * * @author <NAME> */ public interface LinkerConfiguration extends ProcessorConfiguration { public LinkerParam getParam(String name); void link(CCTask task, TargetInfo linkTarget) throws BuildException; Linker getLinker(); boolean isDebug(); }
#!/bin/sh docker build . -t hainm/nglview
from bottle import Bottle, run, request, response app = Bottle() @app.get('/greet') def greet(): return "Hello, welcome to our web service!" @app.post('/personalized_greet') def personalized_greet(): data = request.json name = data.get('name') if name: return f"Hello, {name}! Welcome to our web service!" else: response.status = 400 return "Bad Request: Name not provided." if __name__ == '__main__': run(app, host='localhost', port=8080)
#!/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. set -e set -x pip install opencv-python pip install scipy pip install pygame # Install arcade learning environment if [[ "$OSTYPE" == "linux-gnu" ]]; then sudo apt-get install libsdl1.2-dev libsdl-gfx1.2-dev libsdl-image1.2-dev cmake ninja-build elif [[ "$OSTYPE" == "darwin"* ]]; then brew install sdl sdl_image sdl_mixer sdl_ttf portmidi fi git clone https://github.com/mgbellemare/Arcade-Learning-Environment || true pushd . cd Arcade-Learning-Environment mkdir -p build cd build cmake -DUSE_SDL=ON -DUSE_RLGLUE=OFF -DBUILD_EXAMPLES=ON -GNinja .. ninja cd .. pip install -e . popd cp Arcade-Learning-Environment/ale.cfg . # Copy roms git clone https://github.com/npow/atari || true cp -R atari/roms .
<filename>src/app/shopping/components/shopping/shopping.component.ts import { Component, OnInit } from '@angular/core'; import { Title } from '@angular/platform-browser'; @Component({ selector: 'app-shopping', templateUrl: './shopping.component.html', styleUrls: ['./shopping.component.scss'] }) export class ShoppingComponent implements OnInit { constructor(private titleService: Title // Inject to set document title on browser ) { } ngOnInit(): void { this.titleService.setTitle('MNS237 - Shopping'); // Adding the title Home to the MNS237 main Title } }
class ListNode: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None # Function to delete the node at a given position def delete(self, position): # if list is empty if self.head == None: return # store head node temp = self.head # if head needs to be removed if position == 0: self.head = temp.next temp = None return # find previous node of the node to be deleted for _ in range(position -1 ): temp = temp.next if temp is None: break # if position is more than number of nodes if temp is None: return if temp.next is None: return # Node temp.next is the node to be deleted # store pointer to the next of node to be deleted next = temp.next.next # Unlink the node from linked list temp.next = None temp.next = next # Example list = LinkedList() list.head = ListNode(4) second = ListNode(5) third = ListNode(6) fourth = ListNode(7) list.head.next = second second.next = third third.next = fourth list.delete(2)
public static String longestWord(String input) { String longestWord = ""; String [] words = input.split(" "); for(String word: words){ if(word.length() > longestWord.length()) longestWord = word; } return longestWord; } System.out.println(longestWord(input)); # Output: "jumped"
func extractFunctionNames(_ codeSnippet: String) -> [String] { var functionNames: [String] = [] let pattern = "func\\s+([a-zA-Z0-9_]+)\\s*\\(" do { let regex = try NSRegularExpression(pattern: pattern, options: []) let matches = regex.matches(in: codeSnippet, options: [], range: NSRange(location: 0, length: codeSnippet.utf16.count)) for match in matches { if let range = Range(match.range(at: 1), in: codeSnippet) { let functionName = String(codeSnippet[range]) functionNames.append(functionName) } } } catch { print("Error creating regex") } return functionNames } // Test let codeSnippet = """ } func basicStyle() { view.backgroundColor = .white // self.navigationController?.navigationBar.isTranslucent = false } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) """ print(extractFunctionNames(codeSnippet)) // Output: ["basicStyle", "viewWillAppear"]
import { performance } from 'perf_hooks' import { install as installSourceMap } from 'source-map-support' import consola from 'consola' import { CoverageInstrumenter } from 'collect-v8-coverage' import fs from 'fs-extra' import pragma from 'pragma' import { InstantiableTestEnvironmentClass, mergeConfig } from '@peeky/config' import type { Context, RunTestFileOptions, TestSuiteResult } from '../types' import { useVite } from './vite.js' import { getGlobals } from './globals.js' import { runTests } from './run-tests.js' import { setupRegister } from './test-register.js' import { getCoverage } from './coverage.js' import { mockedModules } from './mocked-files.js' import { getTestEnvironment, NodeEnvironment } from './environment.js' import { createMockedFileSystem } from './fs.js' import { moduleCache, sourceMaps } from './module-cache.js' import { baseConfig, setupWorker } from './setup.js' import { toMainThread } from './message.js' export async function runTestFile (options: RunTestFileOptions) { try { const time = performance.now() await setupWorker() const config = mergeConfig(baseConfig, options.config) options.clearDeps.forEach(file => moduleCache.delete(file)) const source = await fs.readFile(options.entry, { encoding: 'utf8' }) let pragmaObject: Record<string, any> try { const index = source.indexOf('/* @peeky') if (index !== -1) { const endIndex = source.indexOf('*/', index) if (endIndex !== -1) { pragmaObject = pragma(source.substring(index, endIndex + 2)).peeky } } } catch (e) { consola.warn(`Failed to parse pragma for ${options.entry}: ${e.message}`) } const ctx: Context = { options, suites: [], pragma: pragmaObject ?? {}, } // Restore mocked module mockedModules.clear() // Build const { executeWithVite } = useVite({ rootDir: config.targetDirectory, exclude: config.buildExclude, include: config.buildInclude, }, (id) => toMainThread().transform(id)) // Globals const register = setupRegister(ctx) // Source map support installSourceMap({ retrieveSourceMap: (source) => { if (sourceMaps.has(source)) { return { url: source, map: sourceMaps.get(source), } } }, }) // Runtime env const runtimeEnvOption = ctx.pragma.runtimeEnv ?? config.runtimeEnv let RuntimeEnv: InstantiableTestEnvironmentClass if (typeof runtimeEnvOption === 'string') { RuntimeEnv = getTestEnvironment(runtimeEnvOption, config) } else if (runtimeEnvOption) { RuntimeEnv = runtimeEnvOption } else { RuntimeEnv = NodeEnvironment } const runtimeEnv = new RuntimeEnv(config, { testPath: options.entry, pragma: ctx.pragma, }) await runtimeEnv.create() let ufs if ((config.mockFs && ctx.pragma.mockFs !== false) || ctx.pragma.mockFs) { ufs = createMockedFileSystem() } // Execute test file const executionResult = await executeWithVite(options.entry, await getGlobals(ctx, register), config.targetDirectory) // Register suites and tests await register.collect() const instrumenter = new CoverageInstrumenter() await instrumenter.startInstrumenting() // Run all tests in the test file if (ufs) ufs._enabled = true await runTests(ctx) if (ufs) ufs._enabled = false const coverage = await getCoverage(await instrumenter.stopInstrumenting(), ctx) await runtimeEnv.destroy() const duration = performance.now() - time // Result data const suites: TestSuiteResult[] = ctx.suites.map(s => ({ id: s.id, title: s.title, filePath: s.filePath, testErrors: s.testErrors, otherErrors: s.otherErrors, tests: s.tests.map(t => ({ id: t.id, title: t.title, error: t.error, flag: t.flag, })), runTestCount: s.ranTests.length, })) return { filePath: options.entry, suites, duration, coverage, deps: executionResult.deps.concat(options.entry), } } catch (e) { consola.error(`Running tests failed: ${e.stack}`) throw e } }
#!/bin/bash ## Based on https://www.mirantis.com/blog/how-to-install-openstack-on-your-local-machine-using-devstack/ ## It is essential to create a stack user with sudo access or else you will get a HOST_IP error: ## https://stackoverflow.com/questions/46192965/error-in-running-stack-sh-in-devstack ## Revision History: ## 20200113-01 - NS - First version ## It is essential to create a stack user with sudo access or else you will get a HOST_IP error: ## https://stackoverflow.com/questions/46192965/error-in-running-stack-sh-in-devstack ## 20200115-01 - NS - Multiple updates. ## Added timestamping. The script should be copied and pasted in a shell terminal ## Before executing the commands below, execute "sudo ls" to cache the password first. ## 20200115-02 - NS - NB: Very Important!!!, your local DNS server could prevent the script from connecting to the amazon web servers ## e.g. Connecting to github-production-release-asset-2e65be.s3.amazonaws.com (github-production-release-asset-2e65be.s3.amazonaws.com)|52.217.32.204|:443 ## https://github.com/HaxeFoundation/haxe/issues/8900 ## Please use a DNS server such as 8.8.8. or 1.1.1.1. You may have to add it manually on your local desktop or in your DHCP server add these as the first DNS servers. ## 20200228-01 - NS - Installtion of Cinder ## Pages: https://discoposse.com/2013/02/26/openstack-lab-on-vmware-workstation-adding-cinder-volume-features/ ## ## ## 20200229-01 - NS - To use ubuntu 18.04.4 LTS ## Additional services require python 3.6 ## ## ## 20200302-01 - NS - To use ubuntu 16.04.4 LTS ## Installing Rocky release ## ## ### https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get ### sudo add-apt-repository ppa:deadsnakes/ppa -y ### sudo apt-get update -y ### sudo apt-get install python3.6 -y ## https://askubuntu.com/questions/590027/how-to-set-python-3-as-default-interpreter-in-ubuntu-14-04 ## Must execute in new user environment - each time you sudo su - ### alias python=/usr/bin/python3.6 ## https://stackoverflow.com/questions/6587507/how-to-install-pip-with-python-3 ### sudo apt-get install python-pip -y ### sudo apt-get install python3-pip -y ## https://www.liquidweb.com/kb/how-to-install-pip-on-ubuntu-14-04-lts/ ### sudo pip install --upgrade pip ### sudo pip3 install --upgrade pip ## Do not need this: http://devopspy.com/python/install-python-3-6-ubuntu-lts/ ## https://askubuntu.com/questions/590027/how-to-set-python-3-as-default-interpreter-in-ubuntu-14-04 ##alias pip=/usr/bin/python3.6 ### Automatically disabled Acquire::http::Pipeline-Depth due to incorrect response from server/proxy. (man 5 apt.conf) ### https://www.serverlab.ca/tutorials/linux/administration-linux/how-to-set-the-proxy-for-apt-for-ubuntu-18-04/ ### https://askubuntu.com/questions/344802/why-is-apt-get-always-using-proxy-although-no-proxy-is-configured wget https://raw.githubusercontent.com/NareshSeegobin/CourseProjectRepo/master/3606_2019-2020/installOpenStack-site05-release-rocky-pre-Reqs.sh chmod 777 ./installOpenStack-site05-release-rocky-pre-Reqs.sh sudo -H /bin/bash ./installOpenStack-site05-release-rocky-pre-Reqs.sh sudo su - touch /etc/apt/apt.conf.d/proxy.conf cat > /etc/apt/apt.conf.d/proxy.conf <<EOF Acquire::http::Proxy "false"; Acquire::https::Proxy "false"; Acquire::ftp::Proxy "false"; EOF ### https://gist.github.com/trastle/5722089 ### https://askubuntu.com/questions/679233/failed-to-fetch-hash-sum-mismatch-tried-rm-apt-list-but-didnt-work touch /etc/apt/apt.conf.d/99fixbadproxy cat > /etc/apt/apt.conf.d/99fixbadproxy <<EOF Acquire::http::Pipeline-Depth "0"; Acquire::http::Pipeline-Depth "0"; Acquire::http::No-Cache=True; Acquire::https::Pipeline-Depth "0"; Acquire::https::No-Cache=True; Acquire::ftp::Pipeline-Depth "0"; Acquire::ftp::No-Cache=True; Acquire::BrokenProxy=true; EOF ## exit sudo su - exit sudo apt-get update -y && sudo apt-get upgrade -y && sleep 5 ### Execute seprately from apt get update sudo -H apt-get install python -y && sleep 5 && sudo apt-get install python-dev -y && sleep 5 && sudo -H apt-get install python-pip -y && sudo -H python -m pip install "Django<2" && sleep 5 ### https://wiki.openstack.org/wiki/Python3 sudo -H apt-get install python3-dev -y && sudo -H apt-get install python3-pip -y && sudo -H pip3 install --upgrade pip && sudo -H python3 -m pip install python-memcached && sleep 5 ## https://askubuntu.com/questions/712339/how-to-upgrade-pip-to-latest ## https://stackoverflow.com/questions/38613316/how-to-upgrade-pip3 sudo -H pip3 install --upgrade pip && sleep 10 && echo endSleep ## 20200303-01 - NS - May need to install django python module. Not so syre why they just didn't install it. ## https://docs.djangoproject.com/en/3.0/topics/install/ sudo -H python3 -m pip install Django && sleep 10 && echo endSleep ## 20200303-01 - NS - Might have to diable sahara ## ImportError: No module named openstack_dashboard.settings ## https://answers.launchpad.net/horizon/+question/239533 ## https://duckduckgo.com/?q=DJANGO_SETTINGS_MODULE%3Dopenstack_dashboard.settings&t=brave&ia=web ## https://ask.openstack.org/en/question/69331/importerror-could-not-import-settings-openstack_dashboardsettings-is-it-on-syspath-is-there-an-import-error-in-the-settings-file-no-module-named/ sudo -H apt-get install python-pbr -y sudo useradd -s /bin/bash -d /opt/stack -m stack echo "stack ALL=(ALL) NOPASSWD: ALL" | sudo tee /etc/sudoers.d/stack sudo su - stack ## https://askubuntu.com/questions/590027/how-to-set-python-3-as-default-interpreter-in-ubuntu-14-04 ## Must execute in new user environment - each time you sudo su - ### alias python=/usr/bin/python3.6 echo [Time Stamp:] ## https://stackoverflow.com/questions/1401482/yyyy-mm-dd-format-date-in-shell-script printf '%(%Y-%m-%d %H-%M-%S)T\n' -1 echo [Time Stamp:] ### git clone https://github.com/openstack-dev/devstack.git -b stable/pike devstack/ ### Use latest stable as of 20200113 for latest Phyton versions ##git clone https://github.com/openstack-dev/devstack.git -b stable/train devstack/ ### https://releases.openstack.org/ ## git clone https://github.com/openstack-dev/devstack.git -b stable/stein devstack/ ## git clone https://github.com/openstack-dev/devstack.git -b stable/rocky devstack/ ## git clone https://github.com/openstack-dev/devstack.git -b stable/queens devstack/ ## git clone https://github.com/openstack-dev/devstack.git -b stable/pike devstack/ git clone https://git.openstack.org/openstack-dev/devstack -b stable/rocky ## https://www.techrepublic.com/article/how-to-install-openstack-on-a-single-ubuntu-server-virtual-machine/ ## Testing to see if broken pipe will occur. ## Edit: 20200114-01 - Broken pipe error fixed. Not so sure why site01 script didn't have this error. sudo chown -R stack:stack devstack/ cd devstack/ ######## CAT local.conf ############ CAT local.conf ########## CAT local.conf ##### cat > local.conf <<EOF [[local|localrc]] ## https://wiki.openstack.org/wiki/Python3 ## 20200302 - NS - using Ubuntu 16 - sdo not attempt with Pyton3 as yet ### 20200303-01 - NS - Add back as some packages need python3 explicitly installed. USE_PYTHON3=True ## 20200303-02 - NS - TODO for heat. ## https://opendev.org/openstack/devstack/src/branch/stable/pike/stackrc?lang=zh-TW # Control whether Python 3 is enabled for specific services by the # base name of the directory from which they are installed. See # enable_python3_package to edit this variable and use_python3_for to # test membership. ## export ENABLED_PYTHON3_PACKAGES="nova,glance,cinder,uwsgi,python-openstackclient" ENABLED_PYTHON3_PACKAGES=horizon ## https://docs.openstack.org/devstack/latest/configuration.html#use-python3 PIP_UPGRADE=True ## 20200303-01 - NS - Getting Syntax error for tis part - remove. ## """+"="*78, file=sys.stdout) ## ^ ## SyntaxError: invalid syntax ## 20200303-02 - NS - Add back as the errror was replated to python3. ## https://files.pythonhosted.org/packages/f0/bb/f41cbc8eaa807afb9d44418f092aa3e4acf0e4f42b439c49824348f1f45c/dnspython3-1.15.0.zip INSTALL_TEMPEST=True ADMIN_PASSWORD=secret DATABASE_PASSWORD=\$ADMIN_PASSWORD RABBIT_PASSWORD=\$ADMIN_PASSWORD SERVICE_PASSWORD=\$ADMIN_PASSWORD ## Code below was from site01 script without the preceding slashes. ## DATABASE_PASSWORD=$ADMIN_PASSWORD ## RABBIT_PASSWORD=$ADMIN_PASSWORD ## SERVICE_PASSWORD=$ADMIN_PASSWORD ## EDIT: Comment out this comment [Use local host instead. Might get a broken pipe error --- Didn't solve the issue] ## Use localhost IP for when conencting to compute nodes via 6080. ## HOST_IP=10.0.2.15 HOST_IP=127.0.0.1 ## EDIT: Comment out this comment [Try not to reclone, might get a proken pipe error --- Didn't solve the issue] RECLONE=yes ## GIT_BASE was from another setup manual. Remove as required. GIT_BASE=http://git.openstack.org ## https://ask.openstack.org/en/question/11017/how-do-you-mount-an-additional-disk-for-cinder/ ## https://gist.github.com/amotoki/b5ca4affd768177ed911 HORIZON_BRANCH=stable/rocky KEYSTONE_BRANCH=stable/rocky NOVA_BRANCH=stable/rocky NEUTRON_BRANCH=stable/rocky GLANCE_BRANCH=stable/rocky CINDER_BRANCH=stable/rocky ### HEAT_BRANCH=stable/rocky ## https://docs.openstack.org/horizon/pike/contributor/ref/local_conf.html # Enable Heat ### enable_plugin heat https://git.openstack.org/openstack/heat ## 20200302-01 - NS - https://docs.openstack.org/devstack/ocata/configuration.html#swift ### enable_service heat h-api h-api-cfn h-api-cw h-eng # Enable Neutron - installtion parameter duplicated below ### enable_plugin neutron https://git.openstack.org/openstack/neutron # Enable the Trunks extension for Neutron enable_service q-trunk # Enable the QoS extension for Neutron ## 20200302 - NS - duplicated entry below ## enable_service q-qos enable_service ceilometer-acompute ceilometer-acentral ceilometer-collector ceilometer-api ## https://docs.openstack.org/horizon/pike/contributor/ref/local_conf.html ## Enable Swift (Object Store) without replication enable_service s-proxy s-object s-container s-account ## https://ask.openstack.org/en/question/57376/installing-devstack-unable-to-connect-to-gitopenstackorg/ ## 20200303-01 - NS - django error with sahara dashboard ## 20200303-01 - NS - May need to install django python module. Not so syre why they just didn't install it. ## https://docs.djangoproject.com/en/3.0/topics/install/ #### 20200304-01 - NS - ImportError: No module named openstack_dashboard.settings #### enable_plugin sahara https://git.openstack.org/openstack/sahara stable/rocky ## 20200301 - NS - Removed due to dhango ImportError: No module named django.core.management ## 20200302 - NS - added back, could be Python3 issue. ## 20200303-01 - NS - May need to install django python module. Not so syre why they just didn't install it. ## https://docs.djangoproject.com/en/3.0/topics/install/ #### #### 20200304-01 - NS - ImportError: No module named openstack_dashboard.settings #### enable_plugin trove https://git.openstack.org/openstack/trove stable/rocky ## 20200303-01 - NS - django error with sahara dashboard ## 20200303-01 - NS - May need to install django python module. Not so syre why they just didn't install it. ## https://docs.djangoproject.com/en/3.0/topics/install/ #### 20200304-01 - NS - ImportError: No module named openstack_dashboard.settings #### enable_plugin sahara-dashboard https://git.openstack.org/openstack/sahara-dashboard stable/rocky ## 20200301 - NS - Removed due to dhango ImportError: No module named django.core.management ## related to django ## 20200303-01 - NS - May need to install django python module. Not so syre why they just didn't install it. ## https://docs.djangoproject.com/en/3.0/topics/install/ ## 20200302 - NS - added back, could be Python3 issue. #### 20200304-01 - NS - ImportError: No module named openstack_dashboard.settings #### enable_plugin trove-dashboard https://git.openstack.org/openstack/trove-dashboard stable/rocky enable_plugin neutron https://git.openstack.org/openstack/neutron stable/rocky #enable_plugin neutron-lbaas https://git.openstack.org/openstack/neutron-lbaas #NEUTRON_LBAAS_SERVICE_PROVIDERV2="LOADBALANCERV2:Haproxy:neutron_lbaas.drivers.haproxy.plugin_driver.HaproxyOnHostPluginDriver:default" #NEUTRON_LBAAS_SERVICE_PROVIDERV2="LOADBALANCERV2:Octavia:neutron_lbaas.drivers.octavia.driver.OctaviaDriver:default" #enable_plugin neutron-lbaas-dashboard https://git.openstack.org/openstack/neutron-lbaas-dashboard #enable_plugin neutron-lbaas-dashboard file:///home/ubuntu/work/neutron-lbaas-dashboard review/akihiro_motoki/devstack-plugin enable_plugin neutron-vpnaas https://git.openstack.org/openstack/neutron-vpnaas stable/rocky enable_plugin magnum https://git.openstack.org/openstack/magnum master enable_plugin magnum-ui https://git.openstack.org/openstack/magnum-ui master # designate-dashboard is installed by designate devstack plugin ## 20200303-01 - NS - Seems to be error with python3 and the install. Syntax error. ## enable_plugin designate https://git.openstack.org/openstack/designate stable/rocky ## DESIGNATE_BACKEND_DRIVER=fake ## DESIGNATE_BRANCH=stable/rocky ## DESIGNATEDASHBOARD_BRANCH=stable/rocky # murano-dashboard is installed by murano devstack plugin enable_plugin murano https://git.openstack.org/openstack/murano stable/rocky MURANO_BRANCH=stable/rocky MURANO_DASHBOARD_BRANCH=stable/rocky enable_service murano-cfapi MURANO_APPS=io.murano.apps.apache.Tomcat,io.murano.apps.Guacamole # Some more processing for translation check site #### 20200304-01 - NS - ImportError: No module named openstack_dashboard.settings #### enable_plugin horizon-i18n-tools https://github.com/amotoki/horizon-i18n-tools.git ## 20200302-10 - NS - https://docs.openstack.org/horizon/latest/install/plugin-registry.html ## TODO ## 20200301 - NS - Removed due to dhango ImportError: No module named django.core.management ## LIBS_FROM_GIT=django_openstack_auth HORIZONAUTH_BRANCH=stable/rocky ## 20200229-01 - NS - removed becasue of keystone launch error ## 20200302-02 - NS - See lines below... ## KEYSTONE_TOKEN_FORMAT=UUID ## 20200302-02 - NS - See lines below... ## https://wiki.openstack.org/wiki/Swift/DevstackSetupForKeystoneV3 # Select Keystone's token format # Choose from 'UUID', 'PKI', or 'PKIZ' # INSERT THIS LINE... ## KEYSTONE_TOKEN_FORMAT=${KEYSTONE_TOKEN_FORMAT:-UUID} ## KEYSTONE_TOKEN_FORMAT=$(echo ${KEYSTONE_TOKEN_FORMAT} | tr '[:upper:]' '[:lower:]') ## End result - 20200303-01 - NS - See lines below: ## 20200303-01 - NS - https://bugs.launchpad.net/kolla-ansible/+bug/1757520 ## https://bugs.launchpad.net/keystone/+bug/1753584 ## Unable to find 'uuid' driver in 'keystone.token.provider'. ## Remove uuid as keystone_token_provider ## Keystone removed uuid token provider in Rocky ## This patch change the default value and fix comments for the option. ## Change-Id: Idca0004852b688fcdd34ef47c38dec6b8bf05f86 ## Closes-Bug: #1757520 ## KEYSTONE_TOKEN_FORMAT=UUID ## 20200302 - NS - may not be keystone but python3 related. PRIVATE_NETWORK_NAME=net1 PUBLIC_NETWORK_NAME=ext_net ## 20200302 - 01 - NS - https://ask.openstack.org/en/question/27081/enable-swift-in-openstack-devstack/ ## ENABLED_SERVICES+=,s-proxy,s-object,s-container,s-account ???? #----------------------------- # Neutron #----------------------------- disable_service n-net enable_service neutron q-svc q-agt enable_service q-dhcp enable_service q-l3 enable_service q-meta #enable_service q-lbaas enable_service q-lbaasv2 enable_service q-fwaas enable_service q-vpn enable_service q-qos enable_service q-flavors # murano devstack enables q-metering by default disable_service q-metering Q_PLUGIN=ml2 #Q_USE_DEBUG_COMMAND=True if [ "$Q_PLUGIN" = "ml2" ]; then #Q_ML2_TENANT_NETWORK_TYPE=gre Q_ML2_TENANT_NETWORK_TYPE=vxlan : fi ### 20200302-10 NS - https://docs.openstack.org/devstack/train/guides/neutron.html ## TODO ## 20200302 - NS - https://wiki.openstack.org/wiki/Swift/DevstackSetupForKeystoneV3 ## https://stackoverflow.com/questions/21270426/enabled-services-in-devstack enable_service swift ## https://github.com/openstack/devstack/blob/master/samples/local.conf SWIFT_HASH=66a3d6b56c1f479c8b4e70ab5c2000f5 ## https://docs.openstack.org/horizon/pike/contributor/ref/local_conf.html SWIFT_REPLICAS=3 SWIFT_DATA_DIR=$DEST/data/swift ## https://wiki.openstack.org/wiki/Swift/DevstackSetupForKeystoneV3 ## Configure Keystone iniset ${SWIFT_CONFIG_PROXY_SERVER} filter:authtoken auth_version v3.0 ## https://www.rushiagr.com/blog/2014/01/16/playing-around-with-cinder-backend/ CINDER_MULTI_LVM_BACKEND=True ## https://stackoverflow.com/questions/20390267/installing-openstack-errors ## https://ask.openstack.org/en/question/57376/installing-devstack-unable-to-connect-to-gitopenstackorg/ ### Didn't work - need to change git:// to https:// ### GIT_BASE=${GIT_BASE:-https://git.openstack.org} ## 20200302-01 - NS - https://docs.openstack.org/horizon/pike/contributor/ref/local_conf.html [[post-config|$GLANCE_API_CONF]] [DEFAULT] default_store=file ## End of File EOF ############### EOF ######################### EOF ###################### EOF #### ./stack.sh ## 20200301 - Run tests after install completes succesfully. ## ./run_tests.sh ### https://github.com/openstack/devstack/blob/master/samples/local.sh ### https://raw.githubusercontent.com/openstack/devstack/master/samples/local.sh wget https://raw.githubusercontent.com/openstack/devstack/master/samples/local.sh chmod 777 ./local.sh ### 20200301 - NS - error executing ## stack@dcit-ubuntu18:~/devstack$ ./local.sh ## WARNING: setting legacy OS_TENANT_NAME to support cli tools. ## ./local.sh echo [Time Stamp:] ## https://stackoverflow.com/questions/1401482/yyyy-mm-dd-format-date-in-shell-script printf '%(%Y-%m-%d %H-%M-%S)T\n' -1 echo [Time Stamp:] ## Cinder Volume Config [Install] - 20200228-01 - NS ## Install ruby for Chef-client ## https://docs.oracle.com/cd/E78305_01/E78304/html/openstack-envars.html ## $ export OS_AUTH_URL=http://10.0.0.10:5000/v3 export OS_AUTH_URL=http://127.0.0.1/identity export OS_TENANT_NAME=admin export OS_PROJECT_NAME=admin export OS_USERNAME=admin export OS_PASSWORD=secret export OS_PROJECT_DOMAIN_ID=default export OS_PROJECT_DOMAIN_NAME=Default export OS_USER_DOMAIN_ID=default export OS_USER_DOMAIN_NAME=Default ## https://www.tecmint.com/add-new-disks-using-lvm-to-linux/ ## http://www.devops-engineer.com/how-to-create-linux-lvm-step-by-step/ ## https://www.certdepot.net/sys-manage-physical-volumes-volume-groups-and-logical-volumes/ pvcreate /dev/sdb1 pvcreate /dev/sdc1 pvscan ## https://fatmin.com/2015/04/28/openstack-cinder-add-additional-backend-volumes/ vgscan | grep cinder vgcreate cinder-volumes-1 /dev/sdb1 /dev/sdc1 ## vgcreate cinder-volumes-2-c /dev/sdc1 vgscan | grep cinder ## /etc/cinder/cinder.conf ### [lvm1] ### volume_group=cinder-volumes-1 ### volume_driver=cinder.volume.drivers.lvm.LVMISCSIDriver ### volume_backend_name=lvm1 ### [lvm2] ### volume_group=cinder-volumes-2-c ### volume_driver=cinder.volume.drivers.lvm.LVMISCSIDriver ### volume_backend_name=lvm2 cat >> /etc/cinder/cinder.conf <<EOF [lvm1] volume_group=cinder-volumes-1 volume_driver=cinder.volume.drivers.lvm.LVMISCSIDriver volume_backend_name=lvm1 ## END EOF ### service cinder-volume restart ## cinder type-create lvm1 ## cinder type-create lvm2 ## cinder type-key lvm1 set volume_backend_name=cinder-volumes-1-b ## cinder type-key lvm2 set volume_backend_name=cinder-volumes-2-c ## https://blog.csdn.net/weixin_30919235/article/details/99755648 ## vgs ## cinder type-list ## cinder extra-specs-list ## cinder create --volume-type lvm1 --display-name test_multi_backend 1 ## cinder-manage service list ## These below don't help: ## https://ask.openstack.org/en/question/27569/admin-openrcsh/ ### https://docs.openstack.org/mitaka/install-guide-obs/keystone-openrc.html ### cd /opt/stack/devstack ### source /opt/stack/devstack/openrc ### hostname --fqdn ### knife node show DCIT-ubuntu ## Little help: https://docs.chef.io/knife/ ## Some help: https://www.rubydoc.info/gems/knife-openstack/0.6.2 ## https://www.amazon.com/Mastering-OpenStack-Second-Design-infrastructures/dp/1786463989 ### apt install chef -y ## URL: http://127.0.0.1:4000 ### wget https://packages.chef.io/files/stable/chefworkstation/0.14/ubuntu/18.04/chefworkstation_0.14.16-1_amd64.deb ## wget https://packages.chef.io/files/stable/chef-workstation/0.16.31/ubuntu/16.04/chef-workstation_0.16.31-1_amd64.deb ## dpkg -i chef-workstation_0.16.31-1_amd64.deb ## chef -v ### https://docs.chef.io/workstation_setup/ ## which ruby ## echo 'eval "$(chef shell-init bash)"' >> ~/.bash_profile ## which ruby ## echo 'export PATH="/opt/chef-workstation/embedded/bin:$PATH"' >> ~/.configuration_file && source ~/.configuration_file ## echo 'export PATH="/opt/chef-workstation/embedded/bin:$PATH"' >> ~/.bash_profile && source ~/.bash_profile ## chef generate repo chef-repo ## ## mkdir -p ~/chef-repo/.chef ## echo '.chef' >> ~/chef-repo/.gitignore ## chef-server-ctl org-create "DCIT-ubuntu-org" "DCIT-ubuntu-org-fullname" -f /tmp/chef.key ## From this link: https://www.rubydoc.info/gems/knife-openstack/0.6.2 ## gem install knife-openstack ### knife configure -initial ## https://127.0.0.1:443 echo [Time Stamp:] ## https://stackoverflow.com/questions/1401482/yyyy-mm-dd-format-date-in-shell-script printf '%(%Y-%m-%d %H-%M-%S)T\n' -1 echo [Time Stamp
import unified from 'unified'; import md2remark from 'remark-parse'; import smartypants from '@silvenon/remark-smartypants'; import slug from 'remark-slug'; import remark2rehype from 'remark-rehype'; import rehype2html from 'rehype-stringify'; import Handlebars from 'handlebars'; async function buildChecklist(text, layout, info) { // process the markdown into HTML const bodyHtml = await unified() .use(md2remark) .use(smartypants) .use(slug) .use(remark2rehype) .use(rehype2html) .process(text); // fill in the template with the html and the toc const template = Handlebars.compile(layout); const page = template({...info, body: bodyHtml}); return page; } export default buildChecklist;
#!/bin/bash # # Description : Install Nagios4 # Author : Jose Cerrejon Gonzalez (ulysess@gmail_dot._com) # Version : 1.0.0 (11/Aug/20) # Compatible : Raspberry Pi 1-4 (tested) # # TODO : compile from source. Check https://pimylifeup.com/raspberry-pi-nagios/ # . ./scripts/helper.sh || . ./helper.sh || wget -q 'https://github.com/jmcerrejon/PiKISS/raw/master/scripts/helper.sh' clear check_board || { echo "Missing file helper.sh. I've tried to download it for you. Try to run the script again." && exit 1; } PACKAGES=(nagios4) PACKAGES_DEV=(autoconf build-essential wget unzip apache2 apache2-utils php libgd-dev snmp libnet-snmp-perl gettext libssl-dev wget bc gawk dc libmcrypt-dev) IP=$(get_ip) URL="http://${IP}/nagios" post_install() { sudo usermod -a -G nagios www-data sudo htpasswd -c /usr/local/nagios/etc/htpasswd.users nagiosadmin echo read -p "Do you want to reboot? (y/N) " response if [[ $response =~ [Yy] ]]; then sudo reboot fi exit_message } install() { echo echo -e "\nInstalling Nagios, please wait..." sudo apt-get -qq update sudo apt -y full-upgrade sudo dpkg-reconfigure tzdata installPackagesIfMissing "${PACKAGES[@]}" } echo "Install Nagios 4" echo "================" echo echo " · ~70 MB space occupied." echo " · Once installed, this script can uninstall the app." echo " · Nagios is a popular open-source software that is designed to monitor systems, networks, and infrastructure." echo " · Installing on a modified system could overwrite any previous modifications." echo " · When finish and reboot, you can browser to $URL" echo read -p "Are you sure you want to continue? (Y/n) " response if [[ $response =~ [Nn] ]]; then exit_message fi install post_install
class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right # Function to find maximum path sum def maxPathSum(root): if root is None: return 0 # l and r store maximum path sum going through left and # right child of root respetively. l = maxPathSum(root.left) r = maxPathSum(root.right) # Max path for parent call of root. This path must # include at-most one child of root max_single = max(max(l, r) + root.data, root.data) # Max Top represents the sum when the Node under # consideration is the root of the maxsum path and no # ancestors of root are there in max sum path max_top = max(max_single, l + r + root.data) # Static variable to store the changes # Store the maximum result max_path_sum.res = max(max_path_sum.res, max_top) return max_single # Utility function to initialise the # static variable res def maxPathSumUtil(root): max_path_sum.res = float("-infinity") maxPathSum(root) return max_path_sum.res
import argparse def parse_arguments(args_spec): parser = argparse.ArgumentParser(description="Argument Parser") for arg_spec in args_spec: if arg_spec[0].startswith("--"): arg_name = arg_spec[0][2:] arg_type = arg_spec[1] help_msg = arg_spec[2] default_val = arg_spec[3] if len(arg_spec) == 4 else None parser.add_argument(f"--{arg_name}", type=eval(arg_type), help=help_msg, default=default_val) else: arg_name = arg_spec[0] arg_type = arg_spec[1] help_msg = arg_spec[2] parser.add_argument(arg_name, type=eval(arg_type), help=help_msg) args = vars(parser.parse_args()) return args
#!/bin/bash -e usage() { cat <<EOUSAGE Usage: $0 [subcommand] Available subcommands: help - display this help message. test - build and test locally. Some tests may fail if vscode is alreay in use. testlocal - build and test in a locally built container. ci - build and test with headless vscode. Requires Xvfb. EOUSAGE } # TODO(hyangah): commands for building docker container and running tests locally with docker run. root_dir() { local script_name=$(readlink -f "${0}") local script_dir=$(dirname "${script_name}") local parent_dir=$(dirname "${script_dir}") echo "${parent_dir}" } setup_virtual_display() { echo "**** Set up virtual display ****" # Start xvfb (an in-memory display server for UNIX-like operating system) # so we can launch a headless vscode for testing. /usr/bin/Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & trap 'kill "$(jobs -p)"' EXIT export DISPLAY=:99 sleep 3 # Wait for xvfb to be up. } go_binaries_info() { echo "**** Go version ****" which go go version echo "**** Gopls version ****" go version -m "$(which gopls)" } run_test() { echo "**** Run test ****" npm ci npm run compile npm run lint npm run unit-test npm test --silent } run_test_in_docker() { echo "**** Building the docker image ***" docker build -t vscode-test-env ./build docker run --workdir=/workspace -v "$(pwd):/workspace" vscode-test-env ci } main() { cd "$(root_dir)" # always run from the script root. case "$1" in "help"|"-h"|"--help") usage exit 0 ;; "test") go_binaries_info run_test ;; "testlocal") run_test_in_docker ;; "ci") go_binaries_info setup_virtual_display run_test ;; *) usage exit 2 esac } main $@
<reponame>lujjjh/go-cputime package cputime import ( "syscall" "time" "unsafe" ) const clockThreadCputimeId = 3 func currentThread() (time.Duration, error) { var ts syscall.Timespec _, _, err := syscall.RawSyscall(syscall.SYS_CLOCK_GETTIME, uintptr(clockThreadCputimeId), uintptr(unsafe.Pointer(&ts)), 0) if err != 0 { return 0, err } return time.Duration(ts.Nano()), nil }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; 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 java.util.Properties; import javax.mail.Authenticator; /** * The base class for all email messages. This class sets the sender's email * &amp; name, receiver's email &amp; name, subject, and the sent date. * <p> * Subclasses are responsible for setting the message body. * * @since 1.0 */ public abstract class Email { /** * Sets the userName and password if authentication is needed. If this method is * not used, no authentication will be performed. * <p> * This method will create a new instance of {@code DefaultAuthenticator} using * the supplied parameters. * * @param userName User name for the SMTP server * @param password password for the SMTP server * @see DefaultAuthenticator * @see #setAuthenticator * @since 1.0 */ public void setAuthentication(final String userName, final String password) { } /** * Sets the {@code Authenticator} to be used when authentication is requested * from the mail server. * <p> * This method should be used when your outgoing mail server requires * authentication. Your mail server must also support RFC2554. * * @param newAuthenticator the {@code Authenticator} object. * @see Authenticator * @since 1.0 */ public void setAuthenticator(final Authenticator newAuthenticator) { } /** * Set the hostname of the outgoing mail server. * * @param aHostName aHostName * @throws IllegalStateException if the mail session is already initialized * @since 1.0 */ public void setHostName(final String aHostName) { } /** * Set or disable the STARTTLS encryption. Please see EMAIL-105 for the reasons * of deprecation. * * @deprecated since 1.3, use setStartTLSEnabled() instead * @param withTLS true if STARTTLS requested, false otherwise * @since 1.1 */ @Deprecated public void setTLS(final boolean withTLS) { } /** * Set or disable the STARTTLS encryption. * * @param startTlsEnabled true if STARTTLS requested, false otherwise * @return An Email. * @throws IllegalStateException if the mail session is already initialized * @since 1.3 */ public Email setStartTLSEnabled(final boolean startTlsEnabled) { return null; } /** * Set or disable the required STARTTLS encryption. * <p> * Defaults to {@link #smtpPort}; can be overridden by using * {@link #setSmtpPort(int)} * * @param startTlsRequired true if STARTTLS requested, false otherwise * @return An Email. * @throws IllegalStateException if the mail session is already initialized * @since 1.3 */ public Email setStartTLSRequired(final boolean startTlsRequired) { return null; } /** * Set the non-SSL port number of the outgoing mail server. * * @param aPortNumber aPortNumber * @throws IllegalArgumentException if the port number is &lt; 1 * @throws IllegalStateException if the mail session is already initialized * @since 1.0 * @see #setSslSmtpPort(String) */ public void setSmtpPort(final int aPortNumber) { } /** * Set the FROM field of the email to use the specified address. The email * address will also be used as the personal name. The name will be encoded by * the charset of {@link #setCharset(java.lang.String) setCharset()}. If it is * not set, it will be encoded using the Java platform's default charset * (UTF-16) if it contains non-ASCII characters; otherwise, it is used as is. * * @param email A String. * @return An Email. * @throws EmailException Indicates an invalid email address. * @since 1.0 */ public Email setFrom(final String email) throws EmailException { return null; } /** * Set the FROM field of the email to use the specified address and the * specified personal name. The name will be encoded by the charset of * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will * be encoded using the Java platform's default charset (UTF-16) if it contains * non-ASCII characters; otherwise, it is used as is. * * @param email A String. * @param name A String. * @return An Email. * @throws EmailException Indicates an invalid email address. * @since 1.0 */ public Email setFrom(final String email, final String name) throws EmailException { return null; } /** * Set the FROM field of the email to use the specified address, personal name, * and charset encoding for the name. * * @param email A String. * @param name A String. * @param charset The charset to encode the name with. * @return An Email. * @throws EmailException Indicates an invalid email address or charset. * @since 1.1 */ public Email setFrom(final String email, final String name, final String charset) throws EmailException { return null; } /** * Add a recipient TO to the email. The email address will also be used as the * personal name. The name will be encoded by the charset of * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will * be encoded using the Java platform's default charset (UTF-16) if it contains * non-ASCII characters; otherwise, it is used as is. * * @param email A String. * @return An Email. * @throws EmailException Indicates an invalid email address. * @since 1.0 */ public Email addTo(final String email) throws EmailException { return null; } /** * Add a list of TO recipients to the email. The email addresses will also be * used as the personal names. The names will be encoded by the charset of * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will * be encoded using the Java platform's default charset (UTF-16) if it contains * non-ASCII characters; otherwise, it is used as is. * * @param emails A String array. * @return An Email. * @throws EmailException Indicates an invalid email address. * @since 1.3 */ public Email addTo(final String... emails) throws EmailException { return null; } /** * Add a recipient TO to the email using the specified address and the specified * personal name. The name will be encoded by the charset of * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will * be encoded using the Java platform's default charset (UTF-16) if it contains * non-ASCII characters; otherwise, it is used as is. * * @param email A String. * @param name A String. * @return An Email. * @throws EmailException Indicates an invalid email address. * @since 1.0 */ public Email addTo(final String email, final String name) throws EmailException { return null; } /** * Add a recipient TO to the email using the specified address, personal name, * and charset encoding for the name. * * @param email A String. * @param name A String. * @param charset The charset to encode the name with. * @return An Email. * @throws EmailException Indicates an invalid email address or charset. * @since 1.1 */ public Email addTo(final String email, final String name, final String charset) throws EmailException { return null; } /** * Add a recipient CC to the email. The email address will also be used as the * personal name. The name will be encoded by the charset of * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will * be encoded using the Java platform's default charset (UTF-16) if it contains * non-ASCII characters; otherwise, it is used as is. * * @param email A String. * @return An Email. * @throws EmailException Indicates an invalid email address. * @since 1.0 */ public Email addCc(final String email) throws EmailException { return null; } /** * Add an array of CC recipients to the email. The email addresses will also be * used as the personal name. The names will be encoded by the charset of * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will * be encoded using the Java platform's default charset (UTF-16) if it contains * non-ASCII characters; otherwise, it is used as is. * * @param emails A String array. * @return An Email. * @throws EmailException Indicates an invalid email address. * @since 1.3 */ public Email addCc(final String... emails) throws EmailException { return null; } /** * Add a recipient CC to the email using the specified address and the specified * personal name. The name will be encoded by the charset of * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will * be encoded using the Java platform's default charset (UTF-16) if it contains * non-ASCII characters; otherwise, it is used as is. * * @param email A String. * @param name A String. * @return An Email. * @throws EmailException Indicates an invalid email address. * @since 1.0 */ public Email addCc(final String email, final String name) throws EmailException { return null; } /** * Add a recipient CC to the email using the specified address, personal name, * and charset encoding for the name. * * @param email A String. * @param name A String. * @param charset The charset to encode the name with. * @return An Email. * @throws EmailException Indicates an invalid email address or charset. * @since 1.1 */ public Email addCc(final String email, final String name, final String charset) throws EmailException { return null; } /** * Add a blind BCC recipient to the email. The email address will also be used * as the personal name. The name will be encoded by the charset of * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will * be encoded using the Java platform's default charset (UTF-16) if it contains * non-ASCII characters; otherwise, it is used as is. * * @param email A String. * @return An Email. * @throws EmailException Indicates an invalid email address * @since 1.0 */ public Email addBcc(final String email) throws EmailException { return null; } /** * Add an array of blind BCC recipients to the email. The email addresses will * also be used as the personal name. The names will be encoded by the charset * of {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it * will be encoded using the Java platform's default charset (UTF-16) if it * contains non-ASCII characters; otherwise, it is used as is. * * @param emails A String array. * @return An Email. * @throws EmailException Indicates an invalid email address * @since 1.3 */ public Email addBcc(final String... emails) throws EmailException { return null; } /** * Add a blind BCC recipient to the email using the specified address and the * specified personal name. The name will be encoded by the charset of * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will * be encoded using the Java platform's default charset (UTF-16) if it contains * non-ASCII characters; otherwise, it is used as is. * * @param email A String. * @param name A String. * @return An Email. * @throws EmailException Indicates an invalid email address * @since 1.0 */ public Email addBcc(final String email, final String name) throws EmailException { return null; } /** * Add a blind BCC recipient to the email using the specified address, personal * name, and charset encoding for the name. * * @param email A String. * @param name A String. * @param charset The charset to encode the name with. * @return An Email. * @throws EmailException Indicates an invalid email address * @since 1.1 */ public Email addBcc(final String email, final String name, final String charset) throws EmailException { return null; } /** * Add a reply to address to the email. The email address will also be used as * the personal name. The name will be encoded by the charset of * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will * be encoded using the Java platform's default charset (UTF-16) if it contains * non-ASCII characters; otherwise, it is used as is. * * @param email A String. * @return An Email. * @throws EmailException Indicates an invalid email address * @since 1.0 */ public Email addReplyTo(final String email) throws EmailException { return null; } /** * Add a reply to address to the email using the specified address and the * specified personal name. The name will be encoded by the charset of * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will * be encoded using the Java platform's default charset (UTF-16) if it contains * non-ASCII characters; otherwise, it is used as is. * * @param email A String. * @param name A String. * @return An Email. * @throws EmailException Indicates an invalid email address * @since 1.0 */ public Email addReplyTo(final String email, final String name) throws EmailException { return null; } /** * Add a reply to address to the email using the specified address, personal * name, and charset encoding for the name. * * @param email A String. * @param name A String. * @param charset The charset to encode the name with. * @return An Email. * @throws EmailException Indicates an invalid email address or charset. * @since 1.1 */ public Email addReplyTo(final String email, final String name, final String charset) throws EmailException { return null; } /** * Used to specify the mail headers. Example: * * X-Mailer: Sendmail, X-Priority: 1( highest ) or 2( high ) 3( normal ) 4( low * ) and 5( lowest ) Disposition-Notification-To: <EMAIL> * * @param map A Map. * @throws IllegalArgumentException if either of the provided header / value is * null or empty * @since 1.0 */ public void setHeaders(final Map<String, String> map) { } /** * Adds a header ( name, value ) to the headers Map. * * @param name A String with the name. * @param value A String with the value. * @since 1.0 * @throws IllegalArgumentException if either {@code name} or {@code value} is * null or empty */ public void addHeader(final String name, final String value) { } /** * Gets the specified header. * * @param header A string with the header. * @return The value of the header, or null if no such header. * @since 1.5 */ public String getHeader(final String header) { return null; } /** * Gets all headers on an Email. * * @return a Map of all headers. * @since 1.5 */ public Map<String, String> getHeaders() { return null; } /** * Sets the email subject. Replaces end-of-line characters with spaces. * * @param aSubject A String. * @return An Email. * @since 1.0 */ public Email setSubject(final String aSubject) { return null; } /** * Gets the "bounce address" of this email. * * @return the bounce address as string * @since 1.4 */ public String getBounceAddress() { return null; } /** * Set the "bounce address" - the address to which undeliverable messages will * be returned. If this value is never set, then the message will be sent to the * address specified with the System property "mail.smtp.from", or if that value * is not set, then to the "from" address. * * @param email A String. * @return An Email. * @throws IllegalStateException if the mail session is already initialized * @since 1.0 */ public Email setBounceAddress(final String email) { return null; } /** * Define the content of the mail. It should be overridden by the subclasses. * * @param msg A String. * @return An Email. * @throws EmailException generic exception. * @since 1.0 */ public abstract Email setMsg(String msg) throws EmailException; /** * Does the work of actually building the MimeMessage. Please note that a user * rarely calls this method directly and only if he/she is interested in the * sending the underlying MimeMessage without commons-email. * * @throws IllegalStateException if the MimeMessage was already built * @throws EmailException if there was an error. * @since 1.0 */ public void buildMimeMessage() throws EmailException { } /** * Sends the previously created MimeMessage to the SMTP server. * * @return the message id of the underlying MimeMessage * @throws IllegalArgumentException if the MimeMessage has not been created * @throws EmailException the sending failed */ public String sendMimeMessage() throws EmailException { return null; } /** * Sends the email. Internally we build a MimeMessage which is afterwards sent * to the SMTP server. * * @return the message id of the underlying MimeMessage * @throws IllegalStateException if the MimeMessage was already built, ie * {@link #buildMimeMessage()} was already called * @throws EmailException the sending failed */ public String send() throws EmailException { return null; } /** * Sets the sent date for the email. The sent date will default to the current * date if not explicitly set. * * @param date Date to use as the sent date on the email * @since 1.0 */ public void setSentDate(final Date date) { } /** * Gets the sent date for the email. * * @return date to be used as the sent date for the email * @since 1.0 */ public Date getSentDate() { return null; } /** * Gets the subject of the email. * * @return email subject */ public String getSubject() { return null; } /** * Gets the host name of the SMTP server, * * @return host name */ public String getHostName() { return null; } /** * Gets the listening port of the SMTP server. * * @return smtp port */ public String getSmtpPort() { return null; } /** * Gets whether the client is configured to require STARTTLS. * * @return true if using STARTTLS for authentication, false otherwise * @since 1.3 */ public boolean isStartTLSRequired() { return false; } /** * Gets whether the client is configured to try to enable STARTTLS. * * @return true if using STARTTLS for authentication, false otherwise * @since 1.3 */ public boolean isStartTLSEnabled() { return false; } /** * Gets whether the client is configured to try to enable STARTTLS. See * EMAIL-105 for reason of deprecation. * * @deprecated since 1.3, use isStartTLSEnabled() instead * @return true if using STARTTLS for authentication, false otherwise * @since 1.1 */ @Deprecated public boolean isTLS() { return false; } /** * Set details regarding "pop3 before smtp" authentication. * * @param newPopBeforeSmtp Whether or not to log into pop3 server before sending * mail. * @param newPopHost The pop3 host to use. * @param newPopUsername The pop3 username. * @param newPopPassword <PASSWORD>. * @since 1.0 */ public void setPopBeforeSmtp(final boolean newPopBeforeSmtp, final String newPopHost, final String newPopUsername, final String newPopPassword) { } /** * Returns whether SSL/TLS encryption for the transport is currently enabled * (SMTPS/POPS). See EMAIL-105 for reason of deprecation. * * @deprecated since 1.3, use isSSLOnConnect() instead * @return true if SSL enabled for the transport */ @Deprecated public boolean isSSL() { return false; } /** * Returns whether SSL/TLS encryption for the transport is currently enabled * (SMTPS/POPS). * * @return true if SSL enabled for the transport * @since 1.3 */ public boolean isSSLOnConnect() { return false; } /** * Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon * connection (SMTPS/POPS). See EMAIL-105 for reason of deprecation. * * @deprecated since 1.3, use setSSLOnConnect() instead * @param ssl whether to enable the SSL transport */ @Deprecated public void setSSL(final boolean ssl) { } /** * Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon * connection (SMTPS/POPS). Takes precedence over * {@link #setStartTLSRequired(boolean)} * <p> * Defaults to {@link #sslSmtpPort}; can be overridden by using * {@link #setSslSmtpPort(String)} * * @param ssl whether to enable the SSL transport * @return An Email. * @throws IllegalStateException if the mail session is already initialized * @since 1.3 */ public Email setSSLOnConnect(final boolean ssl) { return null; } /** * Is the server identity checked as specified by RFC 2595 * * @return true if the server identity is checked * @since 1.3 */ public boolean isSSLCheckServerIdentity() { return false; } /** * Sets whether the server identity is checked as specified by RFC 2595 * * @param sslCheckServerIdentity whether to enable server identity check * @return An Email. * @throws IllegalStateException if the mail session is already initialized * @since 1.3 */ public Email setSSLCheckServerIdentity(final boolean sslCheckServerIdentity) { return null; } /** * Returns the current SSL port used by the SMTP transport. * * @return the current SSL port used by the SMTP transport */ public String getSslSmtpPort() { return null; } /** * Sets the SSL port to use for the SMTP transport. Defaults to the standard * port, 465. * * @param sslSmtpPort the SSL port to use for the SMTP transport * @throws IllegalStateException if the mail session is already initialized * @see #setSmtpPort(int) */ public void setSslSmtpPort(final String sslSmtpPort) { } /** * If partial sending of email enabled. * * @return true if sending partial email is enabled * @since 1.3.2 */ public boolean isSendPartial() { return false; } /** * Sets whether the email is partially send in case of invalid addresses. * <p> * In case the mail server rejects an address as invalid, the call to * {@link #send()} may throw a {@link javax.mail.SendFailedException}, even if * partial send mode is enabled (emails to valid addresses will be transmitted). * In case the email server does not reject invalid addresses immediately, but * return a bounce message, no exception will be thrown by the {@link #send()} * method. * * @param sendPartial whether to enable partial send mode * @return An Email. * @throws IllegalStateException if the mail session is already initialized * @since 1.3.2 */ public Email setSendPartial(final boolean sendPartial) { return null; } /** * Get the socket connection timeout value in milliseconds. * * @return the timeout in milliseconds. * @since 1.2 */ public int getSocketConnectionTimeout() { return -1; } /** * Set the socket connection timeout value in milliseconds. Default is a 60 * second timeout. * * @param socketConnectionTimeout the connection timeout * @throws IllegalStateException if the mail session is already initialized * @since 1.2 */ public void setSocketConnectionTimeout(final int socketConnectionTimeout) { } /** * Get the socket I/O timeout value in milliseconds. * * @return the socket I/O timeout * @since 1.2 */ public int getSocketTimeout() { return -1; } /** * Set the socket I/O timeout value in milliseconds. Default is 60 second * timeout. * * @param socketTimeout the socket I/O timeout * @throws IllegalStateException if the mail session is already initialized * @since 1.2 */ public void setSocketTimeout(final int socketTimeout) { } }
from pioneer.common.logging_manager import LoggingManager from pioneer.das.api.samples import Image, ImageFisheye from pioneer.das.api.sensors.sensor import Sensor from pioneer.das.api.interpolators import nearest_interpolator import numpy as np class Camera(Sensor): """Camera sensor, expects 'img' datasource, intrinsics matrix and distortion coefficients""" def __init__(self, name, platform): super(Camera, self).__init__(name , platform , { 'img': (Image, nearest_interpolator), 'flimg': (ImageFisheye, nearest_interpolator) }) @property def camera_matrix(self): """np.ndarray: the 3x3 intrinsics matrix See also: https://docs.opencv.org/4.0.0/d9/d0c/group__calib3d.html#ga3207604e4b1a1758aa66acb6ed5aa65d """ try: matrix = self.intrinsics['matrix'] except: LoggingManager.instance().warning(f'Intrinsic matrix of {self.name} not found. Trying to make a generic one.') h = self.yml['configurations']['img']['Width'] v = self.yml['configurations']['img']['Height'] h_fov = self.yml['configurations']['img']['h_fov'] matrix = np.identity(3) matrix[0,2] = h/2 matrix[1,2] = v/2 matrix[0,0] = matrix[1,1] = h/(2*np.tan(h_fov * np.pi / 360.0)) return matrix @property def distortion_coeffs(self): """np.ndarray: Nx1 distortion coefficient, refer to opencv documentation See also: https://docs.opencv.org/4.0.0/d9/d0c/group__calib3d.html#ga3207604e4b1a1758aa66acb6ed5aa65d """ try: k = self.intrinsics['distortion'] except: LoggingManager.instance().warning(f'Distortion coeffients not found for {self.name}.') k = np.zeros((5,1)) return k def load_intrinsics(self, intrinsics_config): super(Camera, self).load_intrinsics(intrinsics_config) if self.intrinsics is not None: assert 'matrix' in self.intrinsics # previous calibration had a typo in the distortion coeffs if (not 'distortion' in self.intrinsics and 'distorsion' in self.intrinsics): self.intrinsics['distortion'] = self.intrinsics['distorsion'] assert 'distortion' in self.intrinsics
def relation_to_Luke(name): if name == 'Darv': return 'Luke, I am your father' elif name == 'Leila': return ' Luke, i am your sister' elif name == 'Han': return ' Luke, i am your brother' print(relation_to_Luke('Leila'))
#!bin/bash # This script will merge split rdtest statistics by split number # The output will be there be 1 file for each chrom+batch+source for allosomes # For sex chromosome the result will be one file per sex chromosome for each sex # The usage format is ```bash rdtest_mergesplit.sh {batch} {source} {chrom} set -e batch=$1 source=$2 chrom=$3 inputfolder="baftest_split" outputfolder="baftest" input=() for item in $inputfolder/$batch.$source.$chrom.*.metrics; do input+=($item) done cat $inputfolder/$batch.$source.$chrom.*.metrics \ | sed -r -e '/^chr/d' \ | sort -k1,1V -k2,2n \ | cat <(head -n1 $input) - \ > $outputfolder/$batch.$source.$chrom.metrics fi
<reponame>MLSDev/activeadmin-map_address # requires the following in config/initializers/active_admin.rb # ActiveAdmin.application.register_javascript "https://maps.googleapis.com/maps/api/js?sensor=false" module Formtastic module Inputs class MapAddressInput < Formtastic::Inputs::StringInput def to_html center = options[:center_at] || [ 43.77, 11.24 ] zoom = options[:zoom_level] || 8 alert_on_error = options[:alert_on_error] || false input_wrapping do label_html << template.content_tag(:div, class: "map-address-input", data: { center: center, zoom: zoom, alert_on_error: alert_on_error }) do template.content_tag(:div, class: "map") do end << builder.text_field(method, input_html_options.merge(role: 'address')) << builder.text_field(options[:latitude] || :latitude, role: 'latitude') << builder.text_field(options[:longitude] || :longitude, role: 'longitude') end end end end end end
<filename>Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter19Exercise5.cpp /* TITLE Class Int Chapter19Exercise5.cpp "<NAME>up "C++ Programming: Principles and Practice."" COMMENT Objcective: Define a class Int having a single member of type int. Define constructors, assignment, operators +, -, /, *, I/O opeators <<, >>. Test and improve desing as needed. Input: - Output: - Author: <NAME> Date: 24.1.2016 */ #include <iostream> #include <algorithm> #include "Chapter19Exercise5.h" int main () { try { // Test class Int members // default constructor Int a; // consrtuctor Int b(5); // copy constuctor Int c = 5; // copy assingment Int d(c); // operator+ Int add = a + b; // operator- Int sub = a - b; // operator/ Int div = b / c; // operator* Int mul = b * c; // I/O operators std::cout <<"default: "<< a <<'\n'; std::cout <<"constructor: "<< b <<'\n'; std::cout <<"copy constructor: "<< c <<'\n'; std::cout <<"copy assignment: "<< d <<'\n'; std::cout <<"addition: "<< add <<'\n'; std::cout <<"subtraction: "<< sub <<'\n'; std::cout <<"division: "<< div <<'\n'; std::cout <<"multiplication: "<< mul <<'\n'; Int input; std::cout <<"Type an Int:\n>>"; std::cin >> input; std::cout <<"You typed: "<< input; std::cin.ignore(); } catch (std::exception& e) { std::cerr << e.what(); } catch (...) { std::cerr <<"Unhandled Exception!\n"; } getchar(); }
#!/bin/bash cd ${WORKSPACE}/test TEST_RESULTS="test_results" ARCHIVE_NAME="${TEST_RESULTS}_${JOB_BASE_NAME}_${BUILD_NUMBER}_${STAGE_NAME/ /}.zip" find $TEST_RESULTS/ -name "*.zip" | xargs -I '{}' mv '{}' ../ zip -qr ${ARCHIVE_NAME} ${TEST_RESULTS} mv ${ARCHIVE_NAME} ../ rm -rf ./${TEST_RESULTS}
<reponame>rsuite/rsuite-icons // Generated by script, don't edit it please. import createSvgIcon from '../../createSvgIcon'; import WeiboSvg from '@rsuite/icon-font/lib/legacy/Weibo'; const Weibo = createSvgIcon({ as: WeiboSvg, ariaLabel: 'weibo', category: 'legacy', displayName: 'Weibo' }); export default Weibo;
<gh_stars>1-10 import pandas as pd from multiprocessing import Pool from os import listdir from os.path import isfile, join from glob import glob import re mypath = "../input/trade_data_filtered/" data_list = glob(mypath + "full*52.csv") YEAR = re.compile(r'full(20\d{2})52') # here you can define the lenght og the product code digit_code = 6 print("NOW USING",digit_code,"DIGIT CODE") def exp_imp(data_name): year = YEAR.search(data_name).group(1) source_out = "../temp/" ######################################################## data = pd.read_csv(data_name) #drop rows where "TOTAL" occures, filter to rows where stat_regime == 1 data = data[data.PRODUCT_NC!="TOTAL"][data.STAT_REGIME == 1] #filter on product code data["PRODUCT_NC"] = data["PRODUCT_NC"].apply(lambda x: int(x / 10**(8 - digit_code))) # select data sixdigit_product_trade = pd.DataFrame(data.groupby(["FLOW",'DECLARANT_ISO','PARTNER_ISO',"PRODUCT_NC"])['VALUE_IN_EUROS'].sum().reset_index()) ######################################################## #separete exports and imports data_EXP = sixdigit_product_trade[sixdigit_product_trade["FLOW"]==2].drop("FLOW",axis=1) data_IMP = sixdigit_product_trade[sixdigit_product_trade["FLOW"]==1].drop("FLOW",axis=1) ######################################################## data_EXP.to_csv(source_out + '/exp_imp/EXP_{}.csv'.format(year)) data_IMP.to_csv(source_out + '/exp_imp/IMP_{}.csv'.format(year)) # initiate multiprocessing pool = Pool(processes=17) pool.map(exp_imp, data_list) pool.close() pool.join()
import datetime import random import string def generate_user_code(db): # Generate a random user code code_length = 8 characters = string.ascii_letters + string.digits return ''.join(random.choice(characters) for _ in range(code_length)) def add_user_to_realm(db, lock, name, realm): # Construct and execute SQL query to add user to realm query = "insert into {0}_users (name, joined) values (?, ?)".format(realm) locked_query(db, lock, query, name, datetime.date.today()) def locked_query(db, lock, query, *args): # Execute the SQL query with proper locking with lock: db.execute(query, args) db.commit()
#!/usr/bin/env bats load assertions.bash pg_image_name="postgres" pg_image_tag="12" @test "$test_label check image postgres:12" { run docker images assert_success assert_match "${pg_image_name}.*${pg_image_tag}" } @test "$test_label check image mongod:4.2.5" { run docker images assert_success assert_match "mongod.*4.2.5" } @test "$test_label check container pg2mongo_pg1_1" { run docker ps assert_success assert_match "pg2mongo_pg1_1" } @test "$test_label check container pg2mongo_pg2_1" { run docker ps assert_success assert_match "pg2mongo_pg2_1" } @test "$test_label check container pg2mongo_mongo_1" { run docker ps assert_success assert_match "pg2mongo_mongo_1" } @test "$test_label mongo show dbs" { # copy files to mongo run docker cp sh-mg/. pg2mongo_mongo_1:/ run docker cp tc-mg/. pg2mongo_mongo_1:/ assert_success run docker exec -it pg2mongo_mongo_1 bash /mongo.sh tc000-mg.txt assert_success assert_match "admin" assert_match "config" assert_match "local" }
rm -rf classes rm -rf TestJarsInJar.jar mkdir classes mkdir classes/sub javac -d classes *.java cd classes jar cf ClassInJar1.jar ClassInJar1.class jar cf sub/ClassInJar2.jar ClassInJar2.class jar cmf ../MANIFEST.MF ../TestJarsInJar.jar ClassInJar0.class ClassInJar1.jar sub/ClassInJar2.jar #jar cf ../TestJarsInJar.jar ClassInJar0.class ClassInJar1.jar sub/ClassInJar2.jar cd .. rm -rf classes jar tf TestJarsInJar.jar
<filename>src/Client/Entity/View/Modal/Confirm.js<gh_stars>0 'use strict'; /** * A modal for responding yes/no * * @memberof HashBrown.Client.Entity.View.Modal */ class Confirm extends HashBrown.Entity.View.Modal.ModalBase { /** * Constructor */ constructor(params) { super(params); this.template = require('template/modal/confirm'); } /** * Event: Clicked yes */ async onClickYes() { this.trigger('yes'); this.close(); } /** * Event: Clicked no */ async onClickNo() { this.trigger('no'); this.close(); } } module.exports = Confirm;
import RepeaterEditor from './RepeaterEditor'; export default RepeaterEditor;
<reponame>tormachris/csk1<gh_stars>1-10 package logic; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; /** * Represents the Switch which can toggle a Hole linked to it. * @author tdani * */ public class Switch extends Tile { private static final long serialVersionUID = 8468456817549292315L; private static final Logger LOGGER = Logger.getLogger(Switch.class.getName()); private Hole hole; /** * Default constructor */ public Switch() { LOGGER.setLevel(Level.ALL); ConsoleHandler handler = new ConsoleHandler(); handler.setFormatter(new SimpleFormatter()); LOGGER.addHandler(handler); handler.setLevel(Level.ALL); } /** * removes the thing from the switch, toggles if it was open before * @param t the thing */ @Override public void remove(Thing t) { // checking if the Thing is on this Tile if (t.equals(super.getThing())) hole.setOpen(false); super.remove(t); } /** * Acts like a normal Tile, however if the Thing gets accepted it will call the * OnSwitch function of the Thing * * @param t * The Thing that moves onto the Switch * @return Shows whether the Thing has been accepted */ @Override public boolean accept(Thing t) { // calls the same function of its superclass Boolean accepted = Boolean.valueOf(super.accept(t)); // if the Thing is allowed to move onto the Tile the Switch will trigger its // OnSwitch() // function in order to inform the Thing that it has moved onto a Switch if (accepted) { t.onSwitch(this); if (!t.getClass().equals(Crate.class)) hole.setOpen(false); } LOGGER.log(Level.FINE, "Switch accepted:{0}", accepted); return accepted.booleanValue(); } /** * This function should be called when a Crate moves onto a switch. If this * happens the Switch will toggle the state of the Hole linked to it. * * @param c * The Crate that has moved onto the Switch. */ public void activate() { LOGGER.log(Level.FINE, "Switch toggling hole"); hole.toggleOpen(); } /** * Setter of the attribute Hole. * * @param newvalue * The new hole */ public void setHole(Hole newvalue) { if (newvalue != null) { // Checking for valid value hole = newvalue; LOGGER.log(Level.FINE, "New value for hole set"); } else throw new NullPointerException("newvalue is null"); } /** * Gets the current hole. */ public Hole getHole() { return hole; } /** * Constructor. Sets the hole. */ public Switch(Hole h) { this.setHole(h); } }
<gh_stars>1000+ import os from dagster import StringSource, check from dagster.serdes import ConfigurableClass, ConfigurableClassData class LocalArtifactStorage(ConfigurableClass): def __init__(self, base_dir, inst_data=None): self._base_dir = base_dir self._inst_data = check.opt_inst_param(inst_data, "inst_data", ConfigurableClassData) @property def inst_data(self): return self._inst_data @property def base_dir(self): return self._base_dir def file_manager_dir(self, run_id): check.str_param(run_id, "run_id") return os.path.join(self.base_dir, "storage", run_id, "files") def intermediates_dir(self, run_id): return os.path.join(self.base_dir, "storage", run_id, "") @property def storage_dir(self): return os.path.join(self.base_dir, "storage") @property def schedules_dir(self): return os.path.join(self.base_dir, "schedules") @staticmethod def from_config_value(inst_data, config_value): return LocalArtifactStorage(inst_data=inst_data, **config_value) @classmethod def config_type(cls): return {"base_dir": StringSource}
<reponame>Nardos111/Data-Visualization-Ethiopia<filename>node_modules/@nivo/pie/dist/types/RadialLabel.d.ts import { RadialLabelData } from './types'; export declare const RadialLabel: <RawDatum>({ label, linkStrokeWidth, }: { label: RadialLabelData<RawDatum>; linkStrokeWidth: number; }) => JSX.Element; //# sourceMappingURL=RadialLabel.d.ts.map
#!/bin/bash set -x set -e python --version apt-get update apt-get install python3-pip cd /reckoner pip3 install . reckoner --version curl -LO https://github.com/ovh/venom/releases/download/v0.27.0/venom.linux-amd64 mv venom.linux-amd64 /usr/local/bin/venom chmod +x /usr/local/bin/venom mkdir -p /tmp/test-results cd /reckoner/end_to_end_testing # The parallelization number must remain relatively low otherwise the tests become flaky due to resources and pending pods and such venom run tests/* --log debug --output-dir=/tmp/test-results --parallel=3 exit $?
const obj = { "Name": "John", "Age": 32, "Location": "San Francisco" } for(let key in obj){ console.log(` ${key}: ${obj[key]}`); } // Output: Name: John, Age: 32, Location: San Francisco
<reponame>cdn198/spring-notes INSERT INTO `mydb`.`user` (`id`, `name`, `sex`, `age`) VALUES ('1', 'zhangsan', '男', '20'); INSERT INTO `mydb`.`user` (`id`, `name`, `sex`, `age`) VALUES ('2', 'lisi', '男', '19');
#!/bin/bash set -eo pipefail IMAGE=kubeovn/kube-ovn:v1.8.2 echo "[Step 0/6] Update ovn-central" kubectl set image deployment/ovn-central -n kube-system ovn-central="$IMAGE" if [[ ! $(kubectl get deploy -n kube-system ovn-central -o jsonpath='{.spec.template.spec.containers[0].livenessProbe}') =~ "periodSeconds" ]]; then kubectl patch deploy/ovn-central -n kube-system --type='json' -p='[{"op": "add", "path": "/spec/template/spec/containers/0/livenessProbe/periodSeconds", "value": 15}]' else kubectl patch deploy/ovn-central -n kube-system --type='json' -p='[{"op": "replace", "path": "/spec/template/spec/containers/0/livenessProbe/periodSeconds", "value": 15}]' fi if [[ ! $(kubectl get deploy -n kube-system ovn-central -o jsonpath='{.spec.template.spec.containers[0].readinessProbe}') =~ "periodSeconds" ]]; then kubectl patch deploy/ovn-central -n kube-system --type='json' -p='[{"op": "add", "path": "/spec/template/spec/containers/0/readinessProbe/periodSeconds", "value": 15}]' else kubectl patch deploy/ovn-central -n kube-system --type='json' -p='[{"op": "replace", "path": "/spec/template/spec/containers/0/readinessProbe/periodSeconds", "value": 15}]' fi kubectl rollout status deployment/ovn-central -n kube-system echo "-------------------------------" echo "" echo "[Step 1/6] Update ovs-ovn" kubectl set image ds/ovs-ovn -n kube-system openvswitch="$IMAGE" kubectl delete pod -n kube-system -lapp=ovs echo "-------------------------------" echo "" echo "[Step 2/6] Update kube-ovn-controller" kubectl set image deployment/kube-ovn-controller -n kube-system kube-ovn-controller="$IMAGE" kubectl rollout status deployment/kube-ovn-controller -n kube-system echo "-------------------------------" echo "" echo "[Step 3/6] Update kube-ovn-cni" kubectl set image ds/kube-ovn-cni -n kube-system cni-server="$IMAGE" if [[ ! $(kubectl get ds -n kube-system kube-ovn-cni -o jsonpath='{.spec.template.spec.containers[0].livenessProbe}') =~ "timeoutSeconds" ]]; then kubectl patch ds/kube-ovn-cni -n kube-system --type='json' -p='[{"op": "add", "path": "/spec/template/spec/containers/0/livenessProbe/timeoutSeconds", "value": 5}]' else kubectl patch ds/kube-ovn-cni -n kube-system --type='json' -p='[{"op": "replace", "path": "/spec/template/spec/containers/0/livenessProbe/timeoutSeconds", "value": 5}]' fi if [[ ! $(kubectl get ds -n kube-system kube-ovn-cni -o jsonpath='{.spec.template.spec.containers[0].readinessProbe}') =~ "timeoutSeconds" ]]; then kubectl patch ds/kube-ovn-cni -n kube-system --type='json' -p='[{"op": "add", "path": "/spec/template/spec/containers/0/readinessProbe/timeoutSeconds", "value": 5}]' else kubectl patch ds/kube-ovn-cni -n kube-system --type='json' -p='[{"op": "replace", "path": "/spec/template/spec/containers/0/readinessProbe/timeoutSeconds", "value": 5}]' fi kubectl rollout status daemonset/kube-ovn-cni -n kube-system echo "-------------------------------" echo "" echo "[Step 4/6] Update kube-ovn-pinger" if [[ $(kubectl get ds -n kube-system kube-ovn-pinger -o jsonpath='{.spec.template}') =~ "tolerations" ]]; then kubectl patch ds/kube-ovn-pinger -n kube-system --type='json' -p='[{"op": "remove", "path": "/spec/template/spec/tolerations"}]' fi if [[ $(kubectl get ds -n kube-system kube-ovn-pinger -o jsonpath='{.spec.template.spec.containers[0].env[2]}') =~ "POD_IPS" ]]; then kubectl patch ds/kube-ovn-pinger -n kube-system --type='json' -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/env/2"}]' fi kubectl set image ds/kube-ovn-pinger -n kube-system pinger="$IMAGE" kubectl rollout status daemonset/kube-ovn-pinger -n kube-system echo "-------------------------------" echo "" echo "[Step 5/6] Update kube-ovn-monitor" kubectl set image deployment/kube-ovn-monitor -n kube-system kube-ovn-monitor="$IMAGE" kubectl rollout status deployment/kube-ovn-monitor -n kube-system echo "-------------------------------" echo "" echo "[Step 6/6] Update kubectl ko plugin" mkdir -p /usr/local/bin cat <<\EOF > /usr/local/bin/kubectl-ko #!/bin/bash set -euo pipefail KUBE_OVN_NS=kube-system OVN_NB_POD= OVN_SB_POD= showHelp(){ echo "kubectl ko {subcommand} [option...]" echo "Available Subcommands:" echo " [nb|sb] [status|kick|backup] ovn-db operations show cluster status, kick stale server or backup database" echo " nbctl [ovn-nbctl options ...] invoke ovn-nbctl" echo " sbctl [ovn-sbctl options ...] invoke ovn-sbctl" echo " vsctl {nodeName} [ovs-vsctl options ...] invoke ovs-vsctl on the specified node" echo " ofctl {nodeName} [ovs-ofctl options ...] invoke ovs-ofctl on the specified node" echo " dpctl {nodeName} [ovs-dpctl options ...] invoke ovs-dpctl on the specified node" echo " appctl {nodeName} [ovs-appctl options ...] invoke ovs-appctl on the specified node" echo " tcpdump {namespace/podname} [tcpdump options ...] capture pod traffic" echo " trace {namespace/podname} {target ip address} {icmp|tcp|udp} [target tcp or udp port] trace ovn microflow of specific packet" echo " diagnose {all|node} [nodename] diagnose connectivity of all nodes or a specific node" } tcpdump(){ namespacedPod="$1"; shift namespace=$(echo "$namespacedPod" | cut -d "/" -f1) podName=$(echo "$namespacedPod" | cut -d "/" -f2) if [ "$podName" = "$namespacedPod" ]; then namespace="default" fi nodeName=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.spec.nodeName}) hostNetwork=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.spec.hostNetwork}) if [ -z "$nodeName" ]; then echo "Pod $namespacedPod not exists on any node" exit 1 fi ovnCni=$(kubectl get pod -n $KUBE_OVN_NS -o wide| grep kube-ovn-cni| grep " $nodeName " | awk '{print $1}') if [ -z "$ovnCni" ]; then echo "kube-ovn-cni not exist on node $nodeName" exit 1 fi if [ "$hostNetwork" = "true" ]; then set -x kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- tcpdump -nn "$@" else nicName=$(kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- ovs-vsctl --data=bare --no-heading --columns=name find interface external-ids:iface-id="$podName"."$namespace" | tr -d '\r') if [ -z "$nicName" ]; then echo "nic doesn't exist on node $nodeName" exit 1 fi podNicType=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.metadata.annotations.ovn\\.kubernetes\\.io/pod_nic_type}) podNetNs=$(kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- ovs-vsctl --data=bare --no-heading get interface "$nicName" external-ids:pod_netns | tr -d '\r' | sed -e 's/^"//' -e 's/"$//') set -x if [ "$podNicType" = "internal-port" ]; then kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- nsenter --net="$podNetNs" tcpdump -nn -i "$nicName" "$@" else kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- nsenter --net="$podNetNs" tcpdump -nn -i eth0 "$@" fi fi } trace(){ namespacedPod="$1" namespace=$(echo "$1" | cut -d "/" -f1) podName=$(echo "$1" | cut -d "/" -f2) if [ "$podName" = "$1" ]; then namespace="default" fi dst="$2" if [ -z "$dst" ]; then echo "need a target ip address" exit 1 fi af="4" nw="nw" proto="" if [[ "$dst" =~ .*:.* ]]; then af="6" nw="ipv6" proto="6" fi podIPs=($(kubectl get pod "$podName" -n "$namespace" -o jsonpath="{.status.podIPs[*].ip}")) mac=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.metadata.annotations.ovn\\.kubernetes\\.io/mac_address}) ls=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.metadata.annotations.ovn\\.kubernetes\\.io/logical_switch}) hostNetwork=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.spec.hostNetwork}) nodeName=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.spec.nodeName}) if [ "$hostNetwork" = "true" ]; then echo "Can not trace host network pod" exit 1 fi if [ -z "$ls" ]; then echo "pod address not ready" exit 1 fi podIP="" for ip in ${podIPs[@]}; do if [ "$af" = "4" ]; then if [[ ! "$ip" =~ .*:.* ]]; then podIP=$ip break fi elif [[ "$ip" =~ .*:.* ]]; then podIP=$ip break fi done if [ -z "$podIP" ]; then echo "Pod has no IPv$af address" exit 1 fi gwMac="" if [ ! -z "$(kubectl get subnet $ls -o jsonpath={.spec.vlan})" ]; then gateway=$(kubectl get subnet "$ls" -o jsonpath={.spec.gateway}) if [[ "$gateway" =~ .*,.* ]]; then if [ "$af" = "4" ]; then gateway=${gateway%%,*} else gateway=${gateway##*,} fi fi ovnCni=$(kubectl get pod -n $KUBE_OVN_NS -o wide | grep -w kube-ovn-cni | grep " $nodeName " | awk '{print $1}') if [ -z "$ovnCni" ]; then echo "No kube-ovn-cni Pod running on node $nodeName" exit 1 fi nicName=$(kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- ovs-vsctl --data=bare --no-heading --columns=name find interface external-ids:iface-id="$podName"."$namespace" | tr -d '\r') if [ -z "$nicName" ]; then echo "nic doesn't exist on node $nodeName" exit 1 fi podNicType=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.metadata.annotations.ovn\\.kubernetes\\.io/pod_nic_type}) podNetNs=$(kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- ovs-vsctl --data=bare --no-heading get interface "$nicName" external-ids:pod_netns | tr -d '\r' | sed -e 's/^"//' -e 's/"$//') if [ "$podNicType" != "internal-port" ]; then nicName="eth0" fi if [[ "$gateway" =~ .*:.* ]]; then cmd="ndisc6 -q $gateway $nicName" output=$(kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- nsenter --net="$podNetNs" ndisc6 -q "$gateway" "$nicName") else cmd="arping -c3 -C1 -i1 -I $nicName $gateway" output=$(kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- nsenter --net="$podNetNs" arping -c3 -C1 -i1 -I "$nicName" "$gateway") fi if [ $? -ne 0 ]; then echo "failed to run '$cmd' in Pod's netns" exit 1 fi gwMac=$(echo "$output" | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}') else lr=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.metadata.annotations.ovn\\.kubernetes\\.io/logical_router}) if [ -z "$lr" ]; then lr=$(kubectl get subnet "$ls" -o jsonpath={.spec.vpc}) fi gwMac=$(kubectl exec $OVN_NB_POD -n $KUBE_OVN_NS -c ovn-central -- ovn-nbctl --data=bare --no-heading --columns=mac find logical_router_port name="$lr"-"$ls" | tr -d '\r') fi if [ -z "$gwMac" ]; then echo "get gw mac failed" exit 1 fi type="$3" case $type in icmp) set -x kubectl exec "$OVN_SB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovn-trace --ct=new "$ls" "inport == \"$podName.$namespace\" && ip.ttl == 64 && icmp && eth.src == $mac && ip$af.src == $podIP && eth.dst == $gwMac && ip$af.dst == $dst" ;; tcp|udp) set -x kubectl exec "$OVN_SB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovn-trace --ct=new "$ls" "inport == \"$podName.$namespace\" && ip.ttl == 64 && eth.src == $mac && ip$af.src == $podIP && eth.dst == $gwMac && ip$af.dst == $dst && $type.src == 10000 && $type.dst == $4" ;; *) echo "type $type not supported" echo "kubectl ko trace {namespace/podname} {target ip address} {icmp|tcp|udp} [target tcp or udp port]" exit 1 ;; esac set +x echo "--------" echo "Start OVS Tracing" echo "" echo "" ovsPod=$(kubectl get pod -n $KUBE_OVN_NS -o wide | grep " $nodeName " | grep ovs-ovn | awk '{print $1}') if [ -z "$ovsPod" ]; then echo "ovs pod doesn't exist on node $nodeName" exit 1 fi inPort=$(kubectl exec "$ovsPod" -n $KUBE_OVN_NS -- ovs-vsctl --format=csv --data=bare --no-heading --columns=ofport find interface external_id:iface-id="$podName"."$namespace") case $type in icmp) set -x kubectl exec "$ovsPod" -n $KUBE_OVN_NS -- ovs-appctl ofproto/trace br-int "in_port=$inPort,icmp$proto,${nw}_src=$podIP,${nw}_dst=$dst,dl_src=$mac,dl_dst=$gwMac" ;; tcp|udp) set -x kubectl exec "$ovsPod" -n $KUBE_OVN_NS -- ovs-appctl ofproto/trace br-int "in_port=$inPort,$type$proto,${nw}_src=$podIP,${nw}_dst=$dst,dl_src=$mac,dl_dst=$gwMac,${type}_src=1000,${type}_dst=$4" ;; *) echo "type $type not supported" echo "kubectl ko trace {namespace/podname} {target ip address} {icmp|tcp|udp} [target tcp or udp port]" exit 1 ;; esac } xxctl(){ subcommand="$1"; shift nodeName="$1"; shift kubectl get no "$nodeName" > /dev/null ovsPod=$(kubectl get pod -n $KUBE_OVN_NS -o wide | grep " $nodeName " | grep ovs-ovn | awk '{print $1}') if [ -z "$ovsPod" ]; then echo "ovs pod doesn't exist on node $nodeName" exit 1 fi kubectl exec "$ovsPod" -n $KUBE_OVN_NS -- ovs-$subcommand "$@" } checkLeader(){ component="$1"; shift count=$(kubectl get ep ovn-$component -n $KUBE_OVN_NS -o yaml | grep ip | wc -l) if [ $count -eq 0 ]; then echo "no ovn-$component exists !!" exit 1 fi if [ $count -gt 1 ]; then echo "ovn-$component has more than one leader !!" exit 1 fi echo "ovn-$component leader check ok" } diagnose(){ kubectl get crd vpcs.kubeovn.io kubectl get crd vpc-nat-gateways.kubeovn.io kubectl get crd subnets.kubeovn.io kubectl get crd ips.kubeovn.io kubectl get crd vlans.kubeovn.io kubectl get crd provider-networks.kubeovn.io kubectl get svc kube-dns -n kube-system kubectl get svc kubernetes -n default kubectl get sa -n kube-system ovn kubectl get clusterrole system:ovn kubectl get clusterrolebinding ovn kubectl get no -o wide kubectl ko nbctl show kubectl ko nbctl lr-route-list ovn-cluster kubectl ko nbctl ls-lb-list ovn-default kubectl ko nbctl list acl kubectl ko sbctl show checkKubeProxy checkDeployment ovn-central checkDeployment kube-ovn-controller checkDaemonSet kube-ovn-cni checkDaemonSet ovs-ovn checkDeployment coredns checkLeader nb checkLeader sb checkLeader northd type="$1" case $type in all) echo "### kube-ovn-controller recent log" set +e kubectl logs -n $KUBE_OVN_NS -l app=kube-ovn-controller --tail=100 | grep E$(date +%m%d) set -e echo "" pingers=$(kubectl -n $KUBE_OVN_NS get po --no-headers -o custom-columns=NAME:.metadata.name -l app=kube-ovn-pinger) for pinger in $pingers do nodeName=$(kubectl get pod "$pinger" -n "$KUBE_OVN_NS" -o jsonpath={.spec.nodeName}) echo "### start to diagnose node $nodeName" echo "#### ovn-controller log:" kubectl exec -n $KUBE_OVN_NS "$pinger" -- tail /var/log/ovn/ovn-controller.log echo "" echo "#### ovs-vswitchd log:" kubectl exec -n $KUBE_OVN_NS "$pinger" -- tail /var/log/openvswitch/ovs-vswitchd.log echo "" echo "#### ovs-vsctl show results:" kubectl exec -n $KUBE_OVN_NS "$pinger" -- ovs-vsctl show echo "" echo "#### pinger diagnose results:" kubectl exec -n $KUBE_OVN_NS "$pinger" -- /kube-ovn/kube-ovn-pinger --mode=job echo "### finish diagnose node $nodeName" echo "" done ;; node) nodeName="$2" kubectl get no "$nodeName" > /dev/null pinger=$(kubectl -n $KUBE_OVN_NS get po -l app=kube-ovn-pinger -o 'jsonpath={.items[?(@.spec.nodeName=="'$nodeName'")].metadata.name}') if [ ! -n "$pinger" ]; then echo "Error: No kube-ovn-pinger running on node $nodeName" exit 1 fi echo "### start to diagnose node $nodeName" echo "#### ovn-controller log:" kubectl exec -n $KUBE_OVN_NS "$pinger" -- tail /var/log/ovn/ovn-controller.log echo "" echo "#### ovs-vswitchd log:" kubectl exec -n $KUBE_OVN_NS "$pinger" -- tail /var/log/openvswitch/ovs-vswitchd.log echo "" kubectl exec -n $KUBE_OVN_NS "$pinger" -- /kube-ovn/kube-ovn-pinger --mode=job echo "### finish diagnose node $nodeName" echo "" ;; *) echo "type $type not supported" echo "kubectl ko diagnose {all|node} [nodename]" ;; esac } getOvnCentralPod(){ NB_POD=$(kubectl get pod -n $KUBE_OVN_NS -l ovn-nb-leader=true | grep ovn-central | head -n 1 | awk '{print $1}') if [ -z "$NB_POD" ]; then echo "nb leader not exists" exit 1 fi OVN_NB_POD=$NB_POD SB_POD=$(kubectl get pod -n $KUBE_OVN_NS -l ovn-sb-leader=true | grep ovn-central | head -n 1 | awk '{print $1}') if [ -z "$SB_POD" ]; then echo "nb leader not exists" exit 1 fi OVN_SB_POD=$SB_POD } checkDaemonSet(){ name="$1" currentScheduled=$(kubectl get ds -n $KUBE_OVN_NS "$name" -o jsonpath={.status.currentNumberScheduled}) desiredScheduled=$(kubectl get ds -n $KUBE_OVN_NS "$name" -o jsonpath={.status.desiredNumberScheduled}) available=$(kubectl get ds -n $KUBE_OVN_NS "$name" -o jsonpath={.status.numberAvailable}) ready=$(kubectl get ds -n $KUBE_OVN_NS "$name" -o jsonpath={.status.numberReady}) if [ "$currentScheduled" = "$desiredScheduled" ] && [ "$desiredScheduled" = "$available" ] && [ "$available" = "$ready" ]; then echo "ds $name ready" else echo "Error ds $name not ready" exit 1 fi } checkDeployment(){ name="$1" ready=$(kubectl get deployment -n $KUBE_OVN_NS "$name" -o jsonpath={.status.readyReplicas}) updated=$(kubectl get deployment -n $KUBE_OVN_NS "$name" -o jsonpath={.status.updatedReplicas}) desire=$(kubectl get deployment -n $KUBE_OVN_NS "$name" -o jsonpath={.status.replicas}) available=$(kubectl get deployment -n $KUBE_OVN_NS "$name" -o jsonpath={.status.availableReplicas}) if [ "$ready" = "$updated" ] && [ "$updated" = "$desire" ] && [ "$desire" = "$available" ]; then echo "deployment $name ready" else echo "Error deployment $name not ready" exit 1 fi } checkKubeProxy(){ dsMode=`kubectl get ds -n kube-system | grep kube-proxy || true` if [ -z "$dsMode" ]; then nodeIps=`kubectl get node -o wide | grep -v "INTERNAL-IP" | awk '{print $6}'` for node in $nodeIps do healthResult=`curl -g -6 -sL -w %{http_code} http://[$node]:10256/healthz -o /dev/null | grep -v 200 || true` if [ -n "$healthResult" ]; then echo "$node kube-proxy's health check failed" exit 1 fi done else checkDaemonSet kube-proxy fi echo "kube-proxy ready" } dbtool(){ suffix=$(date +%m%d%H%M%s) component="$1"; shift action="$1"; shift case $component in nb) case $action in status) kubectl exec "$OVN_NB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovs-appctl -t /var/run/ovn/ovnnb_db.ctl cluster/status OVN_Northbound ;; kick) kubectl exec "$OVN_NB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovs-appctl -t /var/run/ovn/ovnnb_db.ctl cluster/kick OVN_Northbound "$1" ;; backup) kubectl exec "$OVN_NB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovsdb-tool cluster-to-standalone /tmp/ovnnb_db.$suffix.backup /etc/ovn/ovnnb_db.db kubectl cp $KUBE_OVN_NS/$OVN_NB_POD:/tmp/ovnnb_db.$suffix.backup $(pwd)/ovnnb_db.$suffix.backup kubectl exec "$OVN_NB_POD" -n $KUBE_OVN_NS -c ovn-central -- rm -f /tmp/ovnnb_db.$suffix.backup echo "backup ovn-$component db to $(pwd)/ovnnb_db.$suffix.backup" ;; <<<<<<< HEAD:dist/images/update/1.8.0-1.8.2.sh ======= dbstatus) kubectl exec "$OVN_NB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovn-appctl -t /var/run/ovn/ovnnb_db.ctl ovsdb-server/get-db-storage-status OVN_Northbound ;; restore) # set ovn-central replicas to 0 replicas=$(kubectl get deployment -n $KUBE_OVN_NS ovn-central -o jsonpath={.spec.replicas}) kubectl scale deployment -n $KUBE_OVN_NS ovn-central --replicas=0 echo "ovn-central original replicas is $replicas" # backup ovn-nb db declare nodeIpArray declare podNameArray declare nodeIps if [[ $(kubectl get deployment -n kube-system ovn-central -o jsonpath='{.spec.template.spec.containers[0].env[1]}') =~ "NODE_IPS" ]]; then nodeIpVals=`kubectl get deployment -n kube-system ovn-central -o jsonpath='{.spec.template.spec.containers[0].env[1].value}'` nodeIps=(${nodeIpVals//,/ }) else nodeIps=`kubectl get node -lkube-ovn/role=master -o wide | grep -v "INTERNAL-IP" | awk '{print $6}'` fi firstIP=${nodeIps[0]} podNames=`kubectl get pod -n $KUBE_OVN_NS | grep ovs-ovn | awk '{print $1}'` echo "first nodeIP is $firstIP" i=0 for nodeIp in ${nodeIps[@]} do for pod in $podNames do hostip=$(kubectl get pod -n $KUBE_OVN_NS $pod -o jsonpath={.status.hostIP}) if [ $nodeIp = $hostip ]; then nodeIpArray[$i]=$nodeIp podNameArray[$i]=$pod i=`expr $i + 1` echo "ovs-ovn pod on node $nodeIp is $pod" break fi done done echo "backup nb db file" kubectl exec -it -n $KUBE_OVN_NS ${podNameArray[0]} -- ovsdb-tool cluster-to-standalone /etc/ovn/ovnnb_db_standalone.db /etc/ovn/ovnnb_db.db # mv all db files for pod in ${podNameArray[@]} do kubectl exec -it -n $KUBE_OVN_NS $pod -- mv /etc/ovn/ovnnb_db.db /tmp kubectl exec -it -n $KUBE_OVN_NS $pod -- mv /etc/ovn/ovnsb_db.db /tmp done # restore db and replicas echo "restore nb db file, operate in pod ${podNameArray[0]}" kubectl exec -it -n $KUBE_OVN_NS ${podNameArray[0]} -- mv /etc/ovn/ovnnb_db_standalone.db /etc/ovn/ovnnb_db.db kubectl scale deployment -n $KUBE_OVN_NS ovn-central --replicas=$replicas echo "finish restore nb db file and ovn-central replicas" ;; >>>>>>> 5571619d (update nodeips for restore cmd in ko plugin):dist/images/update/1.8.0-1.8.3.sh *) echo "unknown action $action" esac ;; sb) case $action in status) kubectl exec "$OVN_SB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovs-appctl -t /var/run/ovn/ovnsb_db.ctl cluster/status OVN_Southbound ;; kick) kubectl exec "$OVN_SB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovs-appctl -t /var/run/ovn/ovnsb_db.ctl cluster/kick OVN_Southbound "$1" ;; backup) kubectl exec "$OVN_SB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovsdb-tool cluster-to-standalone /tmp/ovnsb_db.$suffix.backup /etc/ovn/ovnsb_db.db kubectl cp $KUBE_OVN_NS/$OVN_SB_POD:/tmp/ovnsb_db.$suffix.backup $(pwd)/ovnsb_db.$suffix.backup kubectl exec "$OVN_SB_POD" -n $KUBE_OVN_NS -c ovn-central -- rm -f /tmp/ovnsb_db.$suffix.backup echo "backup ovn-$component db to $(pwd)/ovnsb_db.$suffix.backup" ;; *) echo "unknown action $action" esac ;; *) echo "unknown subcommand $component" esac } if [ $# -lt 1 ]; then showHelp exit 0 else subcommand="$1"; shift fi getOvnCentralPod case $subcommand in nbctl) kubectl exec "$OVN_NB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovn-nbctl "$@" ;; sbctl) kubectl exec "$OVN_SB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovn-sbctl "$@" ;; vsctl|ofctl|dpctl|appctl) xxctl "$subcommand" "$@" ;; nb|sb) dbtool "$subcommand" "$@" ;; tcpdump) tcpdump "$@" ;; trace) trace "$@" ;; diagnose) diagnose "$@" ;; *) showHelp ;; esac EOF echo "Update Success!" echo " ,,,, ,::, ,,::,,,, ,,,,,::::::::::::,,,,, ,,,::::::::::::::::::::::,,, ,,::::::::::::::::::::::::::::,, ,,::::::::::::::::::::::::::::::::,, ,::::::::::::::::::::::::::::::::::::, ,:::::::::::::,, ,,:::::,,,::::::::::, ,,:::::::::::::, ,::, ,:::::::::, ,:::::::::::::, :x, ,:: :, ,:::::::::, ,:::::::::::::::, ,,, ,::, ,, ,::::::::::, ,:::::::::::::::::,,,,,,:::::,,,,::::::::::::, ,:, ,:, ,xx, ,:::::, ,:, ,:: :::, ,x ,::::::::::::::::::::::::::::::::::::::::::::, :x: ,:xx: , :xx, :xxxxxxxxx, :xx, ,xx:,xxxx, :x ,::::::::::::::::::::::::::::::::::::::::::::, :xxxxx:, ,xx, :x: :xxx:x::, ::xxxx: :xx:, ,:xxx :xx, ,xx: ,xxxxx:, :x ,::::::::::::::::::::::::::::::::::::::::::::, :xxxxx, :xx, :x: :xxx,,:xx,:xx:,:xx, ,,,,,,,,,xxx, ,xx: :xx:xx: ,xxx,:xx::x ,::::::,,::::::::,,::::::::,,:::::::,,,::::::, :x:,xxx: ,xx, :xx :xx: ,xx,xxxxxx:, ,xxxxxxx:,xxx:, ,xxx, :xxx: ,xxx, :xxxx ,::::, ,::::, ,:::::, ,,::::, ,::::, :x: ,:xx,,:xx::xxxx,,xxx::xx: :xx::::x: ,,,,,, ,xxxxxxxxx, ,xx: ,xxx, :xxx ,::::, ,::::, ,::::, ,::::, ,::::, ,:, ,:, ,,::,,:, ,::::,, ,:::::, ,,:::::, ,, :x: ,:: ,::::, ,::::, ,::::, ,::::, ,::::, ,,,,, ,::::, ,::::, ,::::, ,:::, ,,,,,,,,,,,,, ,::::, ,::::, ,::::, ,:::, ,,,:::::::::::::::, ,::::, ,::::, ,::::, ,::::, ,,,,:::::::::,,,,,,,:::, ,::::, ,::::, ,::::, ,::::::::::::,,,,, ,,,, ,::::, ,,,, ,,,::::,,,, ,::::, ,,::, "
#include <iostream> #include <vector> #include <string> #include <map> std::pair<std::map<std::string, std::string>, std::vector<std::string>> parseArguments(const std::vector<std::string>& arguments) { std::map<std::string, std::string> parsedOptions; std::vector<std::string> standaloneArguments; for (size_t i = 1; i < arguments.size(); ++i) { if (arguments[i].find("--") == 0) { size_t pos = arguments[i].find('='); if (pos != std::string::npos) { std::string key = arguments[i].substr(2, pos - 2); std::string value = arguments[i].substr(pos + 1); parsedOptions[key] = value; } else { parsedOptions[arguments[i].substr(2)] = arguments[i + 1]; ++i; } } else if (arguments[i].find('-') == 0) { parsedOptions[arguments[i].substr(1)] = arguments[i + 1]; ++i; } else { standaloneArguments.push_back(arguments[i]); } } return {parsedOptions, standaloneArguments}; } int main() { std::vector<std::string> input = {"./program", "-f", "file.txt", "--output=output.txt", "arg1", "arg2"}; auto result = parseArguments(input); std::cout << "Parsed options:" << std::endl; for (const auto& pair : result.first) { std::cout << pair.first << ": " << pair.second << std::endl; } std::cout << "Standalone arguments:" << std::endl; for (const auto& arg : result.second) { std::cout << arg << std::endl; } return 0; }
package com.alibaba.csp.sentinel.workshop.web; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Run with: {@code -Dcsp.sentinel.api.port=8723 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=web-demo}. * * @author <NAME> */ @SpringBootApplication public class WebApplication { public static void main(String[] args) { SpringApplication.run(WebApplication.class, args); } }
<filename>components/card.tsx<gh_stars>1-10 import CoverImage, { CoverImageProps } from 'components/card-cover-image'; import Avatar from 'components/card-avatar'; import CardIcons from 'components/card-icons'; import { authorType, socialType } from 'types/posts'; import CardTitle from 'components/card-title'; import CardExcerpt from 'components/card-excerpt'; import { Fragment } from 'react'; import SiteDivider from 'components/site-divider'; import { PostSlugs_posts_edges_node } from '../graphql/__generated__/PostSlugs'; interface CardProps { coverImage: CoverImageProps; title: string; slug: string | number; modified: string; author: authorType; excerpt?: string; social: socialType; } const Card = ({ author, coverImage, excerpt, modified, slug, social, title }: CardProps): JSX.Element => { //had to add this in because without it _html was erroring out because it is of type string. if (!excerpt) { excerpt = ''; } return ( <Fragment> <div className='block mx-auto select-none w-full'> <div className='block overflow-x-hidden overflow-y-hidden transition-all duration-1000 ease-in-out transform border-collapse border-current max-w-xsCardGridCima w-xsCardGridCima sm:w-aboutImage600 sm:max-w-aboutimage600 sm:overflow-hidden lg:w-aboutImage400 rounded-custom mx-auto'> <CoverImage coverImage={coverImage} title={title} slug={slug} /> <div className='flex flex-col justify-center flex-grow h-aboutOffsetPRMobile sm:h-auto text-left bg-primary'> <CardTitle slug={slug} title={title} /> <CardExcerpt excerpt={excerpt} /> <div className='block transition-all duration-1000 transform pl-portfolioDivider font-somaRoman translate-y-portfolio'> <Avatar author={author.node} modified={modified} /> </div> <SiteDivider /> <div className='block float-right text-right pr-portfolio font-somaRoman'> <CardIcons social={social} /> </div> </div> </div> </div> </Fragment> ); }; // interface CardSlugProps { // title: string; // } // const CardSlug = ({ title }: CardSlugProps) => { // return ( // <> // <Link as={`/posts/${Card()}`} href='/posts/[slug]'> // <a> // <Card /> // </a> // </Link> // </> // ); // }; export default Card;
#!/usr/bin/env bash # Build subnet based on subnet.json and transform it into removable media. # Build Requirements: # - Operating System: Ubuntu 20.04 # - Packages: coreutils, jq, mtools, tar, util-linux, wget, rclone set -o errexit set -o pipefail BASE_DIR="$(dirname "${BASH_SOURCE[0]}")/.." REPO_ROOT=$(git rev-parse --show-toplevel) # Get keyword arguments for argument in "${@}"; do case ${argument} in -h | --help) echo 'Usage: Removable Media Builder for Boundary Node VMs Arguments: -h, --help show this help message and exit -i=, --input= JSON formatted input file (Default: ./subnet.json) -o=, --output= removable media output directory (Default: ./build-out/) -s=, --ssh= specify directory holding SSH authorized_key files (Default: ../../testnet/config/ssh_authorized_keys) -n=, --nns_urls= specify a file that lists on each line a nns url of the form http://[ip]:port this file will override nns urls derived from input json file --git-revision= git revision for which to prepare the media -x, --debug enable verbose console output ' exit 1 ;; -i=* | --input=*) INPUT="${argument#*=}" shift ;; -o=* | --output=*) OUTPUT="${argument#*=}" shift ;; -s=* | --ssh=*) SSH="${argument#*=}" shift ;; -n=* | --nns_url=*) NNS_URL_OVERRIDE="${argument#*=}" shift ;; --git-revision=*) GIT_REVISION="${argument#*=}" shift ;; *) echo 'Error: Argument is not supported.' exit 1 ;; esac done # Set arguments if undefined INPUT="${INPUT:=${BASE_DIR}/subnet.json}" OUTPUT="${OUTPUT:=${BASE_DIR}/build-out}" SSH="${SSH:=${BASE_DIR}/../../testnet/config/ssh_authorized_keys}" GIT_REVISION="${GIT_REVISION:=}" if [[ -z "$GIT_REVISION" ]]; then echo "Please provide the GIT_REVISION as env. variable or the command line with --git-revision=<value>" exit 1 fi # Load INPUT CONFIG="$(cat ${INPUT})" # Read all the top-level values out in one swoop VALUES=$(echo ${CONFIG} | jq -r -c '[ .deployment, (.name_servers | join(" ")), (.name_servers_fallback | join(" ")), (.journalbeat_hosts | join(" ")), (.journalbeat_tags | join(" ")) ] | join("\u0001")') IFS=$'\1' read -r DEPLOYMENT NAME_SERVERS NAME_SERVERS_FALLBACK JOURNALBEAT_HOSTS JOURNALBEAT_TAGS < <(echo $VALUES) # Read all the node info out in one swoop NODES=0 VALUES=$(echo ${CONFIG} \ | jq -r -c '.datacenters[] | .aux_nodes[] += { "type": "aux" } | .boundary_nodes[] += {"type": "boundary"} | .nodes[] += { "type": "replica" } | [.aux_nodes[], .boundary_nodes[], .nodes[]][] + { "ipv6_prefix": .ipv6_prefix, "ipv6_subnet": .ipv6_subnet } | [ .ipv6_prefix, .ipv6_subnet, .ipv6_address, .hostname, .subnet_type, .subnet_idx, .node_idx, .use_hsm, .type ] | join("\u0001")') while IFS=$'\1' read -r ipv6_prefix ipv6_subnet ipv6_address hostname subnet_type subnet_idx node_idx use_hsm type; do eval "declare -A __RAW_NODE_$NODES=( ['ipv6_prefix']=$ipv6_prefix ['ipv6_subnet']=$ipv6_subnet ['ipv6_address']=$ipv6_address ['subnet_type']=$subnet_type ['hostname']=$hostname ['subnet_idx']=$subnet_idx ['node_idx']=$node_idx ['use_hsm']=$use_hsm ['type']=$type )" NODES=$((NODES + 1)) done < <(printf "%s\n" "${VALUES[@]}") NODES=${!__RAW_NODE_@} function prepare_build_directories() { TEMPDIR=$(mktemp -d /tmp/build-deployment.sh.XXXXXXXXXX) IC_PREP_DIR="$TEMPDIR/IC_PREP" CONFIG_DIR="$TEMPDIR/CONFIG" TARBALL_DIR="$TEMPDIR/TARBALL" mkdir -p "${IC_PREP_DIR}/bin" mkdir -p "${CONFIG_DIR}" mkdir -p "${TARBALL_DIR}" if [ ! -d "${OUTPUT}" ]; then mkdir -p "${OUTPUT}" fi } function download_binaries() { for filename in "boundary-node-control-plane.gz" "boundary-node-prober.gz"; do "${REPO_ROOT}"/gitlab-ci/src/artifacts/rclone_download.py \ --git-rev "$GIT_REVISION" --remote-path=release --include ${filename} --out="${IC_PREP_DIR}/bin/" done find "${IC_PREP_DIR}/bin/" -name "*.gz" -print0 | xargs -P100 -0I{} bash -c "gunzip -f {} && basename {} .gz | xargs -I[] chmod +x ${IC_PREP_DIR}/bin/[]" mkdir -p "$OUTPUT/bin" rsync -a --delete "${IC_PREP_DIR}/bin/" "$OUTPUT/bin/" } function place_control_plane() { cp -a "${IC_PREP_DIR}/bin/boundary-node-control-plane" "$REPO_ROOT/ic-os/boundary-guestos/rootfs/opt/ic/bin/boundary-node-control-plane" cp -a "${IC_PREP_DIR}/bin/boundary-node-prober" "$REPO_ROOT/ic-os/boundary-guestos/rootfs/opt/ic/bin/boundary-node-prober" } function create_tarball_structure() { for n in $NODES; do declare -n NODE=$n if [[ "${NODE["type"]}" = "boundary" ]]; then local subnet_idx=${NODE["subnet_idx"]} local node_idx=${NODE["node_idx"]} NODE_PREFIX=${DEPLOYMENT}.$subnet_idx.$node_idx mkdir -p "${CONFIG_DIR}/$NODE_PREFIX/node/replica_config" fi done } function generate_journalbeat_config() { for n in $NODES; do declare -n NODE=$n if [[ "${NODE["type"]}" == "boundary" ]]; then local subnet_idx=${NODE["subnet_idx"]} local node_idx=${NODE["node_idx"]} # Define hostname NODE_PREFIX=${DEPLOYMENT}.$subnet_idx.$node_idx if [ "${JOURNALBEAT_HOSTS}" != "" ]; then echo "journalbeat_hosts=${JOURNALBEAT_HOSTS}" >"${CONFIG_DIR}/$NODE_PREFIX/journalbeat.conf" fi if [ "${JOURNALBEAT_TAGS}" != "" ]; then echo "journalbeat_tags=${JOURNALBEAT_TAGS}" >>"${CONFIG_DIR}/$NODE_PREFIX/journalbeat.conf" fi fi done } function generate_boundary_node_config() { rm -rf ${IC_PREP_DIR}/NNS_URL if [ -z ${NNS_URL_OVERRIDE+x} ]; then # Query and list all NNS nodes in subnet echo ${CONFIG} | jq -c '.datacenters[]' | while read datacenters; do local ipv6_prefix=$(echo ${datacenters} | jq -r '.ipv6_prefix') echo ${datacenters} | jq -c '.nodes[]' | while read nodes; do NNS_DC_URL=$(echo ${nodes} | jq -c 'select(.subnet_type|test("root_subnet"))' | while read nns_node; do local ipv6_address=$(echo "${nns_node}" | jq -r '.ipv6_address') echo -n "http://[${ipv6_address}]:8080" done) echo ${NNS_DC_URL} >>"${IC_PREP_DIR}/NNS_URL" done done NNS_URL_FILE=${IC_PREP_DIR}/NNS_URL else NNS_URL_FILE=${NNS_URL_OVERRIDE} fi NNS_URL="$(cat ${NNS_URL_FILE} | awk '$1=$1' ORS=',' | sed 's@,$@@g')" #echo ${NNS_URL} # nns config for boundary nodes echo ${CONFIG} | jq -c '.datacenters[]' | while read datacenters; do echo ${datacenters} | jq -c '[.boundary_nodes[]][]' | while read nodes; do local subnet_idx=$(echo ${nodes} | jq -r '.subnet_idx') local node_idx=$(echo ${nodes} | jq -r '.node_idx') NODE_PREFIX=${DEPLOYMENT}.$subnet_idx.$node_idx cp "${IC_PREP_DIR}/nns_public_key.pem" "${CONFIG_DIR}/$NODE_PREFIX/nns_public_key.pem" echo "nns_url=${NNS_URL}" >"${CONFIG_DIR}/$NODE_PREFIX/nns.conf" done done } function generate_network_config() { for n in $NODES; do declare -n NODE=$n if [[ "${NODE["type"]}" == "boundary" ]]; then local hostname=${NODE["hostname"]} local subnet_idx=${NODE["subnet_idx"]} local node_idx=${NODE["node_idx"]} # Define hostname NODE_PREFIX=${DEPLOYMENT}.$subnet_idx.$node_idx echo "hostname=${hostname}" >"${CONFIG_DIR}/$NODE_PREFIX/network.conf" # Set name servers echo "name_servers=${NAME_SERVERS}" >>"${CONFIG_DIR}/$NODE_PREFIX/network.conf" echo "name_servers_fallback=${NAME_SERVERS_FALLBACK}" >>"${CONFIG_DIR}/$NODE_PREFIX/network.conf" # IPv6 network configuration is obtained from the Router Advertisement. fi done } function copy_ssh_keys() { for n in $NODES; do declare -n NODE=$n if [[ "${NODE["type"]}" == "boundary" ]]; then local subnet_idx=${NODE["subnet_idx"]} local node_idx=${NODE["node_idx"]} NODE_PREFIX=${DEPLOYMENT}.$subnet_idx.$node_idx # Copy the contents of the directory, but make sure that we do not # copy/create symlinks (but rather dereference file contents). # Symlinks must be refused by the config injection script (they # can lead to confusion and side effects when overwriting one # file changes another). cp -Lr "${SSH}" "${CONFIG_DIR}/$NODE_PREFIX/accounts_ssh_authorized_keys" fi done } function build_tarball() { for n in $NODES; do declare -n NODE=$n if [[ "${NODE["type"]}" == "boundary" ]]; then local subnet_idx=${NODE["subnet_idx"]} local node_idx=${NODE["node_idx"]} # Create temporary tarball directory per node NODE_PREFIX=${DEPLOYMENT}.$subnet_idx.$node_idx mkdir -p "${TARBALL_DIR}/$NODE_PREFIX" ( cd "${CONFIG_DIR}/$NODE_PREFIX" tar c . ) >${TARBALL_DIR}/$NODE_PREFIX/ic-bootstrap.tar fi done tar czf "${OUTPUT}/config.tgz" -C "${CONFIG_DIR}" . } function build_removable_media() { for n in $NODES; do declare -n NODE=$n if [[ "${NODE["type"]}" == "boundary" ]]; then local subnet_idx=${NODE["subnet_idx"]} local node_idx=${NODE["node_idx"]} #echo "${DEPLOYMENT}.$subnet_idx.$node_idx" NODE_PREFIX=${DEPLOYMENT}.$subnet_idx.$node_idx truncate --size 4M "${OUTPUT}/$NODE_PREFIX.img" mkfs.vfat "${OUTPUT}/$NODE_PREFIX.img" mcopy -i "${OUTPUT}/$NODE_PREFIX.img" -o -s ${TARBALL_DIR}/$NODE_PREFIX/ic-bootstrap.tar :: fi done } function remove_temporary_directories() { rm -rf ${TEMPDIR} } function main() { # Establish run order prepare_build_directories download_binaries place_control_plane create_tarball_structure generate_boundary_node_config generate_journalbeat_config generate_network_config copy_ssh_keys build_tarball build_removable_media # remove_temporary_directories } main
#!/bin/bash # Reset the Django Database /opt/stack/share/stack/bin/django_db_reset.py # Create Django secret key file. Set permissions /opt/stack/share/stack/bin/django_secret.py chown root:apache /opt/stack/etc/django.secret chmod 0640 /opt/stack/etc/django.secret # Create django access to django db /opt/stack/share/stack/bin/django_db_setup.py # Create Django Database tables DJANGO_SETTINGS_MODULE=stack.restapi.settings \ /opt/stack/bin/django-admin.py makemigrations DJANGO_SETTINGS_MODULE=stack.restapi.settings \ /opt/stack/bin/django-admin.py migrate # Create a default group /opt/stack/bin/stack add api group default # Set default permissions /opt/stack/bin/stack add api group perms default perms="list *" # Blacklist commands that must not be run /opt/stack/bin/stack add api blacklist command command="list host message" /opt/stack/bin/stack add api blacklist command command="add api sudo command" # Commands that require "sudo" to be run STACK_CMDS=( "sync *" \ "load *" \ "unload *" \ "remove host" \ "add pallet" \ "remove pallet" \ "list host switch" \ ) for i in "${STACK_CMDS[@]}"; do \ /opt/stack/bin/stack add api sudo command command="${i}" sync=False done /opt/stack/bin/stack sync api sudo command # Create an admin user, and write the credentials # to a webservice credential file /opt/stack/bin/stack add api user admin admin=true output-format=json > /root/stacki-ws.cred # Allow "nobody" to run stack list commands. These will # be run with minimal privileges, and no write access # to the database. This is so that apache can sudo down # to nobody when running commands as non-privileged users /opt/stack/bin/stack set access command='list *' group=nobody # Allow write access to the pallets directory by apache. chgrp apache /export/stack/pallets chmod 0775 /export/stack/pallets
// boardgame.io export const DEFAULT_DEBUG = true export const DEFAULT_LOBBY_PORT = 8080 export const DEFAULT_SERVER_PORT = 8000 // next-auth export const DEFAULT_NEXTAUTH_URL = 'http://localhost:3000' export const DEFAULT_EMAIL_FROM = '<NAME> <<EMAIL>>' // Database export const DEFAULT_POSTGRES_HOST = 'postgres'