text
stringlengths
1
1.05M
#!/bin/sh # Stops script execution if a command has an error set -e INSTALL_ONLY=0 PORT="" # Loop through arguments and process them: https://pretzelhands.com/posts/command-line-flags for arg in "$@"; do case $arg in -i|--install) INSTALL_ONLY=1 ; shift ;; -p=*|--port=*) PORT="${arg#*=}" ; shift ;; # TODO Does not allow --port 1234 *) break ;; esac done if [ ! -f "/usr/local/bin/filebrowser" ]; then echo "Installing Filebrowser. Please wait..." cd $RESOURCES_PATH curl -fsSL https://raw.githubusercontent.com/filebrowser/get/master/get.sh | bash else echo "Filebrowser is already installed" fi # Run if [ $INSTALL_ONLY = 0 ] ; then if [ -z "$PORT" ]; then read -p "Please provide a port for starting Filebrowser: " PORT fi echo "Starting Filebrowser on port "$PORT # Create tool entry for tooling plugin echo '{"id": "filebrowser-link", "name": "Filebrowser", "url_path": "/tools/'$PORT'/", "description": "Browse and manage workspace files"}' > $HOME/.workspace/tools/filebrowser.json /usr/local/bin/filebrowser --port=$PORT sleep 15 fi
import React from 'react' import { useSelector, useDispatch } from 'react-redux' import { parseMindmap } from '@symbiotes/effects/' import { history } from '@lib/routing' import MindMap from './mindmap' export const MindMapWrapper = () => { const teamId = useSelector(state => state.teams.currentTeam) const desk = useSelector(state => state.desks.currentDesk ? state.desks.desks[state.desks.currentDesk] : null ) const dispatch = useDispatch() const handleConvert = tree => { dispatch(parseMindmap(tree, teamId)) } if (!(history.location.state || desk)) { history.push('/') } let name = history.location.state && history.location.state.name let { innerWidth } = window let mindmap = {} let nodes = [] if (desk) { let deskWidth = desk.mindmap.data.name.length * 7 + 55 let deskCoords = { x: innerWidth / 2 - deskWidth / 2, y: 60 } let data = { ...desk.mindmap.data, x: deskCoords.x, y: deskCoords.y } nodes.push(data) mindmap = { ...desk.mindmap, data, children: desk.mindmap.children.map((column, colIndex) => { let deskStep = innerWidth / desk.mindmap.children.length let columnWidth = column.data.name.length * 7 + 55 let colCoords = { x: (colIndex + 1 / 2) * deskStep - columnWidth / 2, y: 140 } data = { ...column.data, x: colCoords.x, y: colCoords.y, startX: deskCoords.x + deskWidth / 2, startY: deskCoords.y + 25 } nodes.push(data) return { ...column, data, children: column.children.map((card, cardIndex) => { let cardStep = deskStep / column.children.length let cardWidth = column.data.name.length * 7 + 55 let cardCoords = { x: (cardIndex + 1 / 2) * cardStep - cardWidth / 2 + deskStep * colIndex, y: 220 } data = { ...card.data, x: cardCoords.x, y: cardCoords.y, startX: colCoords.x + columnWidth / 2, startY: colCoords.y + 25 } nodes.push(data) return { ...card, data, children: card.children.map((item, itemIndex) => { let itemCoords = { x: cardCoords.x + cardWidth / 2, y: cardCoords.y + (itemIndex + 1) * 60 } data = { ...item.data, x: itemCoords.x - (cardWidth / 10) * itemIndex, y: itemCoords.y, // startX: cardCoords.x + cardWidth / 2, startX: cardCoords.x, startY: cardCoords.y + 25 } nodes.push(data) return { ...item, data } }) } }) } }) } } else { mindmap = { data: { name: name, id: 1, x: innerWidth / 2 - 20, y: 80, color: '000000', level: 1 }, level: 1, children: [] } nodes = [ { name: name, id: 1, x: innerWidth / 2 - 20, y: 80, color: '000000', level: 1 } ] } const handleSave = tree => { console.log(tree) } return ( <MindMap onConvert={handleConvert} onSave={handleSave} mindmap={mindmap} nodes={nodes} editable={!desk} /> ) }
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+0+512-NER/model --tokenizer_name model-configs/1024-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+0+512-NER/512+0+512-FW-first-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function remove_all_but_function_words_first_half_quarter --eval_function penultimate_quarter_eval
import csv def refine_customer_csv(csv_file): with open(csv_file, newline='') as csvfile: reader = csv.reader(csvfile) refined_list = [] for row in reader: # Remove rows with empty fields if row[0] and row[1] and row[2] and row[3] and row[4]: # Refine fields first_name = row[0].capitalize() last_name = row[1].capitalize() email = row[2].lower() address = row[3].replace(" ", "") phone_no = row[4].replace("-", "") # Create refined row refined_row = [first_name, last_name, email, address, phone_no] refined_list.append(refined_row) return refined_list
import { getAttributeForHtmlTemplateInsert } from '../utils/ui'; import AbstractView from './abstract-view'; export default class TextBlockView extends AbstractView { constructor({container, classList='', inlineStyles = '', text = ''}) { super(container); this._classList = classList; this._inlineStyles = inlineStyles; this._text = text; } static create({container, classList, inlineStyles, text}) { const c = new TextBlockView({container, classList, inlineStyles, text}); c.render(); return c; } getTemplate() { return `<div ${getAttributeForHtmlTemplateInsert('class', this._classList)} ${getAttributeForHtmlTemplateInsert('style', this._inlineStyles)}>${this._text}</div>`; } init() { } setText(text) { this._text = text; this.getElement().textContent = text; } setInnerTemplate(template) { this._text = template; this.getElement().innerHTML = template; } }
def mean_csv(csv, n): csv_arr = csv.split(",") total = 0.0 for number in csv_arr: total += float(number) return total/n mean_csv("1.2,2.3,3.4,4.5", 4)
config() { NEW="$1" OLD="$(dirname $NEW)/$(basename $NEW .new)" # If there's no config file by that name, mv it over: if [ ! -r $OLD ]; then mv $NEW $OLD elif [ "$(cat $OLD | md5sum)" = "$(cat $NEW | md5sum)" ]; then # toss the redundant copy rm $NEW fi # Otherwise, we leave the .new copy for the admin to consider... } preserve_perms() { NEW="$1" OLD="$(dirname $NEW)/$(basename $NEW .new)" if [ -e $OLD ]; then cp -a $OLD ${NEW}.incoming cat $NEW > ${NEW}.incoming mv ${NEW}.incoming $NEW fi config $NEW } preserve_perms etc/rc.d/rc.salt-master.new preserve_perms etc/rc.d/rc.salt-minion.new preserve_perms etc/rc.d/rc.salt-syndic.new
#!/usr/bin/python # -*- coding: utf-8 -*- import os import json # import logging # logger = logging.getLogger(__name__) __softwarename__ = 'QMarkdowner' __author__ = "dragondjf" __url__ = "dragondjf.github.com" __description__ = ''' This is a SoftwareFrame based on qframer.qt with Metro Style. ''' __logoico__ = os.sep.join([os.getcwd(), 'skin', 'images', 'MarkdownLife.ico']) __version__ = '1.0.0' logo_ico = __logoico__ logo_img_url = os.sep.join([os.getcwd(), 'skin', 'images', 'qmarkdowner.png']) logo_title = u'' from mainwindowcfg import mainwindowsettings from utildialogcfg import utidialogsettings from shortcutcfg import shortcutsettings from markdownthemecfg import markdownthemes try: with open(os.sep.join([os.getcwd(), 'options', 'windowsoptions.json']), 'r') as f: windowsoptions = json.load(f) # logger.info('Load windowsoptions from file') except Exception, e: # logger.exception(e) # logger.info('Load windowsoptions from local') windowsoptions = { 'mainwindow': mainwindowsettings, 'shortcutsettings': shortcutsettings, 'splashimg': os.sep.join([os.getcwd(), 'skin', 'images', 'splash.png']), 'markdownthemes': markdownthemes } windowsoptions.update(utidialogsettings)
const router = require('express').Router(); const auth = require('../../middleware/auth'); const ProfileController = require('../../controllers/ProfileController'); const validator = require('../../controllers/validator'); const checkObjectId = require('../../middleware/checkObjectId'); /** * @api {post} /api/profile/ Post profile * @apiName Post profile * @apiGroup Profile * @apiParam {String} Location * @apiParam {String} Bio * @apiParam {String} Facebook URL * @apiParam {String} Twitter URL * @apiParam {String} Instagram URL */ router.post('/', auth, validator.profilePost, ProfileController.postProfile); /** * @api {get} /api/profile/me Get profile * @apiName Get profile * @apiGroup Profile * @apiParam {User} Authenticated user */ router.get('/me', auth, ProfileController.getProfile); /** * @api {get} /api/profile Get all profiles * @apiName Get all profiles * @apiGroup Profile */ router.get('/', ProfileController.getAllProfiles); /** * @api {get} /api/profile/user/:id Get user's profile from id * @apiName Get user's profile from id * @apiGroup Profile * @apiParam {id} User id */ router.get('/user/:user_id', checkObjectId('user_id'), ProfileController.getProfileFromId); /** * @api {delete} /api/profile/ Delete user * @apiName Delete user * @apiGroup Profile * @apiParam {User} Authenticated user */ router.delete('/', auth, ProfileController.deleteUser); /** * @api {delete} /api/profile/:id Remove user * @apiName Remove user * @apiGroup Profile * @apiParam {id} User id */ router.delete('/:id', auth, ProfileController.removeUser); module.exports = router;
fn f(input: Vec<i32>) -> Vec<i32> { let mut cumulative_sum = 0; let mut output = Vec::new(); for num in input { cumulative_sum += num; output.push(cumulative_sum); } output } #[cfg(test)] mod tests { use super::*; #[test] fn test_cumulative_sum() { assert_eq!(f(vec![1, 2, 3, 4]), vec![1, 3, 6, 10]); assert_eq!(f(vec![-1, 2, -3, 4]), vec![-1, 1, -2, 2]); assert_eq!(f(vec![-1, -2, -3, -4]), vec![-1, -3, -6, -10]); } }
<gh_stars>1-10 import HttpService from '../../src/HttpService/HttpService'; import Application from '../../src/HttpApplication/Application'; var FooService = HttpService({ '$get /' (){ this.resolve('I GET Service', 304) }, '$post /baz': { f: class Foo { }, meta: { description: 'Baz Helper', arguments: { bazValue: 'string' } }, process: [ function (req) { this.resolve('POST:' + req.body.bazValue) } ] } }); var app; UTest({ '$before' (done){ Application.create({ configs: null, config: { debug: true } }) .done(function(app_){ app = app_; app .handlers .registerService('^/foo', FooService) ; done(); }) }, 'get' (done){ app .execute('/foo', 'get') .fail(assert.avoid()) .done(function(content, statusCode){ eq_(statusCode, 304); eq_(content, 'I GET Service'); }) .always(done); }, 'post' (done){ app .execute('/foo/baz', 'post', { bazValue: 'bazzy' }) .fail(assert.avoid()) .done(function(content, statusCode){ eq_(statusCode, 200); eq_(content, 'POST:bazzy'); }) .always(done); }, 'post - invalid' (done){ app .execute('/foo/baz', 'post', { bazValue: 10 }) .done(assert.avoid()) .fail(function(error, statusCode){ eq_(statusCode, 400); eq_(error.name, 'RequestError'); eq_(error.message, 'Invalid type. Expect: string Property: bazValue'); }) .always(() => { done(); }); } })
<gh_stars>1-10 package mindustry.ui.dialogs; import arc.input.*; import arc.scene.ui.*; import arc.util.*; import mindustry.gen.*; import mindustry.graphics.*; public class ControlsDialog extends KeybindDialog{ public ControlsDialog(){ setFillParent(true); title.setAlignment(Align.center); titleTable.row(); titleTable.add(new Image()).growX().height(3f).pad(4f).get().setColor(Pal.accent); } @Override public void addCloseButton(){ buttons.addImageTextButton("$back", Icon.left, this::hide).size(230f, 64f); keyDown(key -> { if(key == KeyCode.ESCAPE || key == KeyCode.BACK) hide(); }); } }
#!/bin/bash set -e ABSOLUTE_SCRIPT=`readlink -m $0` SCRIPT_DIR=`dirname ${ABSOLUTE_SCRIPT}` RUN_DIR="$1" # define RENDER_PIPELINE_BIN, BASE_DATA_URL, exitWithErrorAndUsage(), ensureDirectoryExists(), getRunDirectory(), createLogDirectory() . /groups/flyTEM/flyTEM/render/pipeline/bin/pipeline_common.sh ${RENDER_PIPELINE_BIN}/check_logs.sh ${RUN_DIR} echo """ Stage parameters loaded from `ls ${RUN_DIR}/stage_parameters.*.json` """ cd ${RUN_DIR}/logs ${SCRIPT_DIR}/14_report_all_stats.sh log*.txt
function func(arg) { return arg + 'Bar'; } console.log(func('Foo'));
<reponame>GiantAxeWhy/skyline-vue<gh_stars>1-10 // Copyright 2021 99cloud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { isOsDisk } from 'resources/volume'; import client from 'client'; import Base from 'stores/base'; export class InstanceVolumeStore extends Base { get client() { return client.nova.servers.volumeAttachments; } get isSubResource() { return true; } getFatherResourceId = (params) => params.serverId; get paramsFunc() { return (params) => { const { id, serverId, all_projects, projectId, serverName, ...rest } = params; return rest; }; } get mapperBeforeFetchProject() { return (data, filters) => { const { projectId } = filters; return { ...data, project_id: projectId, }; }; } get mapper() { return (volume) => ({ ...volume, disk_tag: isOsDisk(volume) ? 'os_disk' : 'data_disk', host: volume['os-vol-host-attr:host'], }); } async listDidFetch(items, allProjects, filters) { if (items.length === 0) { return items; } const { serverName, serverId } = filters; const { project_id, project_name } = items[0]; const results = await Promise.all( items.map((it) => { const { volumeId } = it; return client.cinder.volumes.show(volumeId); }) ); const volumes = results.map((result) => { const { volume } = result; const { attachments = [] } = volume; const newAttachments = attachments.filter( (it) => it.server_id === serverId ); newAttachments.forEach((it) => { it.server_name = serverName; }); volume.attachments = newAttachments; return { ...volume, project_id, project_name, }; }); return volumes; } } const globalInstanceVolumeStore = new InstanceVolumeStore(); export default globalInstanceVolumeStore;
printf "Generating Local Token ..." && sleep 60 token=$(curl -s -H "Content-Type: application/json" -H "Authorization: Basic aHVza3lDSVVzZXI6aHVza3lDSVBhc3N3b3Jk" http://localhost:8888/api/1.0/token -X POST -d '{"repositoryURL": "https://github.com/ZupIT/horus.git"}' | awk -F '"' '{print $4}') if [ $? -eq 0 ]; then echo " done" else echo " error. Try running make generate-local-token" fi echo "export HORUS_CLIENT_TOKEN=\"$token\"" >> .env
func maxPossibleScore(_ scores: [Int]) -> Int { var maxScore = 0 var dp = Array(repeating: 0, count: scores.count + 2) for i in 2..<scores.count + 2 { dp[i] = max(dp[i - 1], dp[i - 2]) + scores[i - 2] if dp[i] >= 100 { break } maxScore = dp[i] } return maxScore } // Test let scores = [10, 20, 30, 40, 50, 60, 70, 80, 90] print(maxPossibleScore(scores)) // Output: 240
import Foundation import RxSwift import Action struct EditTaskViewModel { let taskName: Observable<String> let errors: Observable<Error> private let editTaskAction: Action<String, Void> private let taskNameSubject: BehaviorSubject<String> private let errorsSubject: PublishSubject<Error> init(initialTaskName: String) { taskNameSubject = BehaviorSubject(value: initialTaskName) taskName = taskNameSubject.asObservable() errorsSubject = PublishSubject() errors = errorsSubject.asObservable() editTaskAction = Action<String, Void> { [unowned self] newTaskName in self.taskNameSubject.onNext(newTaskName) // Perform task editing logic here // If an error occurs, emit it through errorsSubject return Observable.empty() } } }
package com.supanadit.restsuite.listener; import javax.swing.event.MouseInputAdapter; import java.awt.*; import java.awt.event.MouseEvent; public class DragListener extends MouseInputAdapter { Point location; MouseEvent pressed; public void mousePressed(MouseEvent me) { pressed = me; } public void mouseDragged(MouseEvent me) { Component component = me.getComponent(); location = component.getLocation(location); int x = location.x - pressed.getX() + me.getX(); int y = location.y - pressed.getY() + me.getY(); component.setLocation(x, y); } }
#!/bin/bash ##PBS -l nodes=1:ppn=1,walltime=00:05:00 ##PBS -l mem=1gb ##PBS -q fast cd /home/hnoorazar/analog_codes/00_post_biofix/02_find_analogs_county_avg ########### ########### RCP 45 ########### ########### w_precip, no_gen3 cat /home/hnoorazar/analog_codes/parameters/county_avg_file_names | while read LINE ; do cp 03_template_loc_GFDLG.sh ./rcp45_qsubs/GFDLG/q_rcp45_w_precip_$LINE.sh sed -i s/precip_type/w_precip/g ./rcp45_qsubs/GFDLG/q_rcp45_w_precip_$LINE.sh sed -i s/emission_type/rcp45/g ./rcp45_qsubs/GFDLG/q_rcp45_w_precip_$LINE.sh sed -i s/int_file/"$LINE"/g ./rcp45_qsubs/GFDLG/q_rcp45_w_precip_$LINE.sh done ########### no_precip, no_gen3 cat /home/hnoorazar/analog_codes/parameters/county_avg_file_names | while read LINE ; do cp 03_template_loc_GFDLG.sh ./rcp45_qsubs/GFDLG/q_rcp45_no_precip_$LINE.sh sed -i s/precip_type/no_precip/g ./rcp45_qsubs/GFDLG/q_rcp45_no_precip_$LINE.sh sed -i s/emission_type/rcp45/g ./rcp45_qsubs/GFDLG/q_rcp45_no_precip_$LINE.sh sed -i s/int_file/"$LINE"/g ./rcp45_qsubs/GFDLG/q_rcp45_no_precip_$LINE.sh done ########### ########### RCP 85 ########### ########### w_precip, no_gen3 cat /home/hnoorazar/analog_codes/parameters/county_avg_file_names | while read LINE ; do cp 03_template_loc_GFDLG.sh ./rcp85_qsubs/GFDLG/q_rcp85_w_precip_$LINE.sh sed -i s/precip_type/w_precip/g ./rcp85_qsubs/GFDLG/q_rcp85_w_precip_$LINE.sh sed -i s/emission_type/rcp85/g ./rcp85_qsubs/GFDLG/q_rcp85_w_precip_$LINE.sh sed -i s/int_file/"$LINE"/g ./rcp85_qsubs/GFDLG/q_rcp85_w_precip_$LINE.sh done ########### no_precip, no_gen3 cat /home/hnoorazar/analog_codes/parameters/county_avg_file_names | while read LINE ; do cp 03_template_loc_GFDLG.sh ./rcp85_qsubs/GFDLG/q_rcp85_no_precip_$LINE.sh sed -i s/precip_type/no_precip/g ./rcp85_qsubs/GFDLG/q_rcp85_no_precip_$LINE.sh sed -i s/emission_type/rcp85/g ./rcp85_qsubs/GFDLG/q_rcp85_no_precip_$LINE.sh sed -i s/int_file/"$LINE"/g ./rcp85_qsubs/GFDLG/q_rcp85_no_precip_$LINE.sh done
<reponame>Layton85/akordyukov<filename>chapter_002/src/main/java/ru/job4j/bank/User.java package ru.job4j.bank; /** * User - class describes the user. * User implements interface Comparable for using in Collections. * @author <NAME> (<EMAIL>) * @version $Id$ * @since 0.1 */ public class User implements Comparable<User> { /** User name */ private String name; /** User passport - unigue User identifier */ private String passport; /** * User default constructor. */ public User() { this.name = ""; this.passport = ""; } /** * User constructor * @param name - User name * @param passport - Uset passport */ public User(String name, String passport) { this.name = name; this.passport = passport; } /** * Get-method * @return - Uset name */ public String getName() { return this.name; } /** * Get-method * @return - User passport */ public String getPassport() { return this.passport; } /** * Override method toString() * @return - String about the User */ @Override public String toString() { return "User{" + "name='" + name + '\'' + ", passport='" + passport + '\'' + '}'; } /** * Override method equals() * @param o - another User object * @return - true if the objects are the same, * else - in another case */ @Override public boolean equals(Object o) { boolean result = false; if (this == o) { result = true; } else if (o == null || this.getClass() != o.getClass()) { result = false; } else { User that = (User) o; result = this.name.equals(that.getName()) && this.passport.equals(that.getPassport()); } return result; } /** * Override method hashCode() * @return - User hash code (considering User`s name and passport) */ @Override public int hashCode() { int result = this.name.hashCode(); result = 31 * result + this.passport.hashCode(); return result; } /** * Override method compareTo(..) from the interface Comparable * @param o - Another object which is comparing with this User Object. * @return - the compare code of the passport strings comparison. */ @Override public int compareTo(User o) { return this.passport.compareTo(o.getPassport()); } }
#!/usr/bin/env bash docker build -t naiveproxy:server --rm .
var testutil = require('testutil') , fs = require('fs') , batch = require('../lib/batchflow') describe('batchflow', function() { describe('load testing', function() { it('should pass', function(done) { var a = [] for (var i = 0; i < 10000; ++i) a[i] = i batch(a).seq() .each(function(i, val, next) { next() //<--- before 0.3.2 this would fail }) .end(function() { done() }) }) }) })
module.exports = { basic: { message: "supports basic usage", }, 'basic:color': { message: "supports { color: '<a color>' }", options: { color: 'purple' } }, example: { message: "minimal example", }, };
const states = [ {key: "AL", display: "Alabama"}, {key: "AK", display: "Alaska"}, {key: "AZ", display: "Arizona"}, {key: "AR", display: "Arkansas"}, {key: "CA", display: "California"}, {key: "CO", display: "Colorado"}, {key: "CT", display: "Connecticut"}, {key: "DE", display: "Delaware"}, {key: "DC", display: "District of Columbia"}, {key: "FL", display: "Florida"}, {key: "GA", display: "Georgia"}, {key: "HI", display: "Hawaii"}, {key: "ID", display: "Idaho"}, {key: "IL", display: "Illinois"}, {key: "IN", display: "Indiana"}, {key: "IA", display: "Iowa"}, {key: "KS", display: "Kansas"}, {key: "KY", display: "Kentucky"}, {key: "LA", display: "Louisiana"}, {key: "ME", display: "Maine"}, {key: "MD", display: "Maryland"}, {key: "MA", display: "Massachusetts"}, {key: "MI", display: "Michigan"}, {key: "MN", display: "Minnesota"}, {key: "MS", display: "Mississippi"}, {key: "MO", display: "Missouri"}, {key: "MT", display: "Montana"}, {key: "NE", display: "Nebraska"}, {key: "NV", display: "Nevada"}, {key: "NH", display: "New Hampshire"}, {key: "NJ", display: "New Jersey"}, {key: "NM", display: "New Mexico"}, {key: "NY", display: "New York"}, {key: "NC", display: "North Carolina"}, {key: "ND", display: "North Dakota"}, {key: "OH", display: "Ohio"}, {key: "OK", display: "Oklahoma"}, {key: "OR", display: "Oregon"}, {key: "PA", display: "Pennsylvania"}, {key: "RI", display: "Rhode Island"}, {key: "SC", display: "South Carolina"}, {key: "SD", display: "South Dakota"}, {key: "TN", display: "Tennessee"}, {key: "TX", display: "Texas"}, {key: "UT", display: "Utah"}, {key: "VT", display: "Vermont"}, {key: "VA", display: "Virginia"}, {key: "WA", display: "Washington"}, {key: "WV", display: "West Virginia"}, {key: "WI", display: "Wisconsin"}, {key: "WY", display: "Wyoming"} ]; export default states
<filename>freshet-beam-runner/src/main/java/org/pathirage/freshet/beam/SamzaPipelineTranslator.java /** * Copyright 2016 <NAME> * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pathirage.freshet.beam; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.runners.TransformTreeNode; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.values.PValue; import org.pathirage.freshet.beam.io.KafkaIO; import org.pathirage.freshet.samza.SamzaJobConfigBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; public class SamzaPipelineTranslator extends Pipeline.PipelineVisitor.Defaults implements PipelineTranslationContext { private static Logger log = LoggerFactory.getLogger(SamzaPipelineTranslator.class); private static final Map<Class<? extends PTransform>, TransformTranslator> transformTranslators = new HashMap(); static { transformTranslators.put(KafkaIO.Read.Unbound.class, new KafkaIOReadUnboundTranslator()); transformTranslators.put(KafkaIO.Write.Unbound.class, new KafkaIOWriteUnboundTranslator()); transformTranslators.put(ParDo.Bound.class, new ParDoBoundTranslator()); } private final SamzaPipelineOptions options; private final SamzaPipelineSpecification samzaPipelineSpec = new SamzaPipelineSpecification(); private final SamzaJobConfigBuilder samzaJobConfigBuilder = new SamzaJobConfigBuilder(); public static SamzaPipelineTranslator fromOptions(SamzaPipelineOptions options) { return new SamzaPipelineTranslator(options); } private static String formatNodeName(TransformTreeNode node) { return node.toString().split("@")[1] + node.getTransform(); } private static TransformTranslator<?> getTranslator(PTransform<?, ?> transform) { return transformTranslators.get(transform.getClass()); } private SamzaPipelineTranslator(SamzaPipelineOptions options) { this.options = options; } public SamzaPipelineSpecification translate(Pipeline pipeline) { pipeline.traverseTopologically(this); return samzaPipelineSpec; } @Override public CompositeBehavior enterCompositeTransform(TransformTreeNode node) { return CompositeBehavior.DO_NOT_ENTER_TRANSFORM; } @Override public void leaveCompositeTransform(TransformTreeNode node) { } @Override public void visitPrimitiveTransform(TransformTreeNode node) { log.info("visitPrimitiveTransform-" + formatNodeName(node)); PTransform<?, ?> transform = node.getTransform(); TransformTranslator translator = getTranslator(transform); if (translator == null) { log.error("Could not found translator for " + transform.getClass()); throw new UnsupportedOperationException("The transform " + transform.getClass() + " is not supported yet."); } translator.translate(transform, this); } @Override public void visitValue(PValue value, TransformTreeNode producer) { throw new UnsupportedOperationException("Values are not supported yet."); } private static class KafkaIOReadUnboundTranslator<K, V> implements TransformTranslator<KafkaIO.Read.Unbound<K, V>> { @Override public void translate(KafkaIO.Read.Unbound<K, V> transform, PipelineTranslationContext translationContext) { } } private static class KafkaIOWriteUnboundTranslator<K, V> implements TransformTranslator<KafkaIO.Write.Unbound<K, V>> { @Override public void translate(KafkaIO.Write.Unbound<K, V> transform, PipelineTranslationContext translationContext) { } } private static class ParDoBoundTranslator<InputT, OutputT> implements TransformTranslator<ParDo.Bound<InputT, OutputT>> { @Override public void translate(ParDo.Bound<InputT, OutputT> transform, PipelineTranslationContext translationContext) { } } }
#! /bin/bash ./a.out sudo python /ai_home/socket_src/pywebsocket/mod_pywebsocket/standalone.py -p 9992 -w /ai_home/socket_src/pywebsocket/echo
def fibonacci(n): a = 0 b = 1 for i in range(n): a, b = b, a + b return a num = fibonacci(10) print(num)
#!/usr/bin/env bash description="$0 <command> <args>... Really basic tool to send commands to instantWM. Commands: help Display this help text overlay Toggle overlay (Super + Ctrl + W to define a widnow as overlay) tag <number> Switch to tag described by <number> animated Toggle animations alttab layout <number>|<name> Change window layout to given argument, e.g. $0 layout monocle prefix Set action prefix focusfollowsmouse Toggle window focus will change with mouse movement focusfollowsfloatmouse As above but only for flowting windows focusmon Switch focus to other monitor tagmon Move window to other monitor followmon Two above combined alttag Display tag symbols instead of numbers hidetags 0|1 Hide tags that have no windows on current monitor (0 means hide) nametag <name> change the name/icon of the current tag resetnametag reset all tag names to default" # See config.def.c and look for "Xcommand commands" main() { case $1 in help) usage -h ;; layout) layout "$2"; exit ;; esac xsetroot -name "c;:;$1;$2" } layout() { if [[ $1 =~ ^[0-8]$ ]]; then # between zero and eight layout=$1 else declare -A layouts=( ["tile"]=0 ['grid']=1 ['float']=2 ['monocle']=3 ['tcl']=4 ['deck']=5 ['overview']=6 ['bstack']=7 ['bstackhoriz']=8 ) layout=${layouts[$1]} [ -z "$layout" ] && { echo "Error: Unknown layout '$1'"; exit 1; } fi xsetroot -name "c;:;layout;$layout" } usage() { for itm in "$@"; do if [[ "$itm" =~ ^(-h|--help|-help|-\?)$ ]]; then 1>&2 echo "Usage: $description"; exit 0; fi done } if [ "$0" = "$BASH_SOURCE" ]; then usage "$@" main "$@" fi
#!/bin/bash ./scripts/ast/train.sh nt2n_base_attention_plus_layered eval_nt2n_base_attention_plus_layered_large_embeddings
import { ErrorMapper } from "utils/ErrorMapper"; import { CreepManager } from "tools/creep-manager"; import { RoomManager } from "./tools/room/room-manager"; declare global { interface SourceData { id: string; available_mining_positions: number; used_mining_positions: number; } interface RoomData { name: string; sources: SourceData[] } interface Rooms { roomData: RoomData[]; } // Memory extension samples interface Memory extends Rooms { uuid: number; log: any; } interface CreepMemory { role: string; room: string; working: boolean; } // Syntax for adding properties to `global` (ex "global.log") namespace NodeJS { interface Global { log: any; } } } // When compiling TS to JS and bundling with rollup, the line numbers and file names in error messages change // This utility uses source maps to get the line numbers and file names of the original, TS source code export const loop = ErrorMapper.wrapLoop(() => { RoomManager.run(Game.rooms["W32N23"]); CreepManager.CreateCreeps(); CreepManager.Run(); CreepManager.CleanUp(); });
<reponame>mikoBerries/vending-machine package other import "fmt" func Catch() { rec := recover() if rec != nil { fmt.Println("Error :", rec) } }
#/bin/bash love .
import React, { Component } from 'react'; //import moment from 'moment'; import { Breadcrumb, BreadcrumbItem, Button, Form, FormGroup, Label, Input, Col, FormFeedback , Card, CardImg,CardImgOverlay, CardTitle, CardBody, CardText , Modal, ModalHeader, ModalBody} from 'reactstrap'; import { BrowserRouter, NavLink } from 'react-router-dom'; import Web3 from "web3"; import { render } from 'react-dom'; var util; var util1; var vx; var alldocs = []; var allcus = []; var allmanu = []; var customer; let conver = (x) => { util = (Web3.utils.toWei(x, 'milli')); return util; } let converb =(x) => { util1 = (Web3.utils.fromWei(x, 'milli')); return util1; } async function calDist(c,manu,cnt) { var pin = c.custpincode; var min = 999999; var x; // res var y; // y var add ; for (var i = 0; i < cnt; i++){ y = manu[i].manupincode; x = subtract(pin,y); if(min>x){ min = x; y = manu[i]; add = manu[i].manuadd; } } return add; } function subtract(a, b){ if (a > b){ return a-b; } else{ return b-a; } } var quantity; var total; var finalid; class Allpatrender extends Component{ // var day = moment.unix(dish.dateofComp); // var xy = dish.dateofComp; // var date = new Date(xy*1000); // var time = day.format('dddd MMMM Do YYYY, h:mm:ss a'); // var yz = xy != 0?"bg-success text-white":""; constructor(props){ super(props); this.state = { docCount : 0, dish: [] , isModalOpen: false,qty: 0}; this.toggleModal = this.toggleModal.bind(this); this.converb = this.converb.bind(this); this.conver = this.conver.bind(this); this.handleInputChange = this.handleInputChange.bind(this); this.creatingShipment = this.creatingShipment.bind(this); this.buyitem = this.buyitem.bind(this); } buyitem = async(typeitem) => { var res = await this.props.contract.methods.itemcount().call(); var response2 = []; var response3= []; var cntres2 = 0 ; var cntres3 = 0; var rex2; for(var i=1;i<=res;i++){ var rex = await this.props.contract.methods.Items(i).call(); if(rex.itemtype == typeitem){ response2.push(rex); cntres2++; } } console.log(response2); for(var j = 0;j<cntres2;j++){ rex2 = await this.props.contract?.methods.Manufacturers(response2[j].manadr).call(); response3.push(rex2); cntres3++; } console.log(response3); var nearadd = await calDist(customer,response3,cntres3); console.log(nearadd); // for(var k = 0; k<cntres2;k++){ // if(nearadd == response.manadr){ // finalid = response2.itemid; // } // } return(nearadd); } toggleModal() { this.setState({ isModalOpen: !this.state.isModalOpen }); } handleInputChange(event){ const target = event.target; const value = target.value; const name = target.name; this.setState({ [name] : value }) } converb = async (x) => { util1 = (Web3.utils.fromWei(x, 'milli')); } conver = (x) => { util = (Web3.utils.toWei(x, 'milli')); return util; } totalvalue = () => { quantity = this.qty.value; total = util1 * quantity; alert(total); } creatingShipment = async(event) => { event.preventDefault(); var itemcat = this.props.dish?.itemtype; var qty = this.state.qty; var str = "Added"; var totalamt = conver((util1*qty).toString()); var manadr = await this.buyitem(parseInt(this.props.dish.itemtype)); const res = await this.props.contract?.methods.createShipment(itemcat,qty,str,totalamt,0,manadr).send({from: this.props.accounts,gas : 1000000}); console.log(res); this.toggleModal(); } render() { var but = this.props.registered == 2? "visible" : "invisible"; this.converb(this.props.dish.price.toString()); var cl = this.props.dish.itemtype == 0? "fa fa-laptop fa-5x" :((this.props.dish.itemtype ==1)?"fa fa-mobile fa-5x" :"fa fa-desktop fa-5x" ); return( <Card > <i className={cl}></i> <CardBody> <CardTitle>Item ID : {this.props.dish.itemid}</CardTitle> <CardText><small>Item Type : {category(parseInt(this.props.dish.itemtype))}</small></CardText> <CardText><small>Item Price : {util1}</small></CardText> <CardText><small>GST : {this.props.dish.gst}</small></CardText> <CardText><small>Description : {this.props.dish.description}</small></CardText> <Col md={{size:10, offset:1}}> <Button className={but} type="submit" color="primary" onClick={this.toggleModal}> Buy Item </Button> <Modal isOpen={this.state.isModalOpen} toggle={this.toggleModal} className="modal-md"> <ModalHeader toggle={this.toggleModal} className="pl-5">Item</ModalHeader> <Card className="pb-5"> <p className="m-auto p-4"><i className={cl}></i></p> <p className="m-auto p-2">Item Type : {category(parseInt(this.props.dish.itemtype))}</p> <p className="m-auto p-2">Item Price : {util1}</p> <div className="row m-auto pt-2"> <p>Item Quantity : </p> <p> <Input type="text" id="qty" name="qty" onChange={this.handleInputChange}></Input></p> </div> <p className="m-auto p-2">TotalAmt : {util1 * (this.state.qty)}</p> <p className="m-auto p-2">Description : {this.props.dish.description}</p> <p className="m-auto p-2"><Button type="submit" onClick={this.creatingShipment} >Confirm</Button> </p> </Card> </Modal> </Col> </CardBody> </Card> ) } } function category(i) { switch(i) { case 0: vx = 'Laptop'; break; case 1: vx = 'Mobile'; break; case 2: vx = 'Desktop'; break; } return vx; } function categoryrev(i) { if(i == "Laptop") { return 0; } else if(i == "Mobile") { return 1; } else if(i == "Desktop") { return 2; } } var itemtype; var itemprice; var itemgst; var itemdesc; class AllItemComponent extends Component{ constructor(props){ super(props); this.state = { docCount : 0, dish: [] , cust: [] , manuf: [] , isModalOpen1: false } this.toggleModal1 = this.toggleModal1.bind(this); //this.com = this.com.bind(this); } toggleModal1() { this.setState({ isModalOpen1: !this.state.isModalOpen1 }); } createItem = async(itemtype,itemdesc,itemprice,itemgst) => { const res = await this.props.contract.methods.createItems(itemtype,itemdesc,itemprice,itemgst).send({from: this.props.accounts,gas : 1000000}); console.log(res); } creatingItems = () => { itemtype = categoryrev(this.type.value); console.log(itemtype); itemprice = (conver(this.price.value)); itemgst = this.gst.value; itemdesc = this.desc.value; console.log(itemtype); this.createItem(itemtype,itemdesc,itemprice,itemgst); this.toggleModal1(); } async componentDidMount(){ var res = await this.props.contract?.methods.itemcount().call(); console.log(res); var cus= await this.props.contract?.methods.customercount().call(); console.log(cus); var manu= await this.props.contract?.methods.manufacturercount().call(); console.log(manu); var response= []; for(var i=1;i<=res;i++){ var rex = await this.props.contract?.methods.Items(i).call(); response.push(rex); } alldocs = []; alldocs = response; console.log(response); this.setState({ dish : alldocs}); customer = await this.props.contract?.methods.Customers(this.props.accounts).call(); } render(){ const Menu = this.state.dish.map((x) => { return ( <div key={x} className="col-4 col-md-3"> < Allpatrender dish={x} contract={this.props.contract} accounts={this.props.accounts} registered = {this.props.registered}/> </div> ); }) var ch = this.props.registered == 1? "visible" : "invisible"; return( <div className="container"> <h2>All Items</h2> <Button color="success" className={ch} onClick={this.toggleModal1}> Add Item </Button> <Modal isOpen={this.state.isModalOpen1} toggle={this.toggleModal1} className="modal-xl"> <ModalHeader toggle={this.toggleModal1}> <h3>Add Items</h3> </ModalHeader> <ModalBody> <Form> <div className="row pl-5 pr-5"> <div className="col-6"> <FormGroup> <Label htmlFor="type" className="ml-3">Item Type</Label> <Input type="select" id="type" name="type" innerRef={(input) => this.type = input}> <option>Select Item Type</option> <option>Mobile</option> <option>Laptop</option> <option>Desktop</option> </Input> </FormGroup> </div> <div className="col-6"> <FormGroup> <Label htmlFor="price" className="ml-3">Item Price</Label> <Input type="text" id="price" name="price" innerRef={(input) => this.price = input} /> </FormGroup> </div> </div> <div className="row pl-5 pr-5"> <div className="col-12"> <FormGroup> <Label htmlFor="gst" className="ml-3">Item GST</Label> <Input type="text" id="gst" name="gst" innerRef={(input) => this.gst = input} /> </FormGroup> </div> </div> <div className="row pl-5 pr-5"> <div className="col-12"> <FormGroup> <Label htmlFor="desc" className="ml-3">Item Description</Label> <Input type="text" id="desc" name="desc" innerRef={(input) => this.desc = input} /> </FormGroup> </div> </div> <br/> <div className="row pl-5"> <div className="col-6"> <Button color="primary" onClick={this.creatingItems}>Add Item</Button> </div> </div> <br/> </Form> </ModalBody> </Modal> <br/> <br/> <div className="row"> {Menu} </div> <br/> <br/> <br/> <br/> <br/> </div> ) }; } export default AllItemComponent;
#!/bin/bash # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # test_setup.sh # # Intended to be sourced into a test. # The code here will: # # * Set the following variables: # - DIR_LIST # - EXPECTED_REMOTE_OUTPUT_ENTRIES # - EXPECTED_FS_INPUT_ENTRIES # - EXPECTED_FS_OUTPUT_ENTRIES # * Create the following functions: # - build_recursive_files # - setup_expected_fs_input_entries # - setup_expected_fs_output_entries # - setup_expected_remote_output_entries DIR_LIST=( dir_1/dir_a dir_1/dir_b dir_2/dir_a dir_2/dir_b ) # Passed the path of two directories for shallow, and deep input, this # function will construct a directory structure and populate it with files # having $FILE_CONTENTS as a payload. function build_recursive_files() { local INPUT_DEEP_LOCAL="${1}" local INPUT_SHALLOW_LOCAL="${2}" mkdir -p "${INPUT_DEEP_LOCAL}" for INPUT_DIR in "${INPUT_DEEP_LOCAL}" "${INPUT_SHALLOW_LOCAL}"; do mkdir -p "${INPUT_DIR}" for DIR in "${DIR_LIST[@]}"; do mkdir -p "${INPUT_DIR}/${DIR}" done DIRS=($(find "${INPUT_DIR}" -type d)) for DIR in "${DIRS[@]}"; do echo "${FILE_CONTENTS}" > "${DIR}/in_file1.txt" echo "${FILE_CONTENTS}" > "${DIR}/in_file2.txt" chmod o-rwx "${DIR}"/in_file* done done } function setup_expected_fs_input_entries() { # Strip the trailing slash if it was provided" local PREFIX="${1%/}" EXPECTED_FS_INPUT_ENTRIES=( /mnt/data/input/"${PREFIX}"/deep/dir_1/dir_a/in_file1.txt /mnt/data/input/"${PREFIX}"/deep/dir_1/dir_a/in_file2.txt /mnt/data/input/"${PREFIX}"/deep/dir_1/dir_b/in_file1.txt /mnt/data/input/"${PREFIX}"/deep/dir_1/dir_b/in_file2.txt /mnt/data/input/"${PREFIX}"/deep/dir_1/in_file1.txt /mnt/data/input/"${PREFIX}"/deep/dir_1/in_file2.txt /mnt/data/input/"${PREFIX}"/deep/dir_2/dir_a/in_file1.txt /mnt/data/input/"${PREFIX}"/deep/dir_2/dir_a/in_file2.txt /mnt/data/input/"${PREFIX}"/deep/dir_2/dir_b/in_file1.txt /mnt/data/input/"${PREFIX}"/deep/dir_2/dir_b/in_file2.txt /mnt/data/input/"${PREFIX}"/deep/dir_2/in_file1.txt /mnt/data/input/"${PREFIX}"/deep/dir_2/in_file2.txt /mnt/data/input/"${PREFIX}"/deep/in_file1.txt /mnt/data/input/"${PREFIX}"/deep/in_file2.txt /mnt/data/input/"${PREFIX}"/shallow/in_file1.txt /mnt/data/input/"${PREFIX}"/shallow/in_file2.txt ) } function setup_expected_fs_output_entries() { local PREFIX="${1%/}" EXPECTED_FS_OUTPUT_ENTRIES=( /mnt/data/output/"${PREFIX}"/deep/dir_1/dir_a/file1.txt /mnt/data/output/"${PREFIX}"/deep/dir_1/dir_a/file2.txt /mnt/data/output/"${PREFIX}"/deep/dir_1/dir_b/file1.txt /mnt/data/output/"${PREFIX}"/deep/dir_1/dir_b/file2.txt /mnt/data/output/"${PREFIX}"/deep/dir_1/file1.txt /mnt/data/output/"${PREFIX}"/deep/dir_1/file2.txt /mnt/data/output/"${PREFIX}"/deep/dir_2/dir_a/file1.txt /mnt/data/output/"${PREFIX}"/deep/dir_2/dir_a/file2.txt /mnt/data/output/"${PREFIX}"/deep/dir_2/dir_b/file1.txt /mnt/data/output/"${PREFIX}"/deep/dir_2/dir_b/file2.txt /mnt/data/output/"${PREFIX}"/deep/dir_2/file1.txt /mnt/data/output/"${PREFIX}"/deep/dir_2/file2.txt /mnt/data/output/"${PREFIX}"/deep/file1.txt /mnt/data/output/"${PREFIX}"/deep/file2.txt /mnt/data/output/"${PREFIX}"/shallow/dir_1/dir_a/file1.txt /mnt/data/output/"${PREFIX}"/shallow/dir_1/dir_a/file2.txt /mnt/data/output/"${PREFIX}"/shallow/dir_1/dir_b/file1.txt /mnt/data/output/"${PREFIX}"/shallow/dir_1/dir_b/file2.txt /mnt/data/output/"${PREFIX}"/shallow/dir_1/file1.txt /mnt/data/output/"${PREFIX}"/shallow/dir_1/file2.txt /mnt/data/output/"${PREFIX}"/shallow/dir_2/dir_a/file1.txt /mnt/data/output/"${PREFIX}"/shallow/dir_2/dir_a/file2.txt /mnt/data/output/"${PREFIX}"/shallow/dir_2/dir_b/file1.txt /mnt/data/output/"${PREFIX}"/shallow/dir_2/dir_b/file2.txt /mnt/data/output/"${PREFIX}"/shallow/dir_2/file1.txt /mnt/data/output/"${PREFIX}"/shallow/dir_2/file2.txt /mnt/data/output/"${PREFIX}"/shallow/file1.txt /mnt/data/output/"${PREFIX}"/shallow/file2.txt ) } function setup_expected_remote_output_entries() { local PREFIX="${1%/}" EXPECTED_REMOTE_OUTPUT_ENTRIES=( "${PREFIX}" "${PREFIX}"/deep "${PREFIX}"/deep/dir_1 "${PREFIX}"/deep/dir_1/dir_a "${PREFIX}"/deep/dir_1/dir_a/file1.txt "${PREFIX}"/deep/dir_1/dir_a/file2.txt "${PREFIX}"/deep/dir_1/dir_b "${PREFIX}"/deep/dir_1/dir_b/file1.txt "${PREFIX}"/deep/dir_1/dir_b/file2.txt "${PREFIX}"/deep/dir_1/file1.txt "${PREFIX}"/deep/dir_1/file2.txt "${PREFIX}"/deep/dir_2 "${PREFIX}"/deep/dir_2/dir_a "${PREFIX}"/deep/dir_2/dir_a/file1.txt "${PREFIX}"/deep/dir_2/dir_a/file2.txt "${PREFIX}"/deep/dir_2/dir_b "${PREFIX}"/deep/dir_2/dir_b/file1.txt "${PREFIX}"/deep/dir_2/dir_b/file2.txt "${PREFIX}"/deep/dir_2/file1.txt "${PREFIX}"/deep/dir_2/file2.txt "${PREFIX}"/deep/file1.txt "${PREFIX}"/deep/file2.txt "${PREFIX}"/shallow "${PREFIX}"/shallow/file1.txt "${PREFIX}"/shallow/file2.txt ) }
#!/bin/bash # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. current_dir=`dirname "$0"` current_dir=`cd "$current_dir"; pwd` root_dir=${current_dir}/../../../../../ workload_config=${root_dir}/conf/workloads/tpcds/tpcds.conf . "${root_dir}/bin/functions/load_bench_config.sh" hibench_dir=${root_dir}/report/query63/spark/monitor.log enter_bench TPCDSQuery63 ${workload_config} ${current_dir} show_bannar start # prepare SQL HIVEBENCH_SQL_FILE=${root_dir}/sparkbench/tpcds/query/query63.sql START_TIME=`timestamp` application_name=query63_${START_TIME} run_spark_job --app_name "${application_name}" ${HIVEBENCH_SQL_FILE} END_TIME=`timestamp` sleep 5 SIZE=0 gen_report ${START_TIME} ${END_TIME} ${SIZE:-0} sleep 10 python ${root_dir}/bin/functions/sparkParser.py ${INFLUXDB_IP} ${INFLUXDB_PORT} ${INFLUXDB_USER} ${INFLUXDB_PWD} ${INFLUXDB_NAME} ${SPARK_IP_PORT} ${application_name} ${hibench_dir} show_bannar finish leave_bench
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+512+512-N-VB-ADJ-ADV/13-model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+512+512-N-VB-ADJ-ADV/13-512+512+512-shuffled-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function shuffle_first_third_sixth --eval_function last_sixth_eval
import chalk from 'chalk'; import fs from 'fs'; import rlSync from 'readline-sync'; import { setup, userConfigPath } from './setup'; export const verifySetup = () => { if (!fs.existsSync(userConfigPath)) { console.warn(chalk.yellow(`No Sitecore connection has been configured (missing scjssconfig.json)`)); // tslint:disable-next-line:max-line-length const runSetup = rlSync.keyInYN('This command requires a Sitecore connection. Would you like to configure the connection?'); if (!runSetup) { // tslint:disable-next-line:no-string-throw throw 'This command cannot execute without a Sitecore connection'; } setup(true); console.warn(chalk.yellow(`JSS app configuration must be deployed to Sitecore before continuing.`)); console.warn(`Use ${chalk.green('jss deploy config')} or copy /sitecore/config/*.config manually to Sitecore's /App_Config/Include`); const continueCommand = rlSync.keyInYN(chalk.yellow('Is the config deployed?')); if (!continueCommand) { // tslint:disable-next-line:no-string-throw throw 'Retry this command after deploying your JSS app config to Sitecore.'; } } };
#!/bin/bash fileid="1pkLBpcvZj6BqrXFsjoVFbxpVRAloczHi" html=`curl -c ./cookie -s -L "https://drive.google.com/uc?export=download&id=${fileid}"` curl -Lb ./cookie "https://drive.google.com/uc?export=download&`echo ${html}|grep -Po '(confirm=[a-zA-Z0-9\-_]+)'`&id=${fileid}" -o resources.tar.gz tar -zxvf resources.tar.gz rm resources.tar.gz echo Download finished.
import logging # Create a file handler fh = logging.FileHandler('gootool.log', encoding='utf8') fh.setLevel(logging.DEBUG) # Create a stream handler ch = logging.StreamHandler() ch.setLevel(logging.WARNING) # Define log message format formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # Set formatter for the handlers fh.setFormatter(formatter) ch.setFormatter(formatter) # Get the root logger and add the handlers logger = logging.getLogger() logger.addHandler(fh) logger.addHandler(ch) # Example usage logger.debug('This is a debug message') logger.warning('This is a warning message')
from sklearn.preprocessing import StandardScaler import numpy as np from xgboost import XGBClassifier from sklearn.model_selection import StratifiedKFold from sklearn.metrics import roc_auc_score def train_and_evaluate_model(X, y): # Standardize the features scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # Initialize XGBoost classifier xgb = XGBClassifier() # Initialize stratified k-fold skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) # Initialize list to store ROC AUC scores roc_auc_scores = [] # Perform stratified k-fold cross-validation for train_index, test_index in skf.split(X_scaled, y): X_train, X_test = X_scaled[train_index], X_scaled[test_index] y_train, y_test = y[train_index], y[test_index] # Train the model xgb.fit(X_train, y_train) # Predict probabilities for the test set y_pred_proba = xgb.predict_proba(X_test)[:, 1] # Calculate ROC AUC score and append to the list roc_auc = roc_auc_score(y_test, y_pred_proba) roc_auc_scores.append(roc_auc) # Calculate the mean ROC AUC score mean_roc_auc = np.mean(roc_auc_scores) return mean_roc_auc
/* * MIT License * * Copyright (c) 2019 <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 me.lynxplay.idonis.core.dialect.promise.parser; import me.lynxplay.idonis.core.dialect.promise.ValidStatementPromise; import me.lynxplay.idonis.dialect.promise.StatementPromise; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Represents a very basic statement parser */ public class ValidStatementParser implements Function<String, StatementPromise> { /** * The internal comment pattern to match the comment in which the variables are defined */ private static final Pattern COMMENT_PATTERN = Pattern.compile("(?s)/\\*(.*)\\*/"); /** * Generates the {@link StatementPromise} instance based on the source string * * @param source the string used as a source * * @return the promise instance */ @Override public StatementPromise apply(String source) { Matcher matcher = COMMENT_PATTERN.matcher(source); Map<Integer, List<Integer>> fakeIndexMap = new HashMap<>(); if (matcher.find()) { String group = matcher.group(1); source = matcher.replaceAll(""); // Remove comment from actual SQL script StringBuilder buffer = new StringBuilder(source); List<CachedStringIndexer> indexers = Arrays.stream(group.split(System.lineSeparator())) .filter(s -> !s.isBlank()) .map(t -> new CachedStringIndexer(buffer, t)) .collect(Collectors.toList()); CachedStringIndexer normalParameter = new CachedStringIndexer(buffer, "?"); int fakeIndex = indexers.size(); int subIndex = 0; List<Integer> actualToFake = new ArrayList<>(); while (true) { Map.Entry<Integer, CachedStringIndexer> found = Map.entry(normalParameter.find(subIndex), normalParameter); int nextFakeIndex = fakeIndex; for (int i = 0; i < indexers.size(); i++) { CachedStringIndexer indexer = indexers.get(i); if (indexer.find(subIndex) >= 0 && (indexer.find(subIndex) < found.getKey() || found.getKey() < 0)) { found = Map.entry(indexer.find(subIndex), indexer); nextFakeIndex = i; } } if (found.getKey() < 0) break; if (found.getValue() == normalParameter) { // Increase fake index by one as we found a ? nextFakeIndex = fakeIndex++; } else { // Replace the found variable with the ? int targetLength = found.getValue().getTarget().length(); buffer.replace(found.getKey(), found.getKey() + targetLength, "?"); // Replace the found key in the cache indexers.forEach(i -> i.adjustCache(-targetLength + 1)); // Adjust all caches normalParameter.adjustCache(-targetLength + 1); // Adjust ? indexer } actualToFake.add(nextFakeIndex); subIndex = found.getKey() + 1; // Skip to after variable as we just replaced it with a ? } for (int i = 0; i < actualToFake.size(); i++) { // Add one to all indices as SQL starts at 1 fakeIndexMap.computeIfAbsent(actualToFake.get(i) + 1, $ -> new LinkedList<>()).add(i + 1); } source = buffer.toString(); } String trimmed = source.replaceAll(System.lineSeparator(), " ").replaceAll(" +", " "); return new ValidStatementPromise(trimmed, fakeIndexMap); } }
# Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # What to do sign=false verify=false build=false setupenv=false # Systems to build linux=true windows=true osx=true # Other Basic variables SIGNER= VERSION= commit=false url=https://github.com/natcoin-project/natcoin proc=2 mem=2000 lxc=true osslTarUrl=http://downloads.sourceforge.net/project/osslsigncode/osslsigncode/osslsigncode-1.7.1.tar.gz osslPatchUrl=https://bitcoincore.org/cfields/osslsigncode-Backports-to-1.7.1.patch scriptName=$(basename -- "$0") signProg="gpg --detach-sign" commitFiles=true # Help Message read -d '' usage <<- EOF Usage: $scriptName [-c|u|v|b|s|B|o|h|j|m|] signer version Run this script from the directory containing the natcoin, gitian-builder, gitian.sigs.ltc, and natcoin-detached-sigs. Arguments: signer GPG signer to sign each build assert file version Version number, commit, or branch to build. If building a commit or branch, the -c option must be specified Options: -c|--commit Indicate that the version argument is for a commit or branch -u|--url Specify the URL of the repository. Default is https://github.com/natcoin-project/natcoin -v|--verify Verify the gitian build -b|--build Do a gitian build -s|--sign Make signed binaries for Windows and Mac OSX -B|--buildsign Build both signed and unsigned binaries -o|--os Specify which Operating Systems the build is for. Default is lwx. l for linux, w for windows, x for osx -j Number of processes to use. Default 2 -m Memory to allocate in MiB. Default 2000 --kvm Use KVM instead of LXC --setup Setup the gitian building environment. Uses KVM. If you want to use lxc, use the --lxc option. Only works on Debian-based systems (Ubuntu, Debian) --detach-sign Create the assert file for detached signing. Will not commit anything. --no-commit Do not commit anything to git -h|--help Print this help message EOF # Get options and arguments while :; do case $1 in # Verify -v|--verify) verify=true ;; # Build -b|--build) build=true ;; # Sign binaries -s|--sign) sign=true ;; # Build then Sign -B|--buildsign) sign=true build=true ;; # PGP Signer -S|--signer) if [ -n "$2" ] then SIGNER=$2 shift else echo 'Error: "--signer" requires a non-empty argument.' exit 1 fi ;; # Operating Systems -o|--os) if [ -n "$2" ] then linux=false windows=false osx=false if [[ "$2" = *"l"* ]] then linux=true fi if [[ "$2" = *"w"* ]] then windows=true fi if [[ "$2" = *"x"* ]] then osx=true fi shift else echo 'Error: "--os" requires an argument containing an l (for linux), w (for windows), or x (for Mac OSX)\n' exit 1 fi ;; # Help message -h|--help) echo "$usage" exit 0 ;; # Commit or branch -c|--commit) commit=true ;; # Number of Processes -j) if [ -n "$2" ] then proc=$2 shift else echo 'Error: "-j" requires an argument' exit 1 fi ;; # Memory to allocate -m) if [ -n "$2" ] then mem=$2 shift else echo 'Error: "-m" requires an argument' exit 1 fi ;; # URL -u) if [ -n "$2" ] then url=$2 shift else echo 'Error: "-u" requires an argument' exit 1 fi ;; # kvm --kvm) lxc=false ;; # Detach sign --detach-sign) signProg="true" commitFiles=false ;; # Commit files --no-commit) commitFiles=false ;; # Setup --setup) setup=true ;; *) # Default case: If no more options then break out of the loop. break esac shift done # Set up LXC if [[ $lxc = true ]] then export USE_LXC=1 export LXC_BRIDGE=lxcbr0 sudo ifconfig lxcbr0 up 10.0.2.2 fi # Check for OSX SDK if [[ ! -e "gitian-builder/inputs/MacOSX10.11.sdk.tar.gz" && $osx == true ]] then echo "Cannot build for OSX, SDK does not exist. Will build for other OSes" osx=false fi # Get signer if [[ -n"$1" ]] then SIGNER=$1 shift fi # Get version if [[ -n "$1" ]] then VERSION=$1 COMMIT=$VERSION shift fi # Check that a signer is specified if [[ $SIGNER == "" ]] then echo "$scriptName: Missing signer." echo "Try $scriptName --help for more information" exit 1 fi # Check that a version is specified if [[ $VERSION == "" ]] then echo "$scriptName: Missing version." echo "Try $scriptName --help for more information" exit 1 fi # Add a "v" if no -c if [[ $commit = false ]] then COMMIT="v${VERSION}" fi echo ${COMMIT} # Setup build environment if [[ $setup = true ]] then sudo apt-get install ruby apache2 git apt-cacher-ng python-vm-builder qemu-kvm qemu-utils git clone https://github.com/natcoin-project/gitian.sigs.ltc.git git clone https://github.com/natcoin-project/natcoin-detached-sigs.git git clone https://github.com/devrandom/gitian-builder.git pushd ./gitian-builder if [[ -n "$USE_LXC" ]] then sudo apt-get install lxc bin/make-base-vm --suite trusty --arch amd64 --lxc else bin/make-base-vm --suite trusty --arch amd64 fi popd fi # Set up build pushd ./natcoin git fetch git checkout ${COMMIT} popd # Build if [[ $build = true ]] then # Make output folder mkdir -p ./natcoin-binaries/${VERSION} # Build Dependencies echo "" echo "Building Dependencies" echo "" pushd ./gitian-builder mkdir -p inputs wget -N -P inputs $osslPatchUrl wget -N -P inputs $osslTarUrl make -C ../natcoin/depends download SOURCES_PATH=`pwd`/cache/common # Linux if [[ $linux = true ]] then echo "" echo "Compiling ${VERSION} Linux" echo "" ./bin/gbuild -j ${proc} -m ${mem} --commit natcoin=${COMMIT} --url natcoin=${url} ../natcoin/contrib/gitian-descriptors/gitian-linux.yml ./bin/gsign -p $signProg --signer $SIGNER --release ${VERSION}-linux --destination ../gitian.sigs.ltc/ ../natcoin/contrib/gitian-descriptors/gitian-linux.yml mv build/out/natcoin-*.tar.gz build/out/src/natcoin-*.tar.gz ../natcoin-binaries/${VERSION} fi # Windows if [[ $windows = true ]] then echo "" echo "Compiling ${VERSION} Windows" echo "" ./bin/gbuild -j ${proc} -m ${mem} --commit natcoin=${COMMIT} --url natcoin=${url} ../natcoin/contrib/gitian-descriptors/gitian-win.yml ./bin/gsign -p $signProg --signer $SIGNER --release ${VERSION}-win-unsigned --destination ../gitian.sigs.ltc/ ../natcoin/contrib/gitian-descriptors/gitian-win.yml mv build/out/natcoin-*-win-unsigned.tar.gz inputs/natcoin-win-unsigned.tar.gz mv build/out/natcoin-*.zip build/out/natcoin-*.exe ../natcoin-binaries/${VERSION} fi # Mac OSX if [[ $osx = true ]] then echo "" echo "Compiling ${VERSION} Mac OSX" echo "" ./bin/gbuild -j ${proc} -m ${mem} --commit natcoin=${COMMIT} --url natcoin=${url} ../natcoin/contrib/gitian-descriptors/gitian-osx.yml ./bin/gsign -p $signProg --signer $SIGNER --release ${VERSION}-osx-unsigned --destination ../gitian.sigs.ltc/ ../natcoin/contrib/gitian-descriptors/gitian-osx.yml mv build/out/natcoin-*-osx-unsigned.tar.gz inputs/natcoin-osx-unsigned.tar.gz mv build/out/natcoin-*.tar.gz build/out/natcoin-*.dmg ../natcoin-binaries/${VERSION} fi popd if [[ $commitFiles = true ]] then # Commit to gitian.sigs repo echo "" echo "Committing ${VERSION} Unsigned Sigs" echo "" pushd gitian.sigs git add ${VERSION}-linux/${SIGNER} git add ${VERSION}-win-unsigned/${SIGNER} git add ${VERSION}-osx-unsigned/${SIGNER} git commit -a -m "Add ${VERSION} unsigned sigs for ${SIGNER}" popd fi fi # Verify the build if [[ $verify = true ]] then # Linux pushd ./gitian-builder echo "" echo "Verifying v${VERSION} Linux" echo "" ./bin/gverify -v -d ../gitian.sigs.ltc/ -r ${VERSION}-linux ../natcoin/contrib/gitian-descriptors/gitian-linux.yml # Windows echo "" echo "Verifying v${VERSION} Windows" echo "" ./bin/gverify -v -d ../gitian.sigs.ltc/ -r ${VERSION}-win-unsigned ../natcoin/contrib/gitian-descriptors/gitian-win.yml # Mac OSX echo "" echo "Verifying v${VERSION} Mac OSX" echo "" ./bin/gverify -v -d ../gitian.sigs.ltc/ -r ${VERSION}-osx-unsigned ../natcoin/contrib/gitian-descriptors/gitian-osx.yml # Signed Windows echo "" echo "Verifying v${VERSION} Signed Windows" echo "" ./bin/gverify -v -d ../gitian.sigs.ltc/ -r ${VERSION}-osx-signed ../natcoin/contrib/gitian-descriptors/gitian-osx-signer.yml # Signed Mac OSX echo "" echo "Verifying v${VERSION} Signed Mac OSX" echo "" ./bin/gverify -v -d ../gitian.sigs.ltc/ -r ${VERSION}-osx-signed ../natcoin/contrib/gitian-descriptors/gitian-osx-signer.yml popd fi # Sign binaries if [[ $sign = true ]] then pushd ./gitian-builder # Sign Windows if [[ $windows = true ]] then echo "" echo "Signing ${VERSION} Windows" echo "" ./bin/gbuild -i --commit signature=${COMMIT} ../natcoin/contrib/gitian-descriptors/gitian-win-signer.yml ./bin/gsign -p $signProg --signer $SIGNER --release ${VERSION}-win-signed --destination ../gitian.sigs.ltc/ ../natcoin/contrib/gitian-descriptors/gitian-win-signer.yml mv build/out/natcoin-*win64-setup.exe ../natcoin-binaries/${VERSION} mv build/out/natcoin-*win32-setup.exe ../natcoin-binaries/${VERSION} fi # Sign Mac OSX if [[ $osx = true ]] then echo "" echo "Signing ${VERSION} Mac OSX" echo "" ./bin/gbuild -i --commit signature=${COMMIT} ../natcoin/contrib/gitian-descriptors/gitian-osx-signer.yml ./bin/gsign -p $signProg --signer $SIGNER --release ${VERSION}-osx-signed --destination ../gitian.sigs.ltc/ ../natcoin/contrib/gitian-descriptors/gitian-osx-signer.yml mv build/out/natcoin-osx-signed.dmg ../natcoin-binaries/${VERSION}/natcoin-${VERSION}-osx.dmg fi popd if [[ $commitFiles = true ]] then # Commit Sigs pushd gitian.sigs echo "" echo "Committing ${VERSION} Signed Sigs" echo "" git add ${VERSION}-win-signed/${SIGNER} git add ${VERSION}-osx-signed/${SIGNER} git commit -a -m "Add ${VERSION} signed binary sigs for ${SIGNER}" popd fi fi
max=8 for i in `seq 1 $max` do echo "$i" done
// Solution for the render method of the TransactionConfirmation component render() { const estimatedNEU = this.props.estimatedNEU; const web3Type = this.props.web3Type; return ( <div> <CommitHeaderComponent number="02" title="Confirm your transaction" /> <UserInfo /> {web3Type === Web3Type.LEDGER ? <p className={styles.text}> You now have 20 seconds to confirm the transaction on your wallet.<br /> <Link to="/commit">Or go back to change your commitment.</Link> </p> : <p className={styles.text}> Different message for non-LEDGER web3Type. </p> } </div> ); }
package controller import ( "crypto/md5" "encoding/hex" "fmt" "gin-web-skeleton/model/services" "gin-web-skeleton/util" "github.com/gin-gonic/gin" ) type LoginField struct { Username string `form:"username"` Password string `form:"password"` Csrf string `form:"csrf"` } type RespData struct { Username string `json:"username"` Password string `json:"password"` AccessToken string `json:"access_token"` } func Login(c *gin.Context) { var loginField LoginField if err := c.Bind(&loginField); err != nil { fmt.Println(err) util.SendResponse(c, err, nil) return } fmt.Println(loginField) admin, err := services.GetAdminByUsername(loginField.Username) if err != nil { sendResponse(c, -1, err.Error(), nil) return } if 1 != admin.Status { sendResponse(c, -2, "账号状态异常", nil) return } h := md5.New() h.Write([]byte(loginField.Password)) md5Password := hex.EncodeToString(h.Sum(nil)) if admin.Password != <PASSWORD> { sendResponse(c, -3, "密码错误", nil) return } token, err := util.GenerateToken(admin.Username, admin.Password) if err != nil { sendResponse(c, -4, "token创建失败,请重新登录", nil) return } respData := RespData{Username: admin.Username, Password: <PASSWORD>, AccessToken: token} fmt.Println(respData) sendResponse(c, 0, "success", respData) return }
class BankAccount: def __init__(self, initial_balance): self.balance = initial_balance self.transactions = 0 def deposit(self, amount): self.balance += amount self.transactions += 1 def withdraw(self, amount): if self.balance >= amount: self.balance -= amount self.transactions += 1 def get_balance(self): return self.balance def get_transaction_count(self): return self.transactions # Test the BankAccount class acc = BankAccount(1000) acc.deposit(500) acc.withdraw(200) print(acc.get_balance()) # Output: 1300 print(acc.get_transaction_count()) # Output: 2
import '../css/Footer.css'; import '../css/Footer.mobile.css'; function Footer() { return ( <footer> <p className="float_left"> This is a demo website, to demonstrate my web development skills,<br /> you can order this in fiverr </p> <p className="float_right"> If you like this website, you can order your custom one on fiverr! <h4 className="float_right" style={{width: '100%', textAlign: 'center'}}>console.log("Goodbye world!")</h4> </p> <h4 className="float_right" style={{width: '100%', textAlign: 'center'}}> &copy; <a style={{textDecoration: 'none'}} href="https://github.com/glaukiol1"><NAME></a></h4> </footer> ); } export default Footer;
package com.microsoft.cognitive.speakerrecognition.contract; import com.microsoft.cognitive.speakerrecognition.contract.identification.CreateProfileResponse; import com.microsoft.cognitive.speakerrecognition.contract.identification.Profile; import com.microsoft.cognitive.speakerrecognition.contract.ProfileLocale; import java.util.List; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.GET; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.Part; import retrofit2.http.Path; import retrofit2.http.Query; public interface IdentificationProfileApi { @POST("identificationProfiles") Call<CreateProfileResponse> createProfile(@Body ProfileLocale locale); @DELETE("identificationProfiles/{identificationProfileId}") Call<Void> deleteProfile(@Path("identificationProfileId") String identificationProfileId); @GET("identificationProfiles/{identificationProfileId}") Call<Profile> getProfile(@Path("identificationProfileId") String identificationProfileId); @GET("identificationProfiles") Call<List<Profile>> getProfiles(); @Multipart @POST("identificationProfiles/{identificationProfileId}/enroll") Call<Void> enroll(@Part("enrollmentData") RequestBody audio, @Path("identificationProfileId") String identificationProfileId, @Query("shortAudio") boolean shortAudio); @POST("identificationProfiles/{identificationProfileId}/reset") Call<Void> resetEnrollments(@Path("identificationProfileId") String identificationProfileId); }
package com.goldencarp.lingqianbao.view.util; import android.widget.Toast; import com.goldencarp.lingqianbao.view.LQBApp; /** * Created by sks on 2018/3/5. */ public class ToastUtil { public static void showToast(String msg) { Toast.makeText(LQBApp.getApp(), msg, Toast.LENGTH_SHORT).show(); } }
TestCase("DisplayList", { "testChildAddChild": function() { var a = new DisplayObject(); var b = new DisplayObject(); a.addChild(b); assertEquals("Childed", a.getChildren().indexOf(b), 0); }, "testChildRemoveChild": function() { var a = new DisplayObject(); var b = new DisplayObject(); a.addChild(b); a.removeChild(b); assertEquals("Removed", a.getChildren().indexOf(b), -1); }, "testParentAddChild": function() { var a = new DisplayObject(); var b = new DisplayObject(); a.addChild(b); assertEquals("Parented", b.getParent(), a); }, "testParentRemoveChild": function() { var a = new DisplayObject(); var b = new DisplayObject(); a.addChild(b); a.removeChild(b); assertEquals("Parented", b.getParent(), null); }, "testChildMultipleAdd": function() { var children = []; for (var i = 0; i < 10; i++) { children[i] = new DisplayObject(); } var a = new DisplayObject(); children.forEach(function(item) { item.addChild(a); }); children.slice(0, children.length - 2).forEach(function(item) { assertEquals("Childed", 0, item.getChildren().length); }); assertEquals("Childed", children[9].getChildren()[0], a); }, "testParentMultipleAdd": function() { var children = []; for (var i = 0; i < 10; i++) { children[i] = new DisplayObject(); } var a = new DisplayObject(); children.forEach(function(item) { item.addChild(a); }); assertEquals("Parented", children[9], a.getParent()); }, "testAddSelf": function() { var a = new DisplayObject(); assertException("AddSelf", function() { a.addChild(a); }); } });
const tap = require("tap"); const test = tap.test; const { getDom, getBooon } = require("./dom"); test("filter", t => { t.plan(4); const booon = getBooon(); t.equal(booon("div").length, 4); t.equal(booon("div").filter(n => n.id === "why").length, 1); t.equal(booon("div").filter("div").length, 4); t.equal(booon("div").filter("span").length, 0); }); test("parent", t => { t.plan(3); const booon = getBooon(); t.equal(booon("div>div").parent().length, 1); t.equal(booon("h3,h2").parent().length, 1); t.equal(booon("#why,#what").parent().length, 2); }); test("children", t => { t.plan(2); const booon = getBooon(); t.equal(booon("#what").children().length, 2); t.equal(booon(".w").children().length, 2); }); test("siblings", t => { t.plan(2); const booon = getBooon(); t.equal(booon("#why").siblings().length, 1); t.equal(booon("#why").siblings(true).length, 2); }); test("find", t => { t.plan(2); const booon = getBooon(); t.equal(booon("h2").find("span").length, 1); t.equal(booon("h2").find("h2").length, 0); }); test("limit", t => { t.plan(1); const booon = getBooon(); t.equal(booon("div").limit(2).length, 2); }); test("map", t => { t.plan(1); const booon = getBooon(); t.equal(booon("h3,h2").map(n => n.parentNode).length, 1); }); test("merge", t => { t.plan(2); const booon = getBooon(); t.equal(booon("input").merge("a").length, 2); t.equal(booon("div").merge("#what").length, booon("div").length); });
<form action="" method="post"> <input type="text" name="name" placeholder="Name" required> <input type="email" name="email" placeholder="Email" required> <input type="password" name="password" placeholder="Password" required> <input type="text" name="age" placeholder="Age" required> <input type="text" name="address" placeholder="Address" required> <input type="number" name="phone" placeholder="Phone Number" required> <input type="text" name="avatar" placeholder="Link avatar" required> <input type="submit" value="Register"> </form>
class EvenChecker: def is_even(self, number): return number % 2 == 0 # Create an instance of the EvenChecker class even_checker = EvenChecker() # Check if the numbers are even or odd print(even_checker.is_even(4)) # Output: True print(even_checker.is_even(7)) # Output: False print(even_checker.is_even(10)) # Output: True
def remove_negatives(arr): result = [] for num in arr: if num >= 0: result.append(num) return result arr = [3, -9, 12, -4, 7, -8] result = remove_negatives(arr) print(result)
#!/bin/bash set -v -e pushd $( dirname $0 ) if [ -f ./env ] ; then source ./env fi # set hostname sudo hostnamectl set-hostname glasswall # get source code cd ~ BRANCH=${BRANCH:-main} GITHUB_REPOSITORY=${GITHUB_REPOSITORY:-filetrust/cdr-plugin-folder-to-folder} git clone https://github.com/${GITHUB_REPOSITORY}.git --branch $BRANCH --recursive && cd cdr-plugin-folder-to-folder # build docker images sudo apt-get install \ apt-transport-https \ ca-certificates \ curl \ gnupg-agent \ software-properties-common -y curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository \ "deb [arch=amd64] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) \ stable" sudo apt-get update sudo DEBIAN_FRONTEND=noninteractive apt-get install docker-ce docker-ce-cli containerd.io -y sudo curl -L "https://github.com/docker/compose/releases/download/1.29.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose # install local docker registry sudo docker run -d -p 30500:5000 --restart always --name registry registry:2 # build images cd ~/cdr-plugin-folder-to-folder cp .env.sample .env echo "PWD=/home/ubuntu/cdr-plugin-folder-to-folder" >> .env sudo docker-compose up -d --build # install vmware tools sudo apt install open-vm-tools sudo apt install open-vm-tools-desktop -y # allow password login (useful when deployed to esxi) SSH_PASSWORD=${SSH_PASSWORD:-glasswall} printf "${SSH_PASSWORD}\n${SSH_PASSWORD}" | sudo passwd ubuntu sudo sed -i "s/.*PasswordAuthentication.*/PasswordAuthentication yes/g" /etc/ssh/sshd_config sudo service ssh restart
<reponame>uvworkspace/uvw-node 'use strict'; var path = require('path'); var uvwlib = require('uvwlib'); var nodeUtils = require('../lib/utils'); var metaFactory = require('./meta-factory'); var MetaContext = { instance: function (parent, name, spec) { return Object.create(MetaContext).init(parent, name, spec); }, init: function(parent, name, spec) { spec = spec || {}; if (parent && !name) throw new Error('missing name'); if (parent && !parent.root) throw new Error('parent missing root'); if (!parent && !spec.baseDir) throw new Error('missing baseDir'); this.parent = parent || null; this.name = name || ''; this.spec = spec; this.root = parent ? parent.root : this; this.path = parent ? parent.path.concat(name) : []; this.baseDir = parent ? path.join(parent.baseDir, name) : path.resolve(spec.baseDir); this._factory = spec.factory;; this._index = spec.index || null; this._cntxs = {}; return this; }, filePath: function() { return path.resolve.apply(null, uvwlib.flatten(this.baseDir, arguments)); }, relPathTo: function(cwd) { return path.relative(this.baseDir, cwd || process.cwd()); }, relPathFrom: function(cwd) { return path.relative(cwd || process.cwd(), this.baseDir); }, hasFile: function() { return nodeUtils.isFile(this.filePath.apply(this, arguments)); }, hasDirectory: function() { return nodeUtils.isDirectory(this.filePath.apply(this, arguments)); }, factory: function() { return this._factory || (this.parent ? this.parent.factory() : metaFactory); }, index: function() { return this._index || (this._index = this.factory().createIndex(this)); }, cd: function(name) { return this.child(name) || this.index().cd(name); }, child: function(name) { return this._cntxs[name]; }, pushChild: function(name, spec) { var child = typeof name === 'object' ? name : null; var childName = child ? child.name : name; if (!childName) throw new Error('missing name'); if (this.child(childName)) throw new Error(childName + ' exists'); if (child && child.parent !== this) throw new Error('parent mismatch'); if (!child) child = MetaContext.instance(this, childName, spec); return this._cntxs[childName] = child; }, setIndex: function(index) { if (this._index) throw new Error('index exists'); this._index = index; return this; }, evaluate: function(req) { var sub = req.path[0] && this.index().cd(req.path[0]); if (sub) { req = uvwlib.defaults({ path: req.path.slice(1) }, req); return sub.evaluate(req); } return this.index().evaluate(req); }, }; module.exports = MetaContext;
<filename>pkg/processor/runtime/rpc/abstract.go /* Copyright 2017 The Nuclio Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package rpc import ( "bufio" "encoding/base64" "encoding/json" "fmt" "io" "net" "net/http" "os" "time" "github.com/nuclio/nuclio/pkg/common" "github.com/nuclio/nuclio/pkg/processor/runtime" "github.com/nuclio/nuclio/pkg/processor/status" "github.com/nuclio/nuclio/pkg/processwaiter" "github.com/nuclio/errors" "github.com/nuclio/logger" "github.com/nuclio/nuclio-sdk-go" "github.com/rs/xid" ) // TODO: Find a better place (both on file system and configuration) const ( socketPathTemplate = "/tmp/nuclio-rpc-%s.sock" connectionTimeout = 2 * time.Minute ) type result struct { StatusCode int `json:"status_code"` ContentType string `json:"content_type"` Body string `json:"body"` BodyEncoding string `json:"body_encoding"` Headers map[string]interface{} `json:"headers"` DecodedBody []byte err error } // Runtime is a runtime that communicates via unix domain socket type AbstractRuntime struct { runtime.AbstractRuntime configuration *runtime.Configuration eventEncoder EventEncoder wrapperProcess *os.Process resultChan chan *result functionLogger logger.Logger runtime Runtime startChan chan struct{} socketType SocketType processWaiter *processwaiter.ProcessWaiter } type rpcLogRecord struct { DateTime string `json:"datetime"` Level string `json:"level"` Message string `json:"message"` With map[string]interface{} `json:"with"` } // NewRPCRuntime returns a new RPC runtime func NewAbstractRuntime(logger logger.Logger, configuration *runtime.Configuration, runtimeInstance Runtime) (*AbstractRuntime, error) { var err error abstractRuntime, err := runtime.NewAbstractRuntime(logger, configuration) if err != nil { return nil, errors.Wrap(err, "Can't create AbstractRuntime") } newRuntime := &AbstractRuntime{ AbstractRuntime: *abstractRuntime, configuration: configuration, runtime: runtimeInstance, startChan: make(chan struct{}, 1), } return newRuntime, nil } func (r *AbstractRuntime) Start() error { if err := r.startWrapper(); err != nil { r.SetStatus(status.Error) return errors.Wrap(err, "Failed to run wrapper") } r.SetStatus(status.Ready) return nil } // ProcessEvent processes an event func (r *AbstractRuntime) ProcessEvent(event nuclio.Event, functionLogger logger.Logger) (interface{}, error) { if currentStatus := r.GetStatus(); currentStatus != status.Ready { return nil, errors.Errorf("Processor not ready (current status: %s)", currentStatus) } r.functionLogger = functionLogger // We don't use defer to reset r.functionLogger since it decreases performance if err := r.eventEncoder.Encode(event); err != nil { r.functionLogger = nil return nil, errors.Wrapf(err, "Can't encode event: %+v", event) } result, ok := <-r.resultChan r.functionLogger = nil if !ok { msg := "Client disconnected" r.Logger.Error(msg) r.SetStatus(status.Error) r.functionLogger = nil return nil, errors.New(msg) } return nuclio.Response{ Body: result.DecodedBody, ContentType: result.ContentType, Headers: result.Headers, StatusCode: result.StatusCode, }, nil } // Stop stops the runtime func (r *AbstractRuntime) Stop() error { if r.wrapperProcess != nil { // stop waiting for process if err := r.processWaiter.Cancel(); err != nil { r.Logger.WarnWith("Failed to cancel process waiting") } err := r.wrapperProcess.Kill() if err != nil { r.SetStatus(status.Error) return errors.Wrap(err, "Can't kill wrapper process") } } r.SetStatus(status.Stopped) return nil } // Restart restarts the runtime func (r *AbstractRuntime) Restart() error { if err := r.Stop(); err != nil { return err } // Send error for current event (non-blocking) select { case r.resultChan <- &result{ StatusCode: http.StatusRequestTimeout, err: errors.New("Runtime restarted"), }: default: r.Logger.Warn("Nothing waiting on result channel during restart. Continuing") } close(r.resultChan) if err := r.startWrapper(); err != nil { r.SetStatus(status.Error) return errors.Wrap(err, "Can't start wrapper process") } r.SetStatus(status.Ready) return nil } // GetSocketType returns the type of socket the runtime works with (unix/tcp) func (r *AbstractRuntime) GetSocketType() SocketType { return UnixSocket } // WaitForStart returns whether the runtime supports sending an indication that it started func (r *AbstractRuntime) WaitForStart() bool { return false } // SupportsRestart returns true if the runtime supports restart func (r *AbstractRuntime) SupportsRestart() bool { return true } func (r *AbstractRuntime) startWrapper() error { var err error var listener net.Listener var address string if r.runtime.GetSocketType() == UnixSocket { listener, address, err = r.createUnixListener() } else { listener, address, err = r.createTCPListener() } if err != nil { return errors.Wrap(err, "Can't create listener") } r.processWaiter, err = processwaiter.NewProcessWaiter() if err != nil { return errors.Wrap(err, "Failed to create process waiter") } wrapperProcess, err := r.runtime.RunWrapper(address) if err != nil { return errors.Wrap(err, "Can't run wrapper") } r.wrapperProcess = wrapperProcess go r.watchWrapperProcess() conn, err := listener.Accept() if err != nil { return errors.Wrap(err, "Can't get connection from wrapper") } r.Logger.InfoWith("Wrapper connected", "wid", r.Context.WorkerID) r.eventEncoder = r.runtime.GetEventEncoder(conn) r.resultChan = make(chan *result) go r.wrapperOutputHandler(conn, r.resultChan) // wait for start if required to if r.runtime.WaitForStart() { r.Logger.Debug("Waiting for start") <-r.startChan } r.Logger.Debug("Started") return nil } // Create a listener on unix domian docker, return listener, path to socket and error func (r *AbstractRuntime) createUnixListener() (net.Listener, string, error) { socketPath := fmt.Sprintf(socketPathTemplate, xid.New().String()) if common.FileExists(socketPath) { if err := os.Remove(socketPath); err != nil { return nil, "", errors.Wrapf(err, "Can't remove socket at %q", socketPath) } } r.Logger.DebugWith("Creating listener socket", "path", socketPath) listener, err := net.Listen("unix", socketPath) if err != nil { return nil, "", errors.Wrapf(err, "Can't listen on %s", socketPath) } unixListener, ok := listener.(*net.UnixListener) if !ok { return nil, "", fmt.Errorf("Can't get underlying Unix listener") } if err = unixListener.SetDeadline(time.Now().Add(connectionTimeout)); err != nil { return nil, "", errors.Wrap(err, "Can't set deadline") } return listener, socketPath, nil } // Create a listener on TCP docker, return listener, port and error func (r *AbstractRuntime) createTCPListener() (net.Listener, string, error) { listener, err := net.Listen("tcp", ":0") if err != nil { return nil, "", errors.Wrap(err, "Can't find free port") } tcpListener, ok := listener.(*net.TCPListener) if !ok { return nil, "", errors.Wrap(err, "Can't get underlying TCP listener") } if err = tcpListener.SetDeadline(time.Now().Add(connectionTimeout)); err != nil { return nil, "", errors.Wrap(err, "Can't set deadline") } port := listener.Addr().(*net.TCPAddr).Port return listener, fmt.Sprintf("%d", port), nil } func (r *AbstractRuntime) wrapperOutputHandler(conn io.Reader, resultChan chan *result) { // Reset might close outChan, which will cause panic when sending defer func() { if err := recover(); err != nil { r.Logger.WarnWith("Recovered during output handler (Restart called?)", "err", err) } }() outReader := bufio.NewReader(conn) // Read logs & output for { unmarshalledResult := &result{} var data []byte data, unmarshalledResult.err = outReader.ReadBytes('\n') if unmarshalledResult.err != nil { r.Logger.WarnWith(string(common.FailedReadFromConnection), "err", unmarshalledResult.err) resultChan <- unmarshalledResult continue } switch data[0] { case 'r': // try to unmarshall the result if unmarshalledResult.err = json.Unmarshal(data[1:], unmarshalledResult); unmarshalledResult.err != nil { r.resultChan <- unmarshalledResult continue } switch unmarshalledResult.BodyEncoding { case "text": unmarshalledResult.DecodedBody = []byte(unmarshalledResult.Body) case "base64": unmarshalledResult.DecodedBody, unmarshalledResult.err = base64.StdEncoding.DecodeString(unmarshalledResult.Body) default: unmarshalledResult.err = fmt.Errorf("Unknown body encoding - %q", unmarshalledResult.BodyEncoding) } // write back to result channel resultChan <- unmarshalledResult case 'm': r.handleResponseMetric(data[1:]) case 'l': r.handleResponseLog(data[1:]) case 's': r.handleStart() } } } func (r *AbstractRuntime) handleResponseLog(response []byte) { var logRecord rpcLogRecord if err := json.Unmarshal(response, &logRecord); err != nil { r.Logger.ErrorWith("Can't decode log", "error", err) return } logger := r.resolveFunctionLogger(r.functionLogger) logFunc := logger.DebugWith switch logRecord.Level { case "error", "critical", "fatal": logFunc = logger.ErrorWith case "warning": logFunc = logger.WarnWith case "info": logFunc = logger.InfoWith } vars := common.MapToSlice(logRecord.With) logFunc(logRecord.Message, vars...) } func (r *AbstractRuntime) handleResponseMetric(response []byte) { var metrics struct { DurationSec float64 `json:"duration"` } logger := r.resolveFunctionLogger(r.functionLogger) if err := json.Unmarshal(response, &metrics); err != nil { logger.ErrorWith("Can't decode metric", "error", err) return } if metrics.DurationSec == 0 { logger.ErrorWith("No duration in metrics", "metrics", metrics) return } r.Statistics.DurationMilliSecondsCount++ r.Statistics.DurationMilliSecondsSum += uint64(metrics.DurationSec * 1000) } func (r *AbstractRuntime) handleStart() { r.startChan <- struct{}{} } // resolveFunctionLogger return either functionLogger if provided or root logger if not func (r *AbstractRuntime) resolveFunctionLogger(functionLogger logger.Logger) logger.Logger { if functionLogger == nil { return r.Logger } return functionLogger } func (r *AbstractRuntime) newResultChan() { // We create the channel buffered so we won't block on sending r.resultChan = make(chan *result, 1) } func (r *AbstractRuntime) watchWrapperProcess() { // whatever happens, clear wrapper process defer func() { r.wrapperProcess = nil }() // wait for the process processWaitResult := <-r.processWaiter.Wait(r.wrapperProcess, nil) // if we were simply canceled, do nothing if processWaitResult.Err == processwaiter.ErrCancelled { r.Logger.DebugWith("Process watch cancelled. Returning", "wid", r.Context.WorkerID) return } // if process exited gracefully (i.e. wasn't force killed), do nothing if processWaitResult.Err == nil && processWaitResult.ProcessState.Success() { r.Logger.DebugWith("Process watch done - process exited successfully") return } r.Logger.ErrorWith(string(common.UnexpectedTerminationChildProcess), "error", processWaitResult.Err, "status", processWaitResult.ProcessState.String()) var panicMessage string if processWaitResult.Err != nil { panicMessage = processWaitResult.Err.Error() } else { panicMessage = processWaitResult.ProcessState.String() } panic(fmt.Sprintf("Wrapper process for worker %d exited unexpectedly with: %s", r.Context.WorkerID, panicMessage)) }
fn determine_reply(message: &str) -> String { let mut st = String::new(); if message.contains("public") { st.push_str("Tell the entire channel: "); } else { st.push_str("Reply privately: "); } st.push_str(message); st } fn main() { let public_message = "This is a public message"; let private_message = "This is a private message"; println!("{}", determine_reply(public_message)); // Output: Tell the entire channel: This is a public message println!("{}", determine_reply(private_message)); // Output: Reply privately: This is a private message }
#!/bin/sh #tensorboard --logdir=run1:/tmp/tensorflow/ --port 6006 tensorboard --logdir=run1:./logs/ --port 6006
<reponame>hypebid/twitch-views-service // Code generated by protoc-gen-go-grpc. DO NOT EDIT. package pb import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. // Requires gRPC-Go v1.32.0 or later. const _ = grpc.SupportPackageIsVersion7 // TwitchViewsClient is the client API for TwitchViews service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. type TwitchViewsClient interface { // Used to check on the status of the service and all it's dependencies HealthCheck(ctx context.Context, in *HealthRequest, opts ...grpc.CallOption) (*HealthStatus, error) GetStreamInfo(ctx context.Context, in *TwitchUser, opts ...grpc.CallOption) (*StreamInfo, error) } type twitchViewsClient struct { cc grpc.ClientConnInterface } func NewTwitchViewsClient(cc grpc.ClientConnInterface) TwitchViewsClient { return &twitchViewsClient{cc} } func (c *twitchViewsClient) HealthCheck(ctx context.Context, in *HealthRequest, opts ...grpc.CallOption) (*HealthStatus, error) { out := new(HealthStatus) err := c.cc.Invoke(ctx, "/hypebid.TwitchViews/HealthCheck", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *twitchViewsClient) GetStreamInfo(ctx context.Context, in *TwitchUser, opts ...grpc.CallOption) (*StreamInfo, error) { out := new(StreamInfo) err := c.cc.Invoke(ctx, "/hypebid.TwitchViews/GetStreamInfo", in, out, opts...) if err != nil { return nil, err } return out, nil } // TwitchViewsServer is the server API for TwitchViews service. // All implementations must embed UnimplementedTwitchViewsServer // for forward compatibility type TwitchViewsServer interface { // Used to check on the status of the service and all it's dependencies HealthCheck(context.Context, *HealthRequest) (*HealthStatus, error) GetStreamInfo(context.Context, *TwitchUser) (*StreamInfo, error) mustEmbedUnimplementedTwitchViewsServer() } // UnimplementedTwitchViewsServer must be embedded to have forward compatible implementations. type UnimplementedTwitchViewsServer struct { } func (UnimplementedTwitchViewsServer) HealthCheck(context.Context, *HealthRequest) (*HealthStatus, error) { return nil, status.Errorf(codes.Unimplemented, "method HealthCheck not implemented") } func (UnimplementedTwitchViewsServer) GetStreamInfo(context.Context, *TwitchUser) (*StreamInfo, error) { return nil, status.Errorf(codes.Unimplemented, "method GetStreamInfo not implemented") } func (UnimplementedTwitchViewsServer) mustEmbedUnimplementedTwitchViewsServer() {} // UnsafeTwitchViewsServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to TwitchViewsServer will // result in compilation errors. type UnsafeTwitchViewsServer interface { mustEmbedUnimplementedTwitchViewsServer() } func RegisterTwitchViewsServer(s grpc.ServiceRegistrar, srv TwitchViewsServer) { s.RegisterService(&TwitchViews_ServiceDesc, srv) } func _TwitchViews_HealthCheck_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(HealthRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TwitchViewsServer).HealthCheck(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/hypebid.TwitchViews/HealthCheck", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TwitchViewsServer).HealthCheck(ctx, req.(*HealthRequest)) } return interceptor(ctx, in, info, handler) } func _TwitchViews_GetStreamInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(TwitchUser) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(TwitchViewsServer).GetStreamInfo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/hypebid.TwitchViews/GetStreamInfo", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TwitchViewsServer).GetStreamInfo(ctx, req.(*TwitchUser)) } return interceptor(ctx, in, info, handler) } // TwitchViews_ServiceDesc is the grpc.ServiceDesc for TwitchViews service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) var TwitchViews_ServiceDesc = grpc.ServiceDesc{ ServiceName: "hypebid.TwitchViews", HandlerType: (*TwitchViewsServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "HealthCheck", Handler: _TwitchViews_HealthCheck_Handler, }, { MethodName: "GetStreamInfo", Handler: _TwitchViews_GetStreamInfo_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "twitchViews.proto", }
#!/bin/sh # A hook script to verify that we don't commit files that could contain sensible data or credentials like json, csv, xls(x) or .env sensible_files_pattern="\.(csv|xls|xls(x?)|json|env)$" exception="package.json$" files=$(git diff --cached --name-only | grep -v -E "$exception" | grep -E "$sensible_files_pattern") if [ -z "$files" ]; then exit 0 fi echo echo "ERROR: Preventing commit of potentially sensible files:" echo echo "$files" | sed "s/^/ /" echo echo "Either reset those files, add them to .gitignore or remove them." echo echo "If you know what you are doing, please double-check that you are not commiting" echo "any credentials, password or sensible data and run git commit again with --no-verify." echo exit 1
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs'; import { Post, PostUser } from './post.model'; @Injectable({ providedIn: 'root' }) export class MainService { userId: string; postsChanged = new Subject<PostUser[]>(); private posts: PostUser[] = []; constructor() { } getHomeInfo() { return this.posts.length === 0; } setPosts(posts: PostUser[]) { this.posts = posts; this.postsChanged.next(this.posts.slice()); } getPosts() { return this.posts.slice(); } updatePost(postIndex: number, updatedPost: Post) { this.posts[postIndex].post = updatedPost; this.postsChanged.next(this.posts.slice()); } }
#!/bin/sh # CYBERWATCH SAS - 2017 # # Security fix for DSA-3012-1 # # Security announcement date: 2014-08-26 00:00:00 UTC # Script generation date: 2017-01-01 21:07:01 UTC # # Operating System: Debian 7 (Wheezy) # Architecture: x86_64 # # Vulnerable packages fix on version: # - eglibc:2.13-38+deb7u4 # # Last versions recommanded by security team: # - eglibc:2.13-38+deb7u11 # # CVE List: # - CVE-2014-5119 # # More details: # - https://www.cyberwatch.fr/vulnerabilites # # Licence: Released under The MIT License (MIT), See LICENSE FILE sudo apt-get install --only-upgrade eglibc=2.13-38+deb7u11 -y
func testApplicationLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) { measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } // Replace 5.0 with the expected maximum launch time in seconds XCTAssertLessThanOrEqual(XCTPerformanceMetric_WallClockTime, 5.0, "Application launch time exceeds the expected performance metrics") } else { XCTFail("Platform version does not meet the minimum requirements for performance testing") } }
parallel --jobs 6 < ./results/exp_opennb/run-2/lustre_7n_6t_6d_1000f_617m_5i/jobs/jobs_n3.txt
<filename>src/yimei/jss/gp/terminal/DoubleERC.java package yimei.jss.gp.terminal; import ec.EvolutionState; import ec.Problem; import ec.app.regression.func.RegERC; import ec.gp.ADFStack; import ec.gp.GPData; import ec.gp.GPIndividual; import yimei.jss.gp.data.DoubleData; /** * Created by YiMei on 2/10/16. */ public class DoubleERC extends RegERC { @Override public String toString() { return String.valueOf(value); } @Override public void eval(final EvolutionState state, final int thread, final GPData input, final ADFStack stack, final GPIndividual individual, final Problem problem) { DoubleData a = ((DoubleData)(input)); a.value = value; } }
import curses def main(stdscr): # do not wait for input when calling getch stdscr.nodelay(1) f=open("output.txt","w+") while True: # get keyboard input, returns -1 if none available c = int(stdscr.getch()) if c != -1: f.write(chr(c)) print(chr(c)) # print numeric value stdscr.addstr(str(c) + ' ') stdscr.refresh() # return curser to start position stdscr.move(0, 0) if _name_ == '_main_': curses.wrapper(main)
import pandas as pd df = pd.DataFrame({'Price':[], 'Quantity':[], 'Quality':[] })
# pylint: disable=unused-argument # start_marker from dagster import pipeline, solid @solid def return_one(context) -> int: return 1 @solid def add_one(context, number: int) -> int: return number + 1 @pipeline def linear_pipeline(): add_one(add_one(add_one(return_one()))) # end_marker
<reponame>OpenByteDev/SourceScraper import { VerystreamScraper } from '../lib'; import { ScraperTester } from 'source-scraper-test-utils'; const urls = ['https://verystream.com/stream/3tngLkGr2pn/']; ScraperTester.fromStatic(VerystreamScraper) .testUrlDetection(urls) .testScraping(urls) .run();
from datetime import datetime from sqlalchemy import Column, Integer, ForeignKey, Boolean, DateTime from sqlalchemy.orm import relationship, backref from .base import DeclarativeBase class AccountLink(DeclarativeBase): # table __tablename__ = 'account_link' # columns id = Column(Integer, primary_key=True, nullable=False) peer_id = Column(Integer, ForeignKey('account_link.id')) link_id = Column(Integer, ForeignKey('link.id', ondelete='CASCADE'), nullable=False) from_account_id = Column(Integer, ForeignKey('account.id', ondelete='CASCADE'), nullable=False) to_account_id = Column(Integer, ForeignKey('account.id', ondelete='CASCADE'), nullable=False) created_date = Column(DateTime, nullable=False, default=datetime.now) modified_date = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now) hidden = Column(Boolean, nullable=False, default=False) # relationships peer = relationship('AccountLink', remote_side=[id], post_update=True) link = relationship('Link', backref=backref('account_links', lazy=True), primaryjoin='Link.id==AccountLink.link_id') from_account = relationship('Account', backref=backref('account_links', lazy=True), primaryjoin='Account.id==AccountLink.from_account_id') to_account = relationship('Account', primaryjoin='Account.id==AccountLink.to_account_id') # no backref # constructor def __init__(self, link, from_account, to_account): self.link = link self.from_account = from_account self.to_account = to_account self.hidden = False
import { FileOpener } from '../../core'; import { GameUpdateArgs, Session } from '../../game'; import { DividerMenuItem, MenuDescription, SceneMenu, SceneMenuTitle, TextMenuItem, } from '../../gameObjects'; import { FileMapListReader, MapLoader } from '../../map'; import { GameScene } from '../GameScene'; import { GameSceneType } from '../GameSceneType'; export class ModesCustomScene extends GameScene { private title: SceneMenuTitle; private description: MenuDescription; private loadItem: TextMenuItem; private singlePlayerItem: TextMenuItem; private multiPlayerItem: TextMenuItem; private backItem: TextMenuItem; private menu: SceneMenu; private mapLoader: MapLoader; private session: Session; private fileMapListReader: FileMapListReader = null; protected setup({ mapLoader, session }: GameUpdateArgs): void { this.mapLoader = mapLoader; this.session = session; this.title = new SceneMenuTitle('MODES → CUSTOM MAPS'); this.root.add(this.title); this.description = new MenuDescription( 'LOAD YOUR OWN LIST OF MAPS \nFROM CONSTRUCTION JSON FILES', ); this.description.position.set(16, 180); this.root.add(this.description); this.loadItem = new TextMenuItem('LOAD'); this.loadItem.selected.addListener(this.handleLoadSelected); this.singlePlayerItem = new TextMenuItem('PLAY - 1 PLAYER'); this.singlePlayerItem.selected.addListener(this.handleSinglePlayerSelected); this.singlePlayerItem.setFocusable(false); this.multiPlayerItem = new TextMenuItem('PLAY - 2 PLAYERS'); this.multiPlayerItem.selected.addListener(this.handleMultiPlayerSelected); this.multiPlayerItem.setFocusable(false); this.backItem = new TextMenuItem('BACK'); this.backItem.selected.addListener(this.handleBackSelected); const divider = new DividerMenuItem(); const menuItems = [ this.loadItem, this.singlePlayerItem, this.multiPlayerItem, divider, this.backItem, ]; this.menu = new SceneMenu(); this.menu.position.addY(164); this.menu.setItems(menuItems); this.root.add(this.menu); } private updateMenu(): void { this.singlePlayerItem.setFocusable(this.canPlay()); this.multiPlayerItem.setFocusable(this.canPlay()); } private canPlay(): boolean { return this.fileMapListReader !== null; } private handleLoadSelected = (): void => { const fileOpener = new FileOpener(); fileOpener.opened.addListener((files) => { this.fileMapListReader = new FileMapListReader(files); this.updateMenu(); }); fileOpener.openDialog(); }; private handleSinglePlayerSelected = (): void => { this.mapLoader.setListReader(this.fileMapListReader); this.navigator.replace(GameSceneType.LevelSelection); }; private handleMultiPlayerSelected = (): void => { this.session.setMultiplayer(); this.mapLoader.setListReader(this.fileMapListReader); this.navigator.replace(GameSceneType.LevelSelection); }; private handleBackSelected = (): void => { this.mapLoader.restoreDefaultReader(); this.navigator.back(); }; }
import { GetList, GetListItems } from 'components/Api' export const getList = async (listName) => { let list = await GetList({ listName, expand: 'DefaultView,DefaultView/ViewFields,Views,Views/ViewFields,Fields', }) const options = {} if (list.BaseTemplate === 101) options.expand = 'File' let items = await GetListItems({ listName, ...options }) list.CurrentView = list.DefaultView return { list, items, } }
#!/bin/sh # Change directory to the Node.js application directory cd /var/www/node # Start the Node.js application using PM2 with the specified configurations pm2 start npm --max-memory-restart 200M --name "tsoa-seed" -l /var/log/nodejs/pm2.log --no-daemon -u node -- start
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package brooklyn.entity.webapp.jboss; import static org.testng.Assert.assertEquals; import java.net.URL; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import brooklyn.entity.basic.SoftwareProcess; import brooklyn.entity.proxying.EntitySpec; import brooklyn.entity.rebind.RebindOptions; import brooklyn.entity.rebind.RebindTestFixtureWithApp; import brooklyn.location.basic.LocalhostMachineProvisioningLocation; import brooklyn.test.EntityTestUtils; import brooklyn.test.HttpTestUtils; import brooklyn.test.WebAppMonitor; import brooklyn.test.entity.TestApplication; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; public class JBoss7ServerRebindingIntegrationTest extends RebindTestFixtureWithApp { private static final Logger LOG = LoggerFactory.getLogger(JBoss7ServerRebindingIntegrationTest.class); private URL warUrl; private LocalhostMachineProvisioningLocation localhostProvisioningLocation; private TestApplication newApp; private List<WebAppMonitor> webAppMonitors = new CopyOnWriteArrayList<WebAppMonitor>(); private ExecutorService executor; @BeforeMethod(groups = "Integration") @Override public void setUp() throws Exception { super.setUp(); String warPath = "hello-world.war"; warUrl = getClass().getClassLoader().getResource(warPath); executor = Executors.newCachedThreadPool(); localhostProvisioningLocation = (LocalhostMachineProvisioningLocation) origManagementContext.getLocationRegistry().resolve("localhost"); } @Override @AfterMethod(alwaysRun=true) public void tearDown() throws Exception { for (WebAppMonitor monitor : webAppMonitors) { monitor.terminate(); } if (executor != null) executor.shutdownNow(); super.tearDown(); } private WebAppMonitor newWebAppMonitor(String url) { WebAppMonitor monitor = new WebAppMonitor(url) // .delayMillis(0) .logFailures(LOG); webAppMonitors.add(monitor); executor.execute(monitor); return monitor; } @Test(groups = "Integration") public void testRebindsToRunningServer() throws Exception { // Start an app-server, and wait for it to be fully up JBoss7Server origServer = origApp.createAndManageChild(EntitySpec.create(JBoss7Server.class) .configure("war", warUrl.toString())); origApp.start(ImmutableList.of(localhostProvisioningLocation)); HttpTestUtils.assertHttpStatusCodeEventuallyEquals(origServer.getAttribute(JBoss7Server.ROOT_URL), 200); WebAppMonitor monitor = newWebAppMonitor(origServer.getAttribute(JBoss7Server.ROOT_URL)); // Rebind newApp = rebind(RebindOptions.create().terminateOrigManagementContext(true)); JBoss7Server newServer = (JBoss7Server) Iterables.find(newApp.getChildren(), Predicates.instanceOf(JBoss7Server.class)); String newRootUrl = newServer.getAttribute(JBoss7Server.ROOT_URL); assertEquals(newRootUrl, origServer.getAttribute(JBoss7Server.ROOT_URL)); assertEquals(newServer.getAttribute(JBoss7Server.MANAGEMENT_HTTP_PORT), origServer.getAttribute(JBoss7Server.MANAGEMENT_HTTP_PORT)); assertEquals(newServer.getAttribute(JBoss7Server.DEPLOYED_WARS), origServer.getAttribute(JBoss7Server.DEPLOYED_WARS)); EntityTestUtils.assertAttributeEqualsEventually(newServer, SoftwareProcess.SERVICE_UP, true); HttpTestUtils.assertHttpStatusCodeEventuallyEquals(newRootUrl, 200); // confirm that deploy() effector affects the correct jboss server newServer.deploy(warUrl.toString(), "myhello.war"); HttpTestUtils.assertHttpStatusCodeEventuallyEquals(newRootUrl+"myhello", 200); // check we see evidence of the enrichers and sensor-feeds having an effect. // Relying on WebAppMonitor to cause these to change. EntityTestUtils.assertAttributeChangesEventually(newServer, JBoss7Server.REQUEST_COUNT); EntityTestUtils.assertAttributeChangesEventually(newServer, JBoss7Server.REQUESTS_PER_SECOND_IN_WINDOW); EntityTestUtils.assertAttributeChangesEventually(newServer, JBoss7Server.REQUESTS_PER_SECOND_IN_WINDOW); EntityTestUtils.assertAttributeChangesEventually(newServer, JBoss7Server.PROCESSING_TIME_FRACTION_IN_WINDOW); assertEquals(monitor.getFailures(), 0); } }
import Foundation import AudioToolbox extension AudioStreamBasicDescription { var packetPerSecond: Int { get { return Int(Float(self.mSampleRate) / Float(self.mFramesPerPacket)) } } } func processAudioDescription(_ audioDescription: AudioStreamBasicDescription) -> Bool { let packetsPerSecond = audioDescription.packetPerSecond return (100...1000).contains(packetsPerSecond) } // Example usage let audioDesc = AudioStreamBasicDescription(mSampleRate: 44100.0, mFramesPerPacket: 1024) let isWithinRange = processAudioDescription(audioDesc) print(isWithinRange) // Output: true
Option Explicit Sub unit_test() Dim testCount As Integer Dim passCount As Integer For testCount = 0 To UBound(tests) If tests(testCount).runTest() Then passCount = passCount + 1 Else Debug.Print tests(testCount).name & " failed." End If Next testCount Debug.Print passCount & " of " & (UBound(tests)+1) & " tests passed." End Sub
#!/usr/bin/env bash # Originally written by Ralf Kistner <ralf@embarkmobile.com>, but placed in the public domain set -eu bootanim="" failcounter=0 timeout_in_sec=300 until [[ "$bootanim" =~ "stopped" ]]; do echo "Yes" bootanim=`adb -e shell getprop init.svc.bootanim 2>&1 &` if [[ "$bootanim" =~ "device not found" || "$bootanim" =~ "device offline" || "$bootanim" =~ "running" ]]; then let "failcounter += 1" echo "Waiting for emulator to start" if [[ $failcounter == $timeout_in_sec ]]; then echo "Timeout ($timeout_in_sec seconds) reached; failed to start emulator" exit 1 fi else let "failcounter += 1" echo "Waiting for emulator to start" if [[ $failcounter == $timeout_in_sec ]]; then echo "Timeout ($timeout_in_sec seconds) reached; failed to start emulator" exit 1 fi fi sleep 1 done echo "Emulator is ready"
<reponame>hugofqueiros/gulp-es6-boilerplate import gulp from 'gulp'; gulp.task('default', ['setWatch', 'build'], () => { gulp.start('server'); });
./node_modules/ganache-cli/cli.js --flavor tezos --seed alice --accounts 10 --host 0.0.0.0 --genesisBlockHash BLEY49gkRAU5YN5LABnNNSEvjZz2WU8M5hFdoTrxZSC5GYQ7KZT -k edo
<html> <head> <title>Login Page</title> </head> <body> <h1>Login</h1> <form method="post" action="/login"> <p>Username: <input type="text" name="username"></p> <p>Password: <input type="password" name="password"></p> <p><input type="submit" value="Login"></p> </form> </body> </html>
<reponame>mhammer708/mytinerary import React from 'react' import {connect} from 'react-redux' import { Modal, Form, Input, Select, Button, Switch, Checkbox, Row, Col, } from 'antd' import {fetchBills, postBill} from '../store/bills' import {postPlan} from '../store/plans' import {fetchTrips, fetchTrip} from '../store/trips' class SettleUp extends React.Component { constructor() { super() this.daysArr = [] this.switchFlag = false this.handleSubmit = this.handleSubmit.bind(this) this.handleOk = this.handleOk.bind(this) this.handleCancel = this.handleCancel.bind(this) } state = {visible: false} showModal = () => { this.setState({ visible: true, }) } handleSubmit(formData) { this.props.postPlan(formData, this.props.tripId) this.setState({ visible: false, }) console.log('Success:', formData) } handleOk = (e) => { console.log(e) this.setState({ visible: false, }) } handleCancel = (e) => { console.log(e) this.setState({ visible: false, }) } componentDidMount() { this.props.getTrip(this.props.tripId) } render() { console.log('props', this.props) return ( <span> <Button onClick={this.showModal} block> Settle Up </Button> <Modal title="Settle Up" visible={this.state.visible} onOk={this.handleOk} onCancel={this.handleCancel} // width={800} className="modal" // footer={null} > <div className="center"></div> </Modal> </span> ) } } const mapState = (state) => { return { bills: state.bills, trips: state.trips, trip: state.trip, } } const mapDispatch = (dispatch) => { return { getBills: (tripId) => dispatch(fetchBills(tripId)), postBill: (formData, planId, tripId) => dispatch(postBill(formData, planId, tripId)), postPlan: (plan, tripId) => dispatch(postPlan(plan, tripId)), getTrips: (userId) => dispatch(fetchTrips(userId)), getTrip: (tripId) => dispatch(fetchTrip(tripId)), // getMyTransactions: (tripId) => dispatch(fetchMyTransactions(tripId)), // getPlans: (tripId) => dispatch(fetchPlans(tripId)), } } export default connect(mapState, mapDispatch)(SettleUp)
<gh_stars>0 #include "HOffsetManager.h" #include <sstream> #include <fstream> #include <iomanip> #include "../Utilis/HUtilis.h" #include "../NetVarManager/HNetVarManager.h" namespace Dumper { namespace OffsetManager { void COffsetManager::Dump( void ) { if( !pProcess->GetModuleByName( "client.dll" ) || !pProcess->GetModuleByName( "engine.dll" ) ) return; std::stringstream ss; ss << "- - - - - - Tool by Y3t1y3t ( uc ) - - - - - - " << std::endl; ss << "| -> http://www.unknowncheats.me/forum/counterstrike-global-offensive/100856-cs-go-offset-dumper-small-one.html" << std::endl; ss << "| -> " << Utilis::GetTime(); ss << "- -" << std::endl << std::endl; DumpNetVar( "DT_WeaponCSBase", "m_fAccuracyPenalty", 0x0, ss ); DumpNetVar( "DT_BaseAnimating", "m_nForceBone", 0x0, ss ); DumpNetVar( "DT_BaseCombatWeapon", "m_iState", 0x0, ss ); DumpNetVar( "DT_BaseCombatWeapon", "m_iClip1", 0x0, ss ); DumpNetVar( "DT_BaseCombatWeapon", "m_flNextPrimaryAttack", 0x0, ss ); DumpPatternOffset( "DT_BaseCombatWeapon", "m_bCanReload", "client.dll", "80 B9 ? ? ? ? ? 0F 85 ? ? ? ? A1", Remote::SignatureType_t::READ, 0x2, 0x0, ss ); DumpNetVar( "DT_BaseCombatWeapon", "m_iPrimaryAmmoType", 0x0, ss ); LogToStringStream( "DT_BaseCombatWeapon", "m_iWeaponID", pNetVarManager->GetNetVar( "DT_WeaponCSBase", "m_fAccuracyPenalty" ) + 0x2C, ss ); DumpNetVar( "DT_WeaponCSBaseGun", "m_zoomLevel", 0x0, ss ); DumpNetVar( "DT_BaseEntity", "m_bSpotted", 0x0, ss ); DumpNetVar( "DT_BaseEntity", "m_bSpottedByMask", 0x0, ss ); DumpNetVar( "DT_BaseEntity", "m_hOwnerEntity", 0x0, ss ); DumpNetVar( "DT_BaseEntity", "m_vecOrigin", 0x0, ss ); DumpNetVar( "DT_BaseEntity", "m_iTeamNum", 0x0, ss ); DumpNetVar( "DT_CSPlayer", "m_flFlashMaxAlpha", 0x0, ss ); DumpNetVar( "DT_CSPlayer", "m_flFlashDuration", 0x0, ss ); LogToStringStream( "DT_CSPlayer", "m_iGlowIndex", pNetVarManager->GetNetVar( "DT_CSPlayer", "m_flFlashDuration" ) + 0x18, ss ); DumpNetVar( "DT_CSPlayer", "m_angEyeAngles", 0x0, ss ); DumpNetVar( "DT_CSPlayer", "m_iAccount", 0x0, ss ); DumpNetVar( "DT_CSPlayer", "m_ArmorValue", 0x0, ss ); DumpNetVar( "DT_CSPlayer", "m_bGunGameImmunity", 0x0, ss ); DumpNetVar( "DT_CSPlayer", "m_iShotsFired", 0x0, ss ); DumpPatternOffset( "DT_CSPlayerResource", "CSPlayerResource", "client.dll", "8B 3D ? ? ? ? 85 FF 0F 84 ? ? ? ? 81 C7", Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x2, 0x0, ss ); DumpNetVar( "DT_CSPlayerResource", "m_iCompetitiveRanking", 0x0, ss ); DumpNetVar( "DT_CSPlayerResource", "m_iCompetitiveWins", 0x0, ss ); DumpNetVar( "DT_CSPlayerResource", "m_iKills", 0x0, ss ); DumpNetVar( "DT_CSPlayerResource", "m_iAssists", 0x0, ss ); DumpNetVar( "DT_CSPlayerResource", "m_iDeaths", 0x0, ss ); DumpNetVar( "DT_CSPlayerResource", "m_iPing", 0x0, ss ); DumpNetVar( "DT_CSPlayerResource", "m_iScore", 0x0, ss ); DumpNetVar( "DT_CSPlayerResource", "m_szClan", 0x0, ss ); DumpNetVar( "DT_BasePlayer", "m_lifeState", 0x0, ss ); DumpNetVar( "DT_BasePlayer", "m_fFlags", 0x0, ss ); DumpNetVar( "DT_BasePlayer", "m_iHealth", 0x0, ss ); DumpNetVar( "DT_BasePlayer", "m_hLastWeapon", 0x0, ss ); DumpNetVar( "DT_BasePlayer", "m_hMyWeapons", 0x0, ss ); DumpNetVar( "DT_BasePlayer", "m_hActiveWeapon", 0x0, ss ); DumpNetVar( "DT_BasePlayer", "m_Local", 0x0, ss ); DumpNetVar( "DT_BasePlayer", "m_vecViewOffset[0]", 0x0, ss ); DumpNetVar( "DT_BasePlayer", "m_nTickBase", 0x0, ss ); DumpNetVar( "DT_BasePlayer", "m_vecVelocity[0]", 0x0, ss ); DumpNetVar( "DT_BasePlayer", "m_szLastPlaceName", 0x0, ss ); LogToStringStream( "DT_Local", "m_vecPunch", pNetVarManager->GetNetVar( "DT_BasePlayer", "m_Local" ) + 0x70, ss ); LogToStringStream( "DT_Local", "m_iCrossHairID", pNetVarManager->GetNetVar( "DT_CSPlayer", "m_bHasDefuser" ) + 0x5C, ss ); DumpPatternOffset( "BaseEntity", "m_bDormant", "client.dll", "55 8B EC 53 8B 5D 08 56 8B F1 88 9E ? ? ? ? E8", Remote::SignatureType_t::READ, 0xC, 0x0, ss ); LogToStringStream( "BaseEntity", "m_dwModel", 0x6C, ss ); LogToStringStream( "BaseEntity", "m_dwIndex", 0x64, ss ); LogToStringStream( "BaseEntity", "m_dwBoneMatrix", pNetVarManager->GetNetVar( "DT_BaseAnimating", "m_nForceBone" ) + 0x1C, ss ); LogToStringStream( "BaseEntity", "m_bMoveType", 0x258, ss ); DumpPatternOffset( "ClientState", "m_dwClientState", "engine.dll", "A1 ? ? ? ? F3 0F 11 80 ? ? ? ? D9 46 04 D9 05", Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x0, ss ); DumpPatternOffset( "ClientState", "m_dwLocalPlayerIndex", "engine.dll", "8B 80 ? ? ? ? 40 C3", Remote::SignatureType_t::READ, 0x2, 0x0, ss ); DumpPatternOffset( "ClientState", "m_dwInGame", "engine.dll", "83 B9 ? ? ? ? 06 0F 94 C0 C3", Remote::SignatureType_t::READ, 0x2, 0x0, ss ); DumpPatternOffset( "ClientState", "m_dwMaxPlayer", "engine.dll", "A1 ? ? ? ? 8B 80 ? ? ? ? C3 CC CC CC CC 55 8B EC 8B 45 08", Remote::SignatureType_t::READ, 0x7, 0x0, ss ); DumpPatternOffset( "ClientState", "m_dwMapDirectory", "engine.dll", "05 ? ? ? ? C3 CC CC CC CC CC CC CC 80 3D", Remote::SignatureType_t::READ, 0x1, 0x0, ss ); DumpPatternOffset( "ClientState", "m_dwMapname", "engine.dll", "05 ? ? ? ? C3 CC CC CC CC CC CC CC A1", Remote::SignatureType_t::READ, 0x1, 0x0, ss ); DumpPatternOffset( "ClientState", "m_dwPlayerInfo", "engine.dll", "8B 88 ? ? ? ? 8B 01 8B 40 ? FF D0 8B F8", Remote::SignatureType_t::READ, 0x2, 0x0, ss ); DumpPatternOffset( "ClientState", "m_dwViewAngles", "engine.dll", "F3 0F 11 80 ? ? ? ? D9 46 04 D9 05 ? ? ? ?", Remote::SignatureType_t::READ, 0x4, 0x0, ss ); DumpPatternOffset( "EngineRender", "m_dwViewMatrix", "client.dll", "81 C6 ? ? ? ? 88 45 9A 0F B6 C0", Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x33C, 0xB0, ss ); DumpPatternOffset( "EngineRender", "m_dwEnginePosition", "engine.dll", "F3 0F 11 15 ? ? ? ? F3 0F 11 0D ? ? ? ? F3 0F 11 05 ? ? ? ? F3 0F 11 3D", Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x4, 0x0, ss ); DumpPatternOffset( "RadarBase", "m_dwRadarBase", "client.dll", "A1 ? ? ? ? 8B 0C B0 8B 01 FF 50 ? 46 3B 35 ? ? ? ? 7C EA 8B 0D", Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x0, ss ); DumpNetVar( "RadarBase", "m_dwRadarBasePointer", 0x50, ss ); DumpPatternOffset( "LocalPlayer", "m_dwLocalPlayer", "client.dll", "A3 ? ? ? ? C7 05 ? ? ? ? ? ? ? ? E8 ? ? ? ? 59 C3 6A", Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x10, ss ); DumpPatternOffset( "EntityList", "m_dwEntityList", "client.dll", "BB ? ? ? ? 83 FF 01 0F 8C ? ? ? ? 3B F8", Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x0, ss ); DumpPatternOffset( "WeaponTable", "m_dwWeaponTable", "client.dll", "A1 ? ? ? ? 0F B7 C9 03 C9 8B 44 ? 0C C3", Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x0, ss ); DumpPatternOffset( "WeaponTable", "m_dwWeaponTableIndex", "client.dll", "66 8B 8E ? ? ? ? E8 ? ? ? ? 05 ? ? ? ? 50", Remote::SignatureType_t::READ, 0x3, 0x0, ss ); DumpPatternOffset( "Extra", "m_dwInput", "client.dll", "B9 ? ? ? ? FF 75 08 E8 ? ? ? ? 8B 06", Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x0, ss ); DumpPatternOffset( "Extra", "m_dwGlobalVars", "engine.dll", "8B 0D ? ? ? ? 83 C4 04 8B 01 68 ? ? ? ? FF 35", Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x12, 0x0, ss ); DumpPatternOffset( "Extra", "m_dwGlowObject", "client.dll", "A1 ? ? ? ? A8 01 75 4E 0F 57 C0", Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x58, 0x0, ss ); DumpPatternOffset( "Extra", "m_dwForceJump", "client.dll", "89 15 ? ? ? ? 8B 15 ? ? ? ? F6 C2 03 74 03 83 CE 08", Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x2, 0x0, ss ); DumpPatternOffset( "Extra", "m_dwForceAttack", "client.dll" , "89 15 ? ? ? ? 8B 15 ? ? ? ? F6 C2 03 74 03 83 CE 04", Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x2, 0x0, ss ); DumpPatternOffset( "Extra", "m_dwSensitivity", "client.dll", "F3 0F 10 05 ? ? ? ? EB 17 8B 01 8B 40 30 FF D0 F3 0F 10 0D", Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x4, 0x0, ss ); DumpPatternOffset( "Extra", "m_dwMouseEnable", "client.dll", "F3 0F 10 05 ? ? ? ? EB 17 8B 01 8B 40 30 FF D0 F3 0F 10 0D", Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x4, 0x5C, ss ); std::ofstream( "OffsetManager.txt" ) << ss.str(); } void COffsetManager::DumpNetVar( const std::string& tablename, const std::string& varname, uintptr_t offset, std::stringstream& ss ) { LogToStringStream( tablename, varname, pNetVarManager->GetNetVar( tablename, varname ) + offset, ss ); } void COffsetManager::DumpPatternOffset( const std::string& tablename, const std::string& varname, const std::string& module, const char* pattern, int type, uintptr_t pattern_offset, uintptr_t address_offset, std::stringstream& ss ) { LogToStringStream( tablename, varname, pProcess->FindPattern( module, pattern, type, pattern_offset, address_offset ), ss ); } void COffsetManager::LogToStringStream( const std::string& tablename, const std::string& varname, uintptr_t offset, std::stringstream& ss ) { ss << std::setw( 48 ) << std::setfill( '_' ) << std::left << tablename + " -> " + varname + ": " << std::right << std::hex << " 0x" << std::setw( 8 ) << std::setfill( '0' ) << std::uppercase << offset << std::endl; } COffsetManager* COffsetManager::Singleton( void ) { static auto g_pOffsetManager = new COffsetManager(); return g_pOffsetManager; } } }
<filename>charles-university/deep-learning/labs/02/gym_cartpole.py #!/usr/bin/env python3 import numpy as np import tensorflow as tf class Network: OBSERVATIONS = 4 ACTIONS = 2 def __init__(self, threads, seed=42): # Create an empty graph and a session graph = tf.Graph() graph.seed = seed self.session = tf.Session(graph = graph, config=tf.ConfigProto(inter_op_parallelism_threads=threads, intra_op_parallelism_threads=threads)) def construct(self, args): with self.session.graph.as_default(): self.observations = tf.placeholder(tf.float32, [None, self.OBSERVATIONS], name="observations") self.labels = tf.placeholder(tf.int64, [None], name="labels") # Define the model, with the output layers for actions in `output_layer` hidden_layer = self.observations for _ in range(args.num_dense_layers): hidden_layer = tf.layers.dense(hidden_layer, args.num_dense_nodes, activation=tf.nn.relu) hidden_layer = tf.nn.dropout(hidden_layer, keep_prob=args.dropout) output_layer = tf.layers.dense(hidden_layer, self.ACTIONS, activation=None, name="output_layer") self.predictions = tf.argmax(output_layer, axis=1) self.actions = tf.argmax(output_layer, axis=1, name="actions") # Global step loss = tf.losses.sparse_softmax_cross_entropy(self.labels, output_layer, scope="loss") global_step = tf.train.create_global_step() self.training = tf.train.AdamOptimizer(learning_rate=args.learning_rate).minimize(loss, global_step=global_step, name="training") # Summaries accuracy = tf.reduce_mean(tf.cast(tf.equal(self.labels, self.actions), tf.float32)) summary_writer = tf.contrib.summary.create_file_writer(args.logdir, flush_millis=10 * 1000) with summary_writer.as_default(), tf.contrib.summary.record_summaries_every_n_global_steps(100): self.summaries = [tf.contrib.summary.scalar("train/loss", loss), tf.contrib.summary.scalar("train/accuracy", accuracy)] # Construct the saver tf.add_to_collection("end_points/observations", self.observations) tf.add_to_collection("end_points/actions", self.actions) self.saver = tf.train.Saver() # Initialize variables self.session.run(tf.global_variables_initializer()) with summary_writer.as_default(): tf.contrib.summary.initialize(session=self.session, graph=self.session.graph) def train(self, observations, labels): self.session.run([self.training, self.summaries], {self.observations: observations, self.labels: labels}) def save(self, path): self.saver.save(self.session, path) if __name__ == "__main__": import argparse import datetime import os import re # Fix random seed np.random.seed(42) # Parse arguments parser = argparse.ArgumentParser() parser.add_argument("--epochs", default=20, type=int, help="Number of epochs.") parser.add_argument("--threads", default=1, type=int, help="Maximum number of threads to use.") args = parser.parse_args() args.learning_rate = 0.002 args.num_dense_layers = 1 args.num_dense_nodes = 20 args.epochs = 332 args.dropout = 0.9 # Create logdir name args.logdir = "logs/{}-{}-{}".format( os.path.basename(__file__), datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S"), ",".join(("{}={}".format(re.sub("(.)[^_]*_?", r"\1", key), value) for key, value in sorted(vars(args).items()))) ) if not os.path.exists("logs"): os.mkdir("logs") # TF 1.6 will do this by itself # Load the data observations, labels = [], [] with open("gym_cartpole-data.txt", "r") as data: for line in data: columns = line.rstrip("\n").split() observations.append([float(column) for column in columns[0:4]]) labels.append(int(columns[4])) observations, labels = np.array(observations), np.array(labels) # Construct the network network = Network(threads=args.threads) network.construct(args) # Train for i in range(args.epochs): # Train for an epoch network.train(observations, labels) # Save the network network.save("gym_cartpole/model")
<gh_stars>0 package database import ( "context" "fmt" beego "github.com/beego/beego/v2/server/web" "github.com/qiniu/qmgo" "warehouse/logger" ) // MongoCollections mongoDB collections name struct: type MongoCollections struct { TempQuestions string FinalQuestions string TempTestPapers string FinalTestPaper string } // MongoClient qmgo 驱动配置 var MongoClient *qmgo.Client var ( MgoTempQuestions *qmgo.Collection MgoFinalQuestions *qmgo.Collection MgoTempTestPaper *qmgo.Collection MgoFinalTestPaper *qmgo.Collection ) func init() { // 基本配置加载 mongoAddress, err := beego.AppConfig.String("mongoaddr") if err != nil { fmt.Println("Load mongo config error:", err.Error()) } mongoPort, err := beego.AppConfig.String("mongoport") if err != nil { fmt.Println("Load mongo config error:", err.Error()) } mongoDbName, err := beego.AppConfig.String("mongodb") if err != nil { fmt.Println("Load mongo config error:", err.Error()) } mongoUser, err := beego.AppConfig.String("mongouser") if err != nil { fmt.Println("Load mongo config error:", err.Error()) } mongoPassword, err := beego.AppConfig.String("mongopwd") if err != nil { fmt.Println("Load mongo config error:", err.Error()) } // 配置 collections name, 若配置失败, 不连接 mongo 直接返回 mongoColls, err := loadMongoCollectionsName() if err != nil { fmt.Println("Load mongo collections config error: ", err.Error()) return } // 配置完成后再开启mongo 连接 conn := fmt.Sprintf("mongodb://%s:%s", mongoAddress, mongoPort) // 使用 qmgo 连接 qmgoClient, err := qmgo.NewClient( context.Background(), &qmgo.Config{ Uri: conn, Database: mongoDbName, Auth: &qmgo.Credential{ AuthSource: mongoDbName, Username: mongoUser, Password: <PASSWORD>, }, }, ) MongoClient = qmgoClient if err != nil { logger.Recorder.Error("[Mongo-qmgo]" + err.Error()) return } logger.Recorder.Info("[Mongo-qmgo] Connected successfully") // 对接collections MgoTempQuestions = qmgoClient.Database(mongoDbName).Collection(mongoColls.TempQuestions) MgoFinalQuestions = qmgoClient.Database(mongoDbName).Collection(mongoColls.FinalQuestions) MgoTempTestPaper = qmgoClient.Database(mongoDbName).Collection(mongoColls.TempTestPapers) MgoFinalTestPaper = qmgoClient.Database(mongoDbName).Collection(mongoColls.FinalTestPaper) return } // loadMongoCollectionsName load the collections name of mongo func loadMongoCollectionsName() (*MongoCollections, error) { tempQ, err := beego.AppConfig.String("mongo-collections::tempQuestions") if err != nil { logger.Recorder.Error("[Mongo Config] " + err.Error()) return nil, err } finalQ, err := beego.AppConfig.String("mongo-collections::finalQuestions") if err != nil { logger.Recorder.Error("[Mongo Config] " + err.Error()) return nil, err } tempTP, err := beego.AppConfig.String("mongo-collections::tempTestPapers") if err != nil { logger.Recorder.Error("[Mongo Config] " + err.Error()) return nil, err } finalTP, err := beego.AppConfig.String("mongo-collections::finalTestPapers") if err != nil { logger.Recorder.Error("[Mongo Config] " + err.Error()) return nil, err } colls := &MongoCollections{ TempQuestions: tempQ, FinalQuestions: finalQ, TempTestPapers: tempTP, FinalTestPaper: finalTP, } return colls, nil } // mongoClose close the mongo connection. func mongoClose() { if err := MongoClient.Close(context.Background()); err != nil { logger.Recorder.Error("[Mongo] Close Mongo Connection Error: " + err.Error()) } }
from bs4 import BeautifulSoup import math # Given HTML table snippet html_table = ''' </thead> <tbody> <tr> <th scope="row">1</th> <td>654</td> <td>Otto</td> <td>@mdo</td> <td>Glass</td> <td><a href="#" class="info-data" data-toggle="modal" data-target="#modalSales"><i class="fas fa-info-circle"></i></a></td> </tr> </tbody> </table> ''' # Parse HTML table using BeautifulSoup soup = BeautifulSoup(html_table, 'html.parser') table_row = soup.find('tr') # Extract numerical value from the second column and calculate its square root numerical_value = int(table_row.find_all('td')[1].text) square_root_result = math.sqrt(numerical_value) # Output the result of the square root calculation print("Square root of the numerical value:", square_root_result)
#!/bin/bash BRANCH=`git rev-parse --abbrev-ref HEAD` MESSAGE="$BRANCH npm audit fix" if [[ $BRANCH = 'master' ]] || [[ $BRANCH = 'develop' ]] ; then echo 'skipping audit on '$BRANCH' branch' exit 0 fi npm audit fix git add package*.json npm-shrinkwrap.json git commit -m "$MESSAGE"
#!/bin/sh PLATFORM="ios" TREE_DIR="../../tree/pugixml" SRC_DIR="$TREE_DIR/src" BUILD_DIR="build/$PLATFORM" INSTALL_DIR="tmp/$PLATFORM" SRC_PATH="$(pwd)/$SRC_DIR" INSTALL_PATH="$(pwd)/$INSTALL_DIR" if [ ! -d "$SRC_PATH" ]; then echo "SOURCE NOT FOUND!" exit 1 fi # --- TOOLCHAIN_FILE="$CROSS_PATH/core/cmake/toolchains/ios.cmake" cmake -H"$SRC_DIR" -B"$BUILD_DIR" \ -DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN_FILE" -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DLIBRARY_OUTPUT_PATH="$INSTALL_PATH/lib" \ -DBUILD_SHARED_LIBS=OFF -DBUILD_TESTS=OFF \ -DCMAKE_CXX_FLAGS=-fembed-bitcode if [ $? != 0 ]; then echo "CONFIGURATION FAILED!" exit -1 fi # --- rm -rf "$INSTALL_PATH" cmake --build "$BUILD_DIR" if [ $? != 0 ]; then echo "BUILD FAILED!" exit -1 fi rm -rf "$TREE_DIR/$PLATFORM/lib" mkdir -p "$TREE_DIR/$PLATFORM/lib" mv "tmp/$PLATFORM/lib" "$TREE_DIR/$PLATFORM" cd "$TREE_DIR/$PLATFORM" ln -s "../src/src" include
public class PrimeFactors { public static void main(String[] args) { int n = 48; // traverse through all prime numbers // less than or equal to n for(int i=2; i<=n; i++) { // while n is divisible by i, // print i and divide n while(n%i==0) { System.out.print(i + " "); n=n/i; } } // if the last factor is greater than 2, // then it is a prime number. if(n>2) System.out.print(n); } }
<reponame>finogeeks/FinChat-Web import emojione from 'emojione'; import moment from 'moment'; import sdk, { FinChatNormal, FinChatNetDisk, EventStatus } from '@finogeeks/matrix-js-sdk'; import emitter from '@/utils/event-emitter'; import { last as _last, cloneDeep } from 'lodash'; import { Message } from '@finogeeks/finchat-model'; import { AVATAR_SIZE, MAX_MESSAGES_SHOW, FILTER_DEFINITION, } from '../config'; import vuex from '@/store'; import { ChannelService } from '@/utils/channel'; import { IAM_INFO_KEY, BASE_URL, RoomType } from '@/commonVariable'; export default class BaseModule { constructor(mxClient, opts) { this.mxClient = mxClient; this.baseUrl = opts.baseUrl || window.location.origin; this.deviceId = opts.deviceId; this.accessToken = opts.accessToken; this.jwtToken = opts.apiToken; this.userId = opts.userId; this.mxSdk = sdk; this.fcApis = new FinChatNormal(); this.$fcChannel = new ChannelService(); const myinfo = JSON.parse(window.localStorage.getItem(IAM_INFO_KEY)); this.$fcChannel.init( '', myinfo.user_id, myinfo.jwt, myinfo.access_token, ); } // QQ房间会覆盖这个方法 async buildRoom(mxRoom) { if (!mxRoom) return null; const roomState = mxRoom.currentState; const createEvent = roomState.getStateEvents('m.room.create', ''); const memberEvent = roomState.getStateEvents('m.room.member', this.userId); const topicEvent = roomState.getStateEvents('m.room.topic', ''); const historyEvent = roomState.getStateEvents('m.room.history_visibility', ''); const powerEvent = roomState.getStateEvents('m.room.power_levels', ''); const nameEvent = roomState.getStateEvents('m.room.name', ''); const joinRuleEvent = roomState.getStateEvents('m.room.join_rules', ''); const archiveEvent = roomState.getStateEvents('m.room.archive', ''); const baseUrl = this.baseUrl; const roomId = mxRoom.roomId; const me = roomState.getMember(this.userId); // 非法房间返回 null if (!createEvent) { return {}; } const content = createEvent.event.content || {}; const rawTopic = topicEvent && topicEvent.event && topicEvent.event.content ? topicEvent.event.content.topic : ''; const roomRule = this.mxClient.getRoomPushRule('global', roomId); const isDirect = content.is_direct ? 1 : 0; const isBot = content.is_bot ? 1 : 0; const members = roomState.getMembers().map(mxMember => this.buildRoomMember(mxMember)); const membership = (me && me.membership) || ''; const isSecret = content.is_secret ? 1 : 0; const isEncryped = this.mxClient.isRoomEncrypted(roomId) ? 1 : 0; const isChannel = content.is_channel ? 1 : 0; let isArchiveChannel = archiveEvent && archiveEvent.event && archiveEvent.event.content && archiveEvent.event.content.archive; // TODO channel相关的信息在原版build中是异步的 需要优化一下 let isPrivateChannel = 0; // TODO channel相关的信息在原版build中是异步的 需要优化一下 const enableForward = content.enable_forward ? 1 : 0; const enableFavorite = content.enable_favorite ? 1 : 0; const enableSnapshot = content.enable_snapshot ? 1 : 0; const enableWatermark = content.enable_watermark ? 1 : 0; const unread = mxRoom.getUnreadNotificationCount('total') || 0; // const highlight = mxRoom.getUnreadNotificationCount('highlight') || 0; // TODO @消息需要改用alert事件 所以先去掉highlist字段 const highlight = 0; const powerLevel = (me && me.powerLevel) || 0; const power = this.buildPower(powerEvent); const groupAvatars = []; // TODO build groupAvatars const historyVisibility = (historyEvent && historyEvent.event && historyEvent.event.content && historyEvent.event.content.history_visibility) ? historyEvent.event.content.history_visibility : 'shared'; const isTop = mxRoom.tags['m.favourite'] ? 1 : 0; const createTime = createEvent.event.origin_server_ts; const createrId = createEvent.event.sender; const lastMessage = this.getLastMessage(mxRoom, isDirect); const lastUpdateTime = (lastMessage && lastMessage.eventTime) || 0; const draftMessage = null; // TODO draftMessage const typingCount = 0; const joinRule = (joinRuleEvent && joinRuleEvent.event && joinRuleEvent.event.content && joinRuleEvent.event.content.join_rule) ? joinRuleEvent.event.content.join_rule : 'invite'; const isBan = power && power.default === 100 && powerLevel !== 100; const originalName = (nameEvent && nameEvent.event.content.name) || ''; // 新增新的静音状态字段 let muteStatus = 'default'; if (roomRule && roomRule.enabled && roomRule.actions.length) { const { actions = [] } = roomRule; if (actions.indexOf('dont_notify') > -1) muteStatus = 'mute'; if (actions.indexOf('prohibit_notify') > -1) muteStatus = 'prohibit'; if (actions.indexOf('fold_notify') > -1) muteStatus = 'fold_mute'; } const isMute = muteStatus !== 'default'; // const isMute = (roomRule && roomRule.enabled && roomRule.actions.length === 1 && roomRule.actions[0] === 'dont_notify') ? 1 : 0; let isDelete = mxRoom.tags.delete ? 1 : 0; const isHide = mxRoom.tags.hide ? 1 : 0; const totlaunread = mxRoom.getUnreadNotificationCount('total') || 0; const highlightunread = mxRoom.getUnreadNotificationCount('highlight') || 0; let roomTopic = ''; // TODO buildRoomTopic 方法抽离 try { roomTopic = JSON.parse(rawTopic).topic; } catch (e) { roomTopic = rawTopic; } let isServiceRoom = 0; // TODO buildServiceRoom 方法抽离 let isServiceClosed = 0; try { const custService = JSON.parse(rawTopic).custService; if (custService && custService.type === 'dispatch') { isServiceRoom = 1; isServiceClosed = custService.isClosed ? 1 : 0; } } catch (e) { } let name = ''; // TODO 原来的build中直聊房间有些信息是异步从profile接口拿的,要改掉 ,主要是 peerMemberProfile对象 let avatar = ''; if (isDirect) { const peerMember = members.find(member => (member && member.userId) !== this.userId) || {}; const user = this.mxClient.getUser(peerMember.userId) || {}; name = user.displayName || originalName || '群聊'; avatar = this.mxcTransfer(peerMember.avatarUrl || ''); } else { name = originalName || `${members.length < 2 ? '群聊' : members.map((m) => { if (!m) return {}; const user = this.mxClient.getUser(m.userId) || {}; return user.displayName || m.rawDisplayName || m.userId; }).join('、')}`; avatar = this.mxcTransfer(mxRoom.getAvatarUrl(baseUrl, 60, 60, 'scale', false) || ''); } if (isChannel) { isArchiveChannel = (archiveEvent && archiveEvent.event && archiveEvent.event.content && archiveEvent.event.content.archive) ? archiveEvent.event.content.archive : isArchiveChannel; if (!isDelete) { isDelete = isArchiveChannel; } const res = await this.$fcChannel.getChannelDetail({ roomId }); // // console.log('isPrivateChannel'); // // console.log(res); if (res.status) { isPrivateChannel = res.data.preset === 'private_chat'; } } const { roomType } = this.getRoomMeta(mxRoom); return { roomId, roomType, isDirect, isBot, name, membership, members, groupAvatars, isMute, isDelete, isHide, isSecret, isEncryped, isChannel, isPrivateChannel, isArchiveChannel, isServiceRoom, isServiceClosed, enableForward, enableFavorite, enableSnapshot, enableWatermark, roomTopic, unread, highlight, powerLevel, avatar, historyVisibility, isTop, lastUpdateTime, createTime, createrId, typingCount, power, lastMessage, draftMessage, joinRule, isBan, totlaunread, highlightunread, muteStatus, }; } getRoomMeta(mxRoom) { const roomState = mxRoom.currentState; const topicEvent = roomState.getStateEvents('m.room.topic', ''); let topicData = null; const originTopicData = topicEvent ? topicEvent.event.content.topic : ''; try { if (typeof originTopicData === 'string') { topicData = JSON.parse(originTopicData); } else { topicData = originTopicData; } } catch (error) { topicData = null; } const mxMembers = mxRoom.getJoinedMembers(); // const members: User[] = mxMembers.map(mxUser => this.getLocalUser(mxUser.userId)).filter(user => !!user) // let roomName = mxRoom.name; // let roomAvatar = mxRoom.getAvatarUrl(this.baseUrl, 60, 60, 'scale', false); // // console.log(roomAvatar); // let avatarUserIds = []; // 提供头像的用户id // let isOnline = true; // let orderInfo = {}; let roomType = RoomType.channel; let topicMsg = ''; if (!topicData) { // avatarUserIds = members.slice(0, 4).map(member => member.id); return { // roomName, // avatarUserIds, // roomAvatar, // isOnline, // orderInfo, roomType, // topicMsg, // members, // topic: null, }; } topicMsg = topicData.topic || ''; const { custService, botId, swanBotType } = topicData; // // console.log(topicData); // 投顾房间 if (custService && custService.type == 'dispatch' && custService.staffId) { // const staffInfo = this.getLocalUser(custService.staffId); // // // console.log('meta staffInfo', staffInfo); // orderInfo = { ...custService }; // roomName = staffInfo.name; // roomAvatar = staffInfo.avatar; // isOnline = staffInfo.isOnline; roomType = RoomType.advisor; // avatarUserIds.push(custService.staffId); // 派单房间 } else if (custService && custService.type == 'dispatch') { // orderInfo = { ...custService }; roomType = RoomType.dispatch; // 智能客服房间 } else if (botId && swanBotType === 'smart') { roomType = RoomType.smartBot; // avatarUserIds.push(botId); // 普通机器人房间 } else if (botId) { // avatarUserIds.push(botId); roomType = RoomType.normalBot; // 频道房间 } else { // avatarUserIds = members.slice(0, 4).map(member => member.id); } if (botId) { // const botInfo = this.getLocalUser(botId); // roomAvatar = botInfo.avatar; // roomName = botInfo.name; // avatarUserIds = [botId]; } return { // roomName, // avatarUserIds, // roomAvatar, // isOnline, // orderInfo, roomType, // topicMsg, // members, // topic: topicData, }; } // 获取缩略图的地址 mxcTransfer(mxcUrl, mode = 'raw', width = AVATAR_SIZE, height = AVATAR_SIZE) { if (!mxcUrl) { return ''; } const trimUrl = mxcUrl.trim(); let url = ''; if (trimUrl.startsWith('mxc')) { const params = mode === 'raw' ? [trimUrl] : [trimUrl, width, height, mode]; url = this.mxClient.mxcUrlToHttp(...params); } else if (trimUrl.startsWith('http') || trimUrl.startsWith('blob')) { url = trimUrl; } else if (mode === 'raw') { // console.log('mode === row'); const userSession = JSON.parse(localStorage.getItem('Model:iam-info')); // // console.log(JSON.parse(userSession)); // url = this.mxClient.mxcUrlToHttp(trimUrl); url = `${this.baseUrl}/api/v1/netdisk/download/${mxcUrl}?access_token=${userSession.access_token}&jwt=${userSession.jwt}`; // url = url.replace(/\/\//g, '/') } else { // console.log('getThumbnailUrl'); url = this.fcApis.getThumbnailUrl(trimUrl); } return url; } buildPower(powerEvent) { if (!powerEvent || !powerEvent.event) { return null; } const mxPower = powerEvent.event.content; if (!mxPower) { return null; } return { default: mxPower.events_default, inviteUser: mxPower.invite, kickUser: mxPower.kick, redactUser: mxPower.invite, banUser: mxPower.ban, setAvatar: mxPower.events && mxPower.events['m.room.avatar'] ? mxPower.events['m.room.avatar'] : mxPower.state_default, setHistoryVisibility: mxPower.events && mxPower.events['m.room.history_visibility'] ? mxPower.events['m.room.history_visibility'] : mxPower.state_default, setName: mxPower.events && mxPower.events['m.room.name'] ? mxPower.events['m.room.name'] : mxPower.state_default, setPowerLevel: mxPower.events && mxPower.events['m.room.power_levels'] ? mxPower.events['m.room.power_levels'] : mxPower.state_default, sendMessage: mxPower.events && mxPower.events['m.room.message'] ? mxPower.events['m.room.message'] : mxPower.events_default, }; } getLastMessage(mxRoom, isDirect) { const membership = (mxRoom.getMyMembership && mxRoom.getMyMembership()) || ''; if (!membership) { return {}; } if (membership === 'invite') { const memberEvent = mxRoom.currentState.getStateEvents('m.room.member', mxRoom.myUserId); return this.buildInviteMessage(memberEvent, mxRoom); } const timeline = mxRoom.timeline; const { messages } = this.goThroughTimeLine(timeline); if (mxRoom.roomId === '!173172149777858560:dev.finogeeks.club') { // console.log('get last Message!!'); // console.log(messages); } const filterMessages = messages.filter((message) => { const clearEvent = message._clearEvent.content ? message._clearEvent : message.event; const isCallEvent = this.isCallEvent(clearEvent.type); if (!isCallEvent && clearEvent.type !== 'm.room.message' && !message.event.hint) { return false; } if (isCallEvent) { const reason = clearEvent.content.reason; const info = clearEvent.content.info; if (!info && !reason) { return false; } return true; } else if (FILTER_DEFINITION.room.timeline.types.includes(clearEvent.type)) { return true; } return false; }); const lastMsg = _last(filterMessages); if (lastMsg) { return this.buildMessage(lastMsg, mxRoom, isDirect); } } isCallEvent(type) { return type.startsWith('m.call'); } goThroughTimeLine(timeline) { const result = []; timeline.forEach((mxEvent) => { if (!mxEvent || !mxEvent.event) { return; } const isEncrypted = mxEvent.event.type === 'm.room.encrypted'; const clearEvent = isEncrypted ? mxEvent._clearEvent : mxEvent.event; if (FILTER_DEFINITION.room.timeline.types.includes(clearEvent.type)) { result.push(mxEvent); } }); return { messages: result, startMessage: result[0], lastMessage: result[result.length - 1], }; } buildInviteMessage(messageEvent, mxRoom) { if (mxRoom.getMyMembership() !== 'invite') { return {}; } const sender = (messageEvent && messageEvent.event.sender) || ''; const inviter = mxRoom.currentState.getMember(sender) || {}; return { msgType: 'notice', msgTypeInfo: '', msgBody: `${inviter.rawDisplayName || inviter.name || inviter.userId}向你发起了加入邀请`, eventId: messageEvent.event.event_id, status: 'sent', eventTime: messageEvent.event.origin_server_ts, }; } // 房间timeline的消息实体 buildTimelineMessage(messageEvent, mxRoom) { const clearEvent = messageEvent._clearEvent.content ? messageEvent._clearEvent : messageEvent.event; const sender = messageEvent.sender || mxRoom.getMember(messageEvent.event.sender) || {}; const eventId = messageEvent.event.event_id; const eventType = clearEvent.type; const eventTime = messageEvent.event.origin_server_ts || Date.now(); let status = ''; let content = {}; switch (messageEvent.status) { case 'encrypting': case 'sending': case 'queued': status = 'sending'; break; case 'not_sent': status = 'error'; break; case 'sent': case null: status = 'success'; break; default: break; } let msgType = ''; let msgTypeInfo = ''; const user = this.mxClient.getUser(sender.userId); if (!user) return {}; let msgBody = ''; if (eventType === Message.types.message) { msgType = clearEvent.content.msgtype; switch (msgType) { case Message.types.text: { msgBody += clearEvent.content.body; break; } case Message.types.alert: msgBody += clearEvent.content.body; break; case Message.types.signal: msgBody += clearEvent.content.body; break; case Message.types.convo: msgBody += clearEvent.content.body; break; case Message.types.image: if (clearEvent.content.flag) { msgBody += '[保密消息]'; } else { msgBody += '[图片]'; } break; case Message.types.video: if (clearEvent.content.flag) { msgBody += '[保密消息]'; } else { msgBody += '[视频]'; } break; case Message.types.audio: msgBody += '[语音]'; break; case Message.types.file: if (clearEvent.content.flag) { msgBody += '[保密消息]'; } else { msgBody += `[文件] ${clearEvent.content.body}`; } break; case Message.types.location: msgBody += '[位置]'; break; case Message.types.url: msgBody += '[链接] '; msgBody += `${clearEvent.content.info && (clearEvent.content.info.title || clearEvent.content.info.description)}`; break; case Message.types.businesscard: msgBody += '[个人名片]'; break; case Message.types.badEncrypted: case Message.types.eventEncrypted: msgBody += '[无法解析的加密消息]'; break; case Message.types.notice: msgBody = clearEvent.content.body; break; case Message.types.call: break; case 'fc.applet': msgTypeInfo = '[小程序]'; break; case Message.types.unknown: default: msgBody += '[未知消息类型]'; break; } content = { msgType, msgTypeInfo, sender: user.displayName, msgBody: emojione.unicodeToImage(msgBody), eventId, status, eventTime, senderId: sender.userId, }; } else if (eventType === Message.types.call) { const info = clearEvent.content.info; const reason = clearEvent.content.reason; const isVideoCall = info && info.isVideoCall === '1'; if (!info && !reason) { msgBody = ''; } else if (reason) { msgBody = '未接通'; } else { const duration = parseInt(info.duration, 10); if (duration) { const temp = moment.utc(duration); msgBody = `通话时长${duration > 3600 * 1000 ? temp.format('HH:mm:ss') : temp.format('mm:ss')}`; } else if (messageEvent.event.sender === this.userId) { msgBody = '已取消'; } else { msgBody = '对方已取消'; } } if (isVideoCall) { msgBody = `[视频通话] ${msgBody}`; } else { msgBody = `[语音通话] ${msgBody}`; } content = { msgType, msgTypeInfo, msgBody, eventId, status, eventTime, }; } else { msgType = 'notice'; msgBody = this.getNoticeMsgBody(messageEvent); content = { msgType, msgTypeInfo, sender: user.displayName, msgBody: msgBody ? emojione.unicodeToImage(msgBody) : '', eventId, status, eventTime, }; } let isRedacted; if (messageEvent.isRedacted()) { isRedacted = true; } const { content: oriContent, event_id, origin_server_ts, room_id, type, user_id, state_key } = messageEvent.event; // eslint-disable-line // content.users = oriContent.users; return { content: Object.assign({}, oriContent, content), eventId: event_id, time: origin_server_ts, roomId: room_id, sender: sender.userId || user_id, type, status, state_key, msgType, msgTypeInfo, isRedacted, redacts: clearEvent.redacts, }; } // 用于房间列表最新消息展示用的消息实体 TODO 收拾一下! buildMessage(messageEvent, mxRoom, isDirect) { const clearEvent = messageEvent._clearEvent.content ? messageEvent._clearEvent : messageEvent.event; const sender = messageEvent.sender || mxRoom.getMember(messageEvent.event.sender) || {}; const eventId = messageEvent.event.event_id; const eventType = clearEvent.type; const eventTime = messageEvent.event.origin_server_ts || Date.now(); let status = ''; switch (messageEvent.status) { case 'encrypting': case 'sending': case 'queued': status = 'sending'; break; case 'not_sent': status = 'error'; break; case 'sent': case null: status = 'success'; break; default: break; } let msgType = ''; let msgTypeInfo = ''; const user = this.mxClient.getUser(sender.userId); if (!user) return {}; let msgBody = ''; if (eventType === Message.types.message) { // console.log('buildMessage'); msgType = clearEvent.content.msgtype; // console.log(clearEvent.content); // console.log(msgType); switch (msgType) { case Message.types.text: { msgBody += clearEvent.content.body; break; } case Message.types.alert: msgBody += clearEvent.content.body; break; case Message.types.signal: msgBody += clearEvent.content.body; break; case Message.types.convo: msgBody += clearEvent.content.body; break; case Message.types.image: if (clearEvent.content.flag) { msgBody += '[保密消息]'; } else { msgBody += '[图片]'; } break; case Message.types.video: if (clearEvent.content.flag) { msgBody += '[保密消息]'; } else { msgBody += '[视频]'; } break; case Message.types.audio: msgBody += '[语音]'; break; case Message.types.file: if (clearEvent.content.flag) { msgBody += '[保密消息]'; } else { msgBody += `[文件] ${clearEvent.content.body}`; } break; case Message.types.location: msgBody += '[位置]'; break; case Message.types.url: msgBody += '[链接] '; msgBody += `${clearEvent.content.info && (clearEvent.content.info.title || clearEvent.content.info.description)}`; break; case Message.types.businesscard: msgBody += '[个人名片]'; break; case Message.types.badEncrypted: case Message.types.eventEncrypted: msgBody += '[无法解析的加密消息]'; break; case Message.types.notice: console.log('Message.types.notice'); console.log(clearEvent); msgBody = clearEvent.content.body; break; case Message.types.call: break; case 'fc.applet': msgTypeInfo = '[小程序]'; break; case Message.types.unknown: default: msgBody += '[未知消息类型]'; break; } return { msgType, msgTypeInfo, sender: user.displayName, msgBody, eventId, status, eventTime, senderId: sender.userId, }; } else if (eventType === Message.types.call) { const info = clearEvent.content.info; const reason = clearEvent.content.reason; const isVideoCall = info && info.isVideoCall === '1'; if (!info && !reason) { msgBody = ''; } else if (reason) { msgBody = '未接通'; } else { const duration = parseInt(info.duration, 10); if (duration) { const temp = moment.utc(duration); msgBody = `通话时长${duration > 3600 * 1000 ? temp.format('HH:mm:ss') : temp.format('mm:ss')}`; } else if (messageEvent.event.sender === this.userId) { msgBody = '已取消'; } else { msgBody = '对方已取消'; } } if (isVideoCall) { msgBody = `[视频通话] ${msgBody}`; } else { msgBody = `[语音通话] ${msgBody}`; } return { msgType, msgTypeInfo, msgBody, eventId, status, eventTime, }; } else if (eventType === Message.types.member) { // console.log('elseeeee~~~', eventType); // console.log(clearEvent); // console.log(messageEvent); } msgType = 'notice'; msgBody = this.getNoticeMsgBody(messageEvent); return { msgType, msgTypeInfo, sender: user.displayName, msgBody: msgBody || '', eventId, status, eventTime, }; } getNoticeMsgBody(msgEvent) { const message = msgEvent.event; let res = ''; if (message.hint) { res = message.hint; } if (message.content && message.content.msgtype === 'm.notice') { res = message.content.body; } res = res.replace(/\$\{(.*?)\}/g, (userId, pureId) => { const user = this.mxClient.getUser(pureId) || {}; return user.displayName; }); return res; } buildRoomMember(mxMember) { if (!mxMember || !mxMember.userId) { // console.log('!mxMember'); return null; } const mxUser = this.mxClient.getUser(mxMember && mxMember.userId); if (!mxUser) { // console.log('!mxUser'); // console.log(mxMember.userId); return null; } return { userId: mxMember.userId, membership: mxMember.membership, name: mxMember.name, displayName: mxUser.displayName, rawDisplayName: mxMember.rawDisplayName, typing: mxMember.typing, powerLevel: mxMember.powerLevel, avatarUrl: mxUser.avatarUrl, presence: mxUser.presence, }; } buildUser(mxUser) { if (!mxUser) return null; return { userId: mxUser.userId, displayName: mxUser.displayName, rawDisplayName: mxUser.rawDisplayName, presence: mxUser.presence, lastModified: mxUser._modified, }; } getLastMsg(mxRoom) { if (!mxRoom) return null; } parseUserQQ(bfcid) { if (typeof bfcid !== 'string') return ''; const matched = bfcid.match(/\d+/); return (matched && matched.length && matched[0]) || bfcid; } }
<gh_stars>0 /* * File : WordAssocNet.java * Created : 23-Feb-2012 * By : atrilla * * Emolib - Emotional Library * * Copyright (c) 2012 <NAME> & * 2007-2012 Enginyeria i Arquitectura La Salle (Universitat Ramon Llull) * * This file is part of Emolib. * * You should have received a copy of the rights granted with this * distribution of EmoLib. See COPYING. */ package emolib.wordassoc.wordassocnet; import emolib.wordassoc.*; import org.jsoup.Jsoup; import org.jsoup.Connection; import org.jsoup.nodes.Document; import emolib.util.conf.*; import emolib.util.proc.*; import java.util.ArrayList; /** * The <i>WordAssocNet</i> class associates words using the Word Associations * Network. * * @author <NAME> (<EMAIL>) */ public class WordAssocNet extends WordAssoc { // http://wordassociations.net/ /** * Maximum number of associated terms allowed to retrieve. */ public final static String PROP_MAX_ASSOC = "max_assoc"; private int maxAssociations; /* (non-Javadoc) * @see emolib.util.conf.Configurable#register(java.lang.String, emolib.util.conf.Registry) */ public void register(String name, Registry registry) throws PropertyException { super.register(name, registry); registry.register(PROP_MAX_ASSOC, PropertyType.INT); } /* (non-Javadoc) * @see emolib.util.conf.Configurable#newProperties(emolib.util.conf.PropertySheet) */ public void newProperties(PropertySheet ps) throws PropertyException { super.newProperties(ps); maxAssociations = ps.getInt(PROP_MAX_ASSOC, 10); } /** * Method to initialize the WordAssocNet. */ public void initialize() { } /** * Main constructor of the WordAssocNet. */ public WordAssocNet() { } /** * Method to perform the word association process. * * @param inputTextDataObject The TextData object to process. */ public void applyWordAssociation(TextData inputTextDataObject) { WordData tempWordData; for (int numberOfWords = 0; numberOfWords < inputTextDataObject.getNumberOfWords(); numberOfWords++) { tempWordData = inputTextDataObject.getWordData(numberOfWords); if (tempWordData.hasEmotionalContent()) { try { Document doc = Jsoup.connect("http://wordassociations.net/search?hl=en&q=" + tempWordData.getWord() + "&button=Search").get(); String wText = doc.outerHtml(); String[] wChunk = wText.split("w="); // first one is html overhead String[] assocWord; ArrayList bunchOfAssocWords = new ArrayList(); for (int i = 1; i < (1 + maxAssociations); i++) { if (i < wChunk.length) { assocWord = wChunk[i].split("\""); bunchOfAssocWords.add(assocWord[0]); } } tempWordData.setSense(bunchOfAssocWords); } catch (Exception e) { System.out.println("WordAssocNet: access error!"); e.printStackTrace(); } } } } }
# one signup and one valid message node build/index.js deployVkRegistry && \ node build/index.js setVerifyingKeys -s 10 -i 1 -m 2 -v 2 -b 1 \ -p ./zkeys/ProcessMessages_10-2-1-2_test.0.zkey \ -t ./zkeys/TallyVotes_10-1-2_test.0.zkey \ -k 0x8CdaF0CD259887258Bc13a92C0a6dA92698644C0 && \ node build/index.js create \ -r 0x8CdaF0CD259887258Bc13a92C0a6dA92698644C0 && \ node ./build/index.js deployPoll -x 0xf204a4Ef082f5c04bB89F7D5E6568B796096735a \ -pk macipk.c974f4f168b79727ac98bfd53a65ea0b4e45dc2552fe73df9f8b51ebb0930330 \ -t 20 -g 25 -mv 25 -i 1 -m 2 -b 1 -v 2 && \ node ./build/index.js signup \ -p macipk.3e7bb2d7f0a1b7e980f1b6f363d1e3b7a12b9ae354c2cd60a9cfa9fd12917391 \ -x 0xf204a4Ef082f5c04bB89F7D5E6568B796096735a && \ node build/index.js publish \ -p macipk.3e7bb2d7f0a1b7e980f1b6f363d1e3b7a12b9ae354c2cd60a9cfa9fd12917391 \ -sk macisk.fd7aa614ec4a82716ffc219c24fd7e7b52a2b63b5afb17e81c22fe21515539c \ -x 0xf204a4Ef082f5c04bB89F7D5E6568B796096735a \ -i 1 -v 0 -w 9 -n 1 -o 0 node build/index.js timeTravel -s 30 && \ node build/index.js mergeMessages -x 0xf204a4Ef082f5c04bB89F7D5E6568B796096735a -o 0 && \ node build/index.js mergeSignups -x 0xf204a4Ef082f5c04bB89F7D5E6568B796096735a -o 0 && \ rm -rf tally.json proofs && \ node build/index.js genProofs -x 0xf204a4Ef082f5c04bB89F7D5E6568B796096735a \ -sk macisk.49953af3585856f539d194b46c82f4ed54ec508fb9b882940cbe68bbc57e59e \ -o 0 \ -r ~/rapidsnark/build/prover \ -wp ./zkeys/ProcessMessages_10-2-1-2_test \ -wt ./zkeys/TallyVotes_10-1-2_test \ -zp ./zkeys/ProcessMessages_10-2-1-2_test.0.zkey \ -zt ./zkeys/TallyVotes_10-1-2_test.0.zkey \ -t tally.json \ -f proofs/ node build/index.js proveOnChain \ -x 0xf204a4Ef082f5c04bB89F7D5E6568B796096735a \ -o 0 \ -q 0xEcFcaB0A285d3380E488A39B4BB21e777f8A4EaC \ -f proofs/ node build/index.js verify \ -x 0xf204a4Ef082f5c04bB89F7D5E6568B796096735a \ -o 0 \ -t tally.json \ -q 0xEcFcaB0A285d3380E488A39B4BB21e777f8A4EaC
import io.swagger.annotations.ApiModelProperty; import com.fasterxml.jackson.annotation.JsonProperty; public class User { private String userID; @ApiModelProperty(example = "null", value = "User ID.") @JsonProperty("userID") public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } }
import string import random def generate_password(): # Choose random alphanumeric characters and symbols characters = string.ascii_letters + string.digits + string.punctuation # Generate string of random characters with minimum length of 8 password = ''.join(random.choice(characters) for _ in range(8)) return password
library(sentimentr) sentiment_model <- sentimentr::use_model("default") # predict sentiment sentiment <- sentimentr::predict_sentiment(sentiment_model, c("I love your product")) # print sentiment if (sentiment$sentiment == "positive") { print("The sentiment of the sentence is Positive") } else if (sentiment$sentiment == "negative") { print("The sentiment of the sentence is Negative") } # Output: The sentiment of the sentence is Positive
#! /bin/bash cd /export/scratch/robert/survae_flows teacher="/export/scratch/robert/survae_flows/experiments/student_teacher/log/Teacher/checkerboard/abs_flows4_hidden200_100_affine/adam_lr1e-03/seed0/abs_uniform_teacher" time python experiments/student_teacher/train_baseline.py \ --device cpu \ --baseline gp \ --cond_trans split0 \ --train_samples 25000 \ --test_samples 5000 \ --num_samples 10000 \ --clim 1.0 \ --name checkerboard_gp_split0 \ --teacher_model ${teacher} \ ;
#include <iostream> #include <vector> int calculateSumOfPositiveIntegers(const std::vector<int>& numbers) { int sum = 0; for (int num : numbers) { if (num > 0) { sum += num; } } return sum; } int main() { int n; std::cin >> n; std::vector<int> numbers(n); for (int i = 0; i < n; ++i) { std::cin >> numbers[i]; } int sum = calculateSumOfPositiveIntegers(numbers); std::cout << "Sum of positive integers: " << sum << std::endl; return 0; }
import { NgModule } from '@angular/core'; import { SharedModule } from '../shared/shared.module'; import { EditorComponent } from './editor.component'; import { EditorRoutingModule } from './editor-routing.module'; import { AddTagComponent } from './components/add-tag/add-tag.component'; @NgModule({ imports: [ SharedModule, EditorRoutingModule ], declarations: [ EditorComponent, AddTagComponent ] }) export class EditorModule { }
<gh_stars>100-1000 import { Client } from "eris"; import ClientStatsService from "../services/ClientStatsService"; import commands from "../commands/all"; async function initializeCommandStats(client: Client) { const ClientStats = await ClientStatsService.init(client.user.id); const delays: Array<number> = new Array(commands.length) .fill(0) .map((ele, index, array) => { return array[index - 1] !== undefined || !isNaN(array[index - 1]) ? (array[index] = array[index - 1] + 125) : (array[index] = ele); }); commands.forEach((command, index) => { if (!ClientStats.commandUsageStats.has(JSON.stringify(command.aliases))) { setTimeout(async () => { await ClientStats.setCommandStats(JSON.stringify(command.aliases), { hourlyUsage: 0, hourlyUsageDate: new Date(), dailyUsage: 0, dailyUsageDate: new Date(), weeklyUsage: 0, weeklyUsageDate: new Date(), monthlyUsage: 0, monthlyUsageDate: new Date(), totalUsage: 0, stats: Object.fromEntries(new Map()) }); }, delays[index]); } }); } export default initializeCommandStats;