text
stringlengths
1
1.05M
<reponame>skcary/orangeB<filename>src/client/index.js import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import routes from './routes' import configureStore from './store/configureStore' const store = configureStore(window.__REDUX_STATE__) render( <Provider store={store}> {routes} </Provider>, document.querySelector('.react-container') )
<filename>src/main/basicprogramming/TwoStrings.java package main.basicprogramming; import java.util.Arrays; import java.util.Scanner; public class TwoStrings { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int iter = sc.nextInt(); while (iter-- >0){ String str1 = sc.next(); String str2 = sc.next(); char[] str1Array = str1.toCharArray(); char[] str2Array = str2.toCharArray(); Arrays.sort(str1Array); Arrays.sort(str2Array); String sortedStr1 = new String(str1Array); String sortedStr2 = new String(str2Array); if(sortedStr1.equals(sortedStr2)) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
#!/bin/sh _setup_iptables() { echo "Applying iptables rules..." cp -v /opt/setup/iptables/* /etc/iptables iptables-restore < /etc/iptables/rules.v4 # ip6tables-restore < /etc/iptables/rules.v6 systemctl restart docker echo "Finished applying iptables rules!" } _setup_rancher() { echo "Starting rancher manager..." systemctl enable rancher-manager.service systemctl start rancher-manager.service echo "Rancher manager started!" } _setup_backup() { echo "Starting rancher manager backup timer..." systemctl enable rancher-backup.timer systemctl start rancher-backup.timer echo "Rancher manager backup timer running!" } echo -n "Reloading systemd..." systemctl daemon-reload echo "Done!" _setup_iptables _setup_rancher _setup_backup echo "Restarting sshd..." systemctl restart sshd echo "Done!"
<reponame>lineality/Coding-Challenges-Study-Practice # https://binarysearch.com/ # # GGA 2020.11.04 # # User Problem # You have: list of integers # You Need: for sorted: which consecutive difference is greatest: vvalue # You Must: # # Solution (Feature/Product) # # Edge cases: # # Input/Output Example: # # Largest Gap # Given a list of integers nums, return the largest difference of two consecutive integers in the sorted version of nums. # Constraints # n ≤ 100,000 where n is the length of nums # Example 1 # Input # nums = [4, 1, 2, 8, 9, 10] # Output # 4 # Reflect On, Improvements, Comparisons with other Solutions: # using zip # nums.sort() # return max(b-a for a, b in zip(nums, nums[1:])) class Solution: def solve(self, nums): # sort in place nums.sort() # max diff max_diff = 0 # iterate, enumerate for index, value in enumerate(nums): # exclude last number if index != (len(nums) - 1): if max_diff < (nums[index + 1] - value): max_diff = nums[index + 1] - value return max_diff class Solution_2: def solve(self, nums): pass # Sample Print Solution run_test = Solution() print("\nOutput =", run_test.solve([4, 1, 2, 8, 9, 10])) # run_test_2 = Solution_2() # print("\nOutput 2 =", run_test_2.solve([4, 1, 2, 8, 9, 10])) # # Compare 2 Averaged runtimes # import time # def compare_avg_times(iterations=1000000): # # store runtimes # all_runtimes = 0 # # create class instance # run_test = Solution() # # create class instance # run_test_2 = Solution_2() # # run the program X times # # count the time # for i in range(iterations): # # start timer # start = time.time() # # run program # run_test.solve("input") # # stop clock, store that runtime # all_runtimes += time.time() - start # # store the time for version 1 # time_1 = all_runtimes / iterations # # run the program X times # # count the time # for i in range(iterations): # # start timer # start = time.time() # # run program # run_test_2.solve("input") # # stop clock, store that runtime # all_runtimes += time.time() - start # # store the time for version 2 # time_2 = all_runtimes / iterations # # return average runtime # return print( # "\nCompare Runtimes:", # "\naverage time 1 = ", # time_1, # "\naverage time 2 = ", # time_2, # ) # # print results # compare_avg_times()
import {Entity, model, property} from '@loopback/repository'; @model({settings: {idInjection: false, mysql: {schema: 'bowling', table: 'player'}}}) export class Player extends Entity { @property({ type: 'number', required: true, precision: 19, scale: 0, id: 1, mysql: {columnName: 'id_player', dataType: 'bigint', dataLength: null, dataPrecision: 19, dataScale: 0, nullable: 'N'}, }) idPlayer: number; @property({ type: 'string', length: 45, mysql: {columnName: 'name', dataType: 'varchar', dataLength: 45, dataPrecision: null, dataScale: null, nullable: 'Y'}, }) name?: string; @property({ type: 'string', length: 1, mysql: {columnName: 'sex', dataType: 'char', dataLength: 1, dataPrecision: null, dataScale: null, nullable: 'Y'}, }) sex?: string; @property({ type: 'number', precision: 3, scale: 0, mysql: {columnName: 'height', dataType: 'tinyint', dataLength: null, dataPrecision: 3, dataScale: 0, nullable: 'Y'}, }) height?: number; @property({ type: 'number', precision: 3, scale: 0, mysql: {columnName: 'weight', dataType: 'tinyint', dataLength: null, dataPrecision: 3, dataScale: 0, nullable: 'Y'}, }) weight?: number; @property({ type: 'number', precision: 3, scale: 0, mysql: {columnName: 'shoe_size', dataType: 'tinyint', dataLength: null, dataPrecision: 3, dataScale: 0, nullable: 'Y'}, }) shoeSize?: number; @property({ type: 'date', mysql: {columnName: 'birth_date', dataType: 'date', dataLength: null, dataPrecision: null, dataScale: null, nullable: 'Y'}, }) birthDate?: string; @property({ type: 'number', precision: 3, scale: 0, mysql: {columnName: 'ball_weight', dataType: 'tinyint', dataLength: null, dataPrecision: 3, dataScale: 0, nullable: 'Y'}, }) ballWeight?: number; @property({ type: 'number', precision: 3, scale: 0, mysql: {columnName: 'is_left_hand', dataType: 'tinyint', dataLength: null, dataPrecision: 3, dataScale: 0, nullable: 'Y'}, }) isLeftHand?: number; @property({ type: 'date', mysql: {columnName: 'created_at', dataType: 'datetime', dataLength: null, dataPrecision: null, dataScale: null, nullable: 'Y'}, }) createdAt?: string; @property({ type: 'date', mysql: {columnName: 'modified_at', dataType: 'datetime', dataLength: null, dataPrecision: null, dataScale: null, nullable: 'Y'}, }) modifiedAt?: string; @property({ type: 'string', length: 65535, mysql: {columnName: 'comment', dataType: 'text', dataLength: 65535, dataPrecision: null, dataScale: null, nullable: 'Y'}, }) comment?: string; // Define well-known properties here // Indexer property to allow additional data // eslint-disable-next-line @typescript-eslint/no-explicit-any [prop: string]: any; constructor(data?: Partial<Player>) { super(data); } } export interface PlayerRelations { // describe navigational properties here } export type PlayerWithRelations = Player & PlayerRelations;
<reponame>nickmessing/firemodel<filename>dist/esnext/ModelMeta.d.ts import { IFmModelMeta } from "./decorators/schema"; import { IDictionary } from "common-types"; declare const meta: IDictionary<IFmModelMeta>; export declare function addModelMeta(modelName: keyof typeof meta, props: IFmModelMeta): void; /** * Returns the META info for a given model, it will attempt to resolve * it locally first but if that is not available (as is the case with * self-reflexify relationships) then it will leverage the ModelMeta store * to get the meta information. * * @param modelKlass a model or record which exposes META property */ export declare function getModelMeta(modelKlass: IDictionary): Partial<IFmModelMeta>; export declare function modelsWithMeta(): string[]; export {};
package io.shadowstack; import lombok.EqualsAndHashCode; import lombok.ToString; import sun.reflect.generics.reflectiveObjects.NotImplementedException; @ToString @EqualsAndHashCode public class Bar { public String doSomethingShadowed(Foo f) { return f.getFirstName() + " " + f.getLastName(); } public String doSomethingBad(Foo f) { throw new NotImplementedException(); } }
conda env create -f environment.yml conda activate gtfsutils; python setup.py develop; conda deactivate;
#include <iostream> #include <algorithm> #include <string> using namespace std; // Function to check if the two strings are anagram bool isAnagram(string s1, string s2) { // Sort both strings sort(s1.begin(), s1.end()); sort(s2.begin(), s2.end()); // Compare sorted strings return (s1 == s2); } // Driver Code int main() { string s1 = "abcd"; string s2 = "dcba"; if(isAnagram(s1, s2)) cout << "The two strings are anagram of each other"; else cout << "The two strings are not anagram of each other"; return 0; }
#!/usr/bin/python3 def print_reversed_list_integer(my_list=[]): if my_list is not None: for x in reversed(my_list): print("{:d}".format(x))
#!/bin/ksh dir=/home/cs452/fall16/phase3/testResults #dir=/Users/patrick/Classes/452/project/phase3/testResults if [ "$#" -eq 0 ] then echo "Usage: ksh testphase3.ksh <num>" echo "where <num> is 00, 01, 02, ... or 26" exit 1 fi num=$1 if [ -f test${num} ] then /bin/rm test${num} fi if make test${num} then ./test${num} > test${num}.txt 2> test${num}stderr.txt; if [ -s test${num}stderr.txt ] then cat test${num}stderr.txt >> test${num}.txt fi /bin/rm test${num}stderr.txt if diff --brief test${num}.txt ${dir} then echo echo test${num} passed! else echo diff -C 1 test${num}.txt ${dir} fi fi echo
package org.hexagonal.dd.utils; public interface Constants { String INSERT_ARTICLE = "insert into article (id, title, author) " + "values (:id, :title, :author)"; String DELETE_ARTICLE = "delete from article where id = :id"; String UPDATE_ARTICLE = "update article " + "set title = :title, author = :author " + "where id = :id"; String GET_ARTICLE_BY_ID = "select id, title, author from article where id = :id"; String GET_TOP_10_ARTICLES = "select id, title, author from article limit 10"; String CREATE_TABLE = "DROP TABLE IF EXISTS article; " + "CREATE TABLE article (\n" + " id VARCHAR(250),\n" + " title VARCHAR(250),\n" + " author VARCHAR(250)\n" + ")"; }
#Aqueduct - Compliance Remediation Content #Copyright (C) 2011,2012 Vincent C. Passaro (vincent.passaro@gmail.com) # #This program is free software; you can redistribute it and/or #modify it under the terms of the GNU General Public License #as published by the Free Software Foundation; either version 2 #of the License, or (at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. # #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, #Boston, MA 02110-1301, USA. #!/bin/bash ###################################################################### #By Tummy a.k.a Vincent C. Passaro # #Vincent[.]Passaro[@]gmail[.]com # #www.vincentpassaro.com # ###################################################################### #_____________________________________________________________________ #| Version | Change Information | Author | Date | #|__________|_______________________|____________________|____________| #| 1.0 | Initial Script | Vincent C. Passaro | 20-oct-2011| #| | Creation | | | #|__________|_______________________|____________________|____________| #######################DISA INFORMATION############################### #Group ID (Vulid): V-22511 #Group Title: GEN007020 #Rule ID: SV-26865r1_rule #Severity: CAT II #Rule Version (STIG-ID): GEN007020 #Rule Title: The Stream Control Transmission Protocol (SCTP) must be disabled unless required. # #Vulnerability Discussion: The Stream Control Transmission Protocol (SCTP) is an IETF-standardized transport layer protocol. This protocol is not yet widely used. Binding this protocol to the network stack increases the attack surface of the host. Unprivileged local processes may be able to cause the kernel to dynamically load a protocol handler by opening a socket using the protocol. # #Responsibility: System Administrator #IAControls: ECSC-1 # #Check Content: #Check that the SCTP protocol handler is prevented from dynamic loading. # grep 'install sctp /bin/true' /etc/modprobe.conf /etc/modprobe.d/* #If no result is returned, this is a finding. # #Fix Text: Prevent the SCTP protocol handler for dynamic loading. # echo "install sctp /bin/true" >> /etc/modprobe.conf #######################DISA INFORMATION############################### #Global Variables# PDI=GEN007020 SCTPINSTALL=$( grep 'install sctp /bin/true' /etc/modprobe.conf /etc/modprobe.d/* | wc -l ) #Start-Lockdown if [ $SCTPINSTALL -eq 0 ] then echo "#Added for DISA GEN007020" >> /etc/modprobe.conf echo "install sctp /bin/true" >> /etc/modprobe.conf fi
while true ; do vcgencmd measure_temp ; sleep 1 ; done
CUDA_HOME=/ python3 train_net.py \ --config /root/detectron2/projects/Panoptic-DeepLab/configs/COCO-PanopticSegmentation/panoptic_deeplab_R_52_os16_mg124_poly_200k_bs64_crop_640_640_coco_dsconv.yaml
from django.db import models from django.utils.translation import ugettext_lazy as _ class Season(models.Model): name = models.CharField(_(u'标题'), max_length=16) descr = models.TextField(_(u'描述'), max_length=256, null=True, blank=True) order = models.IntegerField(_(u'排序值'), default=0) def __unicode__(self): return self.name
// // BulkAvatarTraits.ts // // Created by <NAME> on 28 Nov 2021. // Copyright 2021 Vircadia contributors. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // import UDT from "../udt/UDT"; type BulkAvatarTraitsDetails = { traitSequenceNumber: bigint }; const BulkAvatarTraits = new class { // C++ N/A /*@devdoc * Avatar traits information {@link PacketScribe|read} from a {@link PacketType(1)|BulkAvatarTraits} message. * @typedef {object} PacketScribe.BulkAvatarTraitsDetails * @property {bigint} sequenceID - The avatar traits message sequence number. */ /*@devdoc * Reads a {@link PacketType(1)|BulkAvatarTraits} packet. * @function PacketScribe.BulkAvatarTraits&period;read * @param {DataView} data - The BulkAvatarTraits message data to read. * @returns {PacketScribe.BulkAvatarTraitsDetails} The traits information obtained from reading the packet. */ read(data: DataView): BulkAvatarTraitsDetails { /* eslint-disable-line class-methods-use-this */ // C++ void AvatarHashMap::processBulkAvatarTraits(ReceivedMessage* message, Node* sendingNode) let dataPosition = 0; /* eslint-disable @typescript-eslint/no-magic-numbers */ const traitSequenceNumber = data.getBigUint64(dataPosition, UDT.LITTLE_ENDIAN); dataPosition += 8; // WEBRTC TODO: Read further data. /* eslint-enable @typescript-eslint/no-magic-numbers */ // WEBRTC TODO: Assert at end of packet. return { traitSequenceNumber }; } }(); export default BulkAvatarTraits; export type { BulkAvatarTraitsDetails };
#!/bin/bash sudo firewall-cmd --get-default-zone
import {ValidationError} from "class-validator"; export default class ErrorResponseViewModel { constructor(message: string, validationErrors: ValidationError[]|null = null) { this.message = message; this.validationErrors = validationErrors !== null ? validationErrors : []; } message: string; validationErrors: ValidationError[]; }
class SinatraAuthProxy < Sinatra::Base get '/' do erb :index end get '/*' do env['warden'].authenticate! uri = URI::HTTP.build( :host => "localhost", :port => 8080, :path => request.path_info, :query => request.query_string ) content_type 'application/json', :charset => 'utf-8' Net::HTTP.get(uri) end end
package utils import ( "crypto/sha256" "encoding/base64" ) func GenSha256(str string) string { h := sha256.New() h.Write([]byte(str)) return ConvertToBase64(h.Sum(nil)) } func ConvertToBase64(str []byte) string { enc := base64.StdEncoding.EncodeToString(str) return enc }
echo '打包sp.jicu.vip' BRANCH_NAME=master echo '[start] git clone...' read -p "请输入分支名称(回车代表master):" branch if [ "$branch" != "" ] then BRANCH_NAME=$branch fi echo "即将clone的分支名称为:$BRANCH_NAME" git clone -b $BRANCH_NAME git@gitlab.com:superxzl/way-admin-shop.git echo '[end] git clone...' echo '[start] cd way-admin-shop...' shopt -s expand_aliases alias gotosp="cd way-admin-shop" gotosp unalias gotosp shopt -u expand_aliases echo '[end] cd way-admin-shop...' echo '[start] npm install...' cnpm i #npm install --unsafe-perm #yarn echo '[end] npm install...' echo '[start] npm run build...' npm run build #yarn build echo '[end] npm run build...' echo '[start] 部署到/apps/web/sp' rm -rf /apps/web/sp mv dist /apps/web/sp echo '[end] 部署到/apps/web/sp' echo '[start] rm -rf dist way-admin-shop' shopt -s expand_aliases alias leavesp="cd .." leavesp unalias leavesp shopt -u expand_aliases rm -rf way-admin-shop echo '[end] rm -rf dist way-admin-shop' echo '打包完成!'
<filename>src/components/ProfileImage.js<gh_stars>0 import React from "react" import Img from "gatsby-image" import { graphql, useStaticQuery } from "gatsby" const ProfileImage = ({ className = "" }) => { const data = useStaticQuery(graphql` query ProfileImageQuery { stuImg: allFile(filter: { name: { eq: "Stu2019" } }) { edges { node { childImageSharp { fixed(height: 300, width: 300) { ...GatsbyImageSharpFixed } } } } } } `) return ( <div className={`aboutFloat grid w-fit p-1 rounded-full my-6 md:mr-5 relative shadow-lg shadow-neutral-900 ${className}`} > <div className="absolute top-0 right-0 bottom-0 left-0 bg-gradient-to-br from-main to-quaternary rounded-full animate-spin "></div> <Img className="aboutPage__pic rounded-full" fixed={data.stuImg.edges[0].node.childImageSharp.fixed} title="Stu Finn" alt="Stu Finn" /> </div> ) } export default ProfileImage
# Check server response for outgoing RPCs SCHEMA_OUTGOING_RPC = {} # Check incoming RPC parameters SCHEMA_INCOMING_RPC = {} SCHEMA_OUTGOING_RPC["rpc_dht_put_data"] = { "type" : "object", "properties" : { "status" : {"type" : "number"}, "message" : {"type" : "string"} }, "required": ["status"] } SCHEMA_OUTGOING_RPC["rpc_dht_get_data"] = { "type" : "object", "properties" : { "status" : {"type" : "number"}, "data" : { "type" : "array", "items": { "type": "string" } } }, "required": ["status"] } # rpc_find_successor_rec: {'trace': [], 'node_address': 'tcp://127.0.0.1:1339/0', 'node_id': 8} SCHEMA_OUTGOING_RPC["rpc_find_successor_rec"] = { "type" : "object", "properties" : { "status" : {"type" : "number"}, "node_id" : {"type" : "number"}, "node_address" : {"type" : "string"}, "trace" : { "type" : "array", "items" : { "type" : "object", "properties" : { "node_id" : {"type" : "number"}, "node_address" : {"type" : "string"}, }, "required": ["node_id", "node_address"] } } }, "required": ["status"] } SCHEMA_OUTGOING_RPC["rpc_update_predecessor"] = { "type" : "object", "properties" : { "node_id" : {"type" : "number"}, "node_address" : {"type" : "string"}, "old_predecessor" : { "type" : "object", "properties" : { "node_id" : {"type" : "number"}, "node_address" : {"type" : "string"}, "status" : {"type" : "number"} }, "required": ["node_id", "node_address"] } } } SCHEMA_OUTGOING_RPC["rpc_get_node_info"] = {} SCHEMA_INCOMING_RPC["rpc_get_node_info"] = { "type" : "object", "properties" : { "node_id" : {"type" : "number"}, "node_address" : {"type" : "string",}, "successor" : { "type" : "object", "optional": "True", "properties" : { "node_id" : {"type" : "number"}, "node_address" : {"type" : "string"}, }, "required": ["node_id", "node_address"] }, "predecessor" : { "type" : "object", "optional": "TRUE", "properties" : { "node_id" : {"type" : "number"}, "node_address" : {"type" : "string"} }, "required": ["node_id", "node_address"] } } } SCHEMA_INCOMING_RPC["rpc_update_finger_table"] = { "type" : "object", "properties" : { "node_id" : {"type" : "number"}, "node_address" : {"type" : "string"}, }, "required": ["node_id", "node_address"] } SCHEMA_OUTGOING_RPC["rpc_update_finger_table"] = {} SCHEMA_OUTGOING_RPC["rpc_update_successor"] = {} SCHEMA_OUTGOING_RPC["rpc_get_fingertable"] = {} # SCHEMA_RPC[] # Schema for the DHT messages constructed in messageParser.py # # Note: As the bytes do not allow greater values for integers etc, this is pretty useless at the moment. SCHEMA_MSG_DHT = {} SCHEMA_MSG_DHT["MSG_DHT_GET"] = {} SCHEMA_MSG_DHT["MSG_DHT_PUT"] = { "type" : "object", "properties" : { "ttl" : {"type" : "number", "minimum":0, "maximum": 255}, "replication" : {"type" : "number", "minimum":0, "maximum": 255} } } SCHEMA_MSG_DHT["MSG_DHT_TRACE"] = {} SCHEMA_MSG_DHT["MSG_DHT_ERROR"] = {}
IF OBJECT_ID('FactSpectra_DimRetentionTimeRel_fk', 'F') IS NOT NULL ALTER TABLE FactSpectra DROP CONSTRAINT FactSpectra_DimRetentionTimeRel_fk IF OBJECT_ID (N'DimRetentionTimeRel', N'U') IS NOT NULL BEGIN DROP TABLE [dbo].[DimRetentionTimeRel] END CREATE TABLE [dbo].[DimRetentionTimeRel] ( [id] bigint identity PRIMARY KEY NOT NULL, [label] nvarchar(64) NOT NULL, [minrange] numeric(12,6) NULL, [maxrange] numeric(12,6) NULL, [center] numeric(12,6) NULL, [sumofsquares] numeric(12,6) NULL ) ALTER TABLE [dbo].[FactSpectra] ADD CONSTRAINT FactSpectra_DimRetentionTimeRel_fk FOREIGN KEY (RetentionTimeRelID)references DimRetentionTimeRel (id) ALTER TABLE [dbo].[DimRetentionTimeRel] ADD CONSTRAINT DimRetentionTimeRel_label_uq UNIQUE (label) INSERT INTO DimRetentionTimeRel (label, minrange, maxrange, center, sumofsquares) VALUES ('Unknown', null, null, null, null) IF OBJECT_ID('FactSpectra_DimRetentionTimeAbs_fk', 'F') IS NOT NULL ALTER TABLE FactSpectra DROP CONSTRAINT FactSpectra_DimRetentionTimeAbs_fk IF OBJECT_ID('FactSpectra_DimDriftTimeAbs_fk', 'F') IS NOT NULL ALTER TABLE FactSpectra DROP CONSTRAINT FactSpectra_DimDriftTimeAbs_fk IF OBJECT_ID (N'DimRetentionTimeAbs', N'U') IS NOT NULL BEGIN DROP TABLE [dbo].[DimRetentionTimeAbs] END CREATE TABLE [dbo].[DimRetentionTimeAbs] ( [id] bigint identity PRIMARY KEY NOT NULL, [label] nvarchar(64) NOT NULL, [minrange] numeric(12,6) NULL, [maxrange] numeric(12,6) NULL ) IF OBJECT_ID (N'DimDriftTimeAbs', N'U') IS NOT NULL BEGIN DROP TABLE [dbo].[DimDriftTimeAbs] END CREATE TABLE [dbo].[DimDriftTimeAbs] ( [id] bigint identity PRIMARY KEY NOT NULL, [label] nvarchar(64) NOT NULL, [minrange] numeric(12,6) NULL, [maxrange] numeric(12,6) NULL ) ALTER TABLE [dbo].[FactSpectra] ADD CONSTRAINT FactSpectra_DimRetentionTimeAbs_fk FOREIGN KEY (RetentionTimeAbsID)references DimRetentionTimeAbs (id), CONSTRAINT FactSpectra_DimDriftTimeAbs_fk FOREIGN KEY (DriftTimeAbsID) references DimDriftTimeAbs (id) ALTER TABLE [dbo].[DimRetentionTimeAbs] ADD CONSTRAINT DimRetentionTimeAbs_label_uq UNIQUE (label) ALTER TABLE [dbo].[DimDriftTimeAbs] ADD CONSTRAINT DimDriftTimeAbs_label_uq UNIQUE (label) INSERT INTO DimRetentionTimeAbs (label, minrange, maxrange) VALUES ('Unknown', null, null) INSERT INTO DimDriftTimeAbs (label, minrange, maxrange) VALUES ('Unknown', null, null) select * from DimRetentionTimeAbs select * from DimDriftTimeAbs
#!/bin/bash # Remember to run as user nablaweb cd /srv/nablaweb pipenv run python manage.py update_index
<filename>src/main/java/org/rs2server/tools/GiveItemActionListener.java package org.rs2server.tools; import org.rs2server.cache.format.CacheItemDefinition; import org.rs2server.rs2.model.Item; import org.rs2server.rs2.model.player.Player; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class GiveItemActionListener implements ActionListener{ private Player player; private JFrame frame; public GiveItemActionListener(Player player, JFrame frame) { this.player = player; this.frame = frame; } @Override public void actionPerformed(ActionEvent e) { String itemName = JOptionPane.showInputDialog(frame, "Item", null); String[] itemString = itemName.split(","); int id = Integer.parseInt(itemString[0]); int amount = Integer.parseInt(itemString[1]); Item item = new Item(id, amount); if (player.getInventory().add(item)) { player.getActionSender().sendMessage("You have been given; " + item.getCount() + "x " + CacheItemDefinition.get(item.getId()).getName() + " from SERVER" ); } } }
package com.github.couchmove.pojo; import com.couchbase.client.core.deps.com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import org.jetbrains.annotations.Nullable; /** * Class representing a json Document * * @author ctayeb * Created on 28/05/2017 */ @Data public class CouchbaseEntity { /** * The last-known CAS value for the Document * <p> * CAS is for Check And Swap, which is an identifier that permit optimistic concurrency */ @Nullable @JsonIgnore private Long cas; }
import datetime as DT from decimal import Decimal import pytest from libestg3b import Match from libestg3b.rule import Rule def make_rule(slug, **kwargs): return Rule( 'R_' + slug, 'Rule', lambda m: True, **kwargs, ) @pytest.fixture def match(): return Match( DT.datetime(2018, 1, 1, 0), DT.datetime(2018, 1, 1, 2, 30), [ make_rule('m25', multiply=Decimal('0.25')), make_rule('m5', multiply=Decimal('0.5')), make_rule('a5', add=Decimal(5)), make_rule('a3', add=Decimal(3)), ] ) def test_match(match): assert match.minutes == Decimal('150') assert match.bonus_multiply == Decimal('0.75') assert match.bonus_add == Decimal(8) def test_match_no_rules(): match = Match(DT.datetime(2018, 1, 1, 0), DT.datetime(2018, 1, 1, 2, 30), []) assert match.minutes == Decimal('150') assert match.bonus_multiply == Decimal(0) assert match.bonus_add == Decimal(0)
#!/bin/bash parse_blastn.py Blastx2nroutput.xml parsedBlastx2nr.txt #if parse_blast.py does not work, and alternative parser is BlastParse.pl, though you'll have to change the evalue column in the ReParseBlastbycutoffs.py below #the evalue is in column 12 if you're using the parse_blast.py or column 8 if you're using BlastParse.pl in the first step above ReParseBlastbycutoffs.py parsedBlastx2nr.txt columntoparse evaluecutoff tophitreParsedBlastx2nr.txt
// TODO: Review and potentially break into object-specific component directories export { default as AuthScopeCell } from './AuthScopeCell'; export { default as BackupsCell } from './BackupsCell'; export { default as RegionCell } from './RegionCell'; export { default as IPAddressCell } from './IPAddressCell'; export { default as IPRdnsCell } from './IPRdnsCell'; export { default as LastBackupCell } from './LastBackupCell'; export { default as NameserversCell } from './NameserversCell';
var chai = require('chai'), expect = chai.expect; var Add2Calendar = require('../js/add2calendar.js'); /** @type Add2Calendar */ var event = null; // var eventArgs = null; // manipulate "document" object for testing global.document = { URL: 'http://127.0.0.1:5500/' // http://127.0.0.1:5500 }; describe('Test', function() { it('Mocha and Chai should work', function() { expect(true).to.be.true; expect(false).to.be.false; }); }); describe('Add2Calendar: core', function() { before(function() { eventArgs = { title : 'Add2Calendar plugin event', start : 'July 27, 2016 10:30', end : 'July 29, 2016 19:20', location : 'Bangkok, Thailand', description : 'Event description' }; event = new Add2Calendar(eventArgs); }); it('mergeObj', function() { // normal case expect(event.mergeObj({lang: "en", buttonText: "Add to calendar"}, {lang: "cn"})).to.deep.equals({lang: "cn", buttonText: "Add to calendar"}); expect(event.mergeObj({lang: "en", buttonText: ""}, {buttonText: "Custom button text"})).to.deep.equals({lang: "en", buttonText: "Custom button text"}); expect(event.mergeObj({lang: "en", buttonText: ""}, {lang: "cn"})).to.deep.equals({lang: "cn", buttonText: ""}); expect(event.mergeObj({lang: "en", buttonText: ""}, {buttonText: "Custom button text"})).to.deep.equals({lang: "en", buttonText: "Custom button text"}) }); it('pad', function() { // normal case expect(event.pad(2, 1)).to.equals("2") expect(event.pad(8, 2)).to.equals("08") expect(event.pad(3, 3)).to.equals("003") expect(event.pad(12, 4)).to.equals("0012") }); it('formatTime', function() { expect(event.formatTime(new Date('Fri Feb 28 2020 13:03:54 GMT+0700 (Indochina Time)'))).to.equals('20200228T060354Z') expect(event.formatTime(new Date('Sat Feb 29 2020 13:03:54 GMT+0700 (Indochina Time)'))).to.equals('20200229T060354Z') expect(event.formatTime(new Date('Sat Feb 29 2020 20:03:54 GMT+0700 (Indochina Time)'))).to.equals('20200229T130354Z') expect(event.formatTime(new Date('Wed Jul 27 2016 10:30:00 GMT+0700 (Indochina Time)'))).to.equals('20160727T033000Z') expect(event.formatTime(new Date('Wed Jul 27 2016 19:30:00 GMT+0700 (Indochina Time)'))).to.equals('20160727T123000Z') expect(event.formatTime(new Date('Thu Jul 28 2016 10:30:00 GMT+0700 (Indochina Time)'))).to.equals('20160728T033000Z') expect(event.formatTime(new Date('Fri Jul 29 2016 19:20:00 GMT+0700 (Indochina Time)'))).to.equals('20160729T122000Z') }); it('formatTime2', function() { expect(event.formatTime2(new Date('Fri Feb 28 2020 13:03:54 GMT+0700 (Indochina Time)'))).to.equals('20200228') expect(event.formatTime2(new Date('Sat Feb 29 2020 13:03:54 GMT+0700 (Indochina Time)'))).to.equals('20200229') expect(event.formatTime2(new Date('Sat Feb 29 2020 20:03:54 GMT+0700 (Indochina Time)'))).to.equals('20200229') expect(event.formatTime2(new Date('Wed Jul 27 2016 10:30:00 GMT+0700 (Indochina Time)'))).to.equals('20160727') expect(event.formatTime2(new Date('Wed Jul 27 2016 19:30:00 GMT+0700 (Indochina Time)'))).to.equals('20160727') expect(event.formatTime2(new Date('Thu Jul 28 2016 10:30:00 GMT+0700 (Indochina Time)'))).to.equals('20160728') expect(event.formatTime2(new Date('Fri Jul 29 2016 19:20:00 GMT+0700 (Indochina Time)'))).to.equals('20160729') }); it('isObjectType', function() { expect(event.isObjectType({}, 'Array')).to.be.false expect(event.isObjectType(function () {}, 'Function')).to.be.true expect(event.isObjectType(undefined, 'Function')).to.be.false expect(event.isObjectType([{}, {}], 'Array')).to.be.true }); it('serialize', function() { expect(event.serialize({ text: "Add2Calendar plugin event", dates: "20200228T060354Z/20200229T060354Z", location: "Bangkok, Thailand", details: "Welcome everyone to simple plugin that allow you to add event to calendar easily.", sprop: "" })).to.be.equals('text=Add2Calendar%20plugin%20event&dates=20200228T060354Z%2F20200229T060354Z&location=Bangkok%2C%20Thailand&details=Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.&sprop=') expect(event.serialize({ view: "d", type: "20", title: "Add2Calendar plugin event", st: "20200228T060354Z", et: "20200229T130354Z", in_loc: "Bangkok, Thailand", desc: "Welcome everyone to simple plugin that allow you to add event to calendar easily.", })).to.be.equals('view=d&type=20&title=Add2Calendar%20plugin%20event&st=20200228T060354Z&et=20200229T130354Z&in_loc=Bangkok%2C%20Thailand&desc=Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.') }); /* ignore - isValidEventData - isDateObject - isFunc - isArray - replaceSpecialCharacterAndSpaceWithHyphen */ }); describe('Add2Calendar: widget', function() { before(function() { eventArgs = { title : 'Add2Calendar plugin event', start : 'July 27, 2016 10:30', end : 'July 29, 2016 19:20', location : 'Bangkok, Thailand', description : 'Event description' }; event = new Add2Calendar(eventArgs); }); it('getLinkHtml', function() { // Google expect(event.getLinkHtml( 'Google', 'https://www.google.com/calendar/render?action=TEMPLATE&text=Add2Calendar%20plugin%20event&dates=20200228T060354Z%2F20200229T060354Z&location=Bangkok%2C%20Thailand&details=Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.&sprop=', 'icon-google', false )).to.equals('<a class="icon-google" target="_blank" href="https://www.google.com/calendar/render?action=TEMPLATE&text=Add2Calendar%20plugin%20event&dates=20200228T060354Z%2F20200229T060354Z&location=Bangkok%2C%20Thailand&details=Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.&sprop=">Google</a>'); // Yahoo expect(event.getLinkHtml( 'Yahoo!', 'https://calendar.yahoo.com/?v=60&view=d&type=20&title=Add2Calendar%20plugin%20event&st=20200228T060354Z&et=20200229T130354Z&in_loc=Bangkok%2C%20Thailand&desc=Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.', 'icon-yahoo', false )).to.equals('<a class="icon-yahoo" target="_blank" href="https://calendar.yahoo.com/?v=60&view=d&type=20&title=Add2Calendar%20plugin%20event&st=20200228T060354Z&et=20200229T130354Z&in_loc=Bangkok%2C%20Thailand&desc=Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.">Yahoo!</a>'); // Outlook expect(event.getLinkHtml( 'Outlook', 'data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500%0ADTSTART:20200228T060354Z%0ADTEND:20200229T060354Z%0ASUMMARY:Add2Calendar%20plugin%20event%0ADESCRIPTION:Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR', 'icon-outlook', true, uniqueId='123' )).to.equals('<a download="add2Calendar-outlook-123" class="icon-outlook" target="_blank" href="data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500%0ADTSTART:20200228T060354Z%0ADTEND:20200229T060354Z%0ASUMMARY:Add2Calendar%20plugin%20event%0ADESCRIPTION:Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR">Outlook</a>'); expect(event.getLinkHtml( 'Outlook', 'data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500%0ADTSTART:20160727T033000Z%0ADTEND:20160727T123000Z%0ASUMMARY:Add2Calendar%20plugin%20event%201%0ADESCRIPTION:Event%20description%201%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500%0ADTSTART:20160728T033000Z%0ADTEND:20160729T122000Z%0ASUMMARY:Add2Calendar%20plugin%20event%202%0ADESCRIPTION:Event%20description%202%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR', 'icon-outlook', true, uniqueId='456' )).to.equals('<a download="add2Calendar-outlook-456" class="icon-outlook" target="_blank" href="data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500%0ADTSTART:20160727T033000Z%0ADTEND:20160727T123000Z%0ASUMMARY:Add2Calendar%20plugin%20event%201%0ADESCRIPTION:Event%20description%201%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0ABEGIN:VEVENT%0AURL:http://1172.16.31.10:5500%0ADTSTART:20160728T033000Z%0ADTEND:20160729T122000Z%0ASUMMARY:Add2Calendar%20plugin%20event%202%0ADESCRIPTION:Event%20description%202%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR">Outlook</a>'); // iCal expect(event.getLinkHtml( 'iCal', 'data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500%0ADTSTART:20200228T060354Z%0ADTEND:20200229T060354Z%0ASUMMARY:Add2Calendar%20plugin%20event%0ADESCRIPTION:Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR', 'icon-ical', true, uniqueId='789' )).to.equals('<a download="add2Calendar-ical-789" class="icon-ical" target="_blank" href="data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500%0ADTSTART:20200228T060354Z%0ADTEND:20200229T060354Z%0ASUMMARY:Add2Calendar%20plugin%20event%0ADESCRIPTION:Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR">iCal</a>'); expect(event.getLinkHtml( 'iCal', 'data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500%0ADTSTART:20160727T033000Z%0ADTEND:20160727T123000Z%0ASUMMARY:Add2Calendar%20plugin%20event%201%0ADESCRIPTION:Event%20description%201%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500%0ADTSTART:20160728T033000Z%0ADTEND:20160729T122000Z%0ASUMMARY:Add2Calendar%20plugin%20event%202%0ADESCRIPTION:Event%20description%202%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR', 'icon-ical', true, uniqueId='0' )).to.equals('<a download="add2Calendar-ical-0" class="icon-ical" target="_blank" href="data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500%0ADTSTART:20160727T033000Z%0ADTEND:20160727T123000Z%0ASUMMARY:Add2Calendar%20plugin%20event%201%0ADESCRIPTION:Event%20description%201%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500%0ADTSTART:20160728T033000Z%0ADTEND:20160729T122000Z%0ASUMMARY:Add2Calendar%20plugin%20event%202%0ADESCRIPTION:Event%20description%202%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR">iCal</a>'); }); /* ignore - getCurrentUtcTimestamp - getGoogleUrl - getGoogleLiHtml - openGoogle - getICalUrl - getICalLiHtml - openICal - getOutlookUrl - getOutlookLiHtml - openOutlook - getOutlookOnlineUrl - getOutlookOnlineLiHtml - openOutlookOnline - getYahooUrl - getYahooLiHtml - openYahoo - getEventListItemsHtml - getEventNotFoundListHtml - getEventNotFoundListItemsHtml - getWidgetNode - getWidgetBtnText - createWidget - bindClickEvent - hasClass - setOption - resetOption - update - updateWidget - updateAllCalendars - init */ }); describe('Add2Calendar: single event', function() { before(function() { eventArgs = { title: 'Add2Calendar plugin event', start: new Date('Fri Feb 28 2020 15:00:42 GMT+0700 (Indochina Time)'), end: new Date('Sat Feb 29 2020 15:00:42 GMT+0700 (Indochina Time)'), location: 'Bangkok, Thailand', description: 'Welcome everyone to simple plugin that allow you to add event to calendar easily.' }; event = new Add2Calendar(eventArgs); }); it('e2e', function() { expect(event.updateGoogleUrl()).to.equals('https://www.google.com/calendar/render?action=TEMPLATE&text=Add2Calendar%20plugin%20event&dates=20200228T080042Z%2F20200229T080042Z&location=Bangkok%2C%20Thailand&details=Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.&ctz=&locale=&sprop='); expect(event.updateICalUrl()).to.equals('data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20200228T080042Z%0ADTEND:20200229T080042Z%0ASUMMARY:Add2Calendar%20plugin%20event%0ADESCRIPTION:Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR'); expect(event.updateYahooUrl()).to.equals('https://calendar.yahoo.com/?v=60&view=d&type=20&title=Add2Calendar%20plugin%20event&st=20200228T080042Z&et=20200229T150042Z&in_loc=Bangkok%2C%20Thailand&desc=Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.'); // getLiHtml expect(event.getLiHtml( 'Google', 'https://www.google.com/calendar/render?action=TEMPLATE&text=Add2Calendar%20plugin%20event&dates=20200228T074340Z%2F20200229T074340Z&location=Bangkok%2C%20Thailand&details=Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.&sprop=', 'google', undefined )).to.equals('<li class="a2cldr-item a2cldr-google"><a class="icon-google" target="_blank" href="https://www.google.com/calendar/render?action=TEMPLATE&text=Add2Calendar%20plugin%20event&dates=20200228T074340Z%2F20200229T074340Z&location=Bangkok%2C%20Thailand&details=Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.&sprop=">Google</a></li>'); expect(event.getLiHtml( 'iCal', 'data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20200228T074340Z%0ADTEND:20200229T074340Z%0ASUMMARY:Add2Calendar%20plugin%20event%0ADESCRIPTION:Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR', 'ical', true, 1582271020761 // todo fix the hardcode for testing purpose )).to.equals('<li class="a2cldr-item a2cldr-ical"><a download="add2Calendar-ical-1582271020761" class="icon-ical" target="_blank" href="data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20200228T074340Z%0ADTEND:20200229T074340Z%0ASUMMARY:Add2Calendar%20plugin%20event%0ADESCRIPTION:Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR">iCal</a></li>'); expect(event.getLiHtml( 'Outlook', 'data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://1172.16.31.10:5500/%0ADTSTART:20200228T074340Z%0ADTEND:20200229T074340Z%0ASUMMARY:Add2Calendar%20plugin%20event%0ADESCRIPTION:Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR', 'outlook', true, 1582271020763 // todo fix the hardcode for testing purpose )).to.equals('<li class="a2cldr-item a2cldr-outlook"><a download="add2Calendar-outlook-1582271020763" class="icon-outlook" target="_blank" href="data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20200228T074340Z%0ADTEND:20200229T074340Z%0ASUMMARY:Add2Calendar%20plugin%20event%0ADESCRIPTION:Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR">Outlook</a></li>'); expect(event.getLiHtml( 'Outlook Online', '', 'outlook-online', undefined )).to.equals(''); expect(event.getLiHtml( 'Yahoo!', 'https://calendar.yahoo.com/?v=60&view=d&type=20&title=Add2Calendar%20plugin%20event&st=20200228T074340Z&et=20200229T144340Z&in_loc=Bangkok%2C%20Thailand&desc=Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.', 'yahoo', undefined )).to.equals('<li class="a2cldr-item a2cldr-yahoo"><a class="icon-yahoo" target="_blank" href="https://calendar.yahoo.com/?v=60&view=d&type=20&title=Add2Calendar%20plugin%20event&st=20200228T074340Z&et=20200229T144340Z&in_loc=Bangkok%2C%20Thailand&desc=Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.">Yahoo!</a></li>'); // getEventListHtml // todo }); }); describe('Add2Calendar: single event with isAllDay = true', function() { before(function() { eventArgs = { title: 'Add2Calendar plugin event', start: new Date('Fri Feb 28 2020 15:00:42 GMT+0700 (Indochina Time)'), end: new Date('Sat Feb 29 2020 15:00:42 GMT+0700 (Indochina Time)'), location: 'Bangkok, Thailand', description: 'Welcome everyone to simple plugin that allow you to add event to calendar easily.', isAllDay: true }; event = new Add2Calendar(eventArgs); }); it('e2e', function() { // only difference is generated url expect(event.updateGoogleUrl()).to.equals('https://www.google.com/calendar/render?action=TEMPLATE&text=Add2Calendar%20plugin%20event&dates=20200228%2F20200229&location=Bangkok%2C%20Thailand&details=Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.&ctz=&locale=&sprop='); expect(event.updateICalUrl()).to.equals('data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20200228%0ADTEND:20200229%0ASUMMARY:Add2Calendar%20plugin%20event%0ADESCRIPTION:Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR'); expect(event.updateYahooUrl()).to.equals('https://calendar.yahoo.com/?v=60&view=d&type=20&title=Add2Calendar%20plugin%20event&st=20200228&et=20200229&in_loc=Bangkok%2C%20Thailand&desc=Welcome%20everyone%20to%20simple%20plugin%20that%20allow%20you%20to%20add%20event%20to%20calendar%20easily.'); }); }); describe('Add2Calendar: single event, contains special characters', function() { before(function() { eventArgs = { title: 'Add2Calendar plugin event ;,/?:@&=+$# contains special characters', start: new Date('Fri Feb 28 2020 15:00:42 GMT+0700 (Indochina Time)'), end: new Date('Sat Feb 29 2020 15:00:42 GMT+0700 (Indochina Time)'), location: 'Bangkok, ;,/?:@&=+$# Thailand', description: 'Welcome everyone to simple plugin that ;,/?:@&=+$# allow you to add event to calendar easily.' }; event = new Add2Calendar(eventArgs); }); it('e2e', function() { expect(event.updateGoogleUrl()).to.equals('https://www.google.com/calendar/render?action=TEMPLATE&text=Add2Calendar%20plugin%20event%20%3B%2C%2F%3F%3A%40%26%3D%2B%24%23%20contains%20special%20characters&dates=20200228T080042Z%2F20200229T080042Z&location=Bangkok%2C%20%3B%2C%2F%3F%3A%40%26%3D%2B%24%23%20Thailand&details=Welcome%20everyone%20to%20simple%20plugin%20that%20%3B%2C%2F%3F%3A%40%26%3D%2B%24%23%20allow%20you%20to%20add%20event%20to%20calendar%20easily.&ctz=&locale=&sprop='); expect(event.updateICalUrl()).to.equals('data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20200228T080042Z%0ADTEND:20200229T080042Z%0ASUMMARY:Add2Calendar%20plugin%20event%20;,/?:@&=+$%23%20contains%20special%20characters%0ADESCRIPTION:Welcome%20everyone%20to%20simple%20plugin%20that%20;,/?:@&=+$%23%20allow%20you%20to%20add%20event%20to%20calendar%20easily.%0ALOCATION:Bangkok,%20;,/?:@&=+$%23%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR'); expect(event.updateYahooUrl()).to.equals('https://calendar.yahoo.com/?v=60&view=d&type=20&title=Add2Calendar%20plugin%20event%20%3B%2C%2F%3F%3A%40%26%3D%2B%24%23%20contains%20special%20characters&st=20200228T080042Z&et=20200229T150042Z&in_loc=Bangkok%2C%20%3B%2C%2F%3F%3A%40%26%3D%2B%24%23%20Thailand&desc=Welcome%20everyone%20to%20simple%20plugin%20that%20%3B%2C%2F%3F%3A%40%26%3D%2B%24%23%20allow%20you%20to%20add%20event%20to%20calendar%20easily.'); }); }); describe('Add2Calendar: multiple events', function() { before(function() { eventArgs = [ { title: 'Add2Calendar plugin event 1', start: 'July 27, 2016 10:30', end: 'July 27, 2016 19:30', location: 'Bangkok, Thailand', description: 'Event description 1' }, { title: 'Add2Calendar plugin event 2', start: 'July 28, 2016 10:30', end: 'July 29, 2016 19:20', location: 'Bangkok, Thailand', description: 'Event description 2' } ]; event = new Add2Calendar(eventArgs); }); it('e2e', function() { expect(event.updateGoogleUrl()).to.equals('') expect(event.updateICalUrl()).to.equals('data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20160727T033000Z%0ADTEND:20160727T123000Z%0ASUMMARY:Add2Calendar%20plugin%20event%201%0ADESCRIPTION:Event%20description%201%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20160728T033000Z%0ADTEND:20160729T122000Z%0ASUMMARY:Add2Calendar%20plugin%20event%202%0ADESCRIPTION:Event%20description%202%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR') expect(event.updateYahooUrl()).to.equals('') // getLiHtml expect(event.getLiHtml( 'Google', '', 'google', undefined )).to.equals('') expect(event.getLiHtml( 'iCal', 'data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20160727T033000Z%0ADTEND:20160727T123000Z%0ASUMMARY:Add2Calendar%20plugin%20event%201%0ADESCRIPTION:Event%20description%201%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20160728T033000Z%0ADTEND:20160729T122000Z%0ASUMMARY:Add2Calendar%20plugin%20event%202%0ADESCRIPTION:Event%20description%202%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR', 'ical', true, 1582271406220 // todo fix the hardcode for testing purpose )).to.equals('<li class="a2cldr-item a2cldr-ical"><a download="add2Calendar-ical-1582271406220" class="icon-ical" target="_blank" href="data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20160727T033000Z%0ADTEND:20160727T123000Z%0ASUMMARY:Add2Calendar%20plugin%20event%201%0ADESCRIPTION:Event%20description%201%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20160728T033000Z%0ADTEND:20160729T122000Z%0ASUMMARY:Add2Calendar%20plugin%20event%202%0ADESCRIPTION:Event%20description%202%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR">iCal</a></li>'); expect(event.getLiHtml( 'Outlook', 'data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20160727T033000Z%0ADTEND:20160727T123000Z%0ASUMMARY:Add2Calendar%20plugin%20event%201%0ADESCRIPTION:Event%20description%201%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20160728T033000Z%0ADTEND:20160729T122000Z%0ASUMMARY:Add2Calendar%20plugin%20event%202%0ADESCRIPTION:Event%20description%202%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR', 'outlook', true, 1582271406221 // todo fix the hardcode for testing purpose )).to.equals('<li class="a2cldr-item a2cldr-outlook"><a download="add2Calendar-outlook-1582271406221" class="icon-outlook" target="_blank" href="data:text/calendar;charset=utf8,BEGIN:VCALENDAR%0AVERSION:2.0%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20160727T033000Z%0ADTEND:20160727T123000Z%0ASUMMARY:Add2Calendar%20plugin%20event%201%0ADESCRIPTION:Event%20description%201%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0ABEGIN:VEVENT%0AURL:http://127.0.0.1:5500/%0ADTSTART:20160728T033000Z%0ADTEND:20160729T122000Z%0ASUMMARY:Add2Calendar%20plugin%20event%202%0ADESCRIPTION:Event%20description%202%0ALOCATION:Bangkok,%20Thailand%0AEND:VEVENT%0AEND:VCALENDAR">Outlook</a></li>'); expect(event.getLiHtml( 'Outlook Online', '', 'outlook-online', undefined )).to.equals('') expect(event.getLiHtml( 'Yahoo!', '', 'yahoo', undefined )).to.equals('') // getEventListHtml // todo }); }); // todo describe('Add2Calendar: multiple events', function() { });
package com.banano.kaliumwallet.di.activity; import com.banano.kaliumwallet.di.application.ApplicationComponent; import com.banano.kaliumwallet.model.KaliumWalletTest; import dagger.Component; @Component(modules = {ActivityModule.class}, dependencies = {ApplicationComponent.class}) @ActivityScope public interface TestActivityComponent extends ActivityComponent { void inject(KaliumWalletTest kaliumWalletTest); }
import datetime # Sample reminder reminders = [ { "date": "2021-02-14", "title": "Valentine's Day", "description": "Buy a heart-shaped document for your beloved!", }, { "date": "2021-04-01", "title": "April Fool's Day", "description": "Camouflage pranks on the family!", }, ] # Function to add reminders def add_reminder(reminder): reminder['date'] = datetime.datetime.strptime(reminder['date'], '%Y-%m-%d').date() reminders.append(reminder) # Function to remove reminders def remove_reminder(index): reminders.pop(index) # Function to list reminders def list_reminders(): for index, reminder in enumerate(reminders): print(f"{index}. {reminder['title']} - {reminder['date']}: {reminder['description']}")
<gh_stars>0 /* * sr.h: binder live range splitting * Copyright (C) Advanced Risc Machines Ltd., 1993 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _sr_h #define _sr_h struct SuperBinder { SuperBinder *cdr; Binder *binder; int32 spillcount; }; extern SuperBinder *superbinders; extern BindList *splitranges(BindList *local_binders, BindList *regvar_binders); extern void splitrange_init(void); #endif
test_image_nil_profile_list() { # Launch container with default profile list and check its profiles ensure_import_testimage lxc launch testimage c1 lxc info c1 | grep -q "Profiles: default" || false # Cleanup lxc delete c1 -f lxc image delete testimage } test_image_empty_profile_list() { # Set the profiles to be an empty list ensure_import_testimage lxc image show testimage | sed "s/profiles.*/profiles: []/; s/- default//" | lxc image edit testimage # Check that the profile list is correct lxc image show testimage | grep -q 'profiles: \[\]' || false ! lxc image show testimage | grep -q -- '- default' || false # Launch the container and check its profiles storage=$(lxc storage list | grep "^| " | tail -n 1 | cut -d' ' -f2) lxc launch testimage c1 -s "$storage" lxc info c1 | grep -q "Profiles: $" || false # Cleanup lxc delete c1 -f lxc image delete testimage } test_image_alternate_profile_list() { # Add three new profiles to the profile list ensure_import_testimage lxc profile create p1 lxc profile create p2 lxc profile create p3 lxc image show testimage | sed "s/profiles.*/profiles: ['p1','p2','p3']/; s/- default//" | lxc image edit testimage # Check that the profile list is correct lxc image show testimage | grep -q -- '- p1' || false lxc image show testimage | grep -q -- '- p2' || false lxc image show testimage | grep -q -- '- p3' || false ! lxc image show testimage | grep -q -- '- default' || false # Launch the container and check its profiles storage=$(lxc storage list | grep "^| " | tail -n 1 | cut -d' ' -f2) lxc profile device add p1 root disk path=/ pool="$storage" lxc launch testimage c1 lxc info c1 | grep -q "Profiles: p1, p2, p3" || false # Cleanup lxc delete c1 -f lxc profile delete p1 lxc profile delete p2 lxc profile delete p3 lxc image delete testimage } test_profiles_project_default() { lxc project switch default test_image_nil_profile_list test_image_empty_profile_list test_image_alternate_profile_list } test_profiles_project_images_profiles() { lxc project create project1 lxc project switch project1 storage=$(lxc storage list | grep "^| " | tail -n 1 | cut -d' ' -f2) lxc profile device add default root disk path=/ pool="$storage" test_image_nil_profile_list test_image_empty_profile_list test_image_alternate_profile_list lxc project switch default lxc project delete project1 } # Run the tests with a project that only has the features.images enabled test_profiles_project_images() { lxc project create project1 -c features.profiles=false lxc project switch project1 test_image_nil_profile_list test_image_empty_profile_list test_image_alternate_profile_list lxc project switch default lxc project delete project1 } test_profiles_project_profiles() { lxc project create project1 -c features.images=false lxc project switch project1 storage=$(lxc storage list | grep "^| " | tail -n 1 | cut -d' ' -f2) lxc profile device add default root disk path=/ pool="$storage" test_image_nil_profile_list test_image_empty_profile_list test_image_alternate_profile_list lxc project switch default lxc project delete project1 }
<reponame>benstepp/d3sim var expect = require('chai').expect; var legendaryData = require('../src/data/legendary'); var affixes = require('../src/data/affixes'); var affixMap = require('../src/data/affixes/affix-map'); function legendaryTest(item) { describe('verify that legendary data has parameters needed to build an item', function() { it('should have a name', function() { expect(item.name).to.be.a('string'); }); it('should have a weight given for kadala', function() { expect(item.weight).to.be.a('number'); }); it('should have an image pointing to blizzard cdn', function() { expect(item.image).to.be.a('string'); expect(item.image).to.contain('//media.blizzard.com/'); expect(item.image).to.include('.png'); }); it('should have flavor text', function() { expect(item.flavor).to.be.a('string'); }); it('should have a hardcore/season boolean', function() { expect(item.hc).to.be.a('boolean'); expect(item.season).to.be.a('boolean'); }); it('should have explicit primary and secondary objects', function() { expect(item.primary).to.be.an('object'); expect(item.secondary).to.be.an('object'); }); it('should have between 2 and 8 affixes', function() { var affixes = Object.keys(item.primary).concat(Object.keys(item.secondary)); expect(affixes.length).to.be.at.least(2); expect(affixes.length).to.be.at.most(8); }); }); } function test() { for (var slot in legendaryData) { legendaryData[slot].forEach(function(item) { legendaryTest(item); }); //jshint ignore:line } } test();
<reponame>heylenz/python27 #!D:\yinhailin\pyvfx-x\python\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'anyconfig==0.5.0','console_scripts','anyconfig_cli' __requires__ = 'anyconfig==0.5.0' import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.exit( load_entry_point('anyconfig==0.5.0', 'console_scripts', 'anyconfig_cli')() )
#!/bin/sh -x . ~/.screenlayout/shared.sh xrandr xrandr --output ${EXTERNAL} --mode ${EXTERNAL_MODE} --pos 0x0 --rotate normal ${OFFS} . ~/.screenlayout/bg.sh
<reponame>ruritoBlogger/GameAI-FightingAI package cn.centipede.npz; import java.nio.ByteBuffer; import java.nio.DoubleBuffer; import java.util.stream.IntStream; import cn.centipede.numpy.NDArray; import cn.centipede.numpy.Numpy.np; /** * A file in NPY format. * * Currently unsupported types: * * * unsigned integral types (treated as signed) * * bit field, * * complex, * * object, * * Unicode * * void* * * intersections aka types for structured arrays. * * See http://docs.scipy.org/doc/numpy-dev/neps/npy-format.html */ public class NpyFile { public static NDArray read(Header header, ByteBuffer chunks) { int size = IntStream.of(header.shape).reduce(1, (a,b)->a*b); chunks.order(header.order); DoubleBuffer db = chunks.asDoubleBuffer(); double[] data = new double[size]; int offset = 0; while (db.hasRemaining()) { size = db.remaining(); db.get(data, offset, size); offset += size; } return np.array(data, header.shape); } }
#!/bin/bash set -e RUN_MULTI_USER_REPORT=$7 if [ "$RUN_MULTI_USER_REPORT" == "false" ]; then echo "RUN_MULTI_USER_REPORT set to false so exiting..." exit 0 fi MULTI_8_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) source $MULTI_8_DIR/../functions.sh source_bashrc step="multi_user_reports" init_log $step for i in $(ls $MULTI_8_DIR/*.sql | grep -v report.sql); do schema_name=`echo $i | awk -F '.' '{print $2}'` EXECUTE="'cat $MULTI_8_DIR/../log/rollout_$schema_name*.log'" echo "psql -v ON_ERROR_STOP=ON -a -f $i -v EXECUTE=\"$EXECUTE\"" psql -v ON_ERROR_STOP=ON -a -f $i -v EXECUTE="$EXECUTE" echo "" done psql -F $'\t' -A -v ON_ERROR_STOP=ON -P pager=off -f $MULTI_8_DIR/detailed_report.sql echo "" end_step $step
import Vue from "vue"; import VueRouter from "vue-router"; // ページコンポーネントをインポートする import Dashboard from "./pages/Dashboard.vue"; import Login from "./pages/Login.vue"; import ForgotPassword from "./pages/ForgotPassword.vue"; import ForgotPasswordReset from "./pages/ForgotPasswordReset.vue"; import SkillDetail from "./pages/skills/Detail.vue"; import SkillEdit from "./pages/skills/Edit.vue"; import PasswordChange from "./pages/settings/PasswordChange.vue"; import UserRegister from "./pages/manages/Register.vue"; import UserList from "./pages/manages/List.vue"; import SystemError from "./pages/errors/System.vue"; import store from "./store"; // VueRouterプラグインを使用する // これによって<RouterView />コンポーネントなどを使うことができる Vue.use(VueRouter); // パスとコンポーネントのマッピング const routes = [ { path: "/", component: Dashboard }, { path: "/login", component: Login, beforeEnter(to, from, next) { if (store.getters["auth/check"]) { next("/"); } else { next(); } } }, { path: "/password/forgot", component: ForgotPassword, beforeEnter(to, from, next) { if (store.getters["auth/check"]) { next("/"); } else { next(); } } }, { path: "/password/forgot/reset/:token", component: ForgotPasswordReset, beforeEnter(to, from, next) { if (store.getters["auth/check"]) { next("/"); } else { next(); } } }, { path: "/skill/:id", component: SkillDetail }, { path: "/skill/edit/:id", component: SkillEdit, beforeEnter(to, from, next) { if ( !store.getters["auth/isManage"] && to.params.id != store.getters["auth/id"] ) { next("/"); } else { next(); } } }, { path: "/setting/password/change", component: PasswordChange }, { path: "/manage/register", component: UserRegister, beforeEnter(to, from, next) { if (!store.getters["auth/isManage"]) { next("/"); } else { next(); } } }, { path: "/manage/list", component: UserList, beforeEnter(to, from, next) { if (!store.getters["auth/isManage"]) { next("/"); } else { next(); } } }, { path: "/500", component: SystemError } ]; // VueRouterインスタンスを作成する const router = new VueRouter({ mode: "history", routes }); // ログインしていない場合はログイン画面へ router.beforeEach((to, from, next) => { if ( to.path !== "/login" && to.path !== "/password/forgot" && to.path !== `/password/forgot/reset/${to.params.token}` && !store.getters["auth/check"] ) { next("/login"); } else { next(); } }); // VueRouterインスタンスをエクスポートする // app.jsでインポートするため export default router;
#!/bin/sh cd /usr/share/nginx/ echo "Instalando dependências pelo Composer..." composer install > /dev/null echo "Instalando dependências NPM..." npm install > /dev/null echo "Gerando chave da aplicação..." php artisan key:generate echo "Adicionando permissões a pasta storage..." chmod 777 -R storage echo "Aguarde a iniciação da migração do banco de dados..." sleep 80 echo "Gerando migrate da aplicação..." php artisan migrate echo "Gerando seeds da aplicação..." php artisan db:seed echo "Rodando npm run watch" npm run watch & # Update nginx to match worker_processes to no. of cpu's procs=$(cat /proc/cpuinfo |grep processor | wc -l) sed -i -e "s/worker_processes 1/worker_processes $procs/" /etc/nginx/nginx.conf # Always chown webroot for better mounting chown -Rf nginx.nginx /usr/share/nginx/html # Start supervisord and services /usr/local/bin/supervisord -n -c /etc/supervisord.conf
<filename>src/hal/src/arch/arm/armv7-m/core_debug.cpp // MIT License // // Copyright (c) 2020 SunnyCase // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <chino/arch/reg.h> #include <chino/arch/arm/armv7-m/core_debug.h> using namespace chino; using namespace chino::arch; typedef struct { uint32_t cdbg_en : 1; uint32_t halt : 1; uint32_t step : 1; uint32_t hsi_trim : 5; } cdbg_dhcsr_t; typedef struct { uint32_t vc_core_reset : 1; uint32_t reserved0 : 3; uint32_t vc_mm_err : 1; uint32_t vc_no_cperr : 1; uint32_t vc_chk_err : 1; uint32_t vc_stat_err : 1; uint32_t vc_bus_err : 1; uint32_t vc_int_err : 1; uint32_t vc_hard_err : 1; uint32_t reserved1 : 5; uint32_t mon_en : 1; uint32_t mon_pend : 1; uint32_t mon_step : 1; uint32_t mon_req : 1; uint32_t trace_ena : 1; } cdbg_demcr_t; typedef struct { reg_t<cdbg_dhcsr_t> chcsr; reg_t<uint32_t> dcrsr; reg_t<uint32_t> dcrdr; reg_t<cdbg_demcr_t> demcr; } cdbg_t; static volatile cdbg_t &cdbg_r() noexcept { return *reinterpret_cast<volatile cdbg_t *>(CoreDebug_BASE); } bool core_debug::is_enabled() noexcept { return cdbg_r().chcsr.reg_mut().cdbg_en; } void core_debug::monitor_enable() noexcept { cdbg_r().demcr.reg_mut().mon_en = 1; } void core_debug::monitor_enable_step() noexcept { cdbg_r().demcr.reg_mut().mon_step = 1; } void core_debug::trace_enable() noexcept { cdbg_r().demcr.reg_mut().trace_ena = 1; }
// Define a map to store the exported modules const exportedModules = {}; // Simulate the export functionality export function MInputText() { // Implementation of MInputText module } // Implement the importModule function function importModule(moduleName) { // Check if the module exists in the exportedModules map if (exportedModules.hasOwnProperty(moduleName)) { // Return the exported module return exportedModules[moduleName]; } else { // Return null if the module is not found return null; } } // Add the exported module to the exportedModules map exportedModules['MInputText'] = MInputText; // Test the importModule function console.log(importModule('MInputText')); // Output: [Function: MInputText] console.log(importModule('SomeOtherModule')); // Output: null
#!/bin/bash APP="sleek" APP_PATH="dist/mas-universal/$APP.app" PKG_PATH="dist/mas-universal/$APP-mas.pkg" PARENT_PLIST="build/entitlements.mas.plist" CHILD_PLIST="build/entitlements.mas.inherit.plist" LOGINHELPER_PLIST="build/entitlements.mas.loginhelper.plist" APP_KEY="Apple Distribution: Robin Ahle (8QSR3UZXP8)" codesign --force --entitlements "$CHILD_PLIST" --deep --sign "$APP_KEY" "$APP_PATH" codesign --force --entitlements "$PARENT_PLIST" --sign "$APP_KEY" "$APP_PATH" codesign --force --entitlements "$LOGINHELPER_PLIST" --sign "$APP_KEY" "$APP_PATH/Contents/Library/LoginItems/$APP Login Helper.app/Contents/MacOS/$APP Login Helper" codesign --force --entitlements "$LOGINHELPER_PLIST" --sign "$APP_KEY" "$APP_PATH/Contents/Library/LoginItems/$APP Login Helper.app/" productbuild --component "$APP_PATH" /Applications --sign "3rd Party Mac Developer Installer: Robin Ahle (8QSR3UZXP8)" "$PKG_PATH"
export default { contract: { paidType: { pos: { val: 0, text: 'POS机', }, bank: { val: 1, text: '银行转账', }, promissory: { val: 2, text: '本票', }, accumulation: { val: 3, text: '滚存', }, else: { val: 9, text: '其它', }, }, status: { waitingForSubmit: { val: 0, text: '待提交', }, waitingForReview: { val: 1, text: '待审核', }, released: { val: 2, text: '已生效', }, else: { val: 99, text: '其它', }, }, attachmentType: { video: { val: 1, text: '图像', }, picture: { val: 2, text: '图片', }, }, }, product: { status: { waitingForSubmit: { val: 0, text: '待提交', }, waitingForReview: { val: 1, text: '待审核', }, released: { val: 2, text: '已发行', }, else: { val: 99, text: '其它', }, }, }, }
<reponame>kotik-coder/PULsE package pulse.ui.frames; import static java.awt.BorderLayout.CENTER; import static java.awt.BorderLayout.EAST; import static javax.swing.JOptionPane.ERROR_MESSAGE; import static javax.swing.JOptionPane.showMessageDialog; import static javax.swing.SwingUtilities.getWindowAncestor; import static pulse.io.export.ExportManager.askToExport; import static pulse.properties.NumericProperties.def; import static pulse.properties.NumericPropertyKeyword.WINDOW; import static pulse.tasks.processing.ResultFormat.getInstance; import static pulse.ui.Messages.getString; import java.util.ArrayList; import java.util.List; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JScrollPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.TableModelEvent; import pulse.ui.components.ResultTable; import pulse.ui.components.listeners.PreviewFrameCreationListener; import pulse.ui.components.listeners.ResultRequestListener; import pulse.ui.components.models.ResultTableModel; import pulse.ui.components.panels.ResultToolbar; import pulse.ui.frames.dialogs.FormattedInputDialog; @SuppressWarnings("serial") public class ResultFrame extends JInternalFrame { private ResultToolbar resultToolbar; private ResultTable resultTable; private List<PreviewFrameCreationListener> listeners; private FormattedInputDialog averageWindowDialog; public ResultFrame() { super("Results", true, false, true, true); initComponents(); listeners = new ArrayList<>(); addListeners(); setVisible(true); } private void initComponents() { var resultsScroller = new JScrollPane(); resultTable = new ResultTable(getInstance()); resultsScroller.setViewportView(resultTable); getContentPane().add(resultsScroller, CENTER); resultToolbar = new ResultToolbar(); getContentPane().add(resultToolbar, EAST); averageWindowDialog = new FormattedInputDialog(def(WINDOW)); } private void addListeners() { resultToolbar.addResultRequestListener(new ResultRequestListener() { @Override public void onDeleteRequest() { resultTable.deleteSelected(); } @Override public void onPreviewRequest() { if (!resultTable.hasEnoughElements(1)) { showMessageDialog(getWindowAncestor(resultTable), getString("ResultsToolBar.NoDataError"), getString("ResultsToolBar.NoResultsError"), ERROR_MESSAGE); } else { notifyPreview(); } } @Override public void onMergeRequest() { if (resultTable.hasEnoughElements(1)) { showInputDialog(); } } @Override public void onUndoRequest() { resultTable.undo(); } @Override public void onExportRequest() { if (!resultTable.hasEnoughElements(1)) { showMessageDialog(getWindowAncestor(resultTable), getString("ResultsToolBar.7"), getString("ResultsToolBar.8"), ERROR_MESSAGE); return; } askToExport(resultTable, (JFrame) getWindowAncestor(resultTable), "Calculation results"); } }); resultTable.getSelectionModel().addListSelectionListener((ListSelectionEvent arg0) -> { resultToolbar.setDeleteEnabled(!resultTable.isSelectionEmpty()); }); resultTable.getModel().addTableModelListener((TableModelEvent arg0) -> { resultToolbar.setPreviewEnabled(resultTable.hasEnoughElements(3)); resultToolbar.setMergeEnabled(resultTable.hasEnoughElements(2)); resultToolbar.setExportEnabled(resultTable.hasEnoughElements(1)); resultToolbar.setUndoEnabled(resultTable.hasEnoughElements(1)); }); } public void notifyPreview() { listeners.stream().forEach(l -> l.onPreviewFrameRequest()); } public void addFrameCreationListener(PreviewFrameCreationListener l) { listeners.add(l); } private void showInputDialog() { averageWindowDialog.setLocationRelativeTo(null); averageWindowDialog.setVisible(true); averageWindowDialog.setConfirmAction(() -> ((ResultTableModel)resultTable.getModel()) .merge(averageWindowDialog.value().doubleValue())); } public ResultTable getResultTable() { return resultTable; } }
/* * Copyright 2015 Groupon.com * * 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.arpnetworking.metrics.mad.model.statistics; import com.arpnetworking.metrics.mad.model.Quantity; import com.arpnetworking.tsdcore.model.CalculatedValue; /** * Specialization of {@link Calculator} directly supporting streaming * calculations over {@link Quantity} and {@link CalculatedValue} * streams. * * @param <T> The type of supporting data. * @author <NAME> (ville dot koskela at inscopemetrics dot io) */ public interface Accumulator<T> extends Calculator<T> { /** * Add the specified {@link Quantity} to the accumulated value. It is * permissible to mix calls to accumulate with {@link Quantity} and * {@link CalculatedValue}. * * @param quantity The {@link Quantity} to include in the accumulated value. * @return This {@link Accumulator}. */ Accumulator<T> accumulate(Quantity quantity); /** * Add the specified {@link CalculatedValue} to the accumulated value. The * {@link CalculatedValue} was produced by this {@link Accumulator} in * a different context. For example, for a different time period or a different * host. It is permissible to mix calls to accumulate with {@link Quantity} * and {@link CalculatedValue}. * * @param calculatedValue The {@link CalculatedValue} to include in the accumulated value. * @return This {@link Accumulator}. */ Accumulator<T> accumulate(CalculatedValue<T> calculatedValue); /** * Add the specified {@link CalculatedValue} to the accumulated value. The * {@link CalculatedValue} was produced by this {@link Accumulator} in * a different context. For example, for a different time period or a different * host. It is permissible to mix calls to accumulate with {@link Quantity} * and {@link CalculatedValue}. * * If the {@link CalculatedValue}'s supporting data is of an unsupported * type then an {@link IllegalArgumentException} will be thrown. * * @param calculatedValue The {@link CalculatedValue} to include in the accumulated value. * @return This {@link Accumulator}. */ Accumulator<T> accumulateAny(CalculatedValue<?> calculatedValue); }
import template from './createCompany.html'; import companyCtrl from './createCompany.controller'; let createCompanyComponent = { restrict: 'E', bindings: {}, template, companyCtrl }; export default createCompanyComponent;
#!/bin/bash set -e file_env() { local var="$1" local fileVar="${var}_FILE" local def="${2:-}" if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then echo "error: both $var and $fileVar are set (but are exclusive)" >&2 exit 1 fi local val="$def" if [ "${!var:-}" ]; then val="${!var}" elif [ "${!fileVar:-}" ]; then val="$(< "${!fileVar}")" fi export "$var"="$val" unset "$fileVar" } file_env 'ROOT_PASSWORD' ROOT_PASSWORD=${ROOT_PASSWORD:-password} WEBMIN_ENABLED=${WEBMIN_ENABLED:-true} BIND_DATA_DIR=${DATA_DIR}/bind WEBMIN_DATA_DIR=${DATA_DIR}/webmin create_bind_data_dir() { mkdir -p ${BIND_DATA_DIR} if [ ! -d ${BIND_DATA_DIR}/etc ]; then mv /etc/bind ${BIND_DATA_DIR}/etc fi rm -rf /etc/bind ln -sf ${BIND_DATA_DIR}/etc /etc/bind chmod -R 0775 ${BIND_DATA_DIR} chown -R ${BIND_USER}:${BIND_USER} ${BIND_DATA_DIR} if [ ! -d ${BIND_DATA_DIR}/lib ]; then mkdir -p ${BIND_DATA_DIR}/lib chown ${BIND_USER}:${BIND_USER} ${BIND_DATA_DIR}/lib cp -a /var/lib/bind/* ${BIND_DATA_DIR}/lib/ rm -rf /var/lib/bind ln -sf ${BIND_DATA_DIR}/lib /var/lib/bind else rm -rf /var/lib/bind ln -sf ${BIND_DATA_DIR}/lib /var/lib/bind fi } create_webmin_data_dir() { mkdir -p ${WEBMIN_DATA_DIR} chmod -R 0755 ${WEBMIN_DATA_DIR} chown -R root:root ${WEBMIN_DATA_DIR} if [ ! -d ${WEBMIN_DATA_DIR}/etc ]; then mv /etc/webmin ${WEBMIN_DATA_DIR}/etc fi rm -rf /etc/webmin ln -sf ${WEBMIN_DATA_DIR}/etc /etc/webmin } set_root_passwd() { echo "root:$ROOT_PASSWORD" | chpasswd } create_pid_dir() { mkdir -m 0775 -p /var/run/named chown root:${BIND_USER} /var/run/named } create_bind_cache_dir() { mkdir -m 0775 -p /var/cache/bind chown root:${BIND_USER} /var/cache/bind } create_pid_dir create_bind_data_dir create_bind_cache_dir # allow arguments to be passed to named if [[ ${1:0:1} = '-' ]]; then EXTRA_ARGS="$@" set -- elif [[ ${1} == named || ${1} == $(which named) ]]; then EXTRA_ARGS="${@:2}" set -- fi # default behaviour is to launch named if [[ -z ${1} ]]; then if [ "${WEBMIN_ENABLED}" == "true" ]; then create_webmin_data_dir set_root_passwd echo "Starting webmin..." /etc/init.d/webmin start fi echo "Starting named..." exec $(which named) -u ${BIND_USER} -g ${EXTRA_ARGS} else exec "$@" fi
#!/bin/sh . "$HOME/.prompts/global.sh" export PS1="[$bold$red\u$reset@$bold$green\h$reset \w ]$ " promptreset unset -f promptreset
<filename>src/main/java/de/jlo/talendcomp/google/analytics/Util.java /** * Copyright 2015 <NAME> <EMAIL> * * 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 de.jlo.talendcomp.google.analytics; import java.io.IOException; import java.math.BigDecimal; import java.net.SocketException; import java.sql.Timestamp; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo; public class Util { private final static Map<String, NumberFormat> numberformatMap = new HashMap<String, NumberFormat>(); public static NumberFormat getNumberFormat(String localeStr) { String key = localeStr + "-" + Thread.currentThread().getName(); NumberFormat nf = (NumberFormat) numberformatMap.get(key); if (nf == null) { Locale locale = new Locale(localeStr); nf = NumberFormat.getInstance(locale); numberformatMap.put(key, nf); } return nf; } /** * converts a list of values into a collection * @param valuesSeparated * @param dataType String|date|Double| * @param delimiter * @return */ public static List<Object> convertToList(String valuesSeparated, String dataType, String delimiter, String pattern) throws Exception { List<Object> resultList = new ArrayList<Object>(); StringTokenizer st = new StringTokenizer(valuesSeparated, delimiter); while (st.hasMoreElements()) { String value = st.nextToken(); resultList.add(convertToDatatype(value, dataType, pattern)); } return resultList; } public static Object convertToDatatype(String value, String dataType, String options) throws Exception { if (value != null && value.trim().isEmpty() == false) { if ("String".equalsIgnoreCase(dataType)) { return value; } else if ("BigDecimal".equalsIgnoreCase(dataType)) { return convertToBigDecimal(value); } else if ("Boolean".equalsIgnoreCase(dataType)) { return convertToBoolean(value); } else if ("Date".equalsIgnoreCase(dataType)) { return convertToDate(value, options); } else if ("Double".equalsIgnoreCase(dataType)) { return convertToDouble(value, options); } else if ("Float".equalsIgnoreCase(dataType)) { return convertToFloat(value, options); } else if ("Int".equalsIgnoreCase(dataType) || "Integer".equalsIgnoreCase(dataType)) { return convertToInteger(value, options); } else if ("Long".equalsIgnoreCase(dataType)) { return convertToLong(value, options); } else if ("Short".equalsIgnoreCase(dataType)) { return convertToLong(value, options); } else if ("Timestamp".equalsIgnoreCase(dataType)) { return convertToTimestamp(value, options); } else { throw new Exception("Unsupported dataType:" + dataType); } } else { return null; } } /** * concerts the string format into a Date * @param dateString * @param pattern * @return the resulting Date */ public static Date convertToDate(String dateString, String pattern) throws Exception { if (dateString == null || dateString.trim().isEmpty() || dateString.equals("total")) { return null; } if (pattern == null || pattern.isEmpty()) { throw new Exception("convertToDate failed: pattern cannot be null or empty"); } try { SimpleDateFormat sdf = new SimpleDateFormat(pattern); return sdf.parse(dateString.trim()); } catch (Throwable t) { throw new Exception("Failed to convert string to date:" + t.getMessage(), t); } } public static Timestamp convertToTimestamp(String dateString, String pattern) throws Exception { Date date = convertToDate(dateString, pattern); if (date != null) { return new Timestamp(date.getTime()); } else { return null; } } public static Boolean convertToBoolean(String value) throws Exception { if (value == null || value.trim().isEmpty()) { return null; } else { if ("true".equals(value.trim())) { return true; } else if ("false".equals(value.trim())) { return false; } else { throw new Exception("Value:" + value + " is not a boolean value!"); } } } public static Double convertToDouble(String value, String locale) throws Exception { if (value == null || value.trim().isEmpty()) { return null; } return getNumberFormat(locale).parse(value.trim()).doubleValue(); } public static Integer convertToInteger(String value, String locale) throws Exception { if (value == null || value.trim().isEmpty()) { return null; } return getNumberFormat(locale).parse(value.trim()).intValue(); } public static Float convertToFloat(String value, String locale) throws Exception { if (value == null || value.trim().isEmpty()) { return null; } return getNumberFormat(locale).parse(value.trim()).floatValue(); } public static Long convertToLong(String value, String locale) throws Exception { if (value == null || value.trim().isEmpty()) { return null; } return getNumberFormat(locale).parse(value.trim()).longValue(); } public static Short convertToShort(String value, String locale) throws Exception { if (value == null || value.trim().isEmpty()) { return null; } return getNumberFormat(locale).parse(value.trim()).shortValue(); } public static BigDecimal convertToBigDecimal(String value) throws Exception { if (value == null || value.trim().isEmpty()) { return null; } try { return new BigDecimal(value.trim()); } catch (RuntimeException e) { throw new Exception("convertToBigDecimal:" + value + " failed:" + e.getMessage(), e); } } private static IgnorableError[] listIgnorableErrors = { new IgnorableError(403, "userRateLimitExceeded"), new IgnorableError(403, "quotaExceeded"), new IgnorableError(500, null), new IgnorableError(503, null) }; public static boolean canBeIgnored(IOException e) { boolean ignore = false; if (e instanceof GoogleJsonResponseException) { GoogleJsonResponseException gre = (GoogleJsonResponseException) e; GoogleJsonError gje = gre.getDetails(); if (gje != null) { List<ErrorInfo> errors = gje.getErrors(); if (errors != null && errors.isEmpty() == false) { ErrorInfo ei = errors.get(0); for (IgnorableError error : listIgnorableErrors) { if (error.code == gre.getStatusCode()) { if (error.reason == null || error.reason.equals(ei.getReason())) { ignore = true; break; } } } } } } else if (e instanceof SocketException) { if (e.getMessage().contains("reset")) { ignore = true; } } return ignore; } public static class IgnorableError { public IgnorableError(int code, String reason) { this.code = code; this.reason = reason; } private int code = 0; private String reason = null; public int getCode() { return code; } public String getReason() { return reason; } } }
autoload colors && colors # cheers, @ehrenmurdick # http://github.com/ehrenmurdick/config/blob/master/zsh/prompt.zsh if (( $+commands[git] )) then git="$commands[git]" else git="/usr/bin/git" fi git_branch() { echo $($git symbolic-ref HEAD 2>/dev/null | awk -F/ {'print $NF'}) } git_dirty() { if $(! $git status -s &> /dev/null) then echo "" else if [[ $($git status --porcelain) == "" ]] then echo "on %{$fg_bold[green]%}$(git_prompt_info)%{$reset_color%}" else echo "on %{$fg_bold[red]%}$(git_prompt_info)%{$reset_color%}" fi fi } git_prompt_info () { ref=$($git symbolic-ref HEAD 2>/dev/null) || return # echo "(%{\e[0;33m%}${ref#refs/heads/}%{\e[0m%})" echo "${ref#refs/heads/}" } # This assumes that you always have an origin named `origin`, and that you only # care about one specific origin. If this is not the case, you might want to use # `$git cherry -v @{upstream}` instead. need_push () { if [ $($git rev-parse --is-inside-work-tree 2>/dev/null) ] then number=$($git cherry -v origin/$(git symbolic-ref --short HEAD) 2>/dev/null | wc -l | bc) if [[ $number == 0 ]] then echo " " else echo " with %{$fg_bold[magenta]%}$number unpushed%{$reset_color%}" fi fi } directory_name() { echo "%{$fg_bold[cyan]%}%0/%\/%{$reset_color%}" } battery_status() { if [[ $(sysctl -n hw.model) == *"Book"* ]] then $ZSH/bin/battery-status fi } export PROMPT=$'\n$(battery_status)in $(directory_name) $(git_dirty)$(need_push)\n› ' set_prompt () { export RPROMPT="%{$fg_bold[cyan]%}%{$reset_color%}" } precmd() { title "zsh" "%m" "%55<...<%~" set_prompt } gitkraken() { if [ "$1" != "" ] then /Applications/GitKraken.app/Contents/MacOS/GitKraken -p $1 1>/dev/null & else /Applications/GitKraken.app/Contents/MacOS/GitKraken -p . 1>/dev/null & fi } kraken() { if [ "$1" != "" ] then /Applications/GitKraken.app/Contents/MacOS/GitKraken -p $1 1>/dev/null & else /Applications/GitKraken.app/Contents/MacOS/GitKraken -p . 1>/dev/null & fi }
<gh_stars>1-10 import fs from 'fs' import path from 'path' import { BuyerRequest } from '../model/buyerRequest' import { BuyerUpdate } from '../model/buyerUpdate' import Client from './client' let key if (process.env.PRIVATE_KEY) { key = process.env.PRIVATE_KEY } else { const my_path = path.resolve(__dirname, './private_key.pem') key = String(fs.readFileSync(my_path)) } const client = new Client({ gr4vyId: 'spider', environment: 'sandbox', privateKey: key, }) const DISPLAY_NAME = 'Tester T.' let buyerId jest.setTimeout(30000) describe('#addBuyer', () => { test('it should create a buyer', async () => { const buyerRequest = new BuyerRequest() buyerRequest.displayName = DISPLAY_NAME buyerRequest.externalIdentifier = 'test-' + (Math.random() + 1).toString(36).substring(8) const buyer = await client.addBuyer(buyerRequest).catch((error) => { console.dir(error.response.body) // the parsed JSON of the error console.dir(error.response.statusCode) // the status code of the error throw new Error('an error occurred while creating the buyer') }) expect(buyer).toBeDefined() expect(buyer.body).toBeDefined() buyerId = buyer.body.id expect(buyerId).toHaveLength(36) }) }) describe('#listBuyers', () => { test('it should find some buyers', async () => { const buyers = await client.listBuyers() expect(buyers).toBeDefined() expect(buyers.body.items).toBeDefined() expect(buyers.body.items.length).toBeGreaterThan(0) }) }) describe('#getBuyer', () => { test('it should find a specific buyer', async () => { const buyer = await client.getBuyer(buyerId) expect(buyer).toBeDefined() expect(buyer.body).toBeDefined() expect(buyer.body.displayName).toBe(DISPLAY_NAME) }) }) describe('#updateBuyer', () => { test('it should update a specific buyer', async () => { const buyerUpdate = new BuyerUpdate() buyerUpdate.displayName = 'NewDisplayName' const buyer = await client.updateBuyer(buyerId, buyerUpdate) expect(buyer).toBeDefined() expect(buyer.body).toBeDefined() expect(buyer.body.displayName).toBe('NewDisplayName') }) }) describe('#deleteBuyer', () => { test('it should delete a specific buyer', async () => { const buyer = await client.deleteBuyer(buyerId) expect(buyer.response.statusCode).toEqual(204) }) })
export enum MENU { ABOUT = 'ABOUT', EXPERIENCE = 'EXPERIENCE', PROJECTS = 'PROJECTS', SKILLS = 'SKILLS', } export enum PROJECTSTYPE { WORK = 'Work', PERSONAL = 'Personal', } export enum ICONTYPE { PHONE = 'PHONE', EMAIL = 'EMAIL', FILEDOWNLOAD = 'FILEDOWNLOAD', GITHUB = 'GITHUB', LINKEDIN = 'LINKEDIN', DEMO = 'DEMO', CODE = 'CODE', MAP = 'MAP', USER = 'USER', } export enum DESCRIPTIONFOR { USERDESCRIPTION = 'USERDESCRIPTION', }
package com.app.wechat.internal.exception; /** * <p>功 能:微信公众平台API请求与响应异常</p> * <p>版 权:Copyright (c) 2017</p> * <p>创建时间:2017年7月4日 下午2:52:40</p> * @author 王建 * @version 1.0 */ public class WxApiException extends Exception { private static final long serialVersionUID = 1L; /** 错误码 */ private String errCode; /** 错误消息 */ private String errMsg; public WxApiException() { super(); } public WxApiException(String message, Throwable cause) { super(message, cause); } public WxApiException(String message) { super(message); } public WxApiException(Throwable cause) { super(cause); } public WxApiException(String errCode, String errMsg) { super("[" + errCode + "] " + errMsg); this.errCode = errCode; this.errMsg = errMsg; } public String getErrCode() { return errCode; } public String getErrMsg() { return errMsg; } }
<filename>commands/general/help.js const i18n = require("i18n"); const fs = require("fs"); module.exports = { name: "help", usage: "[command]", disabled: true, runPermissions: ["EMBED_LINKS", "SEND_MESSAGES"], description: i18n.__("help.description"), aliases: ["command", "commands"], options: [ { type: 3, name: "command", description: "Choice a command", choices: [ { name: "help", value: "help", }, { name: "ping", value: "ping", }, ], }, ], async execute(interaction, Data) { await interaction.deferReply(); const commandName = interaction.options.getString("command"); if (!commandName) { let fields = []; //Create array for fields const commandFolders = fs.readdirSync("./commands"); for (const folder of commandFolders) { let commands = []; //Create array for commands categories const commandFiles = fs .readdirSync(`./commands/${folder}`) .filter((file) => file.split(".").pop() === "js"); for (const file of commandFiles) { const command = require(`../../commands/${folder}/${file}`); if (command.hidden || command.disabled) continue; //Continue if the command hidden/disabled if ( command.permissions && !interaction.channel .permissionsFor(interaction.member) .has(command.permissions) ) continue; //Continue if the user dosn't have the required permissions let data = `\`/${command.name}\``; if (command.description) { let description = command.description; if (description.length > 32) description = description.substring(0, 32) + "..."; data = `\`/${command.name}\`\n> ${description}`; } //If the command have description add it commands.push(data); } if (!commands[0]) continue; //Continue if the category is empty fields.push({ name: folder, value: commands.join("\n\n"), inline: true, }); } interaction .editReply({ embeds: [ { title: i18n.__("help.embeds.menu.title"), description: i18n.__("help.embeds.menu.description"), timestamp: Date.now(), color: `${Data.color}`, fields: fields, author: { name: interaction.guild.name, iconURL: interaction.guild.iconURL({ dynamic: true }), }, footer: { text: interaction.user.tag, iconURL: interaction.user.displayAvatarURL({ dynamic: true }), }, }, ], }) .catch((error) => { console.warn( `Could not send help menu in ${interaction.channel.name}` ); console.error(error); let errorsChannel = Data.guild.channels.errors ? interaction.guild.channels.cache.get(Data.guild.channels.errors) : interaction.channel; errorsChannel.send( i18n.__mf("error.sendingMessage", { channel: interaction.channel.id, errorMessage: error, }) ); }); } else { const command = interaction.client.cache.commands.get(commandName) || interaction.client.cache.commands.find( (command) => command.aliases && command.aliases.includes(commandName) ); //Get the command data by name or aliases if (!command) return interaction.editReply({ embeds: [ { title: i18n.__("help.embeds.invalidCommand.title"), description: i18n.__("help.embeds.invalidCommand.description"), timestamp: Date.now(), color: `${Data.color}`, }, ], ephemeral: true, }); //Return if not an existing command let fields = []; if (command.aliases) fields.push({ name: i18n.__("help.embeds.command.aliases"), value: `> \`${command.aliases.join("`, `")}\``, }); //If the command have aliases add field for it fields.push({ name: i18n.__("help.embeds.command.usage"), value: i18n.__mf("help.embeds.command.usageValue", { usage: command.usage ? command.name + " " + command.usage : command.name, }), }); //Field for command usage fields.push({ name: i18n.__("help.embeds.command.noPermissions"), value: i18n.__mf("help.embeds.command.noPermissionsValue", { permissions: command.permissions?.join("`, `") || "none", note: command.permissions && !interaction.channel .permissionsFor(interaction.member) .has(command.permissions) ? i18n.__("help.embeds.command.noPermissionsNote") : "", }), }); //Field for required user permissions fields.push({ name: i18n.__("help.embeds.command.noRunPermissions"), value: i18n.__mf("help.embeds.command.noRunPermissionsValue", { permissions: command.runPermissions?.join("`, `") || "none", note: command.runPermissions && !interaction.channel .permissionsFor(interaction.client.user) .has(command.runPermissions) ? i18n.__("help.embeds.command.noRunPermissionsNote") : "", }), }); //Field for required bot permissions interaction.editReply({ embeds: [ { title: command.name, description: command.description, timestamp: Date.now(), color: `${Data.color}`, fields: fields, author: { name: interaction.guild.name, iconURL: interaction.guild.iconURL({ dynamic: true }), }, footer: { text: interaction.user.tag, iconURL: interaction.user.displayAvatarURL({ dynamic: true }), }, }, ], }); } }, };
package com.bo.mower.lawnmover.exceptions; public class MissingDataException extends Exception { public MissingDataException(String msg) { super(msg); } }
for (let i = 0; i < 5; i++) { var newDate = new Date(); var currentDateTime = newDate.toLocaleString(); console.log(currentDateTime); }
<html> <head> <title>My Web Page</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div> <p>Hello World!</p> </div> </body> </html>
#!/usr/bin/env bash apt update && apt install --yes apt-transport-https ca-certificates curl gnupg-agent software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add - add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable" apt update && apt install --yes docker-ce docker-ce-cli containerd.io curl -L "https://github.com/docker/compose/releases/download/1.24.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose chmod +x /usr/local/bin/docker-compose ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose docker run hello-world docker --version docker-compose --version
package moze_intel.projecte.events; import java.util.EnumSet; import java.util.Set; import moze_intel.projecte.PECore; import moze_intel.projecte.api.ProjectEAPI; import moze_intel.projecte.gameObjs.container.AlchBagContainer; import moze_intel.projecte.gameObjs.items.AlchemicalBag; import moze_intel.projecte.gameObjs.items.IFireProtector; import moze_intel.projecte.handlers.CommonInternalAbilities; import moze_intel.projecte.handlers.InternalAbilities; import moze_intel.projecte.handlers.InternalTimers; import moze_intel.projecte.utils.PlayerHelper; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.item.DyeColor; import net.minecraft.item.ItemStack; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; @Mod.EventBusSubscriber(modid = PECore.MODID) public class TickEvents { @SubscribeEvent public static void playerTick(TickEvent.PlayerTickEvent event) { if (event.phase == TickEvent.Phase.END) { event.player.getCapability(ProjectEAPI.ALCH_BAG_CAPABILITY).ifPresent(provider -> { Set<DyeColor> colorsChanged = EnumSet.noneOf(DyeColor.class); for (DyeColor color : getBagColorsPresent(event.player)) { IItemHandler inv = provider.getBag(color); for (int i = 0; i < inv.getSlots(); i++) { ItemStack current = inv.getStackInSlot(i); if (!current.isEmpty()) { current.getCapability(ProjectEAPI.ALCH_BAG_ITEM_CAPABILITY).ifPresent(alchBagItem -> { if (alchBagItem.updateInAlchBag(inv, event.player, current)) { colorsChanged.add(color); } }); } } } for (DyeColor e : colorsChanged) { if (event.player.containerMenu instanceof AlchBagContainer) { ItemStack heldItem = event.player.getItemInHand(((AlchBagContainer) event.player.containerMenu).hand); if (heldItem.getItem() instanceof AlchemicalBag && ((AlchemicalBag) heldItem.getItem()).color == e) { // Do not sync if this color is open, the container system does it for us // and we'll stay out of its way. continue; } } provider.sync(e, (ServerPlayerEntity) event.player); } }); event.player.getCapability(CommonInternalAbilities.CAPABILITY).ifPresent(CommonInternalAbilities::tick); if (!event.player.getCommandSenderWorld().isClientSide) { event.player.getCapability(InternalAbilities.CAPABILITY).ifPresent(InternalAbilities::tick); event.player.getCapability(InternalTimers.CAPABILITY).ifPresent(InternalTimers::tick); if (event.player.isOnFire() && shouldPlayerResistFire((ServerPlayerEntity) event.player)) { event.player.clearFire(); } } } } public static boolean shouldPlayerResistFire(ServerPlayerEntity player) { for (ItemStack stack : player.inventory.armor) { if (!stack.isEmpty() && stack.getItem() instanceof IFireProtector && ((IFireProtector) stack.getItem()).canProtectAgainstFire(stack, player)) { return true; } } for (int i = 0; i < PlayerInventory.getSelectionSize(); i++) { ItemStack stack = player.inventory.getItem(i); if (!stack.isEmpty() && stack.getItem() instanceof IFireProtector && ((IFireProtector) stack.getItem()).canProtectAgainstFire(stack, player)) { return true; } } IItemHandler curios = PlayerHelper.getCurios(player); if (curios != null) { for (int i = 0; i < curios.getSlots(); i++) { ItemStack stack = curios.getStackInSlot(i); if (!stack.isEmpty() && stack.getItem() instanceof IFireProtector && ((IFireProtector) stack.getItem()).canProtectAgainstFire(stack, player)) { return true; } } } return false; } private static Set<DyeColor> getBagColorsPresent(PlayerEntity player) { Set<DyeColor> bagsPresent = EnumSet.noneOf(DyeColor.class); player.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).ifPresent(inv -> { for (int i = 0; i < inv.getSlots(); i++) { ItemStack stack = inv.getStackInSlot(i); if (!stack.isEmpty() && stack.getItem() instanceof AlchemicalBag) { bagsPresent.add(((AlchemicalBag) stack.getItem()).color); } } }); return bagsPresent; } }
go test -bench=Benchmark.*Mul
<filename>tests/extmod/ubinascii_unhexlify.py try: try: import ubinascii as binascii except ImportError: import binascii except ImportError: print("SKIP") raise SystemExit print(binascii.unhexlify(b'0001020304050607')) print(binascii.unhexlify(b'08090a0b0c0d0e0f')) print(binascii.unhexlify(b'7f80ff')) print(binascii.unhexlify(b'313233344142434461626364')) try: a = binascii.unhexlify(b'0') # odd buffer length except ValueError: print('ValueError') try: a = binascii.unhexlify(b'gg') # digit not hex except ValueError: print('ValueError')
""" Application: HealthNet File: hospital/views.py Authors: - <NAME> - <NAME> - <NAME> - <NAME> - <NAME> Description: - This file contains all the view for the hospital functionality """ from base.views import group_required from base.models import Hospital, Logger, Person from django.contrib.auth.models import User, Group from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse_lazy, reverse from django.http import HttpResponseRedirect from django.utils.decorators import method_decorator from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic.edit import UpdateView from .forms import * # Create your views here. @login_required def hospitalRedirect(request): return redirect(reverse('hospital:view'), permanent=True) @login_required @group_required('Root') def createHospital(request): """ @function: createHospital @description: This function handles a request for creating a hospital. """ # Boolean for successful schedule creation_success = False if request.method == 'POST': hospitalForm = HospitalForm(request.POST) addressForm = AddressForm(request.POST) # Get the valid data from the form if (hospitalForm.is_valid() and addressForm.is_valid()): addr = addressForm.save() addr.save() hosp = hospitalForm.save() hosp.address = addr hosp.save() logUser = User.objects.get_by_natural_key(request.user) logPerson = Person.objects.get(user=logUser) Logger.createLog('Created',logPerson,hosp,hosp) Group.objects.create(name=str(hosp)) return HttpResponseRedirect(reverse('hospital:view')) else: pass else: hospitalForm = HospitalForm() addressForm = AddressForm() context = {'hospitalForm': hospitalForm, 'addressForm': addressForm, 'creation_success': creation_success, } return render(request, 'hospital/create.html', context) @login_required @group_required('Root') def viewHospitals(request): is_root = request.user.groups.filter(name='Root').exists() all_hospitals = Hospital.objects.all() context = {'all_hospitals': all_hospitals, 'is_root': is_root} return render(request, 'hospital/view.html', context) @login_required @group_required('Root') def deleteHospital(request, **kwargs): hospitalID = kwargs.get('pk') hospitalModel = Hospital.objects.get(id=hospitalID) if request.method == 'POST': form = DeleteHospital(request.POST, instance=hospitalModel) if form.is_valid(): logUser = User.objects.get_by_natural_key(request.user) logPerson = Person.objects.get(user=logUser) Logger.createLog('Removed',logPerson,str(Hospital.objects.get(id=hospitalID)),None) Hospital.objects.get(id=hospitalID).delete() # Only have to delete use because doing so deletes linked information # Specifically: Address return HttpResponseRedirect(reverse('hospital:view')) else: form = DeleteHospital(instance=hospitalModel) context = {'form': form, 'hospitalID': hospitalID, 'hospital': hospitalModel} return render(request, 'hospital/delete.html', context) class updateHospital(UpdateView): model = Hospital template_name_suffix = '_form' template_name = 'hospital/hospital_form.html' success_url = reverse_lazy('hospital:view') fields = ('name', 'address') # Todo figure out how to do the updated system log event for default view classes @method_decorator(login_required) @method_decorator(group_required('Root')) def dispatch(self, *args, **kwargs): return super(updateHospital, self).dispatch(*args, **kwargs)
/* * */ package net.community.chest.ui.components.input.checkbox; import net.community.chest.ui.helpers.button.TypedCheckBoxReflectiveProxy; /** * <P>Copyright 2008 as per GPLv2</P> * * @param <B> Type of {@link InputCheckBox} being reflected * @author <NAME>. * @since Jan 13, 2009 3:23:27 PM */ public class InputCheckBoxReflectiveProxy<B extends InputCheckBox> extends TypedCheckBoxReflectiveProxy<Boolean,B> { protected InputCheckBoxReflectiveProxy (Class<B> objClass, boolean registerAsDefault) throws IllegalArgumentException, IllegalStateException { super(objClass, registerAsDefault); } public InputCheckBoxReflectiveProxy (Class<B> objClass) throws IllegalArgumentException { this(objClass, false); } public static final InputCheckBoxReflectiveProxy<InputCheckBox> INPCB= new InputCheckBoxReflectiveProxy<InputCheckBox>(InputCheckBox.class, true); }
#!/bin/sh pow "$1" 0.5
import React from "react"; import { View, ScrollView, StyleSheet } from "react-native"; import { Table, Row } from "react-native-table-component"; import axios from "../utils/axios"; export default class RecordScreen extends React.Component { static navigationOptions = { title: "HISTORIAL" }; constructor(props) { super(props); const options = props.navigation.getParam("options"); this.state = { options, tableHead: ["Pregunta", "Respuesta"], widthArr: [200, 200], questions: [] }; this.loadQuestions(); } render() { const state = this.state; const tableData = []; const options = state.options; const questions = state.questions; if (!questions.length) { return null; } for (let i = 0; i < options.length; i++) { const rowData = []; const option = options[i]; const id = option.question_id; const question = questions[id - 1]; const description = question.description; rowData.push(description); rowData.push(option.description); tableData.push(rowData); } return ( <View style={styles.container}> <ScrollView horizontal={true}> <View> <Table borderStyle={{ borderColor: "#C1C0B9" }}> <Row data={state.tableHead} widthArr={state.widthArr} style={styles.header} textStyle={styles.text} /> </Table> <ScrollView style={styles.dataWrapper}> <Table borderStyle={{ borderColor: "#C1C0B9" }}> {tableData.map((rowData, index) => ( <Row key={index} data={rowData} widthArr={state.widthArr} style={[ styles.row, index % 2 && { backgroundColor: "#F7F6E7" } ]} textStyle={styles.text} /> ))} </Table> </ScrollView> </View> </ScrollView> </View> ); } loadQuestions = async () => { axios.get("questions/options").then(response => { let questions = response.data; console.log(questions); this.setState({ questions }); }); }; } const styles = StyleSheet.create({ container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: "#fff" }, header: { height: 50, backgroundColor: "#537791" }, text: { textAlign: "center", fontWeight: "100" }, dataWrapper: { marginTop: -1 }, row: { height: 40, backgroundColor: "#E7E6E1" } });
from twocode import utils import builtins # a custom execution, written however so it works - nests etc # an alternative to the eval cascade # one implemented as a list going on, a pointer travelling the code structure, carrying its memory? # what is there to carry - just scopes # but! whatever loop it is in could also be implemented to only go 100 steps. or stop. # how? # at best: write threading, start a thread, receive "eval" signals from the queue # and the thread's eval can, base on the node's type, decide to continue executign or not # when it hits the bottom level again and knows it's about to exit, it could read the next # eval command off the queue (nvm it would do that anyway) # IndentationError # FileNotFoundError # EOFError # threading: # context.thread. # frame, parser, stack """ # options: # string length after each token # indices of EOL tokens # analyse "EOL" tokens in the non-transformed tree # a mapping from original tree to this one - even pos to pos # + store original string - ParseInfo # code.info """ # typing fail # no impl # move the exc here. maybe. # sme def add_exceptions(context): def throw(obj): exc = context.exc.RuntimeError(obj, [stack.copy() for stack in context.eval_stack]) raise exc from None context.throw = throw def stmt_throw(node): exc = context.eval(node.tuple, type="expr") context.throw(exc) def try_chain(node): try: with context.ScopeContext(): value = context.eval(node.try_block, type="pass") value = context.stmt_value(value) return value except context.exc.RuntimeError as rt_err: for catch_block in node.catch_blocks: exc = rt_err.exc decl = catch_block.decl if decl and decl.type: type = context.eval(decl.type) else: type = None if type: try: exc = context.convert(exc, type) except context.exc.ConversionError: exc = None if exc: with context.ScopeContext(): if decl and decl.id: context.declare(decl.id, exc, type) value = context.eval(catch_block.block, type="pass") value = context.stmt_value(value) return value finally: if node.finally_block: with context.ScopeContext(): value = context.eval(node.finally_block, type="pass") value = context.stmt_value(value) return value context.instructions.update({ "stmt_throw": stmt_throw, "try_chain": try_chain, "expr_try": lambda node: context.eval(node.try_chain, type="pass"), }) class RuntimeError(builtins.Exception): def __init__(self, exc, eval_stack): super().__init__() self.exc = exc self.eval_stack = eval_stack context.exc.RuntimeError = RuntimeError Object, Class, Func = [context.obj[name] for name in "Object, Class, Func".split(", ")] context.exc_types = utils.Object() def gen_type(name): type = context.obj.Class() context.exc_types[name] = type return type def attach(type, name, **kwargs): def wrap(func): type.__fields__[name] = Func(native=func, **kwargs) return wrap Exception = gen_type("Exception") def gen_exc(name): type = gen_type(name) type.__base__ = Exception return type InternalError = gen_exc("InternalError") SyntaxError = gen_exc("SyntaxError") NameError = gen_exc("NameError") AttributeError = gen_exc("AttributeError") ImportError = gen_exc("ImportError") TypeError = gen_exc("TypeError") ValueError = gen_exc("ValueError") # related to some other unfinished eval business as well context.eval_stack = [[]] old_eval = context.eval pass_exc = tuple(context.exc.values()) def eval(node, type="expr"): context.eval_stack[-1].append(node) try: return old_eval(node, type) except context.exc.RuntimeError: raise except pass_exc: raise # workaround, catching with handle_exc sucks tho except builtins.Exception as exc: context.throw(Object(InternalError, __this__=internal_error_msg(exc))) finally: context.eval_stack[-1].pop() context.eval = eval old_call_func = context.call_func def call_func(*args, **kwargs): # hide this + the exc one in the tb context.eval_stack.append([]) try: return old_call_func(*args, **kwargs) finally: context.eval_stack.pop() def internal_error_msg(exc): lines = [] tb = exc.__traceback__ while True: filename = tb.tb_frame.f_code.co_filename lineno = tb.tb_lineno name = tb.tb_frame.f_code.co_name if name not in "filter eval wrapped".split(): lines.append(" " * 2 + 'File "{}", line {}, in {}'.format(filename, lineno, name)) if tb.tb_next: tb = tb.tb_next else: break lines.append("{}: {}".format(type(exc).__qualname__, str(exc))) return "\n" + "\n".join(lines) context.call_func = call_func def traceback(exc): exc, eval_stack = exc.exc, exc.eval_stack r""" File "<cell>", line 653 M.s() File "H:\Twocode\code\M.2c", line 20, in s f() File "H:\Twocode\code\M.2c", line 39, in f throw Exception() """ lines = [] for stack in eval_stack: if not stack: continue # lexical data from node[0] # metadata at code / stmt? # lexer words iterators # chunks, items # file info, line for node in reversed(stack): type_name = type(node).__name__ if type_name.startswith("stmt"): break line = " " * 4 + str(node).splitlines()[0].lstrip() # or from lex data # we can tell boundmethod's path, but not static # can tell from closure? scope analysis lines.append(line) qualname = context.unwrap(context.operators.qualname.native(exc.__type__)) lines.append("{}: {}".format(qualname, "")) # string operator? msg = "\n".join(lines) if exc.__type__ is InternalError: msg += exc.__this__ return msg context.traceback = traceback def handle_exception(): pass # completely artificial, for when you want to "catch runtime exceptions" in eg getattr code context.handle_exception = handle_exception
<gh_stars>10-100 package com.github.mygreen.cellformatter.number; /** * 数値オブジェクトのファクトリクラス。 * * @version 0.10 * @author T.TSUCHIE * */ public abstract class NumberFactory { /** * 何も加工をしない数値のファクトリクラスの取得。 * @return */ public static NumberFactory nativeNumber() { return new NumberFactory() { @Override public FormattedNumber create(double value) { return new NativeNumber(value); } }; } /** * 小数のファクトリクラスの取得 * @param scale 小数の精度(桁数)。 * @param useSeparator 区切り文字があるかどうか。 * @param permilles 千分率の次数。ゼロと指定した場合は、{@code 1000^0}の意味。 * @return {@link DecimalNumberFactory}のインスタンス。 */ public static DecimalNumberFactory decimalNumber(int scale, boolean useSeparator, final int permilles) { return new DecimalNumberFactory(scale, useSeparator, permilles); } /** * パーセントのファクトリクラスの取得 * @param scale 小数の精度(桁数)。 * @param useSeparator 区切り文字があるかどうか。 * @param permilles 千分率の次数。ゼロと指定した場合は、{@code 1000^0}の意味。 * @return {@link PercentNumberFactory}のインスタンス。 */ public static PercentNumberFactory percentNumber(int scale, boolean useSeparator, final int permilles) { return new PercentNumberFactory(scale, useSeparator, permilles); } /** * 指数のファクトリクラスの取得 * @param scale 小数の精度(桁数)。 * @param useSeparator 区切り文字があるかどうか。 * @return {@link ExponentNumberFactory}のインスタンス。 */ public static ExponentNumberFactory exponentNumber(int scale, boolean useSeparator) { return new ExponentNumberFactory(scale, useSeparator); } /** * 分数のファクトリクラスの取得 * @param denominator 分母の値 * @param exactDenom 分母を直接指定かどうか * @param wholeType 帯分数形式かどうか * @return {@link FractionNumberFactory}のインスタンス。 */ public static FractionNumberFactory fractionNumber(final int denominator, final boolean exactDenom, final boolean wholeType) { return new FractionNumberFactory(denominator, exactDenom, wholeType); } /** * 数値オブジェクトのインスタンスを取得する。 * @param value 変換元数値。 * @return 組み立てた数値オブジェクト。 */ public abstract FormattedNumber create(double value); /** * 整数、小数の数値として作成するクラス。 * */ public static class DecimalNumberFactory extends NumberFactory { private int scale; private boolean useSeparator; private int permilles; public DecimalNumberFactory(final int scale, final boolean useSeparator, final int permilles) { this.scale = scale; this.useSeparator = useSeparator; this.permilles = permilles; } @Override public FormattedNumber create(double value) { FormattedNumber number = new DecimalNumber(value, scale, permilles); number.setUseSeparator(useSeparator); return number; } } /** * 指数として数値を作成するクラス。 * */ public static class ExponentNumberFactory extends NumberFactory { private int scale; private boolean useSeparator; public ExponentNumberFactory(final int scale, final boolean useSeparator) { this.scale = scale; this.useSeparator = useSeparator; } @Override public FormattedNumber create(double value) { FormattedNumber number = new ExponentNumber(value, scale); number.setUseSeparator(useSeparator); return number; } } /** * パーセントとして数値を作成するクラス。 * */ public static class PercentNumberFactory extends NumberFactory { private int scale; private boolean useSeparator; private int permilles; public PercentNumberFactory(final int scale, final boolean useSeparator, final int permilles) { this.scale = scale; this.useSeparator = useSeparator; this.permilles = permilles; } @Override public FormattedNumber create(double value) { FormattedNumber number = new PercentNumber(value, scale, permilles); number.setUseSeparator(useSeparator); return number; } } /** * 分数として数値を作成するクラス * */ public static class FractionNumberFactory extends NumberFactory { /** 分母の値 */ private int denominator; /** 分母を直接指定かどうか */ private boolean exactDenom; /** 帯分数形式かどうか */ private boolean wholeType; public FractionNumberFactory(final int denominator, final boolean exactDenom, final boolean wholeType) { this.denominator = denominator; this.exactDenom = exactDenom; this.wholeType = wholeType; } @Override public FormattedNumber create(double value) { FractionNumber number; if(exactDenom) { number = FractionNumber.createExactDenominator(value, denominator, wholeType); } else { number = FractionNumber.createMaxDenominator(value, denominator, wholeType); } return number; } } }
require "test_helper" class AsyncClientTest < Minitest::Test def test_that_it_has_a_version_number refute_nil ::AsyncClient::VERSION end end
<reponame>ramanaditya/data-structure-and-algorithms<filename>leetcode/math/valid-number.py<gh_stars>10-100 """ ## Questions ### 65. [Valid Number](https://leetcode.com/problems/valid-number/) A valid number can be split up into these components (in order): 1. A decimal number or an integer. 2. (Optional) An 'e' or 'E', followed by an integer. A decimal number can be split up into these components (in order): 1. (Optional) A sign character (either '+' or '-'). 2. One of the following formats: 1. At least one digit, followed by a dot '.'. 2. At least one digit, followed by a dot '.', followed by at least one digit. 3. A dot '.', followed by at least one digit. An integer can be split up into these components (in order): 1. (Optional) A sign character (either '+' or '-'). 2. At least one digit. For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]. Given a string s, return true if s is a valid number. """ # Solutions class Solution: """ Solution is from: <NAME> (aynamron), https://leetcode.com/problems/valid-number/discuss/23728/A-simple-solution-in-Python-based-on-DFA """ def isNumber(self, s: str) -> bool: s = s.lower() # DFA State Transition Table state = [ {}, {'blank': 1, 'sign': 2, 'digit': 3, '.': 4}, {'digit': 3, '.': 4}, {'digit': 3, '.': 5, 'e': 6, 'blank': 9}, {'digit': 5}, {'digit': 5, 'e': 6, 'blank': 9}, {'sign': 7, 'digit': 8}, {'digit': 8}, {'digit': 8, 'blank': 9}, {'blank': 9} ] final_state = [3, 5, 8, 9] current_state = 1 for char in s: if '0' <= char <= '9': char = 'digit' if char == ' ': char = 'blank' if char in ['+', '-']: char = 'sign' if char not in state[current_state]: return False current_state = state[current_state][char] if current_state not in final_state: return False return True # Runtime : 36 ms, faster than 58.20% of Python3 online submissions # Memory Usage : 14.2 MB, less than 61.27% of Python3 online submissions
<gh_stars>0 package proptics import scala.Function.const import cats.data.Const import cats.syntax.either._ import cats.syntax.eq._ import cats.syntax.option._ import cats.{Applicative, Eq, Id, Monoid} import spire.algebra.lattice.Heyting import spire.std.boolean._ import proptics.IndexedTraversal_.wander import proptics.data.{Conj, Disj, First} import proptics.internal.{Forget, Indexed, RunBazaar, Stall} import proptics.profunctor.{Traversing, Wander} import proptics.rank2types.LensLikeWithIndex /** [[AnAffineTraversal_]] has at most one focus, but is not a [[Prism_]]. * * [[AnAffineTraversal_]] is an [[AffineTraversal_]] with fixed type [[proptics.internal.Stall]] [[cats.arrow.Profunctor]] * * @tparam S the source of an [[AnAffineTraversal_]] * @tparam T the modified source of an [[AnAffineTraversal_]] * @tparam A the focus of an [[AnAffineTraversal_]] * @tparam B the modified focus of an [[AnAffineTraversal_]] */ abstract class AnAffineTraversal_[S, T, A, B] extends Serializable { self => private[proptics] def apply(pab: Stall[A, B, A, B]): Stall[A, B, S, T] /** view the focus of an [[AnAffineTraversal_]] or return the modified source of an [[AnAffineTraversal_]] */ def viewOrModify(s: S): Either[T, A] /** view an optional focus of an [[AnAffineTraversal_]] */ final def preview(s: S): Option[A] = foldMap(s)(a => First(a.some)).runFirst /** set the modified focus of an [[AnAffineTraversal_]] */ final def set(b: B): S => T = over(const(b)) /** set the focus of an [[AnAffineTraversal_]] conditionally if it is not None */ final def setOption(b: B): S => Option[T] = overOption(const(b)) /** modify the focus type of an [[AnAffineTraversal_]] using a function, resulting in a change of type to the full structure */ final def over(f: A => B): S => T = overF[Id](f) /** modify the focus of a [[AnAffineTraversal_]] using a function conditionally if it is not None, resulting in a change of type to the full structure */ final def overOption(f: A => B): S => Option[T] = s => preview(s).map(a => set(f(a))(s)) /** synonym for [[traverse]], flipped */ final def overF[F[_]: Applicative](f: A => F[B])(s: S): F[T] = traverse(s)(f) /** modify the focus type of an [[AnAffineTraversal_]] using a [[cats.Functor]], resulting in a change of type to the full structure */ final def traverse[F[_]: Applicative](s: S)(f: A => F[B]): F[T] = { val stall: Stall[A, B, S, T] = toStall stall .viewOrModify(s) .fold(Applicative[F].pure, a => Applicative[F].map(f(a))(stall.set(s)(_))) } /** test whether there is no focus or a predicate holds for the focus of a [[Prism_]] */ final def forall(f: A => Boolean): S => Boolean = forall(_)(f) /** test whether there is no focus or a predicate holds for the focus of an [[AnAffineTraversal_]], using a [[spire.algebra.lattice.Heyting]] algebra */ final def forall[R: Heyting](s: S)(f: A => R): R = foldMap(s)(Conj[R] _ compose f).runConj /** test whether a predicate holds for the focus of an [[AnAffineTraversal_]] */ final def exists(f: A => Boolean): S => Boolean = foldMap(_)(Disj[Boolean] _ compose f).runDisj /** test whether a predicate does not hold for the focus of an [[AnAffineTraversal_]] */ final def notExists(f: A => Boolean): S => Boolean = s => !exists(f)(s) /** test whether the focus of an [[AnAffineTraversal_]] contains a given value */ final def contains(a: A)(s: S)(implicit ev: Eq[A]): Boolean = exists(_ === a)(s) /** test whether the focus of an [[AnAffineTraversal_]] does not contain a given value */ final def notContains(a: A)(s: S)(implicit ev: Eq[A]): Boolean = !contains(a)(s) /** check if the [[AnAffineTraversal_]] does not contain a focus */ final def isEmpty(s: S): Boolean = preview(s).isEmpty /** check if the [[AnAffineTraversal_]] contains a focus */ final def nonEmpty(s: S): Boolean = !isEmpty(s) /** find if the focus of an [[AnAffineTraversal_]] is satisfying a predicate. */ final def find(p: A => Boolean): S => Option[A] = preview(_).filter(p) /** convert an [[AnAffineTraversal_]] to the pair of functions that characterize it */ final def withAffineTraversal[R](f: (S => Either[T, A]) => (S => B => T) => R): R = { val stall: Stall[A, B, S, T] = toStall f(stall.viewOrModify)(stall.set) } /** convert an [[AnAffineTraversal_]] to an [[proptics.internal.Stall]] */ final def toStall: Stall[A, B, S, T] = self(Stall(_.asRight[B], const(identity[B]))) /** transform an [[AnAffineTraversal_]] to an [[AffineTraversal_]] */ final def asAffineTraversal: AffineTraversal_[S, T, A, B] = withAffineTraversal(AffineTraversal_[S, T, A, B]) /** transform an [[AnAffineTraversal_]] to a [[Fold_]] */ final def asFold: Fold_[S, T, A, B] = new Fold_[S, T, A, B] { override private[proptics] def apply[R: Monoid](forget: Forget[R, A, B]): Forget[R, S, T] = Forget(self.foldMap(_)(forget.runForget)) } /** compose a [[AnAffineTraversal_]] with a function lifted to a [[Getter_]] */ final def to[C, D](f: A => C): Fold_[S, T, C, D] = compose(Getter_[A, B, C, D](f)) /** compose an [[AnAffineTraversal_]] with an [[Iso_]] */ final def compose[C, D](other: Iso_[A, B, C, D]): AnAffineTraversal_[S, T, C, D] = AnAffineTraversal_ { s: S => self.viewOrModify(s).map(other.view) }(s => d => self.over(other.set(d))(s)) /** compose an [[AnAffineTraversal_]] with an [[AnIso_]] */ final def compose[C, D](other: AnIso_[A, B, C, D]): AnAffineTraversal_[S, T, C, D] = AnAffineTraversal_ { s: S => self.viewOrModify(s).map(other.view) }(s => d => self.over(other.set(d))(s)) /** compose an [[AnAffineTraversal_]] with a [[Lens_]] */ final def compose[C, D](other: Lens_[A, B, C, D]): AnAffineTraversal_[S, T, C, D] = AnAffineTraversal_ { s: S => self.viewOrModify(s).map(other.view) }(s => d => self.over(other.set(d))(s)) /** compose an [[AnAffineTraversal_]] with an [[ALens_]] */ final def compose[C, D](other: ALens_[A, B, C, D]): AnAffineTraversal_[S, T, C, D] = AnAffineTraversal_ { s: S => self.viewOrModify(s).map(other.view) }(s => d => self.over(other.set(d))(s)) /** compose an [[AnAffineTraversal_]] with a [[Prism_]] */ final def compose[C, D](other: Prism_[A, B, C, D]): AnAffineTraversal_[S, T, C, D] = AnAffineTraversal_ { s: S => self.viewOrModify(s).flatMap(other.viewOrModify(_).leftMap(self.set(_)(s))) }(s => d => self.over(other.set(d))(s)) /** compose an [[AnAffineTraversal_]] with an [[APrism_]] */ final def compose[C, D](other: APrism_[A, B, C, D]): AnAffineTraversal_[S, T, C, D] = AnAffineTraversal_ { s: S => self.viewOrModify(s).flatMap(other.viewOrModify(_).leftMap(self.set(_)(s))) }(s => d => self.over(other.set(d))(s)) /** compose an [[AnAffineTraversal_]] with an [[AffineTraversal_]] */ final def compose[C, D](other: AffineTraversal_[A, B, C, D]): AnAffineTraversal_[S, T, C, D] = AnAffineTraversal_ { s: S => self.viewOrModify(s).flatMap(other.viewOrModify(_).leftMap(self.set(_)(s))) }(s => d => self.over(other.set(d))(s)) /** compose an [[AnAffineTraversal_]] with an [[AnAffineTraversal_]] */ final def compose[C, D](other: AnAffineTraversal_[A, B, C, D]): AnAffineTraversal_[S, T, C, D] = AnAffineTraversal_ { s: S => self.viewOrModify(s).flatMap(other.viewOrModify(_).leftMap(self.set(_)(s))) }(s => d => self.over(other.set(d))(s)) /** compose an [[AnAffineTraversal_]] with a [[Traversal_]] */ final def compose[C, D](other: Traversal_[A, B, C, D]): Traversal_[S, T, C, D] = new Traversal_[S, T, C, D] { override private[proptics] def apply[P[_, _]](pab: P[C, D])(implicit ev: Wander[P]): P[S, T] = { val traversing = new Traversing[S, T, C, D] { override def apply[F[_]](f: C => F[D])(s: S)(implicit ev: Applicative[F]): F[T] = self.traverse(s)(other.traverse(_)(f)) } ev.wander(traversing)(pab) } } /** compose an [[AnAffineTraversal_]] with an [[ATraversal_]] */ final def compose[C, D](other: ATraversal_[A, B, C, D]): ATraversal_[S, T, C, D] = ATraversal_(new RunBazaar[* => *, C, D, S, T] { override def apply[F[_]](pafb: C => F[D])(s: S)(implicit ev: Applicative[F]): F[T] = self.traverse(s)(other.traverse(_)(pafb)) }) /** compose an [[AnAffineTraversal_]] with a [[Setter_]] */ final def compose[C, D](other: Setter_[A, B, C, D]): Setter_[S, T, C, D] = new Setter_[S, T, C, D] { override private[proptics] def apply(pab: C => D): S => T = self.over(other.over(pab)) } /** compose an [[AnAffineTraversal_]] with a [[Getter_]] */ final def compose[C, D](other: Getter_[A, B, C, D]): Fold_[S, T, C, D] = self compose other.asFold /** compose an [[AnAffineTraversal_]] with a [[Fold_]] */ final def compose[C, D](other: Fold_[A, B, C, D]): Fold_[S, T, C, D] = new Fold_[S, T, C, D] { override def apply[R: Monoid](forget: Forget[R, C, D]): Forget[R, S, T] = Forget(self.foldMap(_)(other.foldMap(_)(forget.runForget))) } /** compose an [[AnAffineTraversal_]] with an [[IndexedLens_]] */ final def compose[I, C, D](other: IndexedLens_[I, A, B, C, D]): IndexedTraversal_[I, S, T, C, D] = wander(new LensLikeWithIndex[I, S, T, C, D] { override def apply[F[_]](f: ((C, I)) => F[D])(implicit ev: Applicative[F]): S => F[T] = self.overF(other.overF(f)) }) /** compose an [[AnAffineTraversal_]] with an [[AnIndexedLens_]] */ final def compose[I, C, D](other: AnIndexedLens_[I, A, B, C, D]): IndexedTraversal_[I, S, T, C, D] = wander(new LensLikeWithIndex[I, S, T, C, D] { override def apply[F[_]](f: ((C, I)) => F[D])(implicit ev: Applicative[F]): S => F[T] = self.overF(other.overF(f)) }) /** compose an [[AnAffineTraversal_]] with an [[IndexedTraversal_]] */ final def compose[I, C, D](other: IndexedTraversal_[I, A, B, C, D]): IndexedTraversal_[I, S, T, C, D] = wander(new LensLikeWithIndex[I, S, T, C, D] { override def apply[F[_]](f: ((C, I)) => F[D])(implicit ev: Applicative[F]): S => F[T] = self.overF(other.overF(f)) }) /** compose an [[AnAffineTraversal_]] with an [[IndexedSetter_]] */ final def compose[I, C, D](other: IndexedSetter_[I, A, B, C, D]): IndexedSetter_[I, S, T, C, D] = new IndexedSetter_[I, S, T, C, D] { override private[proptics] def apply(indexed: Indexed[* => *, I, C, D]): S => T = self.over(other.over(indexed.runIndex)) } /** compose an [[AnAffineTraversal_]] with an [[IndexedGetter_]] */ final def compose[I, C, D](other: IndexedGetter_[I, A, B, C, D]): IndexedFold_[I, S, T, C, D] = new IndexedFold_[I, S, T, C, D] { override private[proptics] def apply[R: Monoid](indexed: Indexed[Forget[R, *, *], I, C, D]): Forget[R, S, T] = Forget(self.foldMap(_)(indexed.runIndex.runForget compose other.view)) } /** compose an [[AnAffineTraversal_]] with an [[IndexedFold_]] */ final def compose[I, C, D](other: IndexedFold_[I, A, B, C, D]): IndexedFold_[I, S, T, C, D] = new IndexedFold_[I, S, T, C, D] { override private[proptics] def apply[R: Monoid](indexed: Indexed[Forget[R, *, *], I, C, D]): Forget[R, S, T] = Forget(self.foldMap(_)(other.foldMap(_)(indexed.runIndex.runForget))) } private def foldMap[R: Monoid](s: S)(f: A => R): R = overF[Const[R, *]](Const[R, B] _ compose f)(s).getConst } object AnAffineTraversal_ { /** create a polymorphic [[AnAffineTraversal_]] from an [[AnAffineTraversal_]] encoded in [[proptics.internal.Stall]] */ private[proptics] def apply[S, T, A, B](f: Stall[A, B, A, B] => Stall[A, B, S, T]): AnAffineTraversal_[S, T, A, B] = new AnAffineTraversal_[S, T, A, B] { self => override def apply(stall: Stall[A, B, A, B]): Stall[A, B, S, T] = f(stall) /** view the focus of an [[AnAffineTraversal_]] or return the modified source of an [[AnAffineTraversal_]] */ override def viewOrModify(s: S): Either[T, A] = f(Stall(_.asRight[B], const(identity[B]))).viewOrModify(s) } /** create a polymorphic [[AnAffineTraversal_]] from a getter/setter pair */ final def apply[S, T, A, B](viewOrModify: S => Either[T, A])(set: S => B => T): AnAffineTraversal_[S, T, A, B] = AnAffineTraversal_ { stall: Stall[A, B, A, B] => Stall( s => viewOrModify(s).fold(_.asLeft[A], stall.viewOrModify(_).leftMap(set(s)(_))), s => b => viewOrModify(s).fold(identity, a => set(s)(stall.set(a)(b))) ) } /** polymorphic identity of an [[AnAffineTraversal_]] */ final def id[S, T]: AnAffineTraversal_[S, T, S, T] = AnAffineTraversal_[S, T, S, T] { s: S => s.asRight[T] }(const(identity[T])) } object AnAffineTraversal { /** create a monomorphic [[AnAffineTraversal]], using preview and setter functions */ final def fromOption[S, A](preview: S => Option[A])(set: S => A => S): AnAffineTraversal[S, A] = AnAffineTraversal { s: S => preview(s).fold(s.asLeft[A])(_.asRight[S]) }(set) /** create a monomorphic [[AnAffineTraversal]], using a partial function and a setter function */ final def fromPartial[S, A](preview: PartialFunction[S, A])(set: S => A => S): AnAffineTraversal[S, A] = fromOption(preview.lift)(set) /** create a monomorphic [[AnAffineTraversal]] from a matcher function that produces an Either and a setter function * * the matcher function returns an Either to allow for type-changing prisms in the case where the input does not match. */ final def apply[S, A](viewOrModify: S => Either[S, A])(set: S => A => S): AnAffineTraversal[S, A] = AnAffineTraversal_(viewOrModify)(set) /** monomorphic identity of an [[AnAffineTraversal]] */ final def id[S]: AnAffineTraversal[S, S] = AnAffineTraversal_.id[S, S] }
#!/bin/bash # Copyright (c) 2021 Red Hat, Inc. # Copyright Contributors to the Open Cluster Management project set -e echo "> Running build/run-e2e-tests.sh" export DOCKER_IMAGE_AND_TAG=${1} # make docker/run
package test.service.shop; import java.util.List; import model.Shop; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import service.ShopService; import test.base.BaseTestCase; @ContextConfiguration({ "shop.xml" }) public class ShopTest extends BaseTestCase { @Autowired private ShopService shopService; @Autowired private Shop shopToAdd; @Before public void setup() { shopToAdd = shopService.createShop(shopToAdd); } @After public void after() { shopService.archiveShop(shopToAdd.getShopKey()); } @Test public void testCreateShop() { Assert.assertTrue(shopToAdd.getShopKey() > 0); } @Test public void testFindShop() { Shop shop = shopService.findShop(shopToAdd.getShopKey()); Assert.assertNotNull(shop); Assert.assertTrue(shop.getShopKey() == shopToAdd.getShopKey()); } @Test public void testFindShops() { List<Shop> shops = shopService.findAllShops(); Assert.assertTrue(!shops.isEmpty()); } }
from . import library def get_density(food_item): """ Give the area and volume density with a food object. In kilogram per cube meter. Args: food_item: The json object of food information. """ if food_item['group'] in library.density_library: if food_item['name'] in library.density_library[food_item['group']]: return library.density_library[food_item['group']][food_item['name']] else: return [*library.density_library[food_item['group']].values()][0] else: return 0.0, 0.0
EXP_DIR=output/r50_ms_smca_e50 if [ ! -d "output" ]; then mkdir output fi if [ ! -d "${EXP_DIR}" ]; then mkdir ${EXP_DIR} fi srun -p cluster_name \ --job-name=SAM-DETR \ --gres=gpu:8 \ --ntasks=8 \ --ntasks-per-node=8 \ --cpus-per-task=2 \ --kill-on-bad-exit=1 \ python main.py \ --batch_size 2 \ --smca \ --multiscale \ --epochs 50 \ --lr_drop 40 \ --output_dir ${EXP_DIR} \ 2>&1 | tee ${EXP_DIR}/detailed_log.txt
<filename>examples/extensions-zalando/src/main/java/org/zalando/intellij/swagger/examples/extensions/zalando/validator/zally/model/ZallyClientError.java package org.zalando.intellij.swagger.examples.extensions.zalando.validator.zally.model; public class ZallyClientError extends RuntimeException { private final String message; public ZallyClientError(String message) { this.message = message; } @Override public String getMessage() { return message; } }
def find_index(arr, element): # iterate over the array for i in range(len(arr)): if arr[i] == element: return i return -1 arr = [2, 3, 4, 5, 6] element = 6 index = find_index(arr, element) if index == -1: print('Item not found in the array.') else: print('Element found at index', index)
#!/usr/bin/env bash set -o errexit set -o nounset set -o pipefail SCRIPT_ROOT=$(dirname "${BASH_SOURCE[0]}")/.. DIFFROOT="${SCRIPT_ROOT}/api/openapi-spec" TMP_DIFFROOT="${SCRIPT_ROOT}/_tmp/api/openapi-spec" _tmp="${SCRIPT_ROOT}/_tmp" cleanup() { rm -rf "${_tmp}" } trap "cleanup" EXIT SIGINT cleanup mkdir -p "${TMP_DIFFROOT}" cp -a "${DIFFROOT}"/* "${TMP_DIFFROOT}" bash "${SCRIPT_ROOT}/hack/update-swagger-docs.sh" echo "diffing ${DIFFROOT} against freshly generated files" ret=0 diff -Naupr "${DIFFROOT}" "${TMP_DIFFROOT}" || ret=$? cp -a "${TMP_DIFFROOT}"/* "${DIFFROOT}" if [[ $ret -eq 0 ]] then echo "${DIFFROOT} up to date." else echo "${DIFFROOT} is out of date. Please run hack/update-swagger-docs.sh" exit 1 fi
package fr.syncrase.ecosyst.aop.insertdata; import fr.syncrase.ecosyst.domain.Racine; import fr.syncrase.ecosyst.repository.RacineRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Example; import java.util.Optional; public class InsertRacines { private final Logger log = LoggerFactory.getLogger(InsertRacines.class); private RacineRepository racineRepository; public InsertRacines(RacineRepository racineRepository) { this.racineRepository = racineRepository; } public void insertAllRacines() { try { for (String type : new String[]{"pivotante", "fasciculaire", "adventice", "tracante", "contrefort", "crampon", "echasse", "aerienne", "liane", "ventouse", "pneumatophore"}) { getOrInsertRacine(new Racine().type(type)); } } catch (Exception e) { log.error("Error when trying to insert in table Racine. {" + e.getMessage() + "}"); } } private Racine getOrInsertRacine(Racine racine) { if (!racineRepository.exists(Example.of(racine))) { racineRepository.save(racine); } else { Optional<Racine> returned = racineRepository.findOne(Example.of(racine)); if (returned.isPresent()) { racine = returned.get(); log.info("Existing racine : " + racine); } else { log.error("Unable to get instance of : " + racine); } } return racine; } }
#!/bin/bash set -euo pipefail IFS=$'\n\t' SCRIPT_ROOT="$(cd -P "$( dirname "$0" )" && pwd)" SDK_VERSION="2.0.0-preview3-006845" if [ -z "${HOME:-}" ]; then export HOME="$SCRIPT_ROOT/.home" mkdir "$HOME" fi export DOTNET_CLI_TELEMETRY_OPTOUT=1 export DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 export NUGET_PACKAGES="$SCRIPT_ROOT/packages/" "$SCRIPT_ROOT/init-tools.sh" CLIPATH="$SCRIPT_ROOT/Tools/dotnetcli" SDKPATH="$CLIPATH/sdk/$SDK_VERSION" set -x $CLIPATH/dotnet restore tasks/Microsoft.DotNet.SourceBuild.Tasks/Microsoft.DotNet.SourceBuild.Tasks.csproj $CLIPATH/dotnet build tasks/Microsoft.DotNet.SourceBuild.Tasks/Microsoft.DotNet.SourceBuild.Tasks.csproj rm -rf "$NUGET_PACKAGES/*" $CLIPATH/dotnet $SDKPATH/MSBuild.dll $SCRIPT_ROOT/build.proj "$@" /t:WriteDynamicPropsToStaticPropsFiles /p:GeneratingStaticPropertiesFile=true $CLIPATH/dotnet $SDKPATH/MSBuild.dll $SCRIPT_ROOT/build.proj "$@" /t:GenerateRootFs $CLIPATH/dotnet $SDKPATH/MSBuild.dll $SCRIPT_ROOT/build.proj /flp:v=detailed /clp:v=detailed "$@"
<gh_stars>0 #include <iostream> using namespace std; int main(){ try { int age = 5; if(age >= 18) cout << "Access granted" << endl; else throw 500;//some error number } catch(...){//when you don't know the data type to receive cout << "Error" << endl; } return 0; }
export const version = "ethers/5.6.4";
<filename>tests/test_comment.py import unittest from app import db from app.models import Comment, User class CommentModelTest(unittest.TestCase): def setUp(self): self.user_bre = User(username = 'Brenda',password = '<PASSWORD>', email = '<EMAIL>') self.new_comment = Comment(blog_id=2,title='comment',comment='test_comment',user = self.user_bre) def tearDown(self): Comment.query.delete() User.query.delete() def test_check_instance_variables(self): self.assertEquals(self.new_comment.blog_id,2) self.assertEquals(self.new_comment.title,'comment') self.assertEquals(self.new_comment.comment,'test_comment') self.assertEquals(self.new_comment.user,self.user_bre) def test_save_comment(self): self.new_comment.save_comment() self.assertTrue(len(Comment.query.all())>0) def test_get_comment_by_id(self): self.new_comment.save_comment() get_comments = comment.get_comments(2) self.assertTrue(len(get_comments) == 2)
<gh_stars>1-10 /* * MIT License * * Copyright (c) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.jamsimulator.jams.event; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class EventGeneratorTest { static boolean received0 = false, received2 = false; @Test void test() { SimpleEventBroadcast caller = new SimpleEventBroadcast(); caller.registerListeners(new TestListener(), false); TestEvent testEvent = new TestEvent(5); caller.callEvent(testEvent); assertTrue(received0, "Listeners not called."); //Test2 should be called. assertTrue(received2, "Test 2 is not called."); } private static class TestListener { @Listener public void test0(TestEvent event) { received0 = true; assertEquals(5, event.getValue(), "Incorrect value"); System.out.println("Test0"); } @Listener(priority = 10) public void test1(TestEvent event) { assertFalse(received0, "Test0 called first!"); System.out.println("Test1"); } @Listener public void test2(Event event) { received2 = true; } } private static class TestEvent extends Event { private final int value; public TestEvent(int value) { this.value = value; } public int getValue() { return value; } } }
/** * @author github.com/luncliff (<EMAIL>) */ #undef NDEBUG #include <cassert> #include <gsl/gsl> #include <coroutine/return.h> using namespace std; using namespace coro; auto save_current_handle_to_frame(int& status) -> frame_t { auto on_return = gsl::finally([&status]() { // change the status when the frame is going to be destroyed status += 1; }); status += 1; co_await suspend_always{}; status += 1; } int main(int, char*[]) { int status = 0; coroutine_handle<void> coro = save_current_handle_to_frame(status); assert(status == 1); assert(coro.address() != nullptr); coro.resume(); // the coroutine reached end // so, `gsl::finally` should changed the status assert(coro.done()); assert(status == 3); coro.destroy(); return 0; }
import random def generateRandomNumber(min_n, max_n): return random.randint(min_n, max_n)
/* Copyright (c) 2021 Skyward Experimental Rocketry * Author: <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <sensors/Sensor.h> #include <functional> #include "CurrentSensorData.h" /** * @brief Common class for current sense sensors * * It needs a transfer function to convert the read voltage into current. */ class CurrentSensor : public Sensor<CurrentSensorData> { public: static constexpr int MOVING_AVAERAGE_N = 20; CurrentSensor(std::function<ADCData()> getADCVoltage_, std::function<float(float)> adcToCurrent_) : getADCVoltage(getADCVoltage_), adcToCurrent(adcToCurrent_) { last_sample.current = 0; } bool init() override { return true; }; bool selfTest() override { return true; }; ///< Converts the voltage value to pressure CurrentSensorData sampleImpl() override { ADCData adc_data = getADCVoltage(); if (last_sample.current == 0) { last_sample.current = adcToCurrent(adc_data.voltage); } CurrentSensorData current_data; current_data.adc_timestamp = adc_data.adc_timestamp; current_data.channel_id = adc_data.channel_id; current_data.voltage = adc_data.voltage; // Moving average current_data.current = last_sample.current * MOVING_AVAERAGE_COMP_COEFF; current_data.current += adcToCurrent(adc_data.voltage) * MOVING_AVAERAGE_COEFF; return current_data; }; private: ///< Function that returns the adc voltage std::function<ADCData()> getADCVoltage; ///< Function that converts adc voltage to current std::function<float(float)> adcToCurrent; static constexpr float MOVING_AVAERAGE_COEFF = 1 / (float)MOVING_AVAERAGE_N; static constexpr float MOVING_AVAERAGE_COMP_COEFF = 1 - MOVING_AVAERAGE_COEFF; };
<gh_stars>1-10 from ...Helpers.types import Types def object_val_def(commands, data, node): prop_var = data.get_var(node.name.name, object_namespace=data.context_objects[-1]) node.value.compile_vm(commands, data) commands.store_value(prop_var, type=Types.DYNAMIC)
<gh_stars>0 import re import pulsar as psr # Break apart a list into blocks, where the original list # was separated by separator (regex). The first separator is included # if includesep is True def block_list(lst, separator, includesep = False): curline = 0 ret = [] sep = re.compile(separator) for i in range(0, len(lst)): if sep.match(lst[i]): if i != curline: # If the block isn't empty ret.append(lst[curline:i]) curline = i if includesep: curline = i+1 # left over if curline != len(lst): ret.append(lst[curline:]) return ret def read_basis_file(path): validcart = ["spherical", "cartesian"] basismap = {} rawlines = [ l.strip() for l in open(path, 'r').readlines() ] # remove comments and lines = [ l for l in rawlines if not l.startswith("!") and l != "" ] # Get the type from the first line cart = lines[0].lower() if not cart in validcart: raise PulsarException("Unknown shell type in basis set", "file", path, "type", cart) iscart = (cart == "cartesian") bstype = psr.ShellType.CartesianGaussian if iscart else psr.ShellType.SphericalGaussian atomblocks = block_list(lines[1:], r"\*\*\*\*", True) for atomlines in atomblocks: shellvec = [] element, num = atomlines[0].split() shellblocks = block_list(atomlines[1:], r"\D+ *\d+ *\d+(\.\d+)?") for shelllines in shellblocks: am, nprim, num = shelllines[0].split() nprim = int(nprim) rawprims = [ l.split() for l in shelllines[1:] ] prims = [ [ p[0], p[1:] ] for p in rawprims ] if len(prims) != nprim: raise PulsarException("Problem parsing basis set: nprim not equal to the actual number of primitives", "element", element, "file", path, "nprim", nprim, "actual", len(prims)) # Check to see if all primitives have the same number of # general contractions for p in prims: ngen = len(prims[0][1]) if len(p[1]) != ngen: raise psr.PulsarException("Ragged number of general contractions", "element", element, "file", path, "nprim", nprim, "expected", ngen, "actual", len(p[1])) # We have all the information to create a shell now amint = psr.string_to_am(am) bsi = psr.BasisShellInfo(bstype, amint, nprim, ngen) for i in range(0, len(prims)): bsi.set_primitive(i, float(prims[i][0]), [ float(d) for d in prims[i][1] ]) shellvec.append(bsi) element_Z = psr.atomic_z_from_symbol(element) basismap[element_Z] = shellvec return basismap
<reponame>MowHogz/Minesweeper<gh_stars>0 from miner import miner from miner import counter from kbr import press import time import os from scrn import clr cmnd = clr() def clearer(): os.system(cmnd) def Input(text): try: return input(text) except: print("Sorry, Numbers only") return Input(text) mines = Input("enter the number of mines") height = 10 width = 10 mat = [] for row in range(height): mat.append([]) for column in range(width): mat[row].append([False,0]) matrix = miner(mat,mines,height,width) gaming = True counter(matrix,height,width) def key_mov(d,loc,height,width): if 'w' in d and loc[0] > 0: loc[0] += -1 if 's' in d and loc[0] < height - 1: loc[0] += 1 if 'a' in d and loc[1] > 0: loc[1] += -1 if 'd' in d and loc[1] < width - 1: loc[1] += 1 if 'e' in d:#explore return 'e' elif 'f' in d:#flag return 'f' return False def chooser(matrix,loc): unchosen = True while unchosen: print loc d = [] time.sleep(0.05) while d == []: time.sleep(0.01) press(d) a = key_mov(d,loc,len(matrix),len(matrix[0])) text = "\n" for row_n in range(len(matrix)): text += "\n" text += "--"*len(matrix[0]) text += "\n" for column_n in range(len(matrix[row_n])): unit = matrix[row_n][column_n] text += "|" if loc == [row_n,column_n]: text += 'O' elif unit[0] == '#': text += '#' elif unit[0]: text += str(unit[1]) else: text += ' ' clearer() print (text) if a: return a def printer(matrix): text = "\n" for row_n in range(len(matrix)): text += "\n" text += "--"*len(matrix[0]) text += "\n" for column_n in range(len(matrix[row_n])): unit = matrix[row_n][column_n] text += "|" if unit[0] == '#': text += '#' elif unit[0]: text += str(unit[1]) else: text += ' ' clearer() print (text) def round(matrix,loc): printer(matrix) a = chooser(matrix,loc) #row = Input('please enter a row number') #col = Input("plase enter a column number") if a == 'e': if matrix[loc[0]][loc[1]][1] == 'x': print "you landed on a bomb" return False else: zero(matrix,loc[0],loc[1]) return True if a == 'f': matrix[loc[0]][loc[1]][0] = '#' return True def zero(matrix,row,column): if matrix[row][column][0]: return True matrix[row][column][0] = True if matrix[row][column][1] == 0: if row > 0: zero(matrix,row-1,column) if column > 0: zero(matrix,row-1,column-1) if column < len(matrix[0])-1: zero(matrix,row-1,column+1) if row < len(matrix)-1: zero(matrix,row+1,column) if column > 0: zero(matrix,row+1,column-1) if column < len(matrix[0])-1: zero(matrix,row+1,column+1) if column > 0: zero(matrix,row,column-1) if column < len(matrix[0])-1: zero(matrix,row,column+1) return True return False loc = [0,0] while gaming: if not round(matrix,loc): gaming = False
<reponame>LanderlYoung/wire /* * Copyright 2013 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.wire.protos.RepeatedPackedAndMap; import com.squareup.wire.protos.alltypes.AllTypes; import java.util.Arrays; import java.util.List; import okio.ByteString; import org.junit.Test; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; public class GsonTest { private static final String JSON = "{\"opt_int32\":111," + "\"opt_uint32\":112," + "\"opt_sint32\":113," + "\"opt_fixed32\":114," + "\"opt_sfixed32\":115," + "\"opt_int64\":116," + "\"opt_uint64\":117," + "\"opt_sint64\":118," + "\"opt_fixed64\":119," + "\"opt_sfixed64\":120," + "\"opt_bool\":true," + "\"opt_float\":122.0," + "\"opt_double\":123.0," + "\"opt_string\":\"124\"," + "\"opt_bytes\":\"e30=\"," + "\"opt_nested_enum\":\"A\"," + "\"opt_nested_message\":{\"a\":999}," + "\"req_int32\":111," + "\"req_uint32\":112," + "\"req_sint32\":113," + "\"req_fixed32\":114," + "\"req_sfixed32\":115," + "\"req_int64\":116," + "\"req_uint64\":117," + "\"req_sint64\":118," + "\"req_fixed64\":119," + "\"req_sfixed64\":120," + "\"req_bool\":true," + "\"req_float\":122.0," + "\"req_double\":123.0," + "\"req_string\":\"124\"," + "\"req_bytes\":\"e30=\"," + "\"req_nested_enum\":\"A\"," + "\"req_nested_message\":{\"a\":999}," + "\"rep_int32\":[111,111]," + "\"rep_uint32\":[112,112]," + "\"rep_sint32\":[113,113]," + "\"rep_fixed32\":[114,114]," + "\"rep_sfixed32\":[115,115]," + "\"rep_int64\":[116,116]," + "\"rep_uint64\":[117,117]," + "\"rep_sint64\":[118,118]," + "\"rep_fixed64\":[119,119]," + "\"rep_sfixed64\":[120,120]," + "\"rep_bool\":[true,true]," + "\"rep_float\":[122.0,122.0]," + "\"rep_double\":[123.0,123.0]," + "\"rep_string\":[\"124\",\"124\"]," + "\"rep_bytes\":[\"e30=\",\"e30=\"]," + "\"rep_nested_enum\":[\"A\",\"A\"]," + "\"rep_nested_message\":[{\"a\":999},{\"a\":999}]," + "\"pack_int32\":[111,111]," + "\"pack_uint32\":[112,112]," + "\"pack_sint32\":[113,113]," + "\"pack_fixed32\":[114,114]," + "\"pack_sfixed32\":[115,115]," + "\"pack_int64\":[116,116]," + "\"pack_uint64\":[117,117]," + "\"pack_sint64\":[118,118]," + "\"pack_fixed64\":[119,119]," + "\"pack_sfixed64\":[120,120]," + "\"pack_bool\":[true,true]," + "\"pack_float\":[122.0,122.0]," + "\"pack_double\":[123.0,123.0]," + "\"pack_nested_enum\":[\"A\",\"A\"]," + "\"map_int32_int32\":{\"1\":2}," + "\"map_string_string\":{\"key\":\"value\"}," + "\"map_string_message\":{\"message\":{\"a\":1}}," + "\"map_string_enum\":{\"enum\":\"A\"}," + "\"ext_opt_int32\":2147483647," + "\"ext_opt_int64\":-4611686018427387726," + "\"ext_opt_uint64\":13835058055282163890," + "\"ext_opt_sint64\":-4611686018427387726," + "\"ext_opt_bool\":true," + "\"ext_opt_float\":1234500.0," + "\"ext_opt_double\":1.2345E67," + "\"ext_opt_nested_enum\":\"A\"," + "\"ext_opt_nested_message\":{\"a\":999}," + "\"ext_rep_int32\":[2147483647,2147483647]," + "\"ext_rep_uint32\":[]," + "\"ext_rep_sint32\":[]," + "\"ext_rep_fixed32\":[]," + "\"ext_rep_sfixed32\":[]," + "\"ext_rep_int64\":[]," + "\"ext_rep_uint64\":[13835058055282163890,13835058055282163890]," + "\"ext_rep_sint64\":[-4611686018427387726,-4611686018427387726]," + "\"ext_rep_fixed64\":[]," + "\"ext_rep_sfixed64\":[]," + "\"ext_rep_bool\":[true,true]," + "\"ext_rep_float\":[1234500.0,1234500.0]," + "\"ext_rep_double\":[1.2345E67,1.2345E67]," + "\"ext_rep_string\":[]," + "\"ext_rep_bytes\":[]," + "\"ext_rep_nested_enum\":[\"A\",\"A\"]," + "\"ext_rep_nested_message\":[{\"a\":999},{\"a\":999}]," + "\"ext_pack_int32\":[2147483647,2147483647]," + "\"ext_pack_uint32\":[]," + "\"ext_pack_sint32\":[]," + "\"ext_pack_fixed32\":[]," + "\"ext_pack_sfixed32\":[]," + "\"ext_pack_int64\":[]," + "\"ext_pack_uint64\":[13835058055282163890,13835058055282163890]," + "\"ext_pack_sint64\":[-4611686018427387726,-4611686018427387726]," + "\"ext_pack_fixed64\":[]," + "\"ext_pack_sfixed64\":[]," + "\"ext_pack_bool\":[true,true]," + "\"ext_pack_float\":[1234500.0,1234500.0]," + "\"ext_pack_double\":[1.2345E67,1.2345E67]," + "\"ext_pack_nested_enum\":[\"A\",\"A\"]," + "\"ext_map_int32_int32\":{\"1\":2}," + "\"ext_map_string_string\":{\"key\":\"value\"}," + "\"ext_map_string_message\":{\"message\":{\"a\":1}}," + "\"ext_map_string_enum\":{\"enum\":\"A\"}}"; // Return a two-element list with a given repeated value @SuppressWarnings("unchecked") private static <T> List<T> list(T x) { return Arrays.asList(x, x); } private static AllTypes.Builder createBuilder() { ByteString bytes = ByteString.of((byte) 123, (byte) 125); AllTypes.NestedMessage nestedMessage = new AllTypes.NestedMessage.Builder().a(999).build(); return new AllTypes.Builder() .opt_int32(111) .opt_uint32(112) .opt_sint32(113) .opt_fixed32(114) .opt_sfixed32(115) .opt_int64(116L) .opt_uint64(117L) .opt_sint64(118L) .opt_fixed64(119L) .opt_sfixed64(120L) .opt_bool(true) .opt_float(122.0F) .opt_double(123.0) .opt_string("124") .opt_bytes(bytes) .opt_nested_enum(AllTypes.NestedEnum.A) .opt_nested_message(nestedMessage) .req_int32(111) .req_uint32(112) .req_sint32(113) .req_fixed32(114) .req_sfixed32(115) .req_int64(116L) .req_uint64(117L) .req_sint64(118L) .req_fixed64(119L) .req_sfixed64(120L) .req_bool(true) .req_float(122.0F) .req_double(123.0) .req_string("124") .req_bytes(bytes) .req_nested_enum(AllTypes.NestedEnum.A) .req_nested_message(nestedMessage) .rep_int32(list(111)) .rep_uint32(list(112)) .rep_sint32(list(113)) .rep_fixed32(list(114)) .rep_sfixed32(list(115)) .rep_int64(list(116L)) .rep_uint64(list(117L)) .rep_sint64(list(118L)) .rep_fixed64(list(119L)) .rep_sfixed64(list(120L)) .rep_bool(list(true)) .rep_float(list(122.0F)) .rep_double(list(123.0)) .rep_string(list("124")) .rep_bytes(list(bytes)) .rep_nested_enum(list(AllTypes.NestedEnum.A)) .rep_nested_message(list(nestedMessage)) .pack_int32(list(111)) .pack_uint32(list(112)) .pack_sint32(list(113)) .pack_fixed32(list(114)) .pack_sfixed32(list(115)) .pack_int64(list(116L)) .pack_uint64(list(117L)) .pack_sint64(list(118L)) .pack_fixed64(list(119L)) .pack_sfixed64(list(120L)) .pack_bool(list(true)) .pack_float(list(122.0F)) .pack_double(list(123.0)) .pack_nested_enum(list(AllTypes.NestedEnum.A)) .map_int32_int32(singletonMap(1, 2)) .map_string_string(singletonMap("key", "value")) .map_string_message(singletonMap("message", new AllTypes.NestedMessage(1))) .map_string_enum(singletonMap("enum", AllTypes.NestedEnum.A)) .ext_opt_int32(Integer.MAX_VALUE) .ext_opt_int64(Long.MIN_VALUE / 2 + 178) .ext_opt_uint64(Long.MIN_VALUE / 2 + 178) .ext_opt_sint64(Long.MIN_VALUE / 2 + 178) .ext_opt_bool(true) .ext_opt_float(1.2345e6F) .ext_opt_double(1.2345e67) .ext_opt_nested_enum(AllTypes.NestedEnum.A) .ext_opt_nested_message(nestedMessage) .ext_rep_int32(list(Integer.MAX_VALUE)) .ext_rep_uint64(list(Long.MIN_VALUE / 2 + 178)) .ext_rep_sint64(list(Long.MIN_VALUE / 2 + 178)) .ext_rep_bool(list(true)) .ext_rep_float(list(1.2345e6F)) .ext_rep_double(list(1.2345e67)) .ext_rep_nested_enum(list(AllTypes.NestedEnum.A)) .ext_rep_nested_message(list(nestedMessage)) .ext_pack_int32(list(Integer.MAX_VALUE)) .ext_pack_uint64(list(Long.MIN_VALUE / 2 + 178)) .ext_pack_sint64(list(Long.MIN_VALUE / 2 + 178)) .ext_pack_bool(list(true)) .ext_pack_float(list(1.2345e6F)) .ext_pack_double(list(1.2345e67)) .ext_pack_nested_enum(list(AllTypes.NestedEnum.A)) .ext_map_int32_int32(singletonMap(1, 2)) .ext_map_string_string(singletonMap("key", "value")) .ext_map_string_message(singletonMap("message", new AllTypes.NestedMessage(1))) .ext_map_string_enum(singletonMap("enum", AllTypes.NestedEnum.A)); } private final Gson gson = new GsonBuilder() .registerTypeAdapterFactory(new WireTypeAdapterFactory()) .disableHtmlEscaping() .create(); @Test public void serializationOfAllTypes() { AllTypes allTypes = createBuilder().build(); String json = gson.toJson(allTypes); assertThat(json).isEqualTo(JSON); } @Test public void deserializationOfAllTypes() { AllTypes allTypes = createBuilder().build(); AllTypes parsed = gson.fromJson(JSON, AllTypes.class); assertThat(parsed).isEqualTo(allTypes); assertThat(parsed.toString()).isEqualTo(allTypes.toString()); assertThat(gson.toJson(parsed)).isEqualTo(gson.toJson(allTypes)); } @Test public void omitsUnknownFields() { AllTypes.Builder builder = createBuilder(); builder.addUnknownField(9000, FieldEncoding.FIXED32, 9000); builder.addUnknownField(9001, FieldEncoding.FIXED64, 9001L); builder.addUnknownField(9002, FieldEncoding.LENGTH_DELIMITED, ByteString.of((byte) '9', (byte) '0', (byte) '0', (byte) '2')); builder.addUnknownField(9003, FieldEncoding.VARINT, 9003L); AllTypes allTypes = builder.build(); String json = gson.toJson(allTypes); assertThat(json).isEqualTo(JSON); } @Test public void nullRepeatedField() { RepeatedPackedAndMap parsed = gson.fromJson("{rep_int32=null,pack_int32=null,map_int32_int32=null}", RepeatedPackedAndMap.class); assertThat(parsed.rep_int32).isEmpty(); assertThat(parsed.pack_int32).isEmpty(); assertThat(parsed.map_int32_int32).isEmpty(); } }
#!/usr/bin/env bash # exit on error set -e kubectl=${KUBECTL_PATH:-$(>&2 echo '✗ KUBECTL_PATH environment variable not found, please supply the path to a kubectl with the appropriate cluster selected as current context'; exit 1)} # expects env GITHUB_TOKEN to be set # note that this needs to be run again as soon as the GITHUB_TOKEN is replaced echo 'bootstrapping or updating flux' flux bootstrap github \ --components-extra=image-reflector-controller,image-automation-controller \ --kubeconfig=$KUBECTL_PATH \ --owner=public-transport \ --repository=infrastructure \ --private \ --read-write-key \ --branch=main \ --path=kubernetes/cluster # we use a gpg key to encrypt secrets uploaded to github and decrypt them on the # cluster. use the command # gpg --full-generate-key # to generate a 4096-bit RSA key pair, if you don't have one yet. you can then # find out the secret key's id (to use it as GPG_SECRET_KEY_ID below) by running # gpg --list-secret-keys # if you have questions, you can also refer to the official flux docs regarding # this topic: https://fluxcd.io/docs/guides/mozilla-sops/ gpg_secret_key_id=${GPG_SECRET_KEY_ID:-$(>&2 echo '✗ GPG_SECRET_KEY_ID environment variable not found, please supply the id of a secret key in your gpg keychain to use for secrets decryption in the cluster (check bootstrap.sh for instructions if you do not have such a key yet)'; exit 1)} # you can re-run this with a new key id, just make sure to re-encrypt all secrets with the new key as well echo 'creating or updating secret key' gpg --list-secret-keys "$GPG_SECRET_KEY_ID" > /dev/null # unlike --export, this fails if no key with given id exists gpg --export-secret-keys --armor "${GPG_SECRET_KEY_ID}" | kubectl create secret generic sops-gpg \ --kubeconfig=$KUBECTL_PATH \ --namespace=flux-system \ --from-file=sops.asc=/dev/stdin \ --dry-run=client \ --output=yaml | kubectl apply \ -f - \ --kubeconfig=$KUBECTL_PATH SOPS_YAML_PATH=$(dirname "$0")/secrets/.sops.yaml cat <<EOF > ${SOPS_YAML_PATH} creation_rules: - path_regex: .*.yaml encrypted_regex: ^(data|stringData)$ pgp: ${GPG_SECRET_KEY_ID} EOF gpg --export --armor "${GPG_SECRET_KEY_ID}" > $(dirname "$0")/secrets/.sops.pub.asc echo 'if you used this script on new github repository (instead of just updating an existing setup), make sure to also create an empty branch "gh-pages", you can do so by running `git switch --orphan gh-pages && git commit --allow-empty -m "initial commit" && git push origin gh-pages`. this is required for automatic helm chart publishing.'
<gh_stars>10-100 // // Utility.h // Hiyoko // // Created by 天々座理世 on 2018/08/15. // Copyright © 2018 MAL Updater OS X Group. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @class AFHTTPSessionManager; @class AFHTTPRequestSerializer; @class AFJSONRequestSerializer; @class AFJSONResponseSerializer; @class AFHTTPResponseSerializer; @interface Utility : NSObject + (NSString *)urlEncodeString:(NSString *)string; + (NSString *)appendstringwithArray:(NSArray *) a; + (NSString *)statusFromDateRange:(NSString *)start toDate:(NSString *)end; + (NSDate *)stringDatetoDate:(NSString *)stringdate; + (NSString *)stringDatetoLocalizedDateString:(NSString *)stringdate; + (AFHTTPSessionManager*)jsonmanager; + (AFHTTPSessionManager*)httpmanager; + (AFHTTPSessionManager*)syncmanager; + (AFJSONRequestSerializer *)jsonrequestserializer; + (AFHTTPRequestSerializer *)httprequestserializer; + (AFJSONResponseSerializer *)jsonresponseserializer; + (AFHTTPResponseSerializer *)httpresponseserializer; + (double)calculatedays:(NSArray *)list; + (NSString *)dateIntervalToDateString:(double)timeinterval; + (NSString *)convertAnimeType:(NSString *)type; + (NSNumber *)getLastUpdatedDateWithResponseObject:(id)responseObject withService:(int)service; + (NSDate *)dateStringToDate:(NSString *)datestring; @end
<reponame>yannzido/new // Filters an array of objects excluding specified object key export function selectedFilter(arr: any[], search: string, excluded?: string): any[] { // Clean the search string const mysearch = search.toString().toLowerCase(); if (mysearch.trim() === '') { return arr; } const filtered = arr.filter((g: any) => { let filteredKeys = Object.keys(g); // If there is an excluded key remove it from the keys if (excluded) { filteredKeys = filteredKeys.filter((value) => { return value !== 'id'; }); } return filteredKeys.find((key: string) => { return g[key] .toString() .toLowerCase() .includes(mysearch); }); }); return filtered; } // Checks if the given WSDL URL valid export function isValidWsdlURL(str: string) { const pattern = new RegExp('(^(https?):\/\/\/?)[-a-zA-Z0-9]'); return !!pattern.test(str); } // Checks if the given REST URL is valid export function isValidRestURL(str: string) { return isValidWsdlURL(str); }
<reponame>flyaway1217/FeVER # !/usr/bin/env python3 # -*- coding:utf-8 -*- # # Author: Flyaway - <EMAIL> # Blog: zhouyichu.com # # Python release: 3.4.5 # # Date: 2017-03-07 11:57:32 # Last modified: 2019-04-05 09:54:27 """ Config the logger for the system. There are two different handlers for logger: - stream: logs information to the console, such as the loss and using time. - file: logs debug and information to the log file for further diagnosis. """ import logging project_name = 'FeVER' def initLogger(log_path): logger = logging.getLogger(project_name) logger.setLevel(logging.DEBUG) # Config the formatter formatter = logging.Formatter('%(asctime)s-%(levelname)s: %(message)s') # Config the stream handler stream = logging.StreamHandler() stream.setLevel(logging.INFO) stream.setFormatter(formatter) logger.addHandler(stream) # Config the file handler fileHandler = logging.FileHandler(log_path, mode='a') fileHandler.setLevel(logging.DEBUG) fileHandler.setFormatter(formatter) logger.addHandler(fileHandler)
<filename>huatuo/src/main/java/com/huatuo/util/UnitConversionUtil.java package com.huatuo.util; /** * 单位转换 */ public class UnitConversionUtil { /** * 文件大小 单位转换 */ public static String formatSize(float size) { long kb = 1024; long mb = (kb * 1024); long gb = (mb * 1024); if (size < kb) { return String.format("%d B", (int) size); } else if (size < mb) { return String.format("%.2f KB", size / kb); // 保留两位小数 } else if (size < gb) { return String.format("%.2f MB", size / mb); } else { return String.format("%.2f GB", size / gb); } } /** * 距离转换小于1000m的显示?m大于1000m的显示?km * * @param size * @return */ public static String formatDistance(double size) { long m = 1000; if (size < m) { return String.format("%.2f m", size); } else { return String.format("%.2f km", size / m); // 保留两位小数 } } }
#!/bin/bash cat <<HEREDOC > /root/user-data.sh #!/bin/bash ################################################ ######## Install packages and binaries ################################################ cat <<EOF > /etc/yum.repos.d/kubernetes.repo [kubernetes] name=Kubernetes baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64 enabled=1 gpgcheck=1 repo_gpgcheck=1 gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg exclude=kube* EOF setenforce 0 yum install -y docker systemctl enable docker systemctl start docker yum install -y kubelet-1.13.1 kubeadm-1.13.1 kubectl-1.13.1 kubernetes-cni-0.6.0-0 --disableexcludes=kubernetes cat <<EOF > /etc/default/kubelet KUBELET_KUBEADM_EXTRA_ARGS=--cgroup-driver=systemd EOF echo '1' > /proc/sys/net/bridge/bridge-nf-call-iptables curl -s https://api.github.com/repos/kubernetes-sigs/kustomize/releases/latest |\ grep browser_download |\ grep linux |\ cut -d '"' -f 4 |\ xargs curl -O -L chmod u+x kustomize_*_linux_amd64 sudo mv kustomize_*_linux_amd64 /usr/bin/kustomize sudo yum install -y git ################################################ ######## Deploy kubernetes master ################################################ kubeadm init --apiserver-bind-port 8443 --token 2iqzqm.85bs0x6miyx1nm7l --apiserver-cert-extra-sans=$(curl icanhazip.com) --pod-network-cidr=192.168.0.0/16 -v 6 # Enable networking by default. kubectl apply -f https://raw.githubusercontent.com/cloudnativelabs/kube-router/master/daemonset/kubeadm-kuberouter.yaml --kubeconfig /etc/kubernetes/admin.conf # Binaries expected under /opt/cni/bin are actually under /usr/libexec/cni if [[ ! -e /opt/cni/bin ]]; then mkdir -p /opt/cni/bin cp /usr/libexec/cni/bridge /opt/cni/bin cp /usr/libexec/cni/loopback /opt/cni/bin cp /usr/libexec/cni/host-local /opt/cni/bin fi mkdir -p /root/.kube cp -i /etc/kubernetes/admin.conf /root/.kube/config chown $(id -u):$(id -g) /root/.kube/config ################################################ ######## Deploy machine-api plane ################################################ git clone https://github.com/openshift/cluster-api-provider-azure.git cd cluster-api-provider-azure cat <<EOF > secret.yaml apiVersion: v1 kind: Secret metadata: name: test namespace: default type: Opaque data: azure_client_id: FILLIN azure_client_secret: FILLIN azure_region: ZWFzdHVzMg== azure_resource_prefix: b3M0LWNvbW1vbg== azure_resourcegroup: b3M0LWNvbW1vbg== azure_subscription_id: FILLIN azure_tenant_id: FILLIN EOF sudo kubectl apply -f secret.yaml kustomize build config | sudo kubectl apply -f - kubectl apply -f config/master-user-data-secret.yaml kubectl apply -f config/master-machine.yaml ################################################ ######## generate worker machineset user data ################################################ cat <<WORKERSET > /root/workerset-user-data.sh #!/bin/bash cat <<WORKERHEREDOC > /root/workerset-user-data.sh #!/bin/bash cat <<EOF > /etc/yum.repos.d/kubernetes.repo [kubernetes] name=Kubernetes baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64 enabled=1 gpgcheck=1 repo_gpgcheck=1 gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg exclude=kube* EOF setenforce 0 yum install -y docker systemctl enable docker systemctl start docker yum install -y kubelet-1.13.1 kubeadm-1.13.1 kubernetes-cni-0.6.0-0 --disableexcludes=kubernetes cat <<EOF > /etc/default/kubelet KUBELET_KUBEADM_EXTRA_ARGS=--cgroup-driver=systemd EOF echo '1' > /proc/sys/net/bridge/bridge-nf-call-iptables kubeadm join $(curl icanhazip.com):8443 --token 2iqzqm.85bs0x6miyx1nm7l --discovery-token-unsafe-skip-ca-verification WORKERHEREDOC bash /root/workerset-user-data.sh 2>&1 > /root/workerset-user-data.logs WORKERSET ################################################ ######## deploy worker user data and machineset ################################################ # NOTE: The secret is rendered twice, the first time when it's run during bootstrapping. # During bootstrapping, /root/workerset-user-data.sh does not exist yet. # So \$ needs to be used so the command is executed the second time # the script is executed. cat <<EOF > /root/worker-secret.yaml apiVersion: v1 kind: Secret metadata: name: worker-user-data-secret namespace: default type: Opaque data: userData: \$(cat /root/workerset-user-data.sh | base64 --w=0) EOF sudo kubectl apply -f /root/worker-secret.yaml sudo kubectl apply -f config/worker-machineset.yaml HEREDOC bash /root/user-data.sh 2>&1 > /root/user-data.logs