text
stringlengths
1
1.05M
import XCTest import NIO enum APIError: Error { case invalidResponse } struct DCCRule { // Define the structure of DCCRule } class DCCRuleLoader { let session: URLSession init(session: URLSession) { self.session = session } func loadDCCRule(country: String, hash: String) -> EventLoopFuture<DCCRule> { let promise = session.eventLoop.makePromise(of: DCCRule.self) guard !country.isEmpty, !hash.isEmpty else { promise.fail(APIError.invalidResponse) return promise.futureResult } let request = URLRequest(url: URL(string: "https://api.example.com/dcc/\(country)/\(hash)")!) let task = session.dataTask(for: request) { data, response, error in if let error = error { promise.fail(error) } else { // Parse the response data and create DCCRule if let dccRule = parseDCCRule(from: data) { promise.succeed(dccRule) } else { promise.fail(APIError.invalidResponse) } } } task.resume() return promise.futureResult } private func parseDCCRule(from data: Data?) -> DCCRule? { // Implement parsing logic to create DCCRule from data return nil } } class DCCRuleLoaderTests: XCTestCase { func testLoadDCCRule() { let sessionMock = URLSessionMock() let sut = DCCRuleLoader(session: sessionMock) sessionMock.requestResponse = Promise(error: APIError.invalidResponse) do { _ = try sut.loadDCCRule(country: "foo", hash: "bar").wait() XCTFail("Should fail") } catch { XCTAssertEqual(error.localizedDescription, APIError.invalidResponse.localizedDescription) } } } class URLSessionMock: URLSession { var requestResponse: Promise<(Data?, URLResponse?, Error?)>? override func dataTask( with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void ) -> URLSessionDataTask { let task = URLSessionDataTaskMock() if let response = requestResponse { response.futureResult.whenComplete { result in completionHandler(result.0, result.1, result.2) } } return task } } class URLSessionDataTaskMock: URLSessionDataTask { override func resume() {} }
"use strict"; var scrollToHash = function scrollToHash(offsetY) { // Make sure React has had a chance to flush to DOM first. setTimeout(function () { var hash = window.decodeURI(window.location.hash.replace("#", "")); if (hash !== "") { var element = document.getElementById(hash); if (element) { var offset = element.offsetTop; window.scrollTo(0, offset - offsetY); } } }, 10); }; exports.onClientEntry = function (args, pluginOptions) { var offsetY = 0; if (pluginOptions.offsetY) { offsetY = pluginOptions.offsetY; } // This code is only so scrolling to header hashes works in development. // For production, the equivalent code is in gatsby-ssr.js. if (process.env.NODE_ENV !== "production") { scrollToHash(offsetY); } }; exports.onRouteUpdate = function (args, pluginOptions) { var offsetY = 0; if (pluginOptions.offsetY) { offsetY = pluginOptions.offsetY; } scrollToHash(offsetY); };
#!/bin/sh -l # check if the first argument passed in looks like a flag if [ "${1#-}" != "$1" ]; then set -- /sbin/tini -- phpunit "$@" # check if the first argument passed in is phpunit elif [ "$1" = 'phpunit' ]; then set -- /sbin/tini -- "$@" fi exec "$@"
import Vue from 'vue' export default { list (cb, errorCb) { Vue.http.get('/api/user/list').then((result) => { cb(result.data.users) }, (result) => { errorCb(result.data.error) }) }, buyProducts (products, cb, errorCb) { setTimeout(() => { // simulate random checkout failure. (Math.random() > 0.5 || navigator.userAgent.indexOf('PhantomJS') > -1) ? cb() : errorCb() }, 100) } }
<filename>no8/doc.go // 函数 myAtoi(string s) 的算法如下: // // 读入字符串并丢弃无用的前导空格 // 检查下一个字符(假设还未到字符末尾)为正还是负号,读取该字符(如果有)。 确定最终结果是负数还是正数。 如果两者都不存在,则假定结果为正。 // 读入下一个字符,直到到达下一个非数字字符或到达输入的结尾。字符串的其余部分将被忽略。 // 将前面步骤读入的这些数字转换为整数(即,"123" -> 123, "0032" -> 32)。如果没有读入数字,则整数为 0 。必要时更改符号(从步骤 2 开始)。 // 如果整数数超过 32 位有符号整数范围 [−231,  231 − 1] ,需要截断这个整数,使其保持在这个范围内。具体来说,小于 −231 的整数应该被固定为 −231 ,大于 231 − 1 的整数应该被固定为 231 − 1 。 // 返回整数作为最终结果。 // 注意: // // 本题中的空白字符只包括空格字符 ' ' 。 // 除前导空格或数字后的其余字符串外,请勿忽略 任何其他字符。 package no8
<reponame>paketo-buildpacks/poetry package poetry import ( "fmt" "os" "path/filepath" "strings" "time" packit "github.com/paketo-buildpacks/packit/v2" "github.com/paketo-buildpacks/packit/v2/chronos" "github.com/paketo-buildpacks/packit/v2/postal" "github.com/paketo-buildpacks/packit/v2/sbom" "github.com/paketo-buildpacks/packit/v2/scribe" ) //go:generate faux --interface EntryResolver --output fakes/entry_resolver.go //go:generate faux --interface DependencyManager --output fakes/dependency_manager.go //go:generate faux --interface InstallProcess --output fakes/install_process.go //go:generate faux --interface SitePackageProcess --output fakes/site_package_process.go //go:generate faux --interface SBOMGenerator --output fakes/sbom_generator.go type EntryResolver interface { Resolve(name string, entries []packit.BuildpackPlanEntry, priorites []interface{}) (packit.BuildpackPlanEntry, []packit.BuildpackPlanEntry) MergeLayerTypes(name string, entries []packit.BuildpackPlanEntry) (launch, build bool) } type DependencyManager interface { Resolve(path, id, version, stack string) (postal.Dependency, error) Deliver(dependency postal.Dependency, cnbPath, destinationPath, platformPath string) error GenerateBillOfMaterials(dependencies ...postal.Dependency) []packit.BOMEntry } // InstallProcess defines the interface for installing the poetry dependency into a layer. type InstallProcess interface { Execute(srcPath, targetLayerPath string) error } // SitePackageProcess defines the interface for looking site packages within a layer. type SitePackageProcess interface { Execute(targetLayerPath string) (string, error) } type SBOMGenerator interface { GenerateFromDependency(dependency postal.Dependency, dir string) (sbom.SBOM, error) } func Build( entryResolver EntryResolver, dependencyManager DependencyManager, installProcess InstallProcess, siteProcess SitePackageProcess, sbomGenerator SBOMGenerator, clock chronos.Clock, logger scribe.Emitter, ) packit.BuildFunc { return func(context packit.BuildContext) (packit.BuildResult, error) { logger.Title("%s %s", context.BuildpackInfo.Name, context.BuildpackInfo.Version) logger.Process("Resolving Poetry version") entry, entries := entryResolver.Resolve(PoetryDependency, context.Plan.Entries, Priorities) logger.Candidates(entries) version, ok := entry.Metadata["version"].(string) if !ok { version = "default" } dependency, err := dependencyManager.Resolve(filepath.Join(context.CNBPath, "buildpack.toml"), entry.Name, version, context.Stack) if err != nil { return packit.BuildResult{}, err } logger.SelectedDependency(entry, dependency, clock.Now()) legacySBOM := dependencyManager.GenerateBillOfMaterials(dependency) poetryLayer, err := context.Layers.Get(PoetryLayerName) if err != nil { return packit.BuildResult{}, err } launch, build := entryResolver.MergeLayerTypes(PoetryDependency, context.Plan.Entries) var buildMetadata = packit.BuildMetadata{} var launchMetadata = packit.LaunchMetadata{} if build { buildMetadata = packit.BuildMetadata{BOM: legacySBOM} } if launch { launchMetadata = packit.LaunchMetadata{BOM: legacySBOM} } cachedSHA, ok := poetryLayer.Metadata[DependencySHAKey].(string) if ok && cachedSHA == dependency.SHA256 { logger.Process("Reusing cached layer %s", poetryLayer.Path) logger.Break() poetryLayer.Launch, poetryLayer.Build, poetryLayer.Cache = launch, build, build return packit.BuildResult{ Layers: []packit.Layer{poetryLayer}, Build: buildMetadata, Launch: launchMetadata, }, nil } logger.Process("Executing build process") poetryLayer, err = poetryLayer.Reset() if err != nil { return packit.BuildResult{}, err } poetryLayer.Launch, poetryLayer.Build, poetryLayer.Cache = launch, build, build logger.Subprocess("Installing Poetry %s", dependency.Version) duration, err := clock.Measure(func() error { // Install the poetry source to a temporary dir, since we only need access to // it as an intermediate step when installing poetry. // It doesn't need to go into a layer, since we won't need it in future builds. poetrySrcDir, err := os.MkdirTemp("", "poetry-source") if err != nil { return fmt.Errorf("failed to create temp poetry-source dir: %w", err) } err = dependencyManager.Deliver(dependency, context.CNBPath, poetrySrcDir, context.Platform.Path) if err != nil { return err } err = installProcess.Execute(poetrySrcDir, poetryLayer.Path) if err != nil { return err } // Look up the site packages path and prepend it onto $PYTHONPATH sitePackagesPath, err := siteProcess.Execute(poetryLayer.Path) if err != nil { return fmt.Errorf("failed to locate site packages in poetry layer: %w", err) } if sitePackagesPath == "" { return fmt.Errorf("poetry installation failed: site packages are missing from the poetry layer") } poetryLayer.SharedEnv.Prepend("PYTHONPATH", strings.TrimRight(sitePackagesPath, "\n"), ":") return nil }) if err != nil { return packit.BuildResult{}, err } logger.Action("Completed in %s", duration.Round(time.Millisecond)) logger.Break() logger.GeneratingSBOM(poetryLayer.Path) var sbomContent sbom.SBOM duration, err = clock.Measure(func() error { sbomContent, err = sbomGenerator.GenerateFromDependency(dependency, poetryLayer.Path) return err }) if err != nil { return packit.BuildResult{}, err } logger.Action("Completed in %s", duration.Round(time.Millisecond)) logger.Break() logger.FormattingSBOM(context.BuildpackInfo.SBOMFormats...) poetryLayer.SBOM, err = sbomContent.InFormats(context.BuildpackInfo.SBOMFormats...) if err != nil { return packit.BuildResult{}, err } logger.EnvironmentVariables(poetryLayer) poetryLayer.Metadata = map[string]interface{}{ DependencySHAKey: dependency.SHA256, } return packit.BuildResult{ Layers: []packit.Layer{poetryLayer}, Build: buildMetadata, Launch: launchMetadata, }, nil } }
#!/usr/bin/env bats ######################################################################################################################## # Test remove command ######################################################################################################################## load test_helper @test '"cls" empties the timesheet' { "$BATS_TEST_DIRNAME"/ttt s "foo bar baz" "$BATS_TEST_DIRNAME"/ttt v i=0 | grep "foo bar baz" run "$BATS_TEST_DIRNAME"/ttt cls run grep -c '<td class="meta">' "$BATS_TEST_DIRNAME"/timesheet.html [[ "$output" = 0 ]] } @test '"clear" empties the timesheet' { "$BATS_TEST_DIRNAME"/ttt s "foo bar baz" "$BATS_TEST_DIRNAME"/ttt v i=0 | grep "foo bar baz" run $BATS_TEST_DIRNAME/ttt clear run grep -c '<td class="meta">' $BATS_TEST_DIRNAME/timesheet.html [[ "$output" = 0 ]] } @test '"cls" can be undone' { "$BATS_TEST_DIRNAME"/ttt s "foo bar baz" "$BATS_TEST_DIRNAME"/ttt v i=0 | grep "foo bar baz" run "$BATS_TEST_DIRNAME"/ttt cls run grep -c '<td class="meta">' "$BATS_TEST_DIRNAME"/timesheet.html [[ "$output" = 0 ]] run "$BATS_TEST_DIRNAME"/ttt z "$BATS_TEST_DIRNAME"/ttt v i=0 | grep "foo bar baz" }
cd /storage/home/users/pjt6/phy/orthofinder python /storage/home/users/pjt6/misc_python/BLAST_output_parsing/Blast_RBH_two_fasta_file_evalue.py --threads 2 -o ../GCA_001707905.2_PkChile2v2.0_cds_from_genomi.fa_GCA_002911725.1_ASM291172v1_cds_from_genomi.fa GCA_001707905.2_PkChile2v2.0_cds_from_genomi.fa GCA_002911725.1_ASM291172v1_cds_from_genomi.fa
function stringsConstruction(a, b) { let count = 0; while (true) { for (let x of a) { if (b.indexOf(x) < 0) return count; b = b.replace(x, ""); } count++; } } function stringsConstruction(a, b) { return Math.min( ...a .split("") .map(i => Math.floor((b.split(i).length - 1) / (a.split(i).length - 1))) ); } const q1 = ["abc", "abccba"]; // 2 const q2 = ["hnccv", "hncvohcjhdfnhonxddcocjncchnvohchnjohcvnhjdhihsn"]; // 3 const q3 = ["abc", "def"]; // 0 const q4 = ["zzz", "zzzzzzzzzzz"]; // 3 const q5 = ["abcabcabc", "aaaaaaaaaaabbbbbbbbbbcccccccccc"]; // 3 const q6 = ["abc", "xyz"]; // 0 const q7 = ["zbc", "ydlblksdjccdddb"]; // 0 const q8 = ["abdd", "adadapqrtsmnckgljj"]; // 0 const q9 = ["abcde", "edbcaacbdebcedaadbecadbceecabddbaecabecdcdabeabcde"]; // 10 const q10 = ["abcde", "edbcaaclpebcekbadbecadbcefcabddbaecaaaaacdakrabcde"]; // 7 console.log(stringsConstruction(q1[0], q1[1])); console.log(stringsConstruction(q2[0], q2[1])); console.log(stringsConstruction(q3[0], q3[1])); console.log(stringsConstruction(q4[0], q4[1])); console.log(stringsConstruction(q5[0], q5[1])); console.log(stringsConstruction(q6[0], q6[1])); console.log(stringsConstruction(q7[0], q7[1])); console.log(stringsConstruction(q8[0], q8[1])); console.log(stringsConstruction(q9[0], q9[1])); console.log(stringsConstruction(q10[0], q10[1]));
<filename>seeds-db/src/main/java/com/github/smallcreep/cucumber/seeds/storage/StorageWithoutIids.java<gh_stars>1-10 /* * MIT License * * Copyright (c) 2018 <NAME> (@smallcreep) <<EMAIL>> * * 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 com.github.smallcreep.cucumber.seeds.storage; import com.github.smallcreep.cucumber.seeds.Storage; import java.util.Map; import org.cactoos.iterable.Filtered; import org.cactoos.iterable.IterableEnvelope; import org.cactoos.iterable.Mapped; import org.cactoos.map.MapOf; /** * Remove entry with key iid in all iterable maps. * @since 0.2.0 */ public final class StorageWithoutIids extends IterableEnvelope<Map<String, String>> implements Storage { /** * Ctor. * @param maps Iterable maps */ public StorageWithoutIids(final Iterable<Map<String, String>> maps) { super( () -> new Mapped<Map<String, String>, Map<String, String>>( input -> new MapOf<String, String>( new Filtered<Map.Entry<String, String>>( entry -> !entry.getKey().equals("iid"), input.entrySet() ) ), maps ) ); } }
<filename>api/test/unit/routes/policies.test.js 'use strict'; var request = require('supertest'); var expect = require('chai').expect; var fs = require('fs'); var path = require('path'); var settings = require(path.join(__dirname, '../../../lib/config/setting.js'))((JSON.parse( fs.readFileSync(path.join(__dirname, '../../../config/settings.json'), 'utf8')))); var API = require('../../../app.js'); var app; var policy = require('../../../lib/models')(settings.db).policy_json; var logger = require('../../../lib/log/logger'); var nock = require('nock'); var schedulerURI = settings.schedulerUri ; describe('Routing Policy Creation', function() { var fakePolicy; before(function() { fakePolicy = JSON.parse(fs.readFileSync(__dirname+'/../fakePolicy.json', 'utf8')); app = API(path.join(__dirname, '../../../config/settings.json')); }) after(function(done){ app.close(done); }) beforeEach(function() { return policy.truncate(); }); it('should create a policy for app id 12345', function(done) { nock(schedulerURI) .put('/v2/schedules/12345') .reply(200); request(app) .put('/v1/policies/12345') .send(fakePolicy) .end(function(error,result) { expect(result.statusCode).to.equal(201); expect(result.headers.location).exist; expect(result.headers.location).to.be.equal('/v1/policies/12345'); expect(result.body.success).to.equal(true); expect(result.body.error).to.be.null; expect(result.body.result.policy_json).eql(fakePolicy); done(); }); }); it('should fail to create a policy for validation error in scheduler for app id 12346', function(done) { nock(schedulerURI) .put('/v2/schedules/12346') .reply(400); request(app) .put('/v1/policies/12346') .send(fakePolicy) .end(function(error,result) { expect(result.statusCode).to.equal(400); expect(result.body.error.message).eql('Failed to create schedules due to validation error in scheduler'); expect(result.body.success).eql(false); done(); }); }); it('should fail to create a policy for internal error in scheduler for app id 12347', function(done) { var mockError = { 'message':'Failed to create schedules due to an internal' + ' error in scheduler','details':'fake body' }; nock(schedulerURI) .put('/v2/schedules/12347') .replyWithError(mockError); request(app) .put('/v1/policies/12347') .send(fakePolicy) .end(function(error,result) { expect(result.statusCode).to.equal(500); expect(result.body.error.message).eql('Failed to create schedules due to an internal error in scheduler'); expect(result.body.error.details).eql('fake body'); expect(result.body.success).eql(false); done(); }); }); context('when a policy already exists' ,function() { beforeEach(function(done) { nock(schedulerURI) .put('/v2/schedules/12345') .reply(200); request(app) .put('/v1/policies/12345') .send(fakePolicy).end(done) }); it('should update the existing policy for app id 12345', function(done) { nock(schedulerURI) .put('/v2/schedules/12345') .reply(204); request(app) .put('/v1/policies/12345') .send(fakePolicy) .end(function(error,result) { expect(result.statusCode).to.equal(200); expect(result.body.success).to.equal(true); expect(result.body.result[0].policy_json).eql(fakePolicy); expect(result.body.error).to.be.null; done(); }); }); it('should successfully get the details of the policy with app id 12345',function(done){ request(app) .get('/v1/policies/12345') .end(function(error,result) { expect(result.statusCode).to.equal(200); expect(result.body).to.deep.equal(fakePolicy); done(); }); }); it('should successfully delete the policy with app id 12345',function(done){ nock(schedulerURI) .delete('/v2/schedules/12345') .reply(200); request(app) .delete('/v1/policies/12345') .expect(200) .end(function(error) { expect(error).to.be.null; done(); }); }); it('should fail to delete the policy with app id 12345 due to internal server error',function(done){ nock(schedulerURI) .delete('/v2/schedules/12345') .reply(500); request(app) .delete('/v1/policies/12345') .end(function(error,result) { expect(result.statusCode).to.equal(500); done(); }); }); }); context('when policy does not exist' ,function() { it('should return 404 while deleting policy with app id 12345',function(done){ request(app) .delete('/v1/policies/12345') .end(function(error,result) { expect(result.statusCode).to.equal(404); done(); }); }); it('should fail to get the details of a non existing policy with app id 12345',function(done){ request(app) .get('/v1/policies/12345') .end(function(error,result) { expect(result.statusCode).to.equal(404); expect(result.body).eql({}); done(); }); }); }); });
#pragma once #include <goliath/servo.h> #include "basic_command.h" #include "../handles.h" namespace goliath::commands { class MoveArmCommand : public BasicCommand { public: explicit MoveArmCommand(const size_t &id); private: void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override; }; }
// // HotViewController.h // MyCar // // Created by 🐵 on 16-5-26. // Copyright (c) 2016年 MC. All rights reserved. // #import "BaseBBsViewController.h" @interface HotViewController : BaseBBsViewController @end
/** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function onInit() { // Put into a known state. digitalWrite(LED, 0); NRF.setServices({ '0b30acec-193e-11eb-adc1-0242ac120002': { '0b30afd0-193e-11eb-adc1-0242ac120002': { value: [17], broadcast: false, readable: true, writable: false, notify: false, description: 'Single read-only characteristic', } } }); NRF.on('disconnect', (reason) => { // Provide feedback that device no longer connected. digitalWrite(LED, 0); }); NRF.on('connect', (addr) => { // Provide feedback that device is connected. // TODO: Maybe only do this for some devices when external power is // available. For example, this will turn on the backlight on the // Pixl.js screen, which might not be desirable when powered by the // CR2032 coin cell battery. digitalWrite(LED, 1); }); }
<gh_stars>1-10 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.arrowDownLight = void 0; var arrowDownLight = { "viewBox": "0 0 512 512", "children": [{ "name": "path", "attribs": { "fill-rule": "evenodd", "clip-rule": "evenodd", "d": "M0,256c0,141.406,114.609,256,256,256s256-114.594,256-256\r\n\tC512,114.625,397.391,0,256,0S0,114.625,0,256z M472,256c0,119.312-96.703,216-216,216S40,375.312,40,256\r\n\tc0-119.281,96.703-216,216-216S472,136.719,472,256z" }, "children": [] }, { "name": "polygon", "attribs": { "fill-rule": "evenodd", "clip-rule": "evenodd", "points": "239.961,128 239.961,326.406 198.836,288 175.992,309.344 255.992,384 \r\n\t336.008,309.344 313.102,288 271.961,326.406 271.961,128 " }, "children": [] }] }; exports.arrowDownLight = arrowDownLight;
#!/bin/bash echo "install session..." ERROR_CODE_EXTENSION_HOME=10 ERROR_CODE_INSTALL=200 if test -z $DEBIAN_EXTENSION_HOME; then echo "Debian extension home path must be not empty!" exit $ERROR_CODE_EXTENSION_HOME fi ARRAY=(\ "dbus" \ "libpam-systemd") SIZE=${#ARRAY[@]} for ((i = 0; i < SIZE; i++)); do ITEM="${ARRAY[$i]}" $DEBIAN_EXTENSION_HOME/session/install_${ITEM}.sh if test $? -ne 0; then echo "Install \"$ITEM\" error!" exit $((ERROR_CODE_INSTALL + i)) fi done echo "install session success." exit 0
#!/bin/bash echo "Maximizing CPU & GPU clocks within the current" echo "performance mode" if [ -f ~/jetson_clocks.sh ]; then # For JetPack 3.3 and below sudo ~/jetson_clocks.sh sudo ~/jetson_clocks.sh --show else # For JetPack 4.2 and above sudo jetson_clocks sudo jetson_clocks --show fi
#!/bin/bash #SBATCH --job-name=/data/unibas/boittier/test-neighbours2 #SBATCH --nodes=1 #SBATCH --ntasks=1 #SBATCH --partition=short #SBATCH --output=/data/unibas/boittier/test-neighbours2_%A-%a.out hostname # Path to scripts and executables cubefit=/home/unibas/boittier/fdcm_project/mdcm_bin/cubefit.x fdcm=/home/unibas/boittier/fdcm_project/fdcm.x ars=/home/unibas/boittier/fdcm_project/ARS.py # Variables for the job n_steps=2 n_charges=24 scan_name=frame_ suffix=.chk cubes_dir=/data/unibas/boittier/fdcm/amide_graph output_dir=/data/unibas/boittier/test-neighbours2 frames=/home/unibas/boittier/fdcm_project/mdcms/amide/model1/frames.txt initial_fit=/home/unibas/boittier/fdcm_project/mdcms/amide/model1/24_charges_refined.xyz initial_fit_cube=/home/unibas/boittier/fdcm_project/mdcms/amide/model1/amide1.pdb.chk prev_frame=0 start_frame=30 next_frame=65 acd=/home/unibas/boittier/fdcm_project/0_fit.xyz.acd start=$start_frame next=$next_frame dir='frame_'$next output_name=$output_dir/$dir/$dir'-'$start'-'$next'.xyz' initial_fit=$output_dir/"frame_"$start/"frame_"$start'-'$prev_frame'-'$start'.xyz' # Go to the output directory mkdir -p $output_dir cd $output_dir mkdir -p $dir cd $dir # Do Initial Fit # for initial fit esp1=$cubes_dir/$scan_name$start$suffix'.p.cube' dens1=$cubes_dir/$scan_name$start$suffix'.d.cube' esp=$cubes_dir/$scan_name$next$suffix'.p.cube' dens=$cubes_dir/$scan_name$next$suffix'.d.cube' # adjust reference frame python $ars -charges $initial_fit -pcube $dens1 -pcube2 $dens -frames $frames -output $output_name -acd $acd > $output_name.ARS.log # do gradient descent fit $fdcm -xyz $output_name.global -dens $dens -esp $esp -stepsize 0.2 -n_steps $n_steps -learning_rate 0.5 -output $output_name > $output_name.GD.log # adjust reference frame python $ars -charges $output_name -pcube $esp -pcube2 $esp -frames $frames -output $output_name -acd $acd > $output_name.ARS-2.log # make a cube file for the fit $cubefit -v -generate -esp $esp -dens $dens -xyz refined.xyz > $output_name.cubemaking.log # do analysis $cubefit -v -analysis -esp $esp -esp2 $n_charges'charges.cube' -dens $dens > $output_name.analysis.log echo $PWD sbatch /home/unibas/boittier/fdcm_project/job_files/test-neighbours2/frame_30_(30, 8).sh sbatch /home/unibas/boittier/fdcm_project/job_files/test-neighbours2/frame_30_(30, 11).sh sbatch /home/unibas/boittier/fdcm_project/job_files/test-neighbours2/frame_30_(30, 20).sh sbatch /home/unibas/boittier/fdcm_project/job_files/test-neighbours2/frame_30_(30, 38).sh sbatch /home/unibas/boittier/fdcm_project/job_files/test-neighbours2/frame_30_(30, 44).sh sbatch /home/unibas/boittier/fdcm_project/job_files/test-neighbours2/frame_30_(30, 84).sh
<filename>2A. C++ Advanced (STL)/Attic/functor-varargs.cpp // GB derived from http://stackoverflow.com/questions/27604128/c-stdfunction-like-template-syntax #include <functional> std::function<void(int)> f1; std::function<int(std::string, std::string)> f2; #include <iostream> using namespace std; template <typename FType> struct Functor { Functor(FType* fptr) : fptr(fptr) {} template <typename ...Args> void call(Args... args) { fptr(args...); } template <typename ...Args> void operator() (Args... args) { fptr(args...); } private: FType* fptr; }; void foo(int x, char y, bool z) { cout << "x=" << x << ", y=" << y << ", z=" << z << "\n"; } void bar(char x, int y, bool z) { cout << "x=" << x << ", y=" << y << ", z=" << z << "\n"; } int main() { Functor<void(int, char, bool)> f(&foo); f.call(1, 'f', true); f(1, 'f', true); Functor<void(char, int, bool)> b(&bar); b.call('b', 2, false); b('b', 2, false); }
#!/bin/bash # This script intends to change the instance type of an instance started by Auto Scaling Group. # It does not change the existing Launch Configuration in the Auto Scaling Group. # Set to fail script if any command fails. set -e # Define the help menu help_menu() { echo "Usage: ${0##*/} --name-tag NAME_TAG A tag for searching ASG / EC2 name --instance-type INSTANCE_TYPE The target instance type for the primary node; e.g. r3.medium " exit } # Parse arguments while [[ "$#" -gt 0 ]]; do case $1 in --name-tag) NAME_TAG="${2}" ; shift ;; --instance-type) INSTANCE_TYPE="${2}" ; shift ;; -h|--help) help_menu ;; *) echo "Invalid option: ${1}" && help_menu ;; esac; shift; done [[ ! -z "$NAME_TAG" ]] || (echo "Error: NAME_TAG is not provided. Aborted." && exit 1) [[ ! -z "$INSTANCE_TYPE" ]] || (echo "Error: INSTANCE_TYPE is not provided. Aborted." && exit 1) NAME_TAG="informix-${APP_NAME}-${STAGE_NAME}-${STACK_NAME}-db-ha1" # Find Instance ID and check instance type { ec2_instance=$(aws ec2 describe-instances \ --filters "Name=tag:Name,Values=${NAME_TAG}" "Name=instance-state-name,Values=running,pending"\ --query 'Reservations[*].Instances[*].[InstanceType,InstanceId,Tags[?Key==`Name`] | [0].Value]' --output text) } || (echo "Error: Instance (${NAME_TAG}) not found. Aborted." && exit 1) instance_type=$(echo ${ec2_instance} | cut -d' ' -f1) instance_id=$(echo ${ec2_instance} | cut -d' ' -f2) instance_name=$(echo ${ec2_instance} | cut -d' ' -f3) # No need to continue if the instance is currently using the target instance type already [ "$instance_type" != "$INSTANCE_TYPE" ] || (echo "Already running with target instance type. Exit now." && exit 0) echo "Started updating instance ${instance_name} (${instance_id}) from ${instance_type} to ${INSTANCE_TYPE}..." # Find auto scaling group name { asg_name=$(aws autoscaling describe-auto-scaling-groups \ --query 'AutoScalingGroups[].[AutoScalingGroupName]' --output text \ | grep "$NAME_TAG") } || (echo "Error: Auto Scaling Group with prefix (${NAME_TAG}) not found. Aborted." && exit 1) echo "Suspending processes on Auto Scaling Group $asg_name..." { # No output from aws cli command but the change is applied instantly. aws autoscaling suspend-processes --auto-scaling-group-name "$asg_name" } || (echo "Error: Unable to suspend Auto Scaling Group ($asg_name). Aborted." && exit 1) echo "Stopping EC2 instance $instance_id..." { aws ec2 stop-instances --instance-ids "$instance_id" } || (echo "Error: Unable to stop instance ($instance_id). Aborted." && exit 1) aws ec2 wait instance-stopped --instance-ids "$instance_id" echo "Confirmed EC2 instance $instance_id is stopped." echo "Updating instance ${instance_name} (${instance_id}) from ${instance_type} to ${INSTANCE_TYPE}..." { aws ec2 modify-instance-attribute --instance-id "$instance_id" \ --instance-type "{\"Value\": \"${INSTANCE_TYPE}\"}" } || (echo "Error: Unable to change instance type for ($instance_id). Aborted." && exit 1) echo "Starting EC2 instance ${instance_id}..." { aws ec2 start-instances --instance-ids "$instance_id" } || (echo "Error: Unable to start instance ($instance_id). Aborted." && exit 1) aws ec2 wait instance-running --instance-ids "$instance_id" echo "Confirmed EC2 instance ${instance_id} is running." aws ec2 wait instance-status-ok --instance-ids "$instance_id" echo "Confirmed EC2 instance ${instance_id} status OK." echo "Resuming processes on Auto Scaling Group $asg_name..." { aws autoscaling resume-processes --auto-scaling-group-name "$asg_name" } || (echo "Error: Unable to resume Auto Scaling Group ($asg_name). Aborted." && exit 1) echo "All done."
#!/bin/bash set -ex # Install Docker # Random, unaudited, but "official" script from the internet. # What could possibly go wrong? ¯\_(ツ)_/¯ curl -sSL https://get.docker.com | sh # sudo usermod -aG docker pi
using System; class Program { static void Main(string[] args) { int[] arr = new int[] {2, 4, 10, 3, 8}; int max = arr[0]; for (int i = 0; i < arr.Length; i++) { if (arr[i] > max) { max = arr[i]; } } Console.WriteLine("The Maximum number is : " + max); } }
ssh bwg "cd /var/www/blog && git pull origin master"
DELETE FROM table_name WHERE column_name = 'inactive';
// Before refactoring: class Item { .. } class Basket { // .. float getTotalPrice(Item i) { float price = i.getPrice() + i.getTax(); if (i.isOnSale()) price = price - i.getSaleDiscount() * price; return price; } } // After refactoring: class Item { // .. float getTotalPrice() { float price = getPrice() + getTax(); if (isOnSale()) price = price - getSaleDiscount() * price; return price; } }
<filename>pkg/band/band.go<gh_stars>0 // Copyright © 2019 The Things Network Foundation, The Things Industries B.V. // // 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 band contains structs to handle regional bands. package band import ( "math" "strings" "time" "go.thethings.network/lorawan-stack/pkg/ttnpb" ) // eirpDelta is the delta between EIRP and ERP. const eirpDelta = 2.15 // PayloadSizer abstracts the acceptable payload size depending on contextual parameters. type PayloadSizer interface { PayloadSize(dwellTime bool) uint16 } type constPayloadSizer uint16 func (p constPayloadSizer) PayloadSize(_ bool) uint16 { return uint16(p) } type dwellTimePayloadSizer struct { NoDwellTime uint16 DwellTime uint16 } //revive:disable:flag-parameter func (p dwellTimePayloadSizer) PayloadSize(dwellTime bool) uint16 { if dwellTime { return p.DwellTime } return p.NoDwellTime } //revive:enable:flag-parameter // DataRate indicates the properties of a band's data rate. type DataRate struct { Rate ttnpb.DataRate DefaultMaxSize PayloadSizer } // Channel abstracts a band's channel properties. type Channel struct { // Frequency indicates the frequency of the channel. Frequency uint64 // MinDataRate indicates the index of the minimal data rates accepted on this channel. MinDataRate ttnpb.DataRateIndex // MinDataRate indicates the index of the maximal data rates accepted on this channel. MaxDataRate ttnpb.DataRateIndex } // Rx2Parameters contains downlink datarate index and channel. type Rx2Parameters struct { DataRateIndex ttnpb.DataRateIndex Frequency uint64 } type versionSwap func(b Band) Band func bandIdentity(b Band) Band { return b } func composeSwaps(swaps ...versionSwap) versionSwap { return func(b Band) Band { for _, swap := range swaps { b = swap(b) } return b } } func channelIndexIdentity(idx uint8) (uint8, error) { return idx, nil } func channelIndexModulo(n uint8) func(uint8) (uint8, error) { return func(idx uint8) (uint8, error) { return idx % n, nil } } // Beacon parameters of a specific band. type Beacon struct { DataRateIndex int CodingRate string InvertedPolarity bool // Channel returns in Hz on which beaconing is performed. // // beaconTime is the integer value, converted in float64, of the 4 bytes “Time” field of the beacon frame. ComputeFrequency func(beaconTime float64) uint64 } // ChMaskCntlPair pairs a ChMaskCntl with a mask. type ChMaskCntlPair struct { Cntl uint8 Mask [16]bool } // Band contains a band's properties. type Band struct { ID string Beacon Beacon PingSlotFrequency *uint64 // MaxUplinkChannels is the maximum amount of uplink channels that can be defined. MaxUplinkChannels uint8 // UplinkChannels are the default uplink channels. UplinkChannels []Channel // MaxDownlinkChannels is the maximum amount of downlink channels that can be defined. MaxDownlinkChannels uint8 // DownlinkChannels are the default downlink channels. DownlinkChannels []Channel // SubBands define the sub-bands, their duty-cycle limit and Tx power. The frequency ranges may not overlap. SubBands []SubBandParameters DataRates [16]DataRate FreqMultiplier uint64 ImplementsCFList bool CFListType ttnpb.CFListType // ReceiveDelay1 is the default Rx1 window timing in seconds. ReceiveDelay1 time.Duration // ReceiveDelay2 is the default Rx2 window timing in seconds (ReceiveDelay1 + 1s). ReceiveDelay2 time.Duration // ReceiveDelay1 is the default join-accept window timing in seconds. JoinAcceptDelay1 time.Duration // ReceiveDelay2 is the join-accept window timing in seconds. JoinAcceptDelay2 time.Duration // MaxFCntGap MaxFCntGap uint // ADRAckLimit ADRAckLimit ttnpb.ADRAckLimitExponent // ADRAckDelay ADRAckDelay ttnpb.ADRAckDelayExponent MinAckTimeout time.Duration MaxAckTimeout time.Duration // TxOffset in dB: A Tx's power is computed by taking the MaxEIRP (default: +16dBm) and subtracting the offset. TxOffset [16]float32 // MaxTxPowerIndex represents the maximum non-RFU TxPowerIndex, which can be used according to the band's spec. MaxTxPowerIndex uint8 // MaxADRDataRateIndex represents the maximum non-RFU DataRateIndex suitable for ADR, which can be used according to the band's spec. MaxADRDataRateIndex uint8 TxParamSetupReqSupport bool // DefaultMaxEIRP in dBm DefaultMaxEIRP float32 // LoRaCodingRate is the coding rate used for LoRa modulation. LoRaCodingRate string // Rx1Channel computes the Rx1 channel index. Rx1Channel func(uint8) (uint8, error) // Rx1DataRate computes the Rx1 data rate index. Rx1DataRate func(ttnpb.DataRateIndex, uint32, bool) (ttnpb.DataRateIndex, error) // GenerateChMasks generates a mapping ChMaskCntl -> ChMask. // Length of chs must be equal to the maximum number of channels defined for the particular band. // Meaning of chs is as follows: for i in range 0..len(chs) if chs[i] == true, // then channel with index i should be enabled, otherwise it should be disabled. GenerateChMasks func(chs []bool) ([]ChMaskCntlPair, error) // ParseChMask computes the channels that have to be masked given ChMask mask and ChMaskCntl cntl. ParseChMask func(mask [16]bool, cntl uint8) (map[uint8]bool, error) // DefaultRx2Parameters are the default parameters that determine the settings for a Tx sent during Rx2. DefaultRx2Parameters Rx2Parameters regionalParameters1_0 versionSwap regionalParameters1_0_1 versionSwap regionalParameters1_0_2RevA versionSwap regionalParameters1_0_2RevB versionSwap regionalParameters1_0_3RevA versionSwap regionalParameters1_1RevA versionSwap } // SubBandParameters contains the sub-band frequency range, duty cycle and Tx power. type SubBandParameters struct { MinFrequency uint64 MaxFrequency uint64 DutyCycle float32 MaxEIRP float32 } // Comprises returns whether the duty cycle applies to the given frequency. func (d SubBandParameters) Comprises(frequency uint64) bool { return frequency >= d.MinFrequency && frequency <= d.MaxFrequency } // MaxEmissionDuring the period passed as parameter, that is allowed by that duty cycle. func (d SubBandParameters) MaxEmissionDuring(period time.Duration) time.Duration { return time.Duration(d.DutyCycle * float32(period)) } // All contains all the bands available. var All = make(map[string]Band) // GetByID returns the band if it was found, and returns an error otherwise. func GetByID(id string) (Band, error) { if band, ok := All[id]; ok { return band, nil } return Band{}, errBandNotFound.WithAttributes("id", id) } type swapParameters struct { version ttnpb.PHYVersion downgrade versionSwap } func (b Band) downgrades() []swapParameters { return []swapParameters{ {version: ttnpb.PHY_V1_1_REV_B, downgrade: bandIdentity}, {version: ttnpb.PHY_V1_1_REV_A, downgrade: b.regionalParameters1_1RevA}, {version: ttnpb.PHY_V1_0_3_REV_A, downgrade: b.regionalParameters1_0_3RevA}, {version: ttnpb.PHY_V1_0_2_REV_B, downgrade: b.regionalParameters1_0_2RevB}, {version: ttnpb.PHY_V1_0_2_REV_A, downgrade: b.regionalParameters1_0_2RevA}, {version: ttnpb.PHY_V1_0_1, downgrade: b.regionalParameters1_0_1}, {version: ttnpb.PHY_V1_0, downgrade: b.regionalParameters1_0}, } } // Version returns the band parameters for a given version. func (b Band) Version(wantedVersion ttnpb.PHYVersion) (Band, error) { supportedRegionalParameters := []string{} for _, swapParameter := range b.downgrades() { if swapParameter.downgrade == nil { return b, errUnsupportedLoRaWANRegionalParameters.WithAttributes("supported", strings.Join(supportedRegionalParameters, ", ")) } supportedRegionalParameters = append(supportedRegionalParameters, swapParameter.version.String()) b = swapParameter.downgrade(b) if swapParameter.version == wantedVersion { return b, nil } } return b, errUnknownPHYVersion.WithAttributes("version", wantedVersion) } // Versions supported for this band. func (b Band) Versions() []ttnpb.PHYVersion { var versions []ttnpb.PHYVersion for _, swapParameter := range b.downgrades() { if swapParameter.downgrade != nil { versions = append(versions, swapParameter.version) } else { break } } return versions } // FindSubBand returns the sub-band by frequency, if any. func (b Band) FindSubBand(frequency uint64) (SubBandParameters, bool) { for _, sb := range b.SubBands { if sb.Comprises(frequency) { return sb, true } } return SubBandParameters{}, false } func makeBeaconFrequencyFunc(frequencies [8]uint64) func(float64) uint64 { return func(beaconTime float64) uint64 { floor := math.Floor(beaconTime / float64(128)) return frequencies[int32(floor)%8] } } var usAuBeaconFrequencies = func() (freqs [8]uint64) { for i := 0; i < 8; i++ { freqs[i] = 923300000 + uint64(i*600000) } return freqs }() func parseChMask16(mask [16]bool, cntl uint8) (map[uint8]bool, error) { chans := make(map[uint8]bool, 16) switch cntl { case 0: for i := uint8(0); i < 16; i++ { chans[i] = mask[i] } case 6: for i := uint8(0); i < 16; i++ { chans[i] = true } default: return nil, errUnsupportedChMaskCntl.WithAttributes("chmaskcntl", cntl) } return chans, nil } func parseChMask72(mask [16]bool, cntl uint8) (map[uint8]bool, error) { chans := make(map[uint8]bool, 72) switch cntl { case 0, 1, 2, 3, 4: for i := uint8(0); i < 72; i++ { chans[i] = (i >= cntl*16 && i < (cntl+1)*16) && mask[i%16] } case 5: for i := uint8(0); i < 64; i++ { chans[i] = mask[i/8] } for i := uint8(64); i < 72; i++ { chans[i] = mask[i-64] } case 6, 7: for i := uint8(0); i < 64; i++ { chans[i] = cntl == 6 } for i := uint8(64); i < 72; i++ { chans[i] = mask[i-64] } default: return nil, errUnsupportedChMaskCntl.WithAttributes("chmaskcntl", cntl) } return chans, nil } func parseChMask96(mask [16]bool, cntl uint8) (map[uint8]bool, error) { chans := make(map[uint8]bool, 96) switch cntl { case 0, 1, 2, 3, 4, 5: for i := uint8(0); i < 96; i++ { chans[i] = (i >= cntl*16 && i < (cntl+1)*16) && mask[i%16] } case 6: for i := uint8(0); i < 96; i++ { chans[i] = true } default: return nil, errUnsupportedChMaskCntl.WithAttributes("chmaskcntl", cntl) } return chans, nil } func generateChMaskBlock(mask []bool) ([16]bool, error) { if len(mask) > 16 { return [16]bool{}, errInvalidChannelCount } block := [16]bool{} for j, on := range mask { block[j] = on } return block, nil } func generateChMaskMatrix(mask []bool) ([]ChMaskCntlPair, error) { if len(mask) > math.MaxUint8 { return nil, errInvalidChannelCount } n := uint8(len(mask)) if n == 0 { return nil, errInvalidChannelCount } ret := make([]ChMaskCntlPair, 1+(n-1)/16) for i := uint8(0); i <= n/16 && 16*i != n; i++ { end := 16*i + 16 if end > n { end = n } block, err := generateChMaskBlock(mask[16*i : end]) if err != nil { return nil, err } ret[i] = ChMaskCntlPair{Cntl: i, Mask: block} } return ret, nil } func generateChMask16(mask []bool) ([]ChMaskCntlPair, error) { if len(mask) != 16 { return nil, errInvalidChannelCount } for _, on := range mask { if !on { return generateChMaskMatrix(mask) } } return []ChMaskCntlPair{{Cntl: 6, Mask: [16]bool{}}}, nil } func equalChMasks(a, b []bool) bool { if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true } //revive:disable:flag-parameter func makeGenerateChMask72(supportChMaskCntl5 bool) func([]bool) ([]ChMaskCntlPair, error) { return func(mask []bool) ([]ChMaskCntlPair, error) { if len(mask) != 72 { return nil, errInvalidChannelCount } on125 := uint8(0) for i := 0; i < 64; i++ { if mask[i] { on125++ } } if on125 == 0 || on125 == 64 { block, err := generateChMaskBlock(mask[64:72]) if err != nil { return nil, err } idx := uint8(6) if on125 == 0 { idx = 7 } return []ChMaskCntlPair{{Cntl: idx, Mask: block}}, nil } if !supportChMaskCntl5 { return generateChMaskMatrix(mask) } // Find the majority mask. The majority mask is the mask of // FSBs that appears the most in the requested channels mask. // A majority mask of 0b00000001 for example represents the // first FSB. var majorityMask [8]bool majorityCount := 0 for i := 0; i < 8; i++ { var currentMask [8]bool for ch := 0; ch < 8; ch++ { currentMask[ch] = mask[ch*8+i] } if majorityCount == 0 { majorityMask = currentMask majorityCount = 1 } else { if equalChMasks(currentMask[:], majorityMask[:]) { majorityCount++ } else { majorityCount-- } } } // Find the channels which are not respecting the majority mask. // Since we can set two FSBs at a time using only one ChMaskCntl // command, we iterate them in pairs. n := len(mask) var outliers []int for fsb := 0; fsb < 8; fsb++ { for i := 0; i < 8; i += 2 { if mask[i*8+fsb] != majorityMask[i] || mask[(i+1)*8+fsb] != majorityMask[i+1] { outliers = append(outliers, i/2) break } } } if !equalChMasks(majorityMask[:], mask[64:72]) { outliers = append(outliers, 4) } // In order to ensure the minimality of the commands, we must // ensure that the mask couldn't have been generated only using // ChMaskCntl 0-4. if len(outliers) < 5 { var fsbMask [16]bool for i := 0; i < 8; i++ { fsbMask[15-i] = majorityMask[i] } cmds := make([]ChMaskCntlPair, len(outliers)+1) cmds[0] = ChMaskCntlPair{Cntl: 5, Mask: fsbMask} for i, cntl := range outliers { end := cntl*16 + 16 if end > n { end = n } block, err := generateChMaskBlock(mask[cntl*16 : end]) if err != nil { return nil, err } cmds[i+1] = ChMaskCntlPair{Cntl: uint8(cntl), Mask: block} } return cmds, nil } // Fallback to ChMaskCntl 0-4. return generateChMaskMatrix(mask) } } //revive:enable:flag-parameter func generateChMask96(mask []bool) ([]ChMaskCntlPair, error) { if len(mask) != 96 { return nil, errInvalidChannelCount } for _, on := range mask { if !on { return generateChMaskMatrix(mask) } } return []ChMaskCntlPair{{Cntl: 6, Mask: [16]bool{}}}, nil } func uint64Ptr(v uint64) *uint64 { return &v }
#ifndef _UTILS_H_ #define _UTILS_H_ #include <iostream> #include <mutex> using namespace std; mutex stdout_mutex; /* thread-safe cout */ template <class T> void print(T t) { stdout_mutex.lock(); std::cout << t; stdout_mutex.unlock(); } template <class T, class... Args> void print(T t, Args... args) { stdout_mutex.lock(); std::cout << t; stdout_mutex.unlock(); print(args...); } #endif
/* Copyright 2021 Adobe. All rights reserved. This file is licensed 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package application import ( "encoding/json" "errors" log "github.com/sirupsen/logrus" "gopkg.in/yaml.v3" "strings" "swinch/domain/datastore" ) const ( Kind = "Application" API = "spinnaker.adobe.com/alpha1" ) var ( AppNameLen = errors.New("invalid name length, 4 char min") ) type Manifest struct { ApiVersion string `yaml:"apiVersion" json:"apiVersion"` Kind string `yaml:"kind" json:"kind"` Metadata Metadata `yaml:"metadata" json:"metadata"` Spec Spec `yaml:"spec" json:"spec"` } type Metadata struct { Name string `yaml:"name" json:"name"` } type Spec struct { CloudProviders string `yaml:"cloudProviders" json:"cloudProviders"` Email string `yaml:"email" json:"email"` Name string `yaml:"-" json:"name"` Permissions Permissions `yaml:"permissions" json:"permissions"` } type Permissions struct { EXECUTE []string `yaml:"EXECUTE" json:"EXECUTE"` READ []string `yaml:"READ" json:"READ"` WRITE []string `yaml:"WRITE" json:"WRITE"` } func (a *Application) GetKind() string { return Kind } func (a *Application) Load(manifest interface{}) *Application { a.decode(manifest) a.inferFromManifest() err := a.validate() if err != nil { log.Fatalf("Application manifest validation failed: %v", err) } return a } func (a *Application) decode(manifest interface{}) { d := datastore.Datastore{} err := yaml.Unmarshal(d.MarshalYAML(manifest), &a.Manifest) if err != nil { log.Fatalf("Error Load: %v", err) } } func (a *Application) inferFromManifest() { // Spinnaker requires lower case application name a.Spec.Name = strings.ToLower(a.Metadata.Name) } func (a *Application) validate() error { if len(a.Spec.Name) < 3 { return AppNameLen } return nil } func (a *Application) loadSpec(spec []byte) Spec { tmpSpec := new(Spec) err := json.Unmarshal(spec, tmpSpec) if err != nil { log.Fatalf("Error loading spec: %v", err) } return *tmpSpec }
<filename>commonlib/src/main/java/com/common/manager/UserManager.java package com.common.manager; import android.text.TextUtils; import com.common.constant.Const; import com.tencent.mmkv.MMKV; import androidx.annotation.Keep; /** * Created by Richard on 2018/7/31 * 用户信息管理类 */ @Keep public class UserManager { // private static UserManager mInstance; private static MMKV mmkvUser = MmkvManager.mmkvUser; // private UserManager() { // mmkvUser = MmkvManager.mmkvUser; // } // public static UserManager getInstance() { // if (mInstance == null) { // mInstance = new UserManager(); // } // return mInstance; // } public static void clearUserInfo() { mmkvUser.clearAll(); } public static void setToken(String token) { mmkvUser.putString(Const.KEY_TOKEN, token); } public static String getToken() { return mmkvUser.getString(Const.KEY_TOKEN, ""); } public static void removeToken() { mmkvUser.remove(Const.KEY_TOKEN); } public static boolean isLogin() { String token = getToken(); return !TextUtils.isEmpty(token); } // public static void setUserInfo(UserInfo userInfo) { // mmkvUser.encode(Const.KEY_USER_INFO, userInfo); // } // // public static UserInfo getUserInfo() { // return mmkvUser.decodeParcelable(Const.KEY_USER_INFO, UserInfo.class); // } // // public static String getUserId() { // UserInfo info = getUserInfo(); // if(info != null) { // return info.getUserId(); // } // // return null; // } }
package here import "github.com/mdwhatcott/helps/here/there" func JoinedFileLine(sep string) string { return there.Locate(1).Joined(sep) } func FileLine() (string, int) { return there.Locate(1).FileLine() } func Line() int { return there.Locate(1).Line() } func File() string { return there.Locate(1).File() } func Dir() string { return there.Locate(1).Dir() }
<gh_stars>1-10 package binary_search; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author minchoba * 백준 16434번: 드래곤 앤 던전 * * @see https://www.acmicpc.net/problem/16434/ * */ public class Boj16434 { private static final long INF = Long.MAX_VALUE; private static class Room{ int query; int atk; int life; public Room(int query, int atk, int life) { this.query = query; this.atk = atk; this.life = life; } } public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken()); int hAtk = Integer.parseInt(st.nextToken()); Room[] r = new Room[N]; for(int i = 0; i < N; i++) { st = new StringTokenizer(br.readLine()); r[i] = new Room(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())); } System.out.println(expedition(N, hAtk, r)); } private static long expedition(int n, long atk, Room[] arr) { long start = 0, end = INF; long result = 0; while(start <= end) { long mid = (start + end) / 2; // 최소 체력 if(expedition(arr, mid, mid, atk)) { // 정복 end = mid - 1; result = mid; } else { start = mid + 1; } } return result; } private static boolean expedition(Room[] arr, long ml, long cl, long atk) { for(Room state: arr) { if(state.query == 1) { long count = state.life % atk == 0 ? state.life / atk - 1: state.life / atk; // 타격 횟수 cl -= count * state.atk; // 체력 감소 if(cl <= 0) return false; // 몬스터한테 졌을 경우 } else { cl = cl + state.life >= ml ? ml: cl + state.life; atk += state.atk; } } return true; } }
<gh_stars>0 // @ts-ignore import abiDecoder from 'abi-decoder' import Web3 from 'web3' import crypto from 'crypto' import { HttpProvider } from 'web3-core' import { toHex, keccak256 } from 'web3-utils' import * as ethUtils from 'ethereumjs-util' import { Address } from '../../src/relayclient/types/Aliases' import { IForwarderInstance, IRelayHubInstance, TestVerifierEverythingAcceptedInstance, TestRecipientInstance, SmartWalletInstance, TestDeployVerifierEverythingAcceptedInstance } from '../../types/truffle-contracts' import { assertRelayAdded, getTemporaryWorkdirs, ServerWorkdirs } from './ServerTestUtils' import ContractInteractor from '../../src/common/ContractInteractor' import EnvelopingTransactionDetails from '../../src/relayclient/types/EnvelopingTransactionDetails' import PingResponse from '../../src/common/PingResponse' import { KeyManager } from '../../src/relayserver/KeyManager' import { PrefixedHexString } from 'ethereumjs-tx' import { RelayClient } from '../../src/relayclient/RelayClient' import { RelayInfo } from '../../src/relayclient/types/RelayInfo' import { RelayRegisteredEventInfo } from '../../src/relayclient/types/RelayRegisteredEventInfo' import { RelayServer } from '../../src/relayserver/RelayServer' import { ServerConfigParams } from '../../src/relayserver/ServerConfigParams' import { TxStoreManager } from '../../src/relayserver/TxStoreManager' import { configure, EnvelopingConfig } from '../../src/relayclient/Configurator' import { constants } from '../../src/common/Constants' import { deployHub, getTestingEnvironment, createSmartWalletFactory, createSmartWallet, getGaslessAccount } from '../TestUtils' import { removeHexPrefix } from '../../src/common/Utils' import { RelayTransactionRequest } from '../../src/relayclient/types/RelayTransactionRequest' import RelayHubABI from '../../src/common/interfaces/IRelayHub.json' import RelayVerifierABI from '../../src/common/interfaces/IRelayVerifier.json' import DeployVerifierABI from '../../src/common/interfaces/IDeployVerifier.json' import { RelayHubConfiguration } from '../../src/relayclient/types/RelayHubConfiguration' import { ether } from '@openzeppelin/test-helpers' const TestRecipient = artifacts.require('TestRecipient') const TestVerifierEverythingAccepted = artifacts.require('TestVerifierEverythingAccepted') const TestDeployVerifierEverythingAccepted = artifacts.require('TestDeployVerifierEverythingAccepted') const SmartWallet = artifacts.require('SmartWallet') abiDecoder.addABI(RelayHubABI) abiDecoder.addABI(RelayVerifierABI) abiDecoder.addABI(DeployVerifierABI) // @ts-ignore abiDecoder.addABI(TestRecipient.abi) // @ts-ignore abiDecoder.addABI(TestVerifierEverythingAccepted.abi) // @ts-ignore abiDecoder.addABI(TestDeployVerifierEverythingAccepted.abi) export const LocalhostOne = 'http://localhost:8090' export interface PrepareRelayRequestOption { to: string from: string verifier: string // TODO Change to relay and deploy verifiers } export class ServerTestEnvironment { relayHub!: IRelayHubInstance forwarder!: IForwarderInstance relayVerifier!: TestVerifierEverythingAcceptedInstance deployVerifier!: TestDeployVerifierEverythingAcceptedInstance recipient!: TestRecipientInstance relayOwner!: Address gasLess!: Address encodedFunction!: PrefixedHexString clientId!: string options?: PrepareRelayRequestOption /** * Note: do not call methods of contract interactor inside Test Environment. It may affect Profiling Test. */ contractInteractor!: ContractInteractor relayClient!: RelayClient provider: HttpProvider web3: Web3 relayServer!: RelayServer constructor (provider: HttpProvider, accounts: Address[]) { this.provider = provider this.web3 = new Web3(this.provider) this.relayOwner = accounts[4] } /** * @param clientConfig * @param contractFactory - added for Profiling test, as it requires Test Environment to be using * different provider from the contract interactor itself. */ async init (clientConfig: Partial<EnvelopingConfig> = {}, relayHubConfig: Partial<RelayHubConfiguration> = {}, contractFactory?: (clientConfig: Partial<EnvelopingConfig>) => Promise<ContractInteractor>): Promise<void> { this.relayHub = await deployHub(undefined, relayHubConfig) this.recipient = await TestRecipient.new() this.relayVerifier = await TestVerifierEverythingAccepted.new() this.deployVerifier = await TestDeployVerifierEverythingAccepted.new() this.encodedFunction = this.recipient.contract.methods.emitMessage('hello world').encodeABI() const gaslessAccount = await getGaslessAccount() this.gasLess = gaslessAccount.address const sWalletTemplate = await SmartWallet.new() const factory = await createSmartWalletFactory(sWalletTemplate) const chainId = clientConfig.chainId ?? (await getTestingEnvironment()).chainId const defaultAccount = web3.defaultAccount ?? (await web3.eth.getAccounts())[0] const smartWallet: SmartWalletInstance = await createSmartWallet(defaultAccount ?? constants.ZERO_ADDRESS, this.gasLess, factory, gaslessAccount.privateKey, chainId) this.forwarder = smartWallet const shared: Partial<EnvelopingConfig> = { logLevel: 5, relayHubAddress: this.relayHub.address, relayVerifierAddress: this.relayVerifier.address, deployVerifierAddress: this.deployVerifier.address } if (contractFactory == null) { this.contractInteractor = new ContractInteractor(this.provider, configure(shared)) await this.contractInteractor.init() } else { this.contractInteractor = await contractFactory(shared) } const mergedConfig = Object.assign({}, shared, clientConfig) this.relayClient = new RelayClient(this.provider, configure(mergedConfig)) // Regisgter gasless account to avoid signing with RSKJ this.relayClient.accountManager.addAccount(gaslessAccount) } async newServerInstance (config: Partial<ServerConfigParams> = {}, serverWorkdirs?: ServerWorkdirs): Promise<void> { await this.newServerInstanceNoInit(config, serverWorkdirs, undefined) await this.relayServer.init() // initialize server - gas price, stake, owner, etc, whatever const latestBlock = await this.web3.eth.getBlock('latest') const receipts = await this.relayServer._worker(latestBlock.number) await assertRelayAdded(receipts, this.relayServer) // sanity check await this.relayServer._worker(latestBlock.number + 1) } _createKeyManager (workdir?: string): KeyManager { if (workdir != null) { return new KeyManager(1, workdir) } else { return new KeyManager(1, undefined, crypto.randomBytes(32)) } } async newServerInstanceNoInit (config: Partial<ServerConfigParams> = {}, serverWorkdirs?: ServerWorkdirs, unstakeDelay = constants.weekInSec): Promise<void> { this.newServerInstanceNoFunding(config, serverWorkdirs) await web3.eth.sendTransaction({ to: this.relayServer.managerAddress, from: this.relayOwner, value: web3.utils.toWei('2', 'ether') }) await this.relayHub.stakeForAddress(this.relayServer.managerAddress, unstakeDelay, { from: this.relayOwner, value: ether('1') }) } newServerInstanceNoFunding (config: Partial<ServerConfigParams> = {}, serverWorkdirs?: ServerWorkdirs): void { const managerKeyManager = this._createKeyManager(serverWorkdirs?.managerWorkdir) const workersKeyManager = this._createKeyManager(serverWorkdirs?.workersWorkdir) const txStoreManager = new TxStoreManager({ workdir: serverWorkdirs?.workdir ?? getTemporaryWorkdirs().workdir }) const serverDependencies = { contractInteractor: this.contractInteractor, txStoreManager, managerKeyManager, workersKeyManager } const shared: Partial<ServerConfigParams> = { relayHubAddress: this.relayHub.address, checkInterval: 10, logLevel: 5, relayVerifierAddress: this.relayVerifier.address, deployVerifierAddress: this.deployVerifier.address } const mergedConfig: Partial<ServerConfigParams> = Object.assign({}, shared, config) this.relayServer = new RelayServer(mergedConfig, serverDependencies) this.relayServer.on('error', (e) => { console.log('newServer event', e.message) }) this.relayServer.config.trustedVerifiers.push(this.relayVerifier.address) this.relayServer.config.trustedVerifiers.push(this.deployVerifier.address) } async createRelayHttpRequest (overrideDetails: Partial<EnvelopingTransactionDetails> = {}): Promise<RelayTransactionRequest> { const pingResponse = { relayHubAddress: this.relayHub.address, relayWorkerAddress: this.relayServer.workerAddress } const eventInfo: RelayRegisteredEventInfo = { relayManager: '', relayUrl: '' } const relayInfo: RelayInfo = { pingResponse: pingResponse as PingResponse, relayInfo: eventInfo } const transactionDetails: EnvelopingTransactionDetails = { from: this.gasLess, to: this.recipient.address, data: this.encodedFunction, relayHub: this.relayHub.address, callVerifier: this.relayVerifier.address, callForwarder: this.forwarder.address, gas: toHex(1000000), gasPrice: toHex(20000000000), tokenAmount: toHex(0), tokenGas: toHex(0), tokenContract: constants.ZERO_ADDRESS, isSmartWalletDeploy: false } return await this.relayClient._prepareRelayHttpRequest(relayInfo, Object.assign({}, transactionDetails, overrideDetails)) } async relayTransaction (assertRelayed = true, overrideDetails: Partial<EnvelopingTransactionDetails> = {}): Promise<{ signedTx: PrefixedHexString txHash: PrefixedHexString reqSigHash: PrefixedHexString }> { const req = await this.createRelayHttpRequest(overrideDetails) const signedTx = await this.relayServer.createRelayTransaction(req) const txHash = ethUtils.bufferToHex(ethUtils.keccak256(Buffer.from(removeHexPrefix(signedTx), 'hex'))) const reqSigHash = ethUtils.bufferToHex(ethUtils.keccak256(req.metadata.signature)) if (assertRelayed) { await this.assertTransactionRelayed(txHash, keccak256(req.metadata.signature)) } return { txHash, signedTx, reqSigHash } } async clearServerStorage (): Promise<void> { await this.relayServer.transactionManager.txStoreManager.clearAll() assert.deepEqual([], await this.relayServer.transactionManager.txStoreManager.getAll()) } async assertTransactionRelayed (txHash: string, reqSignatureHash: string, overrideDetails: Partial<EnvelopingTransactionDetails> = {}): Promise<void> { const receipt = await web3.eth.getTransactionReceipt(txHash) if (receipt == null) { throw new Error('Transaction Receipt not found') } const decodedLogs = abiDecoder.decodeLogs(receipt.logs).map(this.relayServer.registrationManager._parseEvent) const event1 = decodedLogs.find((e: { name: string }) => e.name === 'SampleRecipientEmitted') assert.exists(event1, 'SampleRecipientEmitted not found, maybe transaction was not relayed successfully') assert.equal(event1.args.message, 'hello world') const event2 = decodedLogs.find((e: { name: string }) => e.name === 'TransactionRelayed') assert.exists(event2, 'TransactionRelayed not found, maybe transaction was not relayed successfully') assert.equal(event2.name, 'TransactionRelayed') /** * event TransactionRelayed( address indexed relayManager, address relayWorker, bytes32 relayRequestSigHash); */ assert.equal(event2.args.relayWorker.toLowerCase(), this.relayServer.workerAddress.toLowerCase()) assert.equal(event2.args.relayManager.toLowerCase(), this.relayServer.managerAddress.toLowerCase()) assert.equal(event2.args.relayRequestSigHash, reqSignatureHash) } }
class File: """A simple file class""" def __init__(self, name, size, type): self.name = name self.size = size self.type = type def get_name(self): return self.name def get_size(self): return self.size def get_type(self): return self.type
import os import tensorflow as tf def save_predictions_to_tsv(estimator, predict_input_fn, output_dir): result = estimator.predict(input_fn=predict_input_fn) output_predict_file = os.path.join(output_dir, "test_results.tsv") with tf.gfile.GFile(output_predict_file, "w") as writer: num_written_lines = 0 tf.logging.info("***** Predict results *****") for (i, prediction) in enumerate(result): probabilities = prediction["probabilities"] writer.write('\t'.join(str(prob) for prob in probabilities) + '\n')
<filename>product-group-business-impl/src/main/java/tr/com/minicrm/productgroup/business/ProductGroupDoesNotExistException.java package tr.com.minicrm.productgroup.business; public class ProductGroupDoesNotExistException extends RuntimeException { private static final long serialVersionUID = -394078545391923795L; public ProductGroupDoesNotExistException(Long groupId) { super("ProductGroup with id " + groupId + " does not exist."); } public ProductGroupDoesNotExistException(String name) { super("ProductGroup with name " + name + " does not exist."); } }
#!/bin/bash { cat <<EOF (define (convert-psd-to-jpg src dest) (let* ( (image (car (file-psd-load RUN-NONINTERACTIVE src src))) (drawable (car (gimp-image-get-active-drawable image))) (img_width nil) (img_height nil) (new_layer nil) (merged_layers nil) ) (set! img_width (car (gimp-image-width image))) (set! img_height (car (gimp-image-height image))) ;; Create new layer the size of the image and fill it with transparent to create ;; a drawable the size of the image (set! new_layer (car (gimp-layer-new image img_width img_height RGBA-IMAGE "new_layer" 100 NORMAL-MODE))) (gimp-image-insert-layer image new_layer 0 0) (gimp-drawable-fill new_layer TRANSPARENT-FILL) (gimp-image-lower-item image new_layer) ;; Merge all layers into the newly created transparent layer (set! merged_layers (car (gimp-image-merge-visible-layers image EXPAND-AS-NECESSARY))) (file-jpeg-save RUN-NONINTERACTIVE image merged_layers dest dest 1 0 0 0 "" 0 0 0 0) (gimp-image-delete image) ) ) EOF echo "(convert-psd-to-jpg \"$2\" \"$3\")" echo "(gimp-quit 0)" } | $1 -i -b -
import networkx as nx class EdgeBetweennessCentrality: def __init__(self, normalized, weight, max_iterations): self.normalized = normalized self.weight = weight self.max_iterations = max_iterations def calculate(self, graph): G = nx.Graph(graph) edge_betweenness = nx.edge_betweenness_centrality(G, normalized=self.normalized, weight=self.weight) return edge_betweenness
package com.product.controller; import com.product.dto.Product; import com.product.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.sql.SQLException; import java.util.List; @RestController public class ProductController { @Autowired private ProductService productService; @GetMapping("/product") public List<Product> list() { try { return productService.selectAll(); } catch (SQLException throwables) { return null; } } @GetMapping("/product/{id}") public Product read(@PathVariable("id") String id) { try { return productService.select(id); } catch (SQLException e) { return null; } } @PostMapping("/product") public String regist(Product product) { try { productService.insert(product); return "SUCCESS"; } catch (SQLException throwables) { return "FAIL"; } } @PutMapping("/product") public String modify(@RequestBody Product product) { try { if (productService.update(product) > 0){ return "SUCCESS"; } } catch (SQLException throwables) { return "FAIL"; } return "FAIL"; } @DeleteMapping("/product/{id}") public String remove(@PathVariable("id") String id) { try { productService.delete(id); } catch (SQLException throwables) { return "FAIL"; } return "SUCCESS"; } }
package com.abner.playground.designpattern.factorymethod; public class BMWFactory implements ICarFactory{ @Override public Car buildCar() { return new BMW(); } }
/** * @license AngularJS v1.5.0-rc.2 * (c) 2010-2016 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /** * @ngdoc module * @name ngAria * @description * * The `ngAria` module provides support for common * [<abbr title="Accessible Rich Internet Applications">ARIA</abbr>](http://www.w3.org/TR/wai-aria/) * attributes that convey state or semantic information about the application for users * of assistive technologies, such as screen readers. * * <div doc-module-components="ngAria"></div> * * ## Usage * * For ngAria to do its magic, simply include the module `ngAria` as a dependency. The following * directives are supported: * `ngModel`, `ngDisabled`, `ngShow`, `ngHide`, `ngClick`, `ngDblClick`, and `ngMessages`. * * Below is a more detailed breakdown of the attributes handled by ngAria: * * | Directive | Supported Attributes | * |---------------------------------------------|----------------------------------------------------------------------------------------| * | {@link ng.directive:ngDisabled ngDisabled} | aria-disabled | * | {@link ng.directive:ngShow ngShow} | aria-hidden | * | {@link ng.directive:ngHide ngHide} | aria-hidden | * | {@link ng.directive:ngDblclick ngDblclick} | tabindex | * | {@link module:ngMessages ngMessages} | aria-live | * | {@link ng.directive:ngModel ngModel} | aria-checked, aria-valuemin, aria-valuemax, aria-valuenow, aria-invalid, aria-required, input roles | * | {@link ng.directive:ngClick ngClick} | tabindex, keypress event, button role | * * Find out more information about each directive by reading the * {@link guide/accessibility ngAria Developer Guide}. * * ##Example * Using ngDisabled with ngAria: * ```html * <md-checkbox ng-disabled="disabled"> * ``` * Becomes: * ```html * <md-checkbox ng-disabled="disabled" aria-disabled="true"> * ``` * * ##Disabling Attributes * It's possible to disable individual attributes added by ngAria with the * {@link ngAria.$ariaProvider#config config} method. For more details, see the * {@link guide/accessibility Developer Guide}. */ /* global -ngAriaModule */ var ngAriaModule = angular.module('ngAria', ['ng']). provider('$aria', $AriaProvider); /** * Internal Utilities */ var nodeBlackList = ['BUTTON', 'A', 'INPUT', 'TEXTAREA', 'SELECT', 'DETAILS', 'SUMMARY']; var isNodeOneOf = function(elem, nodeTypeArray) { if (nodeTypeArray.indexOf(elem[0].nodeName) !== -1) { return true; } }; /** * @ngdoc provider * @name $ariaProvider * * @description * * Used for configuring the ARIA attributes injected and managed by ngAria. * * ```js * angular.module('myApp', ['ngAria'], function config($ariaProvider) { * $ariaProvider.config({ * ariaValue: true, * tabindex: false * }); * }); *``` * * ## Dependencies * Requires the {@link ngAria} module to be installed. * */ function $AriaProvider() { var config = { ariaHidden: true, ariaChecked: true, ariaDisabled: true, ariaRequired: true, ariaInvalid: true, ariaMultiline: true, ariaValue: true, tabindex: true, bindKeypress: true, bindRoleForClick: true }; /** * @ngdoc method * @name $ariaProvider#config * * @param {object} config object to enable/disable specific ARIA attributes * * - **ariaHidden** – `{boolean}` – Enables/disables aria-hidden tags * - **ariaChecked** – `{boolean}` – Enables/disables aria-checked tags * - **ariaDisabled** – `{boolean}` – Enables/disables aria-disabled tags * - **ariaRequired** – `{boolean}` – Enables/disables aria-required tags * - **ariaInvalid** – `{boolean}` – Enables/disables aria-invalid tags * - **ariaMultiline** – `{boolean}` – Enables/disables aria-multiline tags * - **ariaValue** – `{boolean}` – Enables/disables aria-valuemin, aria-valuemax and aria-valuenow tags * - **tabindex** – `{boolean}` – Enables/disables tabindex tags * - **bindKeypress** – `{boolean}` – Enables/disables keypress event binding on `&lt;div&gt;` and * `&lt;li&gt;` elements with ng-click * - **bindRoleForClick** – `{boolean}` – Adds role=button to non-interactive elements like `div` * using ng-click, making them more accessible to users of assistive technologies * * @description * Enables/disables various ARIA attributes */ this.config = function(newConfig) { config = angular.extend(config, newConfig); }; function watchExpr(attrName, ariaAttr, nodeBlackList, negate) { return function(scope, elem, attr) { var ariaCamelName = attr.$normalize(ariaAttr); if (config[ariaCamelName] && !isNodeOneOf(elem, nodeBlackList) && !attr[ariaCamelName]) { scope.$watch(attr[attrName], function(boolVal) { // ensure boolean value boolVal = negate ? !boolVal : !!boolVal; elem.attr(ariaAttr, boolVal); }); } }; } /** * @ngdoc service * @name $aria * * @description * @priority 200 * * The $aria service contains helper methods for applying common * [ARIA](http://www.w3.org/TR/wai-aria/) attributes to HTML directives. * * ngAria injects common accessibility attributes that tell assistive technologies when HTML * elements are enabled, selected, hidden, and more. To see how this is performed with ngAria, * let's review a code snippet from ngAria itself: * *```js * ngAriaModule.directive('ngDisabled', ['$aria', function($aria) { * return $aria.$$watchExpr('ngDisabled', 'aria-disabled'); * }]) *``` * Shown above, the ngAria module creates a directive with the same signature as the * traditional `ng-disabled` directive. But this ngAria version is dedicated to * solely managing accessibility attributes. The internal `$aria` service is used to watch the * boolean attribute `ngDisabled`. If it has not been explicitly set by the developer, * `aria-disabled` is injected as an attribute with its value synchronized to the value in * `ngDisabled`. * * Because ngAria hooks into the `ng-disabled` directive, developers do not have to do * anything to enable this feature. The `aria-disabled` attribute is automatically managed * simply as a silent side-effect of using `ng-disabled` with the ngAria module. * * The full list of directives that interface with ngAria: * * **ngModel** * * **ngShow** * * **ngHide** * * **ngClick** * * **ngDblclick** * * **ngMessages** * * **ngDisabled** * * Read the {@link guide/accessibility ngAria Developer Guide} for a thorough explanation of each * directive. * * * ## Dependencies * Requires the {@link ngAria} module to be installed. */ this.$get = function() { return { config: function(key) { return config[key]; }, $$watchExpr: watchExpr }; }; } ngAriaModule.directive('ngShow', ['$aria', function($aria) { return $aria.$$watchExpr('ngShow', 'aria-hidden', [], true); }]) .directive('ngHide', ['$aria', function($aria) { return $aria.$$watchExpr('ngHide', 'aria-hidden', [], false); }]) .directive('ngModel', ['$aria', function($aria) { function shouldAttachAttr(attr, normalizedAttr, elem) { return $aria.config(normalizedAttr) && !elem.attr(attr); } function shouldAttachRole(role, elem) { return !elem.attr('role') && (elem.attr('type') === role) && (elem[0].nodeName !== 'INPUT'); } function getShape(attr, elem) { var type = attr.type, role = attr.role; return ((type || role) === 'checkbox' || role === 'menuitemcheckbox') ? 'checkbox' : ((type || role) === 'radio' || role === 'menuitemradio') ? 'radio' : (type === 'range' || role === 'progressbar' || role === 'slider') ? 'range' : (type || role) === 'textbox' || elem[0].nodeName === 'TEXTAREA' ? 'multiline' : ''; } return { restrict: 'A', require: '?ngModel', priority: 200, //Make sure watches are fired after any other directives that affect the ngModel value compile: function(elem, attr) { var shape = getShape(attr, elem); return { pre: function(scope, elem, attr, ngModel) { if (shape === 'checkbox' && attr.type !== 'checkbox') { //Use the input[checkbox] $isEmpty implementation for elements with checkbox roles ngModel.$isEmpty = function(value) { return value === false; }; } }, post: function(scope, elem, attr, ngModel) { var needsTabIndex = shouldAttachAttr('tabindex', 'tabindex', elem) && !isNodeOneOf(elem, nodeBlackList); function ngAriaWatchModelValue() { return ngModel.$modelValue; } function getRadioReaction() { if (needsTabIndex) { needsTabIndex = false; return function ngAriaRadioReaction(newVal) { var boolVal = (attr.value == ngModel.$viewValue); elem.attr('aria-checked', boolVal); elem.attr('tabindex', 0 - !boolVal); }; } else { return function ngAriaRadioReaction(newVal) { elem.attr('aria-checked', (attr.value == ngModel.$viewValue)); }; } } function ngAriaCheckboxReaction() { elem.attr('aria-checked', !ngModel.$isEmpty(ngModel.$viewValue)); } switch (shape) { case 'radio': case 'checkbox': if (shouldAttachRole(shape, elem)) { elem.attr('role', shape); } if (shouldAttachAttr('aria-checked', 'ariaChecked', elem)) { scope.$watch(ngAriaWatchModelValue, shape === 'radio' ? getRadioReaction() : ngAriaCheckboxReaction); } if (needsTabIndex) { elem.attr('tabindex', 0); } break; case 'range': if (shouldAttachRole(shape, elem)) { elem.attr('role', 'slider'); } if ($aria.config('ariaValue')) { var needsAriaValuemin = !elem.attr('aria-valuemin') && (attr.hasOwnProperty('min') || attr.hasOwnProperty('ngMin')); var needsAriaValuemax = !elem.attr('aria-valuemax') && (attr.hasOwnProperty('max') || attr.hasOwnProperty('ngMax')); var needsAriaValuenow = !elem.attr('aria-valuenow'); if (needsAriaValuemin) { attr.$observe('min', function ngAriaValueMinReaction(newVal) { elem.attr('aria-valuemin', newVal); }); } if (needsAriaValuemax) { attr.$observe('max', function ngAriaValueMinReaction(newVal) { elem.attr('aria-valuemax', newVal); }); } if (needsAriaValuenow) { scope.$watch(ngAriaWatchModelValue, function ngAriaValueNowReaction(newVal) { elem.attr('aria-valuenow', newVal); }); } } if (needsTabIndex) { elem.attr('tabindex', 0); } break; case 'multiline': if (shouldAttachAttr('aria-multiline', 'ariaMultiline', elem)) { elem.attr('aria-multiline', true); } break; } if (ngModel.$validators.required && shouldAttachAttr('aria-required', 'ariaRequired', elem)) { scope.$watch(function ngAriaRequiredWatch() { return ngModel.$error.required; }, function ngAriaRequiredReaction(newVal) { elem.attr('aria-required', !!newVal); }); } if (shouldAttachAttr('aria-invalid', 'ariaInvalid', elem)) { scope.$watch(function ngAriaInvalidWatch() { return ngModel.$invalid; }, function ngAriaInvalidReaction(newVal) { elem.attr('aria-invalid', !!newVal); }); } } }; } }; }]) .directive('ngDisabled', ['$aria', function($aria) { return $aria.$$watchExpr('ngDisabled', 'aria-disabled', []); }]) .directive('ngMessages', function() { return { restrict: 'A', require: '?ngMessages', link: function(scope, elem, attr, ngMessages) { if (!elem.attr('aria-live')) { elem.attr('aria-live', 'assertive'); } } }; }) .directive('ngClick',['$aria', '$parse', function($aria, $parse) { return { restrict: 'A', compile: function(elem, attr) { var fn = $parse(attr.ngClick, /* interceptorFn */ null, /* expensiveChecks */ true); return function(scope, elem, attr) { if (!isNodeOneOf(elem, nodeBlackList)) { if ($aria.config('bindRoleForClick') && !elem.attr('role')) { elem.attr('role', 'button'); } if ($aria.config('tabindex') && !elem.attr('tabindex')) { elem.attr('tabindex', 0); } if ($aria.config('bindKeypress') && !attr.ngKeypress) { elem.on('keypress', function(event) { var keyCode = event.which || event.keyCode; if (keyCode === 32 || keyCode === 13) { scope.$apply(callback); } function callback() { fn(scope, { $event: event }); } }); } } }; } }; }]) .directive('ngDblclick', ['$aria', function($aria) { return function(scope, elem, attr) { if ($aria.config('tabindex') && !elem.attr('tabindex') && !isNodeOneOf(elem, nodeBlackList)) { elem.attr('tabindex', 0); } }; }]); })(window, window.angular);
#include "gtest/gtest.h" #include "util/util.h" #include "util/data_filler.h" namespace { void ZeroFillTest() { cux::DataFiller filler; int len = 20; cux::half *arr = new cux::half[len]; filler.ZeroFill(len, arr); for (int i = 0; i < len; i++) { EXPECT_EQ(float(arr[i]), 0); } delete[]arr; } template <typename DType> void ConstantFillTest(float value, float deviation) { cux::DataFiller filler; int len = 20; DType *arr = new DType[len]; filler.ConstantFill(value, len, arr); for (int i = 0; i < len; i++) { if (deviation == 0) EXPECT_EQ(float(arr[i]), value); else { EXPECT_LE(float(arr[i]) - deviation, value); EXPECT_GE(float(arr[i]) + deviation, value); } } delete[]arr; } template <typename DType> void RandomFillTest(int min, int max, int decimal_pose, float deviation) { cux::DataFiller filler; int len = 20; DType *arr = new DType[len]; filler.RandomFill(min, max, decimal_pose, len, arr); for (int i = 0; i < len; i++) { EXPECT_LE(float(arr[i]) - deviation, max); EXPECT_GE(float(arr[i]) + deviation, min); } delete[]arr; } TEST(FillerTest, Zero) { ZeroFillTest(); } TEST(FillerTest, Constant) { ConstantFillTest<cux::half>(1.234, 0.01); ConstantFillTest<float>(2.345, 0); ConstantFillTest<int>(3, 0); } TEST(FillerTest, Random) { RandomFillTest<cux::half>(-100, -11, 3, 0.001); RandomFillTest<cux::half>(-100, 200, 2, 0.001); RandomFillTest<cux::half>(123, 345, 1, 0.001); RandomFillTest<float>(-1, 1, 4, 0); RandomFillTest<float>(-123, 168, 5, 0); RandomFillTest<float>(0, 168, 5, 0); RandomFillTest<float>(-100, -10, 3, 0); RandomFillTest<int>(9, 999, 0, 0); RandomFillTest<int>(-99, 99, 0, 0); RandomFillTest<int>(-123, -23, 0, 0); } } // namespace
use regex::Regex; fn process_positions(input_data: &str) -> Result<Vec<i32>, String> { let re = Regex::new(r"\((\d+), (\d+)\)").unwrap(); let mut positions = Vec::new(); for caps in re.captures_iter(input_data) { let x: i32 = caps.get(1).unwrap().as_str().parse().map_err(|e| format!("{:?}", e))?; let y: i32 = caps.get(2).unwrap().as_str().parse().map_err(|e| format!("{:?}", e))?; positions.push(x); positions.push(y); } Ok(positions) } fn main() { let input_data = "(1, 2)\n(3, 4)\n(5, 6)"; match process_positions(input_data) { Ok(result) => println!("{:?}", result), Err(err) => println!("Error: {}", err), } }
var express = require("express"); var app = express(); app.use(express.static(__dirname)); app.get("/", function (request, response){ response.sendFile(__dirname+"/postman.html"); }); app.listen(5000); console.log("Something awesome to happen at http://localhost:5000");
<gh_stars>0 package co.com.bancolombia.commons.jms.api; import javax.jms.JMSContext; import javax.jms.JMSException; import javax.jms.Message; public interface MQMessageCreator { Message create(JMSContext context) throws JMSException; }
#include "input/joystick.hpp" void Joystick::setState(unsigned int state) { this->state = state; } void Joystick::release() { state = JOYSTICK_NONE; }
#!/bin/bash . ./_error_handling.sh . ./_config.sh . ./_common_functions.sh # To keep my kernel minimal I want to disable these things that I'm not # actively using. They're interesting enough that they warrant additional # research and when I get there I'll want to turn them on. log "Disabling features that may be useful in the future but are generally unused" # Process accounting seem particularly fascinating but may be covered by the # auditing subsystem already. The tools would allow me to quickly view usage # breakdown at the expense of disk space. Could also be used for tracking down # how background processes spawn and the like. If I use this I'll likely want # to enable the V3 file format as it allow tracking process hierarchy # information. # # https://www.linuxjournal.com/article/6144 kernel_config --disable BSD_PROCESS_ACCT #kernel_config --enable BSD_PROCESS_ACCT_V3 # This may be used by tools like top but I'm not sure. For now I'm going to # disable it and see if any packages request it get re-enabled. If this is not # what is used by those programs it may be worth looking into similar to # process accounting. kernel_config --disable TASKSTATS kernel_config --disable TASK_DELAY_ACCT kernel_config --disable TASK_IO_ACCOUNTING kernel_config --disable TASK_XACCT # The following may be needed by kexec but until then I don't need it kernel_config --disable FIRMWARE_MEMMAP kernel_config --disable KEXEC
#!/bin/sh -e set -x xsltproc merge.xsl index.xml > tmp.xml xsltproc uniq.xsl tmp.xml > bla.xml
#!/bin/bash echo $PATH arch=$(dpkg --print-architecture) case "$arch" in amd64) echo Architecture: amd64 wget --no-check-certificate https://cdn.statically.io/gh/simonpla/ArduinoFingerprintLogin/main/releases/0.1/linux/main_amd64.afplogin ;; i386) echo Architecture: i386 wget --no-check-certificate https://cdn.statically.io/gh/simonpla/ArduinoFingerprintLogin/main/releases/0.1/linux/main_386.afplogin ;; armhf) echo Architecture: armhf wget --no-check-certificate https://cdn.statically.io/gh/simonpla/ArduinoFingerprintLogin/main/releases/0.1/linux/main_arm.afplogin ;; arm64) echo Architecture: arm64 wget --no-check-certificate https://cdn.statically.io/gh/simonpla/ArduinoFingerprintLogin/main/releases/0.1/linux/main_arm64.afplogin ;; esac mv *.afplogin afplogin cp afplogin /usr/local/bin rm afplogin chmod +x /usr/local/bin/afplogin echo File installed... if systemctl --version ; then echo systemctl recognized wget --no-check-certificate https://cdn.statically.io/gh/simonpla/ArduinoFingerprintLogin/main/afplogin.service cp afplogin.service /etc/systemd/system systemctl enable afplogin.service rm afplogin.service else echo No systemctl there: There is currently no support for your init manager. Please open a Github issue or Pull Request. fi echo "Finished!"
public class SoilProfile { public string Name { get; set; } public double FieldWaterCapacity { get; set; } public double WiltWaterCapacity { get; set; } public double ReadilyEvaporableWater { get; set; } public double TotalEvaporableWater { get; set; } public string Description { get; set; } public string AuthorId { get; set; } public double CalculateAvailableWaterCapacity() { return FieldWaterCapacity - WiltWaterCapacity; } }
package com.touch.air.mall.order; import com.touch.air.mall.order.entity.OrderEntity; import com.touch.air.mall.order.entity.OrderReturnReasonEntity; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.amqp.core.AmqpAdmin; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.DirectExchange; import org.springframework.amqp.core.Queue; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.boot.test.context.SpringBootTest; import javax.annotation.Resource; import java.util.Date; import java.util.HashMap; import java.util.UUID; /** * @author: bin.wang * @date: 2021/2/8 08:36 */ @Slf4j @SpringBootTest public class MallOrderApplicationTests { @Resource private AmqpAdmin amqpAdmin; @Resource private RabbitTemplate rabbitTemplate; /** * 1、如何创建Exchange、Queue、Binding * 1.1、使用AmqpAdmin进行创建 * 2、如何收发消息 */ @Test public void test() { DirectExchange directExchange = new DirectExchange("direct-exchange",true,false); amqpAdmin.declareExchange(directExchange); log.info("路由交换机[{}]创建成功", directExchange.getName()); } /** * 创建队列 */ @Test public void createQueue() { Queue queue = new Queue("mall-order-1", true, false, false); amqpAdmin.declareQueue(queue); log.info("队列[{}]创建成功", queue.getName()); } /** * 创建绑定 * destination;【目的地】 * destinationType;【目的地类型】 * routingKey;【路由键】 * exchange 【交换机】 * arguments 【自定义参数】 */ @Test public void createBinding() { Binding binding = new Binding("mall-order-1", Binding.DestinationType.QUEUE, "direct-exchange", "order-1", new HashMap<>()); amqpAdmin.declareBinding(binding); log.info("绑定[{}]创建成功", binding.getRoutingKey()); } /** * 发送消息 */ @Test public void sendMessage() { // String str = "hello-mall-order-1"; // rabbitTemplate.convertAndSend("direct-exchange", "order-1", str); // log.info("消息[{}]发送完成", str); //发送对象 for (int i = 0; i < 10; i++) { if (i % 2 == 0) { OrderReturnReasonEntity orderReturnReasonEntity = new OrderReturnReasonEntity(); orderReturnReasonEntity.setId(1L); orderReturnReasonEntity.setName("其他七天理由"); orderReturnReasonEntity.setCreateTime(new Date()); //发送对象,序列化机制,将对象写出去,对象必须实现序列化 rabbitTemplate.convertAndSend("direct-exchange", "order-1", orderReturnReasonEntity); }else{ OrderEntity orderEntity = new OrderEntity(); orderEntity.setOrderSn(UUID.randomUUID().toString()); rabbitTemplate.convertAndSend("direct-exchange", "order-1", orderEntity); } } } }
def is_rename_allowed(oldname, newname, allowed_type): if oldname != '' and newname.split('.')[-1] in allowed_type: return True else: return False
#pragma once #warning USING DEVELOPMENT IDs namespace ladspa_ids { constexpr auto peaking = 100; constexpr auto linkwitz_riley_lowpass = 108; constexpr auto linkwitz_riley_highpass = 116; constexpr auto low_shelf = 124; constexpr auto high_shelf = 132; constexpr auto delay = 140; constexpr auto invert = 148; constexpr auto gain = 156; constexpr auto butterworth_lowpass = 164; constexpr auto butterworth_highpass = 172; }
const express = require('express'); const request = require('request'); // Create an express application const app = express(); // An API endpoint to get the current temperature app.get('/temperature', (req, res) => { const city = req.query.city; const weatherURL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=YOUR_API_KEY`; request(weatherURL, { json: true }, (err, response, body) => { if (err) { res.send(err); } else { const temp = body.main.temp; res.send(`It is currently ${temp}°C in ${city}`); } }); }); const port = process.env.PORT || 3000; app.listen(port, () => console.log(`Listening on port ${port}`));
/* * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.dbflute.optional; /** * @param <OBJ> The type of object. * @author jflute * @since 1.1.0-sp1 (2015/01/19 Monday) */ public class OptionalObject<OBJ> extends BaseOptional<OBJ> { // =================================================================================== // Definition // ========== private static final long serialVersionUID = 1L; // basically cannot use (for optional entity) protected static final OptionalObject<Object> EMPTY_INSTANCE; static { EMPTY_INSTANCE = new OptionalObject<Object>(null, () -> { String msg = "The empty optional so the value is null."; throw new IllegalStateException(msg); }); } protected static final OptionalThingExceptionThrower NOWAY_THROWER = () -> { throw new IllegalStateException("no way"); }; // =================================================================================== // Constructor // =========== /** * @param thing The wrapped instance of thing. (NullAllowed) * @param thrower The exception thrower when illegal access. (NotNull) */ public OptionalObject(OBJ thing, OptionalThingExceptionThrower thrower) { // basically called by DBFlute super(thing, thrower); } /** * @param <EMPTY> The type of empty optional object. * @return The fixed instance as empty. (NotNull) */ @SuppressWarnings("unchecked") public static <EMPTY> OptionalObject<EMPTY> empty() { return (OptionalObject<EMPTY>) EMPTY_INSTANCE; } /** * @param <OBJ> The type of object wrapped in the optional object. * @param object The wrapped thing which is optional. (NotNull) * @return The new-created instance as existing optional object. (NotNull) */ public static <OBJ> OptionalObject<OBJ> of(OBJ object) { if (object == null) { String msg = "The argument 'object' should not be null."; throw new IllegalArgumentException(msg); } return new OptionalObject<OBJ>(object, NOWAY_THROWER); } /** * @param <OBJ> The type of object wrapped in the optional object. * @param object The wrapped instance or thing. (NullAllowed) * @param noArgLambda The callback for exception when illegal access. (NotNull) * @return The new-created instance as existing or empty optional object. (NotNull) */ public static <OBJ> OptionalObject<OBJ> ofNullable(OBJ object, OptionalThingExceptionThrower noArgLambda) { if (object != null) { return of(object); } else { return new OptionalObject<OBJ>(object, noArgLambda); } } // =================================================================================== // Standard Handling // ================= /** {@inheritDoc} */ public OptionalThingIfPresentAfter ifPresent(OptionalThingConsumer<OBJ> oneArgLambda) { assertOneArgLambdaNotNull(oneArgLambda); return callbackIfPresent(oneArgLambda); } /** {@inheritDoc} */ public boolean isPresent() { return exists(); } /** {@inheritDoc} */ public OBJ get() { return directlyGet(); } /** {@inheritDoc} */ public OptionalObject<OBJ> filter(OptionalThingPredicate<OBJ> oneArgLambda) { assertOneArgLambdaNotNull(oneArgLambda); return (OptionalObject<OBJ>) callbackFilter(oneArgLambda); } /** {@inheritDoc} */ @Override protected <ARG> OptionalObject<ARG> createOptionalFilteredObject(ARG obj) { return new OptionalObject<ARG>(obj, _thrower); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") public <RESULT> OptionalThing<RESULT> map(OptionalThingFunction<? super OBJ, ? extends RESULT> oneArgLambda) { assertOneArgLambdaNotNull(oneArgLambda); return (OptionalThing<RESULT>) callbackMapping(oneArgLambda); // downcast allowed because factory is overridden } /** {@inheritDoc} */ @Override protected <ARG> OptionalObject<ARG> createOptionalMappedObject(ARG obj) { return new OptionalObject<ARG>(obj, _thrower); } /** {@inheritDoc} */ public <RESULT> OptionalThing<RESULT> flatMap(OptionalThingFunction<? super OBJ, OptionalThing<RESULT>> oneArgLambda) { assertOneArgLambdaNotNull(oneArgLambda); return callbackFlatMapping(oneArgLambda); } /** {@inheritDoc} */ @Override protected <ARG> OptionalObject<ARG> createOptionalFlatMappedObject(ARG obj) { return new OptionalObject<ARG>(obj, _thrower); } /** {@inheritDoc} */ public OBJ orElse(OBJ other) { return directlyGetOrElse(other); } /** {@inheritDoc} */ public OBJ orElseGet(OptionalThingSupplier<OBJ> noArgLambda) { return directlyGetOrElseGet(noArgLambda); } /** {@inheritDoc} */ @Override public <CAUSE extends Throwable> OBJ orElseThrow(OptionalThingSupplier<? extends CAUSE> noArgLambda) throws CAUSE { return directlyGetOrElseThrow(noArgLambda); } /** {@inheritDoc} */ public <CAUSE extends Throwable, TRANSLATED extends Throwable> OBJ orElseTranslatingThrow( OptionalThingFunction<CAUSE, TRANSLATED> oneArgLambda) throws TRANSLATED { return directlyGetOrElseTranslatingThrow(oneArgLambda); } // =================================================================================== // DBFlute Extension // ================= /** {@inheritDoc} */ public void alwaysPresent(OptionalThingConsumer<OBJ> oneArgLambda) { assertOneArgLambdaNotNull(oneArgLambda); callbackAlwaysPresent(oneArgLambda); } /** * {@inheritDoc} * @deprecated basically use ifPresent() or use orElse(null) */ public OBJ orElseNull() { return directlyGetOrElse(null); } // =================================================================================== // Assert Helper // ============= protected void assertOneArgLambdaNotNull(Object oneArgLambda) { if (oneArgLambda == null) { throw new IllegalArgumentException("The argument 'oneArgLambda' should not be null."); } } }
<reponame>TingKaiChen/B-SHOT-SLAM<filename>include/bshot_headers_bits.h #ifndef headers_bshot_bits #define headers_bshot_bits #include <iostream> #include <bitset> #include <vector> #include <ctime> #include <chrono> #include <dirent.h> // for looping over the files in the directory #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/PointIndices.h> #include <pcl/common/transforms.h> #include <pcl/common/common_headers.h> #include <pcl/common/geometry.h> #include <pcl/common/impl/centroid.hpp> #include <pcl/keypoints/iss_3d.h> #include <pcl/filters/voxel_grid.h> #include <pcl/filters/extract_indices.h> #include <pcl/registration/correspondence_estimation.h> #include <pcl/registration/correspondence_rejection_sample_consensus.h> #include <pcl/features/normal_3d_omp.h> #include <pcl/features/normal_3d.h> #include <pcl/features/shot_omp.h> #include <pcl/kdtree/kdtree_flann.h> // #include <pcl/geometry> // #include <pcl/visualization/pcl_visualizer.h> // #include <pcl/visualization/point_cloud_handlers.h> #include <string> #include <fstream> #include <string> using namespace std; using namespace std::chrono; using namespace Eigen; using namespace pcl; using namespace pcl::io; using namespace pcl::console; #define PI 3.14159265 #endif // headers_bshot_bits
<gh_stars>0 require 'test_helper' describe BrNfe::Product::Operation::NfeDownloadNf do subject { FactoryGirl.build(:product_operation_nfe_download_nf) } let(:gateway) { FactoryGirl.build(:product_gateway_web_service_svrs) } before do subject.stubs(:gateway).returns(gateway) end describe '#aliases' do it { must_have_alias_attribute :chNFe, :chave_nfe } end describe 'Validations' do describe '#chave_nfe' do before { subject.stubs(:generate_key) } it { must validate_presence_of(:chave_nfe) } it { must validate_length_of(:chave_nfe).is_equal_to(44) } end end describe '#gateway' do before do subject.unstub(:gateway) subject.ibge_code_of_issuer_uf = 42 end it "Por padrão deve pegar o gateway conforme o estado" do subject.gateway.must_be_kind_of BrNfe::Product::Gateway::WebServiceSVRS subject.class.new(ibge_code_of_issuer_uf: 23).gateway.must_be_kind_of BrNfe::Product::Gateway::WebServiceCE end it "Deve ser possível forçar a utilizar o gateway do SVAN" do subject.force_gateway = :SVAN subject.gateway.must_be_kind_of BrNfe::Product::Gateway::WebServiceSVAN end it "Deve ser possível forçar a utilizar o gateway do AN - Vai pegar o base" do subject.force_gateway = 'AN' subject.gateway.class.must_equal BrNfe::Product::Gateway::Base end end describe 'gateway methods' do it 'o método #wsdl deve pegar o valor do método wsdl_download_nf do gateway ' do gateway.expects(:wsdl_download_nf).returns('http://teste.wsdl_download_nf.com') subject.wsdl.must_equal 'http://teste.wsdl_download_nf.com' end it 'o método #method_wsdl deve pegar o valor do método operation_download_nf do gateway ' do gateway.expects(:operation_download_nf).returns(:operation_download_nf) subject.method_wsdl.must_equal :operation_download_nf end it 'o método #gateway_xml_version deve pegar o valor do método version_xml_download_nf do gateway ' do gateway.expects(:version_xml_download_nf).returns(:v3_20) subject.gateway_xml_version.must_equal :v3_20 end it 'o método #url_xmlns deve pegar o valor do método url_xmlns_download_nf do gateway ' do gateway.expects(:url_xmlns_download_nf).returns('http://teste.url_xmlns_download_nf.com') subject.url_xmlns.must_equal 'http://teste.url_xmlns_download_nf.com' end it 'o método #ssl_version deve pegar o valor do método ssl_version_download_nf do gateway ' do gateway.expects(:ssl_version_download_nf).returns(:SSLv1) subject.ssl_version.must_equal :SSLv1 end end describe '#xml_builder' do it "Deve renderizar o XML e setar o valor na variavel @xml_builder" do subject.expects(:render_xml).returns('<xml>OK</xml>') subject.xml_builder.must_equal '<xml>OK</xml>' subject.instance_variable_get(:@xml_builder).must_equal '<xml>OK</xml>' end it "Se já houver valor setado na variavel @xml_builder não deve renderizar o xml novamente" do subject.instance_variable_set(:@xml_builder, '<xml>OK</xml>') subject.expects(:render_xml).never subject.xml_builder.must_equal '<xml>OK</xml>' end end describe "Validação do XML através do XSD" do it "Deve ser válido em ambiente de produção" do subject.env = :production nfe_must_be_valid_by_schema 'downloadNFe_v1.00.xsd' end it "Deve ser válido em ambiente de homologação" do subject.env = :test nfe_must_be_valid_by_schema 'downloadNFe_v1.00.xsd' end end end
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package operators; import java.lang.Math; import Evaluator.Operand; /** * * @author handa */ public class PowerOperator extends Operator { @Override public int priority() { return 4; } @Override public Operand execute(Operand op1, Operand op2) { int result = 1; for (int i = 1; i <= op2.getValue(); i++) { result *= op1.getValue(); } Operand newOp = new Operand(result); return newOp; } }
package com.github.starter.core.exception; import java.util.Arrays; public enum StatusCodes { OK(200), BAD_REQUEST(400), NOT_FOUND(404), UNAUTHORIZED(401), FORBIDDEN(403), INTERNAL_SERVER_ERROR(500); private int code; private StatusCodes(int code) { this.code = code; } public int getCode() { return code; } public static StatusCodes fromValue(int value) { return Arrays.stream(StatusCodes.values()).filter(statusCode -> statusCode.code == value) .findAny().orElse(StatusCodes.INTERNAL_SERVER_ERROR); } }
#!/bin/sh cp $1/ClickCounter-other.spec.js src/__tests__/
#!/bin/bash gcloud beta compute network-endpoint-groups create sumservice-neg-$1 \ --region=$1 \ --network-endpoint-type=SERVERLESS \ --cloud-run-service=sumservice gcloud beta compute backend-services add-backend --global sumservice-backend \ --network-endpoint-group-region=$1 \ --network-endpoint-group=sumservice-neg-$1
def find_closest_value(input_array, target): closest_value = float('inf') for array in input_array: for num in array: if abs(target - num) < abs(target - closest_value): closest_value = num return closest_value input_array = [[1, 5, 10], [3, 6, 8], [8, 11, 15]] target = 7 closest_value = find_closest_value(input_array, target) print(closest_value)
// Image.h // // An image class that can load a file from disk into main memory and to VRAM. // // Copyright (c) 2019-2022 <NAME>. // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby // granted, provided that the above copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN // AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. #pragma once #include <thread> #include <atomic> #include <glad/glad.h> #include <Foundation/tList.h> #include <Foundation/tString.h> #include <System/tFile.h> #include <Image/tPicture.h> #include <Image/tTexture.h> #include <Image/tCubemap.h> #include <Image/tImageHDR.h> #include "Config.h" #include "Undo.h" namespace Viewer { class Image : public tLink<Image> { public: Image(); // These constructors do not actually load the image, but Load() may be called at any point afterwards. Image(const tString& filename); Image(const tSystem::tFileInfo& fileInfo); virtual ~Image(); // These params are in principle different to the ones in tPicture since a Image does not necessarily // only use tPicture to do the loading. For example, we might include dds load params here. void ResetLoadParams(); tImage::tPicture::LoadParams LoadParams; void Play(); void Stop(); void UpdatePlaying(float dt); bool FrameDurationPreviewEnabled = false; float FrameDurationPreview = 1.0f/30.0f; float FrameCurrCountdown = 0.0f; bool FramePlaying = false; bool FramePlayRev = false; bool FramePlayLooping = true; int FrameNum = 0; bool Load(const tString& filename); bool Load(); // Load into main memory. bool IsLoaded() const { return (Pictures.Count() > 0); } int GetNumFrames() const { return Pictures.Count(); } bool IsOpaque() const; bool Unload(bool force = false); float GetLoadedTime() const { return LoadedTime; } // Bind to a texture ID and load into VRAM. If already in VRAM, it makes the texture current. Since some ImGui // functions require a texture ID as parameter, this function return the ID. // If the alt image is enabled, the bound texture and ID will be the alt image's. // Returns 0 (invalid id) if there was a problem. uint64 Bind(); void Unbind(); int GetWidth() const; int GetHeight() const; int GetArea() const; tColouri GetPixel(int x, int y) const; // Some images can store multiple complete images inside a single file (multiple frames). // The primary one is the first one. tImage::tPicture* GetPrimaryPic() const { return Pictures.First(); } tImage::tPicture* GetCurrentPic() const { tImage::tPicture* pic = Pictures.First(); for (int i = 0; i < FrameNum; i++) pic = pic ? pic->Next() : nullptr; return pic; } tList<tImage::tPicture>& GetPictures() { return Pictures; } // Functions that edit and cause dirty flag to be set. void Rotate90(bool antiClockWise); void Rotate(float angle, const tColouri& fill, tImage::tResampleFilter upFilter, tImage::tResampleFilter downFilter); void Flip(bool horizontal); void Crop(int newWidth, int newHeight, int originX, int originY, const tColouri& fillColour = tColour::black); void Crop(int newWidth, int newHeight, tImage::tPicture::Anchor, const tColouri& fillColour = tColour::black); void Crop(const tColouri& borderColour, uint32 channels = tMath::ColourChannel_RGBA); void Resample(int newWidth, int newHeight, tImage::tResampleFilter filter, tImage::tResampleEdgeMode edgeMode); void SetPixelColour(int x, int y, const tColouri&, bool pushUndo, bool supressDirty = false); void SetAllPixels(const tColouri& colour, uint32 channels = tMath::ColourChannel_RGBA); void AlphaBlendColour(const tColouri& blendColour, bool resetAlpha); void SetFrameDuration(float duration, bool allFrames = false); // Undo and redo functions. void Undo() { UndoStack.Undo(Pictures, Dirty); } void Redo() { UndoStack.Redo(Pictures, Dirty); } bool IsUndoAvailable() const { return UndoStack.UndoAvailable(); } bool IsRedoAvailable() const { return UndoStack.RedoAvailable(); } tString GetUndoDesc() const { tString desc; tsPrintf(desc, "[%s]", UndoStack.GetUndoDesc().Chars()); return desc; } tString GetRedoDesc() const { tString desc; tsPrintf(desc, "[%s]", UndoStack.GetRedoDesc().Chars()); return desc; } // Since from outside this class you can save to any filename, we need the ability to clear the dirty flag. void ClearDirty() { Dirty = false; } bool IsDirty() const { return Dirty; } struct ImgInfo { bool IsValid() const { return (SrcPixelFormat != tImage::tPixelFormat::Invalid); } tImage::tPixelFormat SrcPixelFormat = tImage::tPixelFormat::Invalid; bool Opaque = false; int FileSizeBytes = 0; int MemSizeBytes = 0; }; bool IsAltMipmapsPictureAvail() const { return DDSTexture2D.IsValid() && AltPicture.IsValid(); } bool IsAltCubemapPictureAvail() const { return DDSCubemap.IsValid() && AltPicture.IsValid(); } void EnableAltPicture(bool enabled) { AltPictureEnabled = enabled; } bool IsAltPictureEnabled() const { return AltPictureEnabled; } // Thumbnail generation is done on a seperate thread. Calling RequestThumbnail starts the thread. You should call it // over and over as it will only ever start one thread, and it may not start it if too mnay threads are already // working. BindThumbnail will at some point return a non-zero texture ID, but not necessarily right away. Just keep // calling it. Unloaded images remain unloaded after thumbnail generation. void RequestThumbnail(); // Call this if you need to invaidate the thumbnail. For example, if the file was saved/edited this should be called // to force regeneration. void RequestInvalidateThumbnail(); // You are allowed to unrequest. It will succeed if a worker was never assigned. void UnrequestThumbnail(); bool IsThumbnailWorkerActive() const { return ThumbnailThreadRunning; } uint64 BindThumbnail(); inline static int GetThumbnailNumThreadsRunning() { return ThumbnailNumThreadsRunning; } ImgInfo Info; // Info is only valid AFTER loading. tString Filename; // Valid before load. tSystem::tFileType Filetype; // Valid before load. Based on extension. std::time_t FileModTime; // Valid before load. uint64 FileSizeB; // Valid before load. int CachePrimaryWidth = 0; // Valid once thumbnail loaded. Used for sorting without having to do full load. int CachePrimaryHeight = 0; int CachePrimaryArea = 0; const static uint32 ThumbChunkInfoID; const static int ThumbWidth; // = 256; const static int ThumbHeight; // = 144; const static int ThumbMinDispWidth; // = 64; static tString ThumbCacheDir; bool TypeSupportsProperties() const; private: void PushUndo(const tString& desc) { UndoStack.Push(Pictures, desc, Dirty); } // Dds files are special and already in HW ready format. The tTexture can store dds files, while tPicture stores // other types (tga, gif, jpg, bmp, tif, png, etc). If the image is a dds file, the tTexture is valid and in order // to read pixel data, the image is fetched from the framebuffer to ALSO make a valid PictureImage. // // Note: A tTexture contains all mipmap levels while a tPicture does not. That's why we have a list of tPictures. tImage::tTexture DDSTexture2D; tImage::tCubemap DDSCubemap; tList<tImage::tPicture> Pictures; // The 'alternative' picture is valid when there is another valid way of displaying the image. // Specifically for cubemaps and dds files with mipmaps this offers an alternative view. bool AltPictureEnabled = false; tImage::tPicture AltPicture; bool ThumbnailRequested = false; // True if ever requested. bool ThumbnailInvalidateRequested = false; bool ThumbnailThreadRunning = false; // Only true while worker thread going. static int ThumbnailNumThreadsRunning; // How many worker threads active. std::thread ThumbnailThread; std::atomic_flag ThumbnailThreadFlag = ATOMIC_FLAG_INIT; tImage::tPicture ThumbnailPicture; // These 2 functions run on a helper thread. static void GenerateThumbnailBridge(Image*); void GenerateThumbnail(); // Zero is invalid and means texture has never been bound and loaded into VRAM. uint TexIDAlt = 0; uint TexIDThumbnail = 0; // Returns the approx main mem size of this image. Considers the Pictures list and the AltPicture. int GetMemSizeBytes() const; bool ConvertTexture2DToPicture(); bool ConvertCubemapToPicture(); void GetGLFormatInfo(GLint& srcFormat, GLenum& srcType, GLint& dstFormat, bool& compressed, tImage::tPixelFormat); void BindLayers(const tList<tImage::tLayer>&, uint texID); void CreateAltPictureFromDDS_2DMipmaps(); void CreateAltPictureFromDDS_Cubemap(); float LoadedTime = -1.0f; bool Dirty = false; // Undo / Redo Undo::Stack UndoStack; }; // Implementation below. inline bool Image::TypeSupportsProperties() const { return ( (Filetype == tSystem::tFileType::HDR) || (Filetype == tSystem::tFileType::EXR) ); } }
import consola from 'consola' import yargs from 'yargs' import { DruxtDocgen } from '..' const argv = yargs .option('config', { alias: 'c', description: 'Path to config', type: 'string', }) .help() .alias('help', 'h') .argv const druxtDocgen = new DruxtDocgen(argv.config || null) async function main() { // Generate documentation. await druxtDocgen.generateDocs() } main().catch((error) => { consola.error(error) process.exit(1) })
#!/bin/bash # Usage - from the repository root, enter # # ./releasing/localbuild.sh # # The script attempts to use cloudbuild configuration # to create a release "locally". # # See https://cloud.google.com/cloud-build/docs/build-debug-locally # # At the time of writing, # # https://pantheon.corp.google.com/cloud-build/triggers?project=kustomize-199618 # # has a trigger such that whenever a git tag is # applied to the kustomize repo, the cloud builder # reads the repository-relative file # # releasing/cloudbuild.yaml # # Inside this yaml file is a reference to the script # # releasing/cloudbuild.sh # # which runs goreleaser from the proper directory. # # The script you are reading now does something # analogous via docker tricks. set -e # Modify cloudbuild.yaml to add the --snapshot flag. # This suppresses the github release, and leaves # the build output in the kustomize/dist directory. config=$(mktemp) sed 's|\["releasing/cloudbuild.sh"\]|["releasing/cloudbuild.sh", "--snapshot"]|' \ releasing/cloudbuild.yaml > $config cloud-build-local \ --config=$config \ --bind-mount-source \ --dryrun=false \ . # Print results of local build echo "##########################################" tree ./kustomize/dist echo "##########################################"
import doctest import unittest from zope import interface, component, schema from zope.testing.cleanup import cleanUp from z3c.form import testing def setUp(test): testing.setUp(test) test.globs.update(dict( interface=interface, component=component, schema=schema)) def tearDown(test): cleanUp() def test_suite(): return unittest.TestSuite(( doctest.DocFileSuite( 'README.txt', setUp=setUp, tearDown=tearDown, optionflags=doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS), ))
#!/usr/bin/env python # coding=utf-8 """ This file contains a collection of miscellaneous utility functions. """ from __future__ import absolute_import from __future__ import print_function import imp import os import shutil import stat import sys import tempfile import uuid __author__ = "<NAME>" __copyright__ = "Copyright 2012-2016, <NAME> (www.albertopettarin.it)" __license__ = "MIT" __version__ = "3.1.3" __email__ = "<EMAIL>" __status__ = "Production" PY2 = (sys.version_info[0] == 2) def print_debug(msg, do_print=True): if do_print: print(u"[DEBU] %s" % msg) def print_error(msg): print(u"[ERRO] %s" % msg) def print_info(msg): print(u"[INFO] %s" % msg) def print_warning(msg): print(u"[WARN] %s" % msg) def get_uuid(): return str(uuid.uuid4()).replace("-", "") def load_input_parser(parser_file_path): parser = None if os.path.exists(parser_file_path): try: # load source file parser = imp.load_source("", parser_file_path) try: # try calling parse function parser.parse(None, None) except: print_error("Error trying to call the parse() function. Does file '%s' contain a parse() function?" % parser_file_path) except: print_error("Error trying to load parser from file '%s'" % parser_file_path) else: print_error("File '%s' does not exist" % parser_file_path) return parser def load_transform_headword(transform_headword_path): transform_headword = lambda headword: headword if transform_headword_path is not None: if os.path.exists(transform_headword_path): try: # load source file transform_headword = imp.load_source("", transform_headword_path) try: # try calling parse function transform_headword.transform_headword(None) except: print_error("Error trying to call the transform_headword() function. Does file '%s' contain a transform_headword() function?" % transform_headword_path) except: print_error("Error trying to load transform_headword from file '%s'" % transform_headword_path) else: print_error("File '%s' does not exist" % transform_headword_path) return lambda headword: transform_headword.transform_headword(headword) def create_temp_file(): tmp_handler, tmp_path = tempfile.mkstemp() return (tmp_handler, tmp_path) def create_temp_directory(): return tempfile.mkdtemp() def copy_file(origin, destination): try: shutil.copy(origin, destination) except: pass def rename_file(origin, destination): try: os.rename(origin, destination) except: pass def delete_file(handler, path): """ Safely delete file. :param handler: the file handler (as returned by tempfile) :type handler: obj :param path: the file path :type path: string (path) """ if handler is not None: try: os.close(handler) except: pass if path is not None: try: os.remove(path) except: pass def delete_directory(path): """ Safely delete a directory. :param path: the file path :type path: string (path) """ def remove_readonly(func, path, _): """ Clear the readonly bit and reattempt the removal Adapted from https://docs.python.org/3.5/library/shutil.html#rmtree-example See also http://stackoverflow.com/questions/2656322/python-shutil-rmtree-fails-on-windows-with-access-is-denied """ try: os.chmod(path, stat.S_IWRITE) func(path) except: pass if path is not None: shutil.rmtree(path, onerror=remove_readonly) def utf_lower(string, encoding="utf-8", lower=True): """ Convert the given Unicode string (unicode on Python 2, str on Python 3) to a byte string in the given encoding, and lowercase it. :param string: the string to convert :type string: Unicode string :param encoding: the encoding to use :type encoding: string :param lower: lowercase the string :type lower: bool :rtype: byte string """ native_str = isinstance(string, str) ret = None if (PY2 and native_str) or ((not PY2) and (not native_str)): ret = string else: try: ret = string.encode(encoding) except UnicodeEncodeError: print_warning(u"UnicodeEncodeError in collate function, ignoring it") ret = string.encode(encoding, errors="ignore") if lower: return ret.lower() return ret
package com.p.g.j.lenovo.jgp; import android.support.design.widget.BottomNavigationView; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.p.g.j.lenovo.jgp.util.HandleBottomNavigationView; public class MyAccount extends AppCompatActivity implements View.OnClickListener{ private Toolbar toolbar; //toolbar实例 private Button toolBarButton; //toolbar上按钮实例 private ImageView headProtrait; //头像照片实例 private TextView userName; //用户名TextView实例 private TextView userId; //用户ID TextView实例 private Button message; //消息按钮实例 private Button history; //历史按钮实例 private Button collect; //收藏按钮实例 private Button setting; //设置按钮实例 private Button feedback; //反馈按钮实例 private Button logout; //注销按钮实例 private BottomNavigationView bottomNavigationView; //底部BottomNavigationView实例 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.myaccount); toolbar=(Toolbar)findViewById(R.id.myAccountToolBar); //32行-43行为各实例绑定ID toolBarButton=(Button)findViewById(R.id.myAccountToolBarButton); headProtrait=(ImageView)findViewById(R.id.myAccountHeadProtrait); userName=(TextView)findViewById(R.id.myAccountUserName); userId=(TextView)findViewById(R.id.myAccountUserId); message=(Button)findViewById(R.id.myAccountMessage); history=(Button)findViewById(R.id.myAccountHistory); collect=(Button)findViewById(R.id.myAccountCollect); setting=(Button)findViewById(R.id.myAccountSetting); feedback=(Button)findViewById(R.id.myAccountFeedback); logout=(Button)findViewById(R.id.myAccountLogout); bottomNavigationView=(BottomNavigationView)findViewById(R.id.bottomNavigationView); setSupportActionBar(toolbar); toolbar.setTitle(""); //去掉toolbar的标题 setSupportActionBar(toolbar); toolBarButton.setOnClickListener(this); //48-54行为设置各按钮点击事件 message.setOnClickListener(this); history.setOnClickListener(this); collect.setOnClickListener(this); setting.setOnClickListener(this); feedback.setOnClickListener(this); logout.setOnClickListener(this); HandleBottomNavigationView.handle(bottomNavigationView); } @Override public void onClick(View view){ switch (view.getId()){ case R.id.myAccountToolBarButton:{ break; } case R.id.myAccountMessage:{ break; } case R.id.myAccountHistory:{ break; } case R.id.myAccountCollect:{ break; } case R.id.myAccountSetting:{ break; } case R.id.myAccountFeedback:{ break; } case R.id.myAccountLogout:{ break; } } } }
<filename>client/src/components/Loading.js import React, { Component } from 'react' import ReactDOM from 'react-dom' class Loading extends Component { render() { return ReactDOM.createPortal( <div className="ui dimmer modals visible active"> <div className="ui active inverted"> <div className="ui text loader">Loading</div> </div> <p></p> </div>, document.querySelector('#modal') ) } } export default Loading
import React, { useEffect, useState } from "react"; // import Navbar from "../components/Navbar"; import API from "./../utils/API"; import Logo from "../components/Logo"; import MenuItem from "../components/MenuItem"; import "../index.css"; function Pickup() { const [formState, setFormState] = useState({ _id: "5f048d7df60cf32c3ca97f83", _idUser: "", menuItemName: "", isSpecial: "", image: "", ingredients: "", price: 0, specialPrice: 0, quantity: 0, tax: 0, tip: 5, createdAt: "2012-12-12T05:00:00.000Z", grandTotal: 0, posts: [], }); const handleChange = (event) => { const { name, value } = event.target; setFormState({ ...formState, [name]: value, }); }; function getOrderPost() { // const id = "5f048d7df60cf32c3ca97f83"; API.getMenu() .then((res) => { // console.log({ res }); const data = res.data.data; setFormState({ posts: data }); console.log("data has been received"); }) .catch(() => { alert("data has not found"); }); } const submit = (event) => { event.preventDefault(); API.postOrder(formState.title, formState.body) .then((res) => { // console.log(res); return res; }) .catch((err) => alert(err)); getOrderPost(); }; function displayorder(posts) { if (!posts.length) { return null; } return posts.map((post, index) => { // console.log({ post }); // console.log({ post }.post.menuType); const ordermade = { post }.post; // const menuStarters = posts.map(post => // <post key={post.idAuto} name={post.title} // ingredients={post.body}/>) // console.log(menuStarters) return ( <div> <p>Id {ordermade._id} </p> <p>userId{ordermade._idUser} </p> <p>{ordermade.menuItemName} </p> <p>{ordermade.image} </p> <p>{ordermade.menuType} </p> <p>{ordermade.ingredients} </p> <p>{ordermade.price} </p> <p>{ordermade.specialPrice} </p> <p>{ordermade.quantity} </p> <p>{ordermade.tax} </p> <p>{ordermade.grandTotal} </p> <p>{ordermade.createdAt} </p> {/* <p>{post} </p> */} </div> ); }); } return ( <> <Logo /> <div> <form className="form" onSubmit={submit}> <div> <input type="text" name="title" placeholder="title" //value={this.state.tile} onChange={handleChange} /> </div> <div className="from-input"> <textarea placeholder="text" name="body" cols="30" row="10" //value={this.state.body} onChange={handleChange} ></textarea> <br /> </div> <button>Submit</button> </form> </div> <div className="blog">{displayorder(formState.posts)}</div> </> ); } export default Pickup;
<filename>oauth2-server-boot/src/main/java/com/newnil/cas/oauth2/provider/config/SecurityConfig.java<gh_stars>100-1000 package com.newnil.cas.oauth2.provider.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.domain.AuditorAware; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableJpaAuditing @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http .exceptionHandling() .accessDeniedPage("/login.html?authorization_error=true") .and() .logout() .permitAll() .and() .formLogin() .loginPage("/login.html") .permitAll() .and() .authorizeRequests() .anyRequest().authenticated(); // @formatter:on } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public AuditorAware<String> auditorAwareBean(@Autowired AuthenticationTrustResolver authenticationTrustResolver) { return () -> { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || authenticationTrustResolver.isAnonymous(authentication)) { return "@SYSTEM"; } Object principal = authentication.getPrincipal(); if (principal instanceof String) { return (String) principal; } else if (principal instanceof UserDetails) { return ((UserDetails) principal).getUsername(); } else { return String.valueOf(principal); } }; } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
<reponame>thanhdanh/todo-app import React, { useState } from 'react'; import moment from 'moment'; import { EuiCheckbox, htmlIdGenerator, EuiTitle, EuiListGroupItem, EuiBadge, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { ITodo, TodoPriority } from '../../types'; import { updateTodo, deleteTodo } from '../../requests'; export default function TodoItem({ item, onUpdated, onSelect }: { item: ITodo, onUpdated: Function, onSelect: Function }) { const [checked, setCheck] = useState(item.completed); const isOverdue = !!item.dueDate && moment().isAfter(item.dueDate, 'day'); const handleToogleTodo = async () => { const value = !checked; setCheck(value); await updateTodo(item._id, { completed: value }); onUpdated() } const handleDeleteTodo = async () => { await deleteTodo(item._id); onUpdated() } const getPriorityBadge = (item: ITodo) => { if (isOverdue && !item.completed) return <EuiBadge color="warning">{item.priority}</EuiBadge> switch (item.priority) { case TodoPriority.High: return <EuiBadge color="accent">{item.priority}</EuiBadge> case TodoPriority.Low: return <EuiBadge color="default">{item.priority}</EuiBadge> case TodoPriority.Normal: default: return <EuiBadge color="primary">{item.priority}</EuiBadge> } } return ( <EuiListGroupItem icon={ <EuiCheckbox id={htmlIdGenerator()()} checked={checked} onChange={handleToogleTodo} /> } label={ <div onClick={() => onSelect()} style={{ cursor: 'pointer' }}> <EuiTitle size="xxs"><h4>{item.title}</h4></EuiTitle> <EuiFlexGroup justifyContent="spaceBetween"> <EuiFlexItem grow={false}>{getPriorityBadge(item)}</EuiFlexItem> <EuiFlexItem grow={false}> {isOverdue? <small>Overdue {moment(item.dueDate).format("ll")} </small> : item.dueDate ? <small>Due on {moment(item.dueDate).format("ll")}</small> : null} </EuiFlexItem> </EuiFlexGroup> </div> } extraAction={{ color: 'danger', onClick: handleDeleteTodo, iconType: 'minusInCircle', iconSize: 's', 'aria-label': 'Delete todo', }} style={{ borderBottom: '1px solid #e1e1e1' }} /> ) }
#!/usr/bin/env bash # Push HTML files to gh-pages automatically. # Fill this out with the correct org/repo ORG=icopy-site REPO=icopy-site.github.io # This probably should match an email for one of your users. EMAIL=chenjiajia1@gmail.com set -e git remote add gh-token "https://${GH_TOKEN}@github.com/$ORG/$REPO.git"; git fetch gh-token && git fetch gh-token master:master; # Update git configuration so I can push. if [ "$1" != "dry" ]; then # Update git config. git config user.name "Travis Builder" git config user.email "$EMAIL" fi mkdocs gh-deploy -v --clean --force --remote-name gh-token --remote-branch master;
#!/usr/bin/env bash set -e dir="$(pwd)" cacheDir="${CACHE_DIR:-"$HOME/.kibana"}" RED='\033[0;31m' C_RESET='\033[0m' # Reset color ### ### Since the Jenkins logging output collector doesn't look like a TTY ### Node/Chalk and other color libs disable their color output. But Jenkins ### can handle color fine, so this forces https://github.com/chalk/supports-color ### to enable color support in Chalk and other related modules. ### export FORCE_COLOR=1 ### ### check that we seem to be in a kibana project ### if [ -f "$dir/package.json" ] && [ -f "$dir/.node-version" ]; then echo "Setting up node.js and yarn in $dir" else echo "${RED}src/dev/ci_setup/setup.sh must be run within a kibana repo${C_RESET}" exit 1 fi export KIBANA_DIR="$dir" export XPACK_DIR="$KIBANA_DIR/x-pack" parentDir="$(cd "$KIBANA_DIR/.."; pwd)" export PARENT_DIR="$parentDir" kbnBranch="$(jq -r .branch "$KIBANA_DIR/package.json")" export KIBANA_PKG_BRANCH="$kbnBranch" echo " -- KIBANA_DIR='$KIBANA_DIR'" echo " -- XPACK_DIR='$XPACK_DIR'" echo " -- PARENT_DIR='$PARENT_DIR'" echo " -- KIBANA_PKG_BRANCH='$KIBANA_PKG_BRANCH'" echo " -- TEST_ES_SNAPSHOT_VERSION='$TEST_ES_SNAPSHOT_VERSION'" ### ### download node ### UNAME=$(uname) OS="linux" if [[ "$UNAME" = *"MINGW64_NT"* ]]; then OS="win" fi echo " -- Running on OS: $OS" nodeVersion="$(cat "$dir/.node-version")" nodeDir="$cacheDir/node/$nodeVersion" if [[ "$OS" == "win" ]]; then nodeBin="$HOME/node" nodeUrl="https://nodejs.org/dist/v$nodeVersion/node-v$nodeVersion-win-x64.zip" else nodeBin="$nodeDir/bin" nodeUrl="https://nodejs.org/dist/v$nodeVersion/node-v$nodeVersion-linux-x64.tar.gz" fi echo " -- node: version=v${nodeVersion} dir=$nodeDir" echo " -- setting up node.js" if [ -x "$nodeBin/node" ] && [ "$("$nodeBin/node" --version)" == "v$nodeVersion" ]; then echo " -- reusing node.js install" else if [ -d "$nodeDir" ]; then echo " -- clearing previous node.js install" rm -rf "$nodeDir" fi echo " -- downloading node.js from $nodeUrl" mkdir -p "$nodeDir" if [[ "$OS" == "win" ]]; then nodePkg="$nodeDir/${nodeUrl##*/}" curl --silent -o "$nodePkg" "$nodeUrl" unzip -qo "$nodePkg" -d "$nodeDir" mv "${nodePkg%.*}" "$nodeBin" else curl --silent "$nodeUrl" | tar -xz -C "$nodeDir" --strip-components=1 fi fi ### ### "install" node into this shell ### export PATH="$nodeBin:$PATH" ### ### downloading yarn ### yarnVersion="$(node -e "console.log(String(require('./package.json').engines.yarn || '').replace(/^[^\d]+/,''))")" npm install -g "yarn@^${yarnVersion}" ### ### setup yarn offline cache ### yarn config set yarn-offline-mirror "$cacheDir/yarn-offline-cache" ### ### "install" yarn into this shell ### yarnGlobalDir="$(yarn global bin)" export PATH="$PATH:$yarnGlobalDir" ### ### install dependencies ### echo " -- installing node.js dependencies" yarn kbn bootstrap --prefer-offline ### ### verify no git modifications ### GIT_CHANGES="$(git ls-files --modified)" if [ "$GIT_CHANGES" ]; then echo -e "\n${RED}ERROR: 'yarn kbn bootstrap' caused changes to the following files:${C_RESET}\n" echo -e "$GIT_CHANGES\n" exit 1 fi ### ### rebuild kbn-pm distributable to ensure it's not out of date ### echo " -- building kbn-pm distributable" yarn kbn run build -i @kbn/pm ### ### verify no git modifications ### GIT_CHANGES="$(git ls-files --modified)" if [ "$GIT_CHANGES" ]; then echo -e "\n${RED}ERROR: 'yarn kbn run build -i @kbn/pm' caused changes to the following files:${C_RESET}\n" echo -e "$GIT_CHANGES\n" exit 1 fi
#!/bin/sh cd $(dirname $0)/../web SDK="../../ext-6.0.1" sencha compile --classpath=app.js,app,$SDK/packages/core/src,$SDK/packages/core/overrides,$SDK/classic/classic/src,$SDK/classic/classic/overrides \ exclude -all \ and \ include -recursive -file app.js \ and \ exclude -namespace=Ext \ and \ concatenate -closure app.min.js
<reponame>matheusca/jamef<gh_stars>1-10 require 'spec_helper' items = [ Jamef::Item.new(10, 9, 8, 7, 6, 10.0), Jamef::Item.new(8, 7, 6, 5, 4, 10.0), ] describe Jamef::Cubage do before(:each) do @cubage = Jamef::Cubage.new(items) end it "should return the cubage" do @cubage.total.should == 6720 end it "should human readable" do @cubage.to_s.should == '6720,00' end it "should total price" do @cubage.price.total.should == 20.0 end it "should total weight" do @cubage.weight.total.should == 10.0 end end
PK
import os def process_config(cfg: dict, settings: dict): log_path = settings.get('log_path') if log_path and not os.path.isdir(log_path): os.mkdir(log_path) handlers = cfg.get('handlers', {}) for handler in handlers.values(): filename = handler.get('filename') if filename and log_path: log_file_path = os.path.join(log_path, filename) # Create an empty log file if it does not exist if not os.path.exists(log_file_path): with open(log_file_path, 'w'): pass
int[] arr = {2, 4, 5, 6, 7, 8}; int evenCount = 0; int oddCount = 0; for(int i = 0; i < arr.length; i++) { if(arr[i] % 2 == 0) { evenCount++; } else { oddCount++; } } Console.WriteLine("Number of even numbers: " + evenCount); Console.WriteLine("Number of odd numbers: " + oddCount);
// Setup view pager ViewPager viewPager = findViewById(R.id.view_pager); viewPager.setAdapter(new PageAdapter(getSupportFragmentManager())); // Setup tab layout TabLayout tabLayout = findViewById(R.id.tab_layout); tabLayout.setupWithViewPager(viewPager); // Create fragments Fragment fragment1 = new Fragment1(); Fragment fragment2 = new Fragment2(); Fragment fragment3 = new Fragment3(); // Create page adapter class PageAdapter extends FragmentPagerAdapter { @Override public int getCount() { return 3; } @Override public Fragment getItem(int position) { switch (position) { case 0: return fragment1; case 1: return fragment2; case 2: return fragment3; default: return null; } } }
'use strict'; const secret = require('./secret'); const keepAlive = require('./keepAlive'); const auth = require('./auth'); module.exports = { secret, keepAlive, auth };
set echo off set feedback off set linesize 512 prompt prompt All Operators in Database prompt SELECT OWNER, OPERATOR_NAME, NUMBER_OF_BINDS FROM DBA_OPERATORS ORDER BY OWNER, OPERATOR_NAME;
#!/bin/bash # Copyright 2017 Google Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); . $(dirname $0)/../common.sh set -x rm -rf $CORPUS fuzz-*.log mkdir $CORPUS test_source_location() { SRC_LOC="$1" echo "test_source_location: $SRC_LOC" [ -e $EXECUTABLE_NAME_BASE ] && \ ./$EXECUTABLE_NAME_BASE -artifact_prefix=$CORPUS/ -exit_on_src_pos=$SRC_LOC -jobs=$JOBS -workers=$JOBS $CORPUS seeds grep "INFO: found line matching '$SRC_LOC'" fuzz-*.log || (date && exit 1) } # test_source_location ttinterp.c:2186 test_source_location ttgload.c:1710:7
import numpy as np print("--------------------------------------") print("eindimensionale Arrays indizieren") print("--------------------------------------") F = np.array([1, 1, 2, 3, 5, 8, 13, 21]) # Ausgabe erstes Element print(F[0]) # Ausgabe letzes Element print(F[-1]) S = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) print(S[2:5]) print(S[:4]) print(S[6:]) print(S[:]) print("--------------------------------------") print("Mehrdimensionale Arrays indizieren") print("--------------------------------------") # Spalte # 0 1 2 A = np.array([[3.4, 5.7, -3.2], # 0 [1.1, -3.8, 7.7], # 1 Zeile [2.2, 5.9, -1.0]]) # 2 # [Zeile][Spalte] print(A[1][2]) # komplette Zeile print(A[1]) # Position : [0, 1][0, 1] # Spalte # 0 1 B = np.array([ [[111, 112], [121, 122]], # 0 [[211, 212], [221, 222]], # 1 Zeile [[311, 312], [321, 322]] ]) # 2 # [Zeile][Spalte][Position] print(B[1][1][1]) print("--------------------------------------") print("Mehrdimensionale Arrays indizieren") print(" Teilbereichoperator") print("--------------------------------------") A = np.array([ [11, 12, 13, 14, 15], [21, 22, 23, 24, 25], [31, 32, 33, 34, 35], [41, 42, 43, 44, 45], [51, 52, 53, 54, 55] ]) # [start:stop:step] # Spalte , Zeile von(inklusive) : bis(exklusive) print(A[:3, 2:]) print("------------------") print(A[3:,:]) print("------------------") print(A[:, 4:]) print("------------------") X = np.arange(28).reshape(4, 7) print(X) print("------------------") print(X[::2, ::3]) print("------------------") print(X[::, ::3]) print("------------------") # dreidimensionales Array A = np.array([ [ [45, 12, 4], [45, 13, 5], [46, 12, 6] ], [ [46, 14, 4], [45, 14, 5], [46, 11, 5] ], [ [47, 13, 2], [48, 15, 5], [46, 15, 1] ], ]) print(A[1:3, 0:2, :])
export BROWSERSTACK_KEY="your_browserstack_access_key" export BITBUCKET_COMMIT="your_bitbucket_commit_identifier" cd AtlasKit/build/bin ./browserstack.tunnel.start.sh
#!/bin/bash NODE_PATH=$(which node) USER1='0x5399850AB7BFE194FA1594F8051329CcC8aCfd56' # owner of token, savebox contract USER2='0x02c3d28f9d2618f03f8a499774ac28332471ae6a' USER3='0x5ba199b049453802cd3ddaaf45781c8ab31df5e2' SAVEBOX='0x590061696601268f4784822F546A8CdB5388b7a8'
<reponame>vovajr11/swf-client import React from 'react'; import ReactModal from 'react-modal'; import { ReactComponent as CloseIcon } from '../../assets/svg/close-icon.svg'; const customStyles = { content: { top: '50%', left: '50%', right: 'auto', bottom: 'auto', marginRight: '-50%', transform: 'translate(-50%, -50%)', padding: '20px 50px', }, }; interface IModal { isShowing: boolean; hide?: React.MouseEventHandler<HTMLButtonElement>; children: React.ReactNode; } const Modal = ({ isShowing, hide, children }: IModal) => { return ( <div> <ReactModal isOpen={isShowing} onRequestClose={hide} ariaHideApp={false} style={customStyles} contentLabel="Example Modal" > <button onClick={hide} style={{ position: 'relative', left: '95%' }}> <CloseIcon /> </button> {children} </ReactModal> </div> ); }; export default Modal;
<reponame>edge-fortress/OSS-13<filename>OSS13 Client/Sources/Network/SyncCommandsProcessor.cpp #include "SyncCommandsProcessor.h" #include <Client.hpp> #include <Graphics/Window.hpp> #include <Graphics/UI/UI.hpp> #include <Graphics/UI/UIModule/GameProcessUI.hpp> #include <Graphics/TileGrid/TileGrid.hpp> #include <Graphics/TileGrid/Object.hpp> using namespace network; using namespace network::protocol; void SyncCommandsProcessor::ProcessCommand(network::protocol::Command &generalCommand) { using namespace network::protocol::server; _REGISTRATE_COMMAND_PROCESSOR(AuthorizationSuccessCommand); _REGISTRATE_COMMAND_PROCESSOR(AuthorizationFailedCommand); _REGISTRATE_COMMAND_PROCESSOR(RegistrationSuccessCommand); _REGISTRATE_COMMAND_PROCESSOR(RegistrationFailedCommand); _REGISTRATE_COMMAND_PROCESSOR(GraphicsUpdateCommand); _REGISTRATE_COMMAND_PROCESSOR(ControlUIUpdateCommand); _REGISTRATE_COMMAND_PROCESSOR(OverlayUpdateCommand); _REGISTRATE_COMMAND_PROCESSOR(OverlayResetCommand); _REGISTRATE_COMMAND_PROCESSOR(OpenWindowCommand); _REGISTRATE_COMMAND_PROCESSOR(OpenSpawnWindowCommand); _REGISTRATE_COMMAND_PROCESSOR(UpdateSpawnWindowCommand); _REGISTRATE_COMMAND_PROCESSOR(UpdateContextMenuCommand); _REGISTRATE_COMMAND_PROCESSOR(UpdateWindowCommand); _REGISTRATE_COMMAND_PROCESSOR(AddChatMessageCommand); LOGE << __FUNCTION__ << ": unknown command (ser id is 0x" << std::hex << generalCommand.SerID() << ") was not processed!"; } void SyncCommandsProcessor::commandProcessor_AuthorizationSuccessCommand(network::protocol::server::AuthorizationSuccessCommand &) { AuthUI *authUI = dynamic_cast<AuthUI *>(CC::Get()->GetWindow()->GetUI()->GetCurrentUIModule()); EXPECT(authUI); authUI->SetServerAnswer(true); } void SyncCommandsProcessor::commandProcessor_AuthorizationFailedCommand(network::protocol::server::AuthorizationFailedCommand &) { AuthUI *authUI = dynamic_cast<AuthUI *>(CC::Get()->GetWindow()->GetUI()->GetCurrentUIModule()); EXPECT(authUI); authUI->SetServerAnswer(false); } void SyncCommandsProcessor::commandProcessor_RegistrationSuccessCommand(network::protocol::server::RegistrationSuccessCommand &) { AuthUI *authUI = dynamic_cast<AuthUI *>(CC::Get()->GetWindow()->GetUI()->GetCurrentUIModule()); EXPECT(authUI); authUI->SetServerAnswer(true); } void SyncCommandsProcessor::commandProcessor_RegistrationFailedCommand(network::protocol::server::RegistrationFailedCommand &) { AuthUI *authUI = dynamic_cast<AuthUI *>(CC::Get()->GetWindow()->GetUI()->GetCurrentUIModule()); EXPECT(authUI); authUI->SetServerAnswer(false); } void SyncCommandsProcessor::commandProcessor_GraphicsUpdateCommand(network::protocol::server::GraphicsUpdateCommand &command) { GameProcessUI *gameProcessUI = dynamic_cast<GameProcessUI *>(CC::Get()->GetWindow()->GetUI()->GetCurrentUIModule()); EXPECT(gameProcessUI); TileGrid *tileGrid = gameProcessUI->GetTileGrid(); EXPECT(tileGrid); if (command.options & server::GraphicsUpdateCommand::Option::TILES_SHIFT) { tileGrid->ShiftBlocks(command.firstTile); for (auto &tileInfo : command.tilesInfo) { tileGrid->SetBlock(tileInfo.coords, std::make_shared<Tile>(tileGrid, std::move(tileInfo))); } } if (command.options & server::GraphicsUpdateCommand::Option::CAMERA_MOVE) { tileGrid->SetCameraPosition(command.camera); } if (command.options & server::GraphicsUpdateCommand::Option::DIFFERENCES) { for (auto &generalDiff : command.diffs) { if (auto *diff = dynamic_cast<network::protocol::AddDiff *>(generalDiff.get())) { auto obj = std::make_unique<Object>(std::move(diff->objectInfo)); tileGrid->AddObject(obj.release()); tileGrid->RelocateObject(diff->objId, diff->coords, diff->layer); } else if (auto *diff = dynamic_cast<network::protocol::RemoveDiff *>(generalDiff.get())) { tileGrid->RemoveObject(diff->objId); } else if (auto *diff = dynamic_cast<network::protocol::FieldsDiff *>(generalDiff.get())) { tileGrid->AmendObjectChanges(std::forward<network::protocol::FieldsDiff>(*diff)); } else if (auto *diff = dynamic_cast<network::protocol::RelocateDiff *>(generalDiff.get())) { tileGrid->RelocateObject(diff->objId, diff->newCoords, diff->layer); } else if (auto *diff = dynamic_cast<network::protocol::MoveIntentDiff *>(generalDiff.get())) { tileGrid->SetMoveIntentObject(diff->objId, diff->direction); } else if (auto *diff = dynamic_cast<network::protocol::MoveDiff *>(generalDiff.get())) { tileGrid->MoveObject(diff->objId, diff->direction, diff->speed); } else if (auto *diff = dynamic_cast<network::protocol::UpdateIconsDiff *>(generalDiff.get())) { tileGrid->UpdateObjectIcons(diff->objId, diff->iconsIds); } else if (auto *diff = dynamic_cast<network::protocol::PlayAnimationDiff *>(generalDiff.get())) { tileGrid->PlayAnimation(diff->objId, diff->animationId); } else if (auto *diff = dynamic_cast<network::protocol::StunnedDiff *>(generalDiff.get())) { tileGrid->Stunned(diff->objId, sf::microseconds(diff->duration.count())); }; } } if (command.options & server::GraphicsUpdateCommand::Option::NEW_CONTROLLABLE) { tileGrid->SetControllable(command.controllableId, command.controllableSpeed); } if (command.options & server::GraphicsUpdateCommand::Option::NEW_FOV) { tileGrid->SetFOV(command.fov, command.fovZ); } } void SyncCommandsProcessor::commandProcessor_ControlUIUpdateCommand(network::protocol::server::ControlUIUpdateCommand &command) { GameProcessUI *gameProcessUI = dynamic_cast<GameProcessUI *>(CC::Get()->GetWindow()->GetUI()->GetCurrentUIModule()); EXPECT(gameProcessUI); TileGrid *tileGrid = gameProcessUI->GetTileGrid(); EXPECT(tileGrid); tileGrid->UpdateControlUI(command.elements, command.clear); } void SyncCommandsProcessor::commandProcessor_OverlayUpdateCommand(network::protocol::server::OverlayUpdateCommand &command) { GameProcessUI *gameProcessUI = dynamic_cast<GameProcessUI *>(CC::Get()->GetWindow()->GetUI()->GetCurrentUIModule()); EXPECT(gameProcessUI); TileGrid *tileGrid = gameProcessUI->GetTileGrid(); EXPECT(tileGrid); tileGrid->UpdateOverlay(command.overlayInfo); } void SyncCommandsProcessor::commandProcessor_OverlayResetCommand(network::protocol::server::OverlayResetCommand &) { GameProcessUI *gameProcessUI = dynamic_cast<GameProcessUI *>(CC::Get()->GetWindow()->GetUI()->GetCurrentUIModule()); EXPECT(gameProcessUI); TileGrid *tileGrid = gameProcessUI->GetTileGrid(); EXPECT(tileGrid); tileGrid->ResetOverlay(); } void SyncCommandsProcessor::commandProcessor_OpenWindowCommand(network::protocol::server::OpenWindowCommand &command) { UIModule *uiModule = CC::Get()->GetWindow()->GetUI()->GetCurrentUIModule(); EXPECT(uiModule); uiModule->OpenWindow(command.id.c_str(), command.data); } void SyncCommandsProcessor::commandProcessor_OpenSpawnWindowCommand(network::protocol::server::OpenSpawnWindowCommand &) { GameProcessUI *gameProcessUI = dynamic_cast<GameProcessUI *>(CC::Get()->GetWindow()->GetUI()->GetCurrentUIModule()); EXPECT(gameProcessUI); gameProcessUI->OpenSpawnWindow(); } void SyncCommandsProcessor::commandProcessor_UpdateSpawnWindowCommand(network::protocol::server::UpdateSpawnWindowCommand &command) { GameProcessUI *gameProcessUI = dynamic_cast<GameProcessUI *>(CC::Get()->GetWindow()->GetUI()->GetCurrentUIModule()); EXPECT(gameProcessUI); gameProcessUI->UpdateSpawnWindow(std::forward<std::vector<network::protocol::ObjectType>>(command.types)); } void SyncCommandsProcessor::commandProcessor_UpdateContextMenuCommand(network::protocol::server::UpdateContextMenuCommand &command) { GameProcessUI *gameProcessUI = dynamic_cast<GameProcessUI *>(CC::Get()->GetWindow()->GetUI()->GetCurrentUIModule()); EXPECT(gameProcessUI); gameProcessUI->UpdateContextMenu(std::forward<network::protocol::ContextMenuData>(command.data)); } void SyncCommandsProcessor::commandProcessor_UpdateWindowCommand(network::protocol::server::UpdateWindowCommand &command) { UIModule *uiModule = CC::Get()->GetWindow()->GetUI()->GetCurrentUIModule(); EXPECT(uiModule); uiModule->UpdateWindow(command.data->window, *command.data); } void SyncCommandsProcessor::commandProcessor_AddChatMessageCommand(network::protocol::server::AddChatMessageCommand &command) { GameProcessUI *gameProcessUI = dynamic_cast<GameProcessUI *>(CC::Get()->GetWindow()->GetUI()->GetCurrentUIModule()); EXPECT(gameProcessUI); gameProcessUI->Receive(command.message); }
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2014 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jooby; import com.google.common.base.Preconditions; import com.google.inject.Key; import com.google.inject.TypeLiteral; import static java.util.Objects.requireNonNull; import org.jooby.internal.RouteMatcher; import org.jooby.internal.RoutePattern; import org.jooby.internal.WebSocketImpl; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.Closeable; import java.util.Map; import java.util.Optional; import java.util.Set; /** * <h1>WebSockets</h1> * <p> * Creating web sockets is pretty straightforward: * </p> * * <pre> * { * ws("/", (ws) {@literal ->} { * // connected * ws.onMessage(message {@literal ->} { * System.out.println(message.value()); * ws.send("Message Received"); * }); * ws.send("Connected"); * }); * } * </pre> * * First thing you need to do is to register a new web socket in your App using the * {@link Jooby#ws(String, WebSocket.OnOpen1)} method. * You can specify a path to listen for web socket connection. The path can be a static path or * a path pattern (like routes). * * On new connections the {@link WebSocket.OnOpen1#onOpen(WebSocket)} will be executed from there * you can listen using the {@link #onMessage(OnMessage)}, {@link #onClose(OnClose)} or * {@link #onError(OnError)} events. * * Inside a handler you can send text or binary message. * * <h2>mvc</h2> * <p> * Starting from <code>1.1.0</code> is it possible to use a class as web socket listener (in * addition to the script web sockets supported). Your class must implement * {@link WebSocket#onMessage(OnMessage)}, like: * </p> * * <pre>{@code * &#64;Path("/ws") * class MyHandler implements WebSocket.OnMessage<String> { * * private WebSocket ws; * * &#64;Inject * public MyHandler(WebSocket ws) { * this.ws = ws; * } * * &#64;Override * public void onMessage(String message) { * ws.send("Got it!"); * } * } * * { * ws(MyHandler.class); * } * * }</pre> * * <p> * <strong>Optionally</strong>, your listener might implements the * {@link WebSocket.OnClose}, * {@link WebSocket.OnError} or {@link WebSocket.OnOpen} callbacks. Or if you want to * implement all them, then just {@link WebSocket.Handler} * </p> * * <h2>data types</h2> * <p> * If your web socket is suppose to send/received a specific data type, like: * <code>json</code> it is nice to define a consume and produce types: * </p> * * <pre> * ws("/", (ws) {@literal ->} { * ws.onMessage(message {@literal ->} { * // read as json * MyObject object = message.to(MyObject.class); * }); * * MyObject object = new MyObject(); * ws.send(object); // convert to text message using a json converter * }) * .consumes(MediaType.json) * .produces(MediaType.json); * </pre> * * <p> * Or via annotations for mvc listeners: * </p> * * <pre>{@code * * &#64;Consumes("json") * &#64;Produces("json") * &#64;Path("/ws") * class MyHandler implements WebSocket.OnMessage<MyObject> { * * public void onMessage(MyObject message) { * // ... * ws.send(new ResponseObject()); * } * * } * }</pre> * * <p> * The message <code>MyObject</code> will be processed by a <code>json</code> parser and the * response object will be renderered as json too. * </p> * * @author edgar * @since 0.1.0 */ public interface WebSocket extends Closeable, Registry { /** Websocket key. */ Key<Set<WebSocket.Definition>> KEY = Key.get(new TypeLiteral<Set<WebSocket.Definition>>() { }); /** * A web socket connect handler. Executed every time a new client connect to the socket. * * @author edgar * @since 0.1.0 */ interface OnOpen { /** * Inside a connect event, you can listen for {@link WebSocket#onMessage(OnMessage)}, * {@link WebSocket#onClose(OnClose)} or {@link WebSocket#onError(OnError)} events. * * Also, you can send text and binary message. * * @param req Current request. * @param ws A web socket. * @throws Exception If something goes wrong while connecting. */ void onOpen(Request req, WebSocket ws) throws Exception; } /** * A web socket connect handler. Executed every time a new client connect to the socket. * * @author edgar * @since 0.1.0 */ interface OnOpen1 extends OnOpen { @Override default void onOpen(final Request req, final WebSocket ws) throws Exception { onOpen(ws); } /** * Inside a connect event, you can listen for {@link WebSocket#onMessage(OnMessage)}, * {@link WebSocket#onClose(OnClose)} or {@link WebSocket#onError(OnError)} events. * * Also, you can send text and binary message. * * @param ws A web socket. * @throws Exception If something goes wrong while connecting. */ void onOpen(WebSocket ws) throws Exception; } /** * Hold a status code and optionally a reason message for {@link WebSocket#close()} operations. * * @author edgar * @since 0.1.0 */ class CloseStatus { /** A status code. */ private final int code; /** A close reason. */ private final String reason; /** * Create a new {@link CloseStatus} instance. * * @param code the status code */ private CloseStatus(final int code) { this(code, null); } /** * Create a new {@link CloseStatus} instance. * * @param code the status code * @param reason the reason */ private CloseStatus(final int code, final String reason) { Preconditions.checkArgument((code >= 1000 && code < 5000), "Invalid code: %s", code); this.code = code; this.reason = reason == null || reason.isEmpty() ? null : reason; } /** * Creates a new {@link CloseStatus}. * * @param code A status code. * @return A new close status. */ public static CloseStatus of(final int code) { return new CloseStatus(code); } /** * Creates a new {@link CloseStatus}. * * @param code A status code. * @param reason A close reason. * @return A new close status. */ public static CloseStatus of(final int code, final String reason) { requireNonNull(reason, "A reason is required."); return new CloseStatus(code, reason); } /** * @return the status code. */ public int code() { return this.code; } /** * @return the reason or {@code null}. */ public String reason() { return this.reason; } @Override public String toString() { if (reason == null) { return code + ""; } return code + " (" + reason + ")"; } } /** * Web socket message callback. * * @author edgar * @since 0.1.0 * @param <T> Param type. */ interface OnMessage<T> { /** * Invoked from a web socket. * * @param message Client message. * @throws Exception If something goes wrong. */ void onMessage(T message) throws Exception; } interface OnClose { void onClose(CloseStatus status) throws Exception; } /** * Web socket success callback. * * @author edgar * @since 0.1.0 */ interface SuccessCallback { /** * Invoked from a web socket. * * @throws Exception If something goes wrong. */ void invoke() throws Exception; } /** * Web socket err callback. * * @author edgar * @since 0.1.0 */ interface OnError { /** * Invoked if something goes wrong. * * @param err Err cause. */ void onError(Throwable err); } /** * Configure a web socket. * * @author edgar * @since 0.1.0 */ class Definition { /** * A route compiled pattern. */ private RoutePattern routePattern; /** * Defines the media types that the methods of a resource class or can consumes. Default is: * {@literal *}/{@literal *}. */ private MediaType consumes = MediaType.plain; /** * Defines the media types that the methods of a resource class or can produces. Default is: * {@literal *}/{@literal *}. */ private MediaType produces = MediaType.plain; /** A path pattern. */ private String pattern; /** A ws handler. */ private OnOpen handler; /** * Creates a new {@link Definition}. * * @param pattern A path pattern. * @param handler A ws handler. */ public Definition(final String pattern, final OnOpen handler) { requireNonNull(pattern, "A route path is required."); requireNonNull(handler, "A handler is required."); this.routePattern = new RoutePattern("WS", pattern); // normalized pattern this.pattern = routePattern.pattern(); this.handler = handler; } /** * @return A route pattern. */ public String pattern() { return pattern; } /** * Test if the given path matches this web socket. * * @param path A path pattern. * @return A web socket or empty optional. */ public Optional<WebSocket> matches(final String path) { RouteMatcher matcher = routePattern.matcher("WS" + path); if (matcher.matches()) { return Optional.of(asWebSocket(matcher)); } return Optional.empty(); } /** * Set the media types the route can consume. * * @param type The media types to test for. * @return This route definition. */ public Definition consumes(final String type) { return consumes(MediaType.valueOf(type)); } /** * Set the media types the route can consume. * * @param type The media types to test for. * @return This route definition. */ public Definition consumes(final MediaType type) { this.consumes = requireNonNull(type, "A type is required."); return this; } /** * Set the media types the route can produces. * * @param type The media types to test for. * @return This route definition. */ public Definition produces(final String type) { return produces(MediaType.valueOf(type)); } /** * Set the media types the route can produces. * * @param type The media types to test for. * @return This route definition. */ public Definition produces(final MediaType type) { this.produces = requireNonNull(type, "A type is required."); return this; } /** * @return All the types this route can consumes. */ public MediaType consumes() { return this.consumes; } /** * @return All the types this route can produces. */ public MediaType produces() { return this.produces; } @Override public boolean equals(final Object obj) { if (obj instanceof Definition) { Definition def = (Definition) obj; return this.pattern.equals(def.pattern); } return false; } @Override public int hashCode() { return pattern.hashCode(); } @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append("WS ").append(pattern()).append("\n"); buffer.append(" consume: ").append(consumes()).append("\n"); buffer.append(" produces: ").append(produces()).append("\n"); return buffer.toString(); } /** * Creates a new web socket. * * @param matcher A route matcher. * @return A new web socket. */ private WebSocket asWebSocket(final RouteMatcher matcher) { return new WebSocketImpl(handler, matcher.path(), pattern, matcher.vars(), consumes, produces); } } interface Handler<T> extends OnClose, OnMessage<T>, OnError, OnOpen { } /** Default success callback. */ SuccessCallback SUCCESS = () -> { }; /** Default err callback. */ OnError ERR = (ex) -> { LoggerFactory.getLogger(WebSocket.class).error("error while sending data", ex); }; /** * "1000 indicates a normal closure, meaning that the purpose for which the connection * was established has been fulfilled." */ CloseStatus NORMAL = new CloseStatus(1000, "Normal"); /** * "1001 indicates that an endpoint is "going away", such as a server going down or a * browser having navigated away from a page." */ CloseStatus GOING_AWAY = new CloseStatus(1001, "Going away"); /** * "1002 indicates that an endpoint is terminating the connection due to a protocol * error." */ CloseStatus PROTOCOL_ERROR = new CloseStatus(1002, "Protocol error"); /** * "1003 indicates that an endpoint is terminating the connection because it has * received a type of data it cannot accept (e.g., an endpoint that understands only * text data MAY send this if it receives a binary message)." */ CloseStatus NOT_ACCEPTABLE = new CloseStatus(1003, "Not acceptable"); /** * "1007 indicates that an endpoint is terminating the connection because it has * received data within a message that was not consistent with the type of the message * (e.g., non-UTF-8 [RFC3629] data within a text message)." */ CloseStatus BAD_DATA = new CloseStatus(1007, "Bad data"); /** * "1008 indicates that an endpoint is terminating the connection because it has * received a message that violates its policy. This is a generic status code that can * be returned when there is no other more suitable status code (e.g., 1003 or 1009) * or if there is a need to hide specific details about the policy." */ CloseStatus POLICY_VIOLATION = new CloseStatus(1008, "Policy violation"); /** * "1009 indicates that an endpoint is terminating the connection because it has * received a message that is too big for it to process." */ CloseStatus TOO_BIG_TO_PROCESS = new CloseStatus(1009, "Too big to process"); /** * "1010 indicates that an endpoint (client) is terminating the connection because it * has expected the server to negotiate one or more extension, but the server didn't * return them in the response message of the WebSocket handshake. The list of * extensions that are needed SHOULD appear in the /reason/ part of the Close frame. * Note that this status code is not used by the server, because it can fail the * WebSocket handshake instead." */ CloseStatus REQUIRED_EXTENSION = new CloseStatus(1010, "Required extension"); /** * "1011 indicates that a server is terminating the connection because it encountered * an unexpected condition that prevented it from fulfilling the request." */ CloseStatus SERVER_ERROR = new CloseStatus(1011, "Server error"); /** * "1012 indicates that the service is restarted. A client may reconnect, and if it * chooses to do, should reconnect using a randomized delay of 5 - 30s." */ CloseStatus SERVICE_RESTARTED = new CloseStatus(1012, "Service restarted"); /** * "1013 indicates that the service is experiencing overload. A client should only * connect to a different IP (when there are multiple for the target) or reconnect to * the same IP upon user action." */ CloseStatus SERVICE_OVERLOAD = new CloseStatus(1013, "Service overload"); /** * @return Current request path. */ @Nonnull String path(); /** * @return The currently matched pattern. */ @Nonnull String pattern(); /** * @return The currently matched path variables (if any). */ @Nonnull Map<Object, String> vars(); /** * @return The type this route can consumes, defaults is: {@code * / *}. */ @Nonnull MediaType consumes(); /** * @return The type this route can produces, defaults is: {@code * / *}. */ @Nonnull MediaType produces(); /** * Register a callback to execute when a new message arrive. * * @param callback A callback * @throws Exception If something goes wrong. */ void onMessage(OnMessage<Mutant> callback) throws Exception; /** * Register an error callback to execute when an error is found. * * @param callback A callback */ void onError(OnError callback); /** * Register an close callback to execute when client close the web socket. * * @param callback A callback * @throws Exception If something goes wrong. */ void onClose(OnClose callback) throws Exception; /** * Gracefully closes the connection, after sending a description message * * @param code Close status code. * @param reason Close reason. */ default void close(final int code, final String reason) { close(CloseStatus.of(code, reason)); } /** * Gracefully closes the connection, after sending a description message * * @param code Close status code. */ default void close(final int code) { close(CloseStatus.of(code)); } /** * Gracefully closes the connection, after sending a description message */ @Override default void close() { close(NORMAL); } /** * True if the websocket is still open. * * @return True if the websocket is still open. */ boolean isOpen(); /** * Gracefully closes the connection, after sending a description message * * @param status Close status code. */ void close(CloseStatus status); /** * Resume the client stream. */ void resume(); /** * Pause the client stream. */ void pause(); /** * Immediately shuts down the connection. * * @throws Exception If something goes wrong. */ void terminate() throws Exception; /** * Send data through the connection. * * If the web socket is closed this method throw an {@link Err} with {@link #NORMAL} close status. * * @param data Data to send. * @throws Exception If something goes wrong. */ default void send(final Object data) throws Exception { send(data, SUCCESS, ERR); } /** * Send data through the connection. * * If the web socket is closed this method throw an {@link Err} with {@link #NORMAL} close status. * * @param data Data to send. * @param success A success callback. * @throws Exception If something goes wrong. */ default void send(final Object data, final SuccessCallback success) throws Exception { send(data, success, ERR); } /** * Send data through the connection. * * If the web socket is closed this method throw an {@link Err} with {@link #NORMAL} close status. * * @param data Data to send. * @param err An err callback. * @throws Exception If something goes wrong. */ default void send(final Object data, final OnError err) throws Exception { send(data, SUCCESS, err); } /** * Send data through the connection. * * If the web socket is closed this method throw an {@link Err} with {@link #NORMAL} close status. * * @param data Data to send. * @param success A success callback. * @param err An err callback. * @throws Exception If something goes wrong. */ void send(Object data, SuccessCallback success, OnError err) throws Exception; /** * Send data to all connected sessions. * * If the web socket is closed this method throw an {@link Err} with {@link #NORMAL} close status. * * @param data Data to send. * @throws Exception If something goes wrong. */ default void broadcast(final Object data) throws Exception { broadcast(data, SUCCESS, ERR); } /** * Send data to all connected sessions. * * If the web socket is closed this method throw an {@link Err} with {@link #NORMAL} close status. * * @param data Data to send. * @param success A success callback. * @throws Exception If something goes wrong. */ default void broadcast(final Object data, final SuccessCallback success) throws Exception { broadcast(data, success, ERR); } /** * Send data to all connected sessions. * * If the web socket is closed this method throw an {@link Err} with {@link #NORMAL} close status. * * @param data Data to send. * @param err An err callback. * @throws Exception If something goes wrong. */ default void broadcast(final Object data, final OnError err) throws Exception { broadcast(data, SUCCESS, err); } /** * Send data to all connected sessions. * * If the web socket is closed this method throw an {@link Err} with {@link #NORMAL} close status. * * @param data Data to send. * @param success A success callback. * @param err An err callback. * @throws Exception If something goes wrong. */ void broadcast(Object data, SuccessCallback success, OnError err) throws Exception; /** * Set a web socket attribute. * * @param name Attribute name. * @param value Attribute value. * @return This socket. */ @Nullable WebSocket set(String name, Object value); /** * Get a web socket attribute. * * @param name Attribute name. * @return Attribute value. */ <T> T get(String name); /** * Get a web socket attribute or empty value. * * @param name Attribute name. * @param <T> Attribute type. * @return Attribute value or empty value. */ <T> Optional<T> ifGet(String name); /** * Clear/remove a web socket attribute. * * @param name Attribute name. * @param <T> Attribute type. * @return Attribute value (if any). */ <T> Optional<T> unset(String name); /** * Clear/reset all the web socket attributes. * * @return This socket. */ WebSocket unset(); /** * Web socket attributes. * * @return Web socket attributes. */ Map<String, Object> attributes(); }
<reponame>Andrey-V-Georgiev/SPRING_DATA package spring_data.ex_spring_data_intro.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import spring_data.ex_spring_data_intro.entities.Author; import java.util.*; @Repository public interface AuthorRepository extends JpaRepository<Author, Long> { List<Author> findAuthorsByFirstNameEndsWith(String endingStr); }
#!/bin/sh EXEC=2D_af if ( [ $# -ne 1 ] ) ; then echo "This script requires the number of processors" exit fi rm -f "$YALES2_HOME"/lib/*.a make clean cd "$YALES2_HOME"/src make -j $1 cd - make mpirun -np $1 ./$EXEC
def solve(board): find = find_empty(board) if not find: return True else: row, col = find for i in range(1,10): if valid(board, i, (row, col)): board[row][col] = i if solve(board): return True board[row][col] = 0 return False def valid(board, num, pos): # Check row for i in range(len(board[0])): if board[pos[0]][i] == num and pos[1] != i: return False # Check column for i in range(len(board)): if board[i][pos[1]] == num and pos[0] != i: return False # Check box box_x = pos[1] // 3 box_y = pos[0] // 3 for i in range(box_y*3, box_y*3 + 3): for j in range(box_x * 3, box_x*3 + 3): if board[i][j] == num and (i,j) != pos: return False return True def find_empty(board): for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == 0: return (i, j) # row, col
#!/bin/bash function findinjar() { for jar in `find . -iname \*.jar | sort -u`; do echo "$jar: "; jar tvf $jar | grep $1; done } function gcstat() { $JAVA_HOME/bin/jstat -gcutil -h 10 $1 5s } function heapSummary() { $JAVA_HOME/bin/jmap -heap $1 } function threadDump() { $JAVA_HOME/bin/jstack $1; heapSummary $1 }
/** * Copyright (c) 2016 Wind River Systems * * 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. */ var schemas = require('../schemas.js') var scs = schemas.types; var bpID = {title: "bpID", type:'string'}; var double = {title: "double", type:'number'}; var list = {title: "list", type:'array'}; var symbol = {title: "symbol", type:'string'}; module.exports = { name: "Diagnostics", cmds: [ {name: "echo", args:[scs.string], results: [scs.string]}, {name: "echoFp", args:[double], results: [double]}, {name: "echoErr", args:[], results: [scs.err]}, {name: "getTestList", args:[], results: [scs.err, list]}, {name: "runTest", args:[scs.string], results: [scs.err, scs.ctxID]}, {name: "cancelTest", args:[scs.string], results: [scs.err]}, {name: "getSymbol", args:[scs.ctxID, scs.string], results: [scs.err, symbol]}, {name: "createTestStreams", args:[scs.integer, scs.integer], results: [scs.err, scs.string, scs.string]}, {name: "disposeTestStream", args:[scs.string], results: [scs.err]} ], evs: [] };
DELETE FROM Employee WHERE id NOT IN (SELECT MAX(id) FROM Employee GROUP BY name)
/* TITLE Draw a diagram Chapter12Exercise10.cpp Bjarne Stroustrup "Programming: Principles and Practice Using C++" COMMENT Objective: Draw the FLTK and helper GUI headers and source files hierarchical diagram, from Chapter 12.8. Input: - Output: Graph on screen. Author: <NAME> Date: 31. 08. 2015 */ #include <iostream> #include "Simple_window.h" /* Simple_window& boxWithText(Simple_window& sw, int topLeftX, int topLeftY, const string& upLine, const string& line1, const string& line2, const string& line3); */ //-------------------------------------------------------------------------------------------------------------------- int main() { try { // create a centered window const int windowWidth = 800; const int windowHeight = 600; Point centerScreen(x_max() / 2.- windowWidth / 2., y_max() / 2. - windowHeight / 2.); Simple_window sw(centerScreen, windowWidth, windowHeight, "Chapter 12 Exercise 10"); // create all text boxes const int frameSize = 1; const int heightSeparator = 200; const int widthSeparator = 150; // Line 1 // center box const int l1b1Width = 200; const int l1b1Height = 75; Graph_lib::Rectangle line1Box1(Point(sw.x_max() / 2. - l1b1Width / 2. - 4 * frameSize, sw.y_max() - frameSize - l1b1Height), l1b1Width, l1b1Height); line1Box1.set_fill_color(Color::yellow); sw.attach(line1Box1); // center box text const int textHeight = 20; Text l1b1Text(Point(sw.x_max() / 2. - l1b1Width / 2. + frameSize, sw.y_max() - 2 * frameSize - l1b1Height), "#include Chapter12.cpp"); sw.attach(l1b1Text); Text l1b1Text1(Point(sw.x_max() / 2. - l1b1Width / 2. + frameSize, sw.y_max() - (2 * frameSize) - l1b1Height + textHeight), "#include \"Graph.h\""); sw.attach(l1b1Text1); Text l1b1Text2(Point(sw.x_max() / 2. - l1b1Width / 2. + frameSize, sw.y_max() - (2 * frameSize) - l1b1Height + 2 * textHeight), "#include \"Simple_window.h\""); sw.attach(l1b1Text2); Text l1b1Text3(Point(sw.x_max() / 2. - l1b1Width / 2. + frameSize, sw.y_max() - (2 * frameSize) - l1b1Height + 3 * textHeight), "#include \int main() { ... }"); sw.attach(l1b1Text3); // Line 2 (from bottom): // left box const int l2b1Width = 100; const int l2b1Height = 20; Graph_lib::Rectangle line2Box1(Point(frameSize, sw.y_max() - heightSeparator), l2b1Width, l2b1Height); line2Box1.set_fill_color(Color::yellow); sw.attach(line2Box1); // left box text Text l2b1Text(Point(frameSize, sw.y_max() - heightSeparator - 2 * frameSize), "#include Graph.cpp"); sw.attach(l2b1Text); Text l2b1Text1(Point(frameSize, sw.y_max() - heightSeparator + textHeight - 2 * frameSize), "Graph code"); sw.attach(l2b1Text1); // center box const int l2b2Width = 200; const int l2b2Height = 60; Graph_lib::Rectangle line2Box2(Point(sw.x_max() / 2. - l2b2Width / 2. - 4 * frameSize, sw.y_max() - heightSeparator), l2b2Width, l2b2Height); line2Box2.set_fill_color(Color::yellow); sw.attach(line2Box2); // center box text Text l2b2Text(Point(sw.x_max() / 2. - l2b2Width / 2. - 4 * frameSize, sw.y_max() - heightSeparator - 2 * frameSize), "Simple_window.h"); sw.attach(l2b2Text); Text l2b2Text1(Point(sw.x_max() / 2. - l2b2Width / 2. - 4 * frameSize, sw.y_max() - heightSeparator + textHeight + frameSize), "// window interface"); sw.attach(l2b2Text1); Text l2b2Text2(Point(sw.x_max() / 2. - l2b2Width / 2. - 4 * frameSize, sw.y_max() - heightSeparator + 2 * textHeight + frameSize), "Class Simple_window { ... };"); sw.attach(l2b2Text2); Text l2b2Text3(Point(sw.x_max() / 2. - l2b2Width / 2. - 4 * frameSize, sw.y_max() - heightSeparator + 3 * textHeight - 2 * frameSize), "..."); sw.attach(l2b2Text3); // right box const int l2b3Width = 100; const int l2b3Height = 20; Graph_lib::Rectangle line2Box3(Point(sw.x_max() - l2b3Width - frameSize, sw.y_max() - heightSeparator), l2b3Width, l2b3Height); line2Box3.set_fill_color(Color::yellow); sw.attach(line2Box3); // right box text Text l2b3Text(Point(sw.x_max() - l2b3Width - frameSize, sw.y_max() - heightSeparator - 2 * frameSize), "GUI.cpp"); sw.attach(l2b3Text); Text l2b3Text1(Point(sw.x_max() - l2b3Width - frameSize, sw.y_max() - heightSeparator + textHeight - 2 * frameSize), "GUI code"); sw.attach(l2b3Text1); // Line 3 // center box const int l3b1Width = 100; const int l3b1Height = 20; Graph_lib::Rectangle line3Box1(Point(sw.x_max() / 2. - l3b1Width - 6 * frameSize, sw.y_max() - 1.5 * heightSeparator), l3b1Width, l3b1Height); line3Box1.set_fill_color(Color::yellow); sw.attach(line3Box1); // center box text Text l3b1Text(Point(sw.x_max() / 2. - l3b1Width - 6 * frameSize, sw.y_max() - 1.5 * heightSeparator - 2 * frameSize), "window.cpp"); sw.attach(l3b1Text); Text l3b1Text1(Point(sw.x_max() / 2. - l3b1Width - 6 * frameSize, sw.y_max() - 1.5 * heightSeparator + textHeight - 2 * frameSize), "Window code"); sw.attach(l3b1Text1); // Line 4 // left box const int l4b1Width = 200; const int l4b1Height = 60; Graph_lib::Rectangle line4Box1(Point(frameSize, sw.y_max() - 2 * heightSeparator), l4b1Width, l4b1Height); line4Box1.set_fill_color(Color::yellow); sw.attach(line4Box1); // left box text Text l4b1Text(Point(frameSize, sw.y_max() - 2 * heightSeparator - 2 * frameSize), "Graph.h"); sw.attach(l4b1Text); Text l4b1Text1(Point(frameSize, sw.y_max() - 2 * heightSeparator + textHeight - frameSize), "// graphical interface"); sw.attach(l4b1Text1); Text l4b1Text2(Point(frameSize, sw.y_max() - 2 * heightSeparator + 2 * textHeight - 2 * frameSize), "Graph code"); sw.attach(l4b1Text2); Text l4b1Text3(Point(frameSize, sw.y_max() - 2 * heightSeparator + 3 * textHeight - 3 * frameSize), "Struct Shape { ... };"); sw.attach(l4b1Text3); // center box const int l4b2Width = 200; const int l4b2Height = 60; Graph_lib::Rectangle line4Box2(Point(sw.x_max() / 2. - l4b2Width / 2. - 4 * frameSize, sw.y_max() - 2 * heightSeparator), l4b2Width, l4b2Height); line4Box2.set_fill_color(Color::yellow); sw.attach(line4Box2); // center box text Text l4b2Text(Point(sw.x_max() / 2. - l4b2Width / 2. - 4 * frameSize, sw.y_max() - 2 * heightSeparator - 2 * frameSize), "Window.h"); sw.attach(l4b2Text); Text l4b2Text1(Point(sw.x_max() / 2. - l4b2Width / 2. - 4 * frameSize, sw.y_max() - 2 * heightSeparator + textHeight - frameSize), "// window interface"); sw.attach(l4b2Text1); Text l4b2Text2(Point(sw.x_max() / 2. - l4b2Width / 2. - 4 * frameSize, sw.y_max() - 2 * heightSeparator + 2 * textHeight - 2 * frameSize), "class Window {...};"); sw.attach(l4b2Text2); Text l4b2Text3(Point(sw.x_max() / 2. - l4b2Width / 2. - 4 * frameSize, sw.y_max() - 2 * heightSeparator + 3 * textHeight - 3 * frameSize), "..."); sw.attach(l4b2Text3); // right box const int l4b3Width = 200; const int l4b3Height = 60; Graph_lib::Rectangle line4Box3(Point(sw.x_max() - l4b3Width - frameSize, sw.y_max() - 2 * heightSeparator), l4b3Width, l4b3Height); line4Box3.set_fill_color(Color::yellow); sw.attach(line4Box3); // center box text Text l4b3Text(Point(sw.x_max() - l4b3Width - frameSize, sw.y_max() - 2 * heightSeparator - 2 * frameSize), "GUI.h"); sw.attach(l4b3Text); Text l4b3Text1(Point(sw.x_max() - l4b3Width - frameSize, sw.y_max() - 2 * heightSeparator + textHeight - frameSize), "// GUI interface"); sw.attach(l4b3Text1); Text l4b3Text2(Point(sw.x_max() - l4b3Width - frameSize, sw.y_max() - 2 * heightSeparator + 2 * textHeight - 2 * frameSize), "struct In_box {...};"); sw.attach(l4b3Text2); Text l4b3Text3(Point(sw.x_max() - l4b3Width - frameSize, sw.y_max() - 2 * heightSeparator + 3 * textHeight - 3 * frameSize), "..."); sw.attach(l4b3Text3); // Line 5 const int l5b1Width = 200; const int l5b1Height = 40; Graph_lib::Rectangle line5Box1(Point(frameSize, sw.y_max() - 2.5 * heightSeparator), l5b1Width, l5b1Height); line5Box1.set_fill_color(Color::yellow); sw.attach(line5Box1); // left box text Text l5b1Text(Point(frameSize, sw.y_max() - 2.5 * heightSeparator - 2 * frameSize), "Point.h"); sw.attach(l5b1Text); Text l5b1Text1(Point(frameSize, sw.y_max() - 2.5 * heightSeparator + textHeight - frameSize), "struct Point {...};"); sw.attach(l5b1Text1); // center box const int l5b2Width = 200; const int l5b2Height = 40; // two background empty polygons Graph_lib::Rectangle b1line5Box2(Point(sw.x_max() / 2. - l5b2Width / 2. - 4 * frameSize - - 6 * frameSize, sw.y_max() - 2.5 * heightSeparator - - 6 * frameSize), l5b2Width, l5b2Height); b1line5Box2.set_fill_color(Color::yellow); sw.attach(b1line5Box2); Graph_lib::Rectangle b2line5Box2(Point(sw.x_max() / 2. - l5b2Width / 2. - 4 * frameSize - - 3 * frameSize, sw.y_max() - 2.5 * heightSeparator - - 3 * frameSize), l5b2Width, l5b2Height); b2line5Box2.set_fill_color(Color::yellow); sw.attach(b2line5Box2); Graph_lib::Rectangle line5Box2(Point(sw.x_max() / 2. - l5b2Width / 2. - 4 * frameSize, sw.y_max() - 2.5 * heightSeparator), l5b2Width, l5b2Height); line5Box2.set_fill_color(Color::yellow); sw.attach(line5Box2); // center box text Text l5b2Text1(Point(sw.x_max() / 2. - l5b2Width / 2. - 4 * frameSize, sw.y_max() - 2.5 * heightSeparator + textHeight - frameSize), "FLTK headers"); sw.attach(l5b2Text1); // right box const int l5b3Width = 200; const int l5b3Height = 40; // two background empty polygons Graph_lib::Rectangle b1line5Box3(Point(sw.x_max() - l5b3Width - 6 * frameSize, sw.y_max() - 2.5 * heightSeparator - 6 * frameSize), l5b3Width, l5b3Height); b1line5Box3.set_fill_color(Color::yellow); sw.attach(b1line5Box3); Graph_lib::Rectangle b2line5Box3(Point(sw.x_max() - l5b3Width - 3 * frameSize, sw.y_max() - 2.5 * heightSeparator - 3 * frameSize), l5b3Width, l5b3Height); b2line5Box3.set_fill_color(Color::yellow); sw.attach(b2line5Box3); Graph_lib::Rectangle line5Box3(Point(sw.x_max() - l5b3Width - frameSize, sw.y_max() - 2.5 * heightSeparator), l5b3Width, l5b3Height); line5Box3.set_fill_color(Color::yellow); sw.attach(line5Box3); // right box text Text l5b3Text1(Point(sw.x_max() - l5b3Width - frameSize, sw.y_max() - 2.5 * heightSeparator + textHeight - frameSize), "FLTK code"); sw.attach(l5b3Text1); // Arrows connecting the boxes // Line 1: box center -> Line 2: box center Graph_lib::Marked_polyline l1bc_l2bc("^"); l1bc_l2bc.add(Point(sw.x_max() / 2. - l1b1Width / 2., sw.y_max() - frameSize - l1b1Height)); l1bc_l2bc.add(Point(sw.x_max() / 2. - 4 * frameSize, sw.y_max() - heightSeparator + l2b2Height + 2 * frameSize)); sw.attach(l1bc_l2bc); // Line 1: box center -> Line 4: box left Graph_lib::Marked_polyline l1bc_l4bl("^"); l1bc_l4bl.add(Point(sw.x_max() / 2. - l1b1Width / 2., sw.y_max() - frameSize - l1b1Height)); l1bc_l4bl.add(Point(frameSize + l4b1Width / 2., sw.y_max() - 2 * heightSeparator + l4b1Height + 2 * frameSize)); sw.attach(l1bc_l4bl); // Line 2: box left -> Line 4: box left Graph_lib::Marked_polyline l2bl_l4bl("^"); l2bl_l4bl.add(Point(frameSize + l2b1Width / 2., sw.y_max() - heightSeparator)); l2bl_l4bl.add(Point(frameSize + l4b1Width / 2., sw.y_max() - 2 * heightSeparator + l4b1Height + 2 * frameSize)); sw.attach(l2bl_l4bl); // Line 2: box center -> Line 4: box center Graph_lib::Marked_polyline l2bc_l4bc("^"); l2bc_l4bc.add(Point(sw.x_max() / 2. - 4 * frameSize, sw.y_max() - heightSeparator)); l2bc_l4bc.add(Point(sw.x_max() / 2. - 4 * frameSize, sw.y_max() - 2 * heightSeparator + l4b2Height)); sw.attach(l2bc_l4bc); // Line 2: box center -> Line 4: box right Graph_lib::Marked_polyline l2bc_l4br("^"); l2bc_l4br.add(Point(sw.x_max() / 2. - 4 * frameSize, sw.y_max() - heightSeparator)); l2bc_l4br.add(Point(sw.x_max() - l4b3Width / 2. - frameSize, sw.y_max() - 2 * heightSeparator + l4b3Height)); sw.attach(l2bc_l4br); // Line 2: box right -> Line 4: box right Graph_lib::Marked_polyline l2br_l4br("^"); l2br_l4br.add(Point(sw.x_max() - l2b3Width / 2. - frameSize, sw.y_max() - heightSeparator)); l2br_l4br.add(Point(sw.x_max() - l4b3Width / 2. - frameSize, sw.y_max() - 2 * heightSeparator + l4b3Height)); sw.attach(l2br_l4br); // Line 3 : box center -> Line 4: box center Graph_lib::Marked_polyline l3bc_l4bc("^"); l3bc_l4bc.add(Point(sw.x_max() / 2. - l3b1Width / 2. - 6 * frameSize, sw.y_max() - 1.5 * heightSeparator)); l3bc_l4bc.add(Point(sw.x_max() / 2. - 4 * frameSize, sw.y_max() - 2 * heightSeparator + l4b2Height)); sw.attach(l3bc_l4bc); // Line 4: box left -> Line 5: box left Graph_lib::Marked_polyline l4bl_l5bl("^"); l4bl_l5bl.add(Point(frameSize + l4b1Width / 2., sw.y_max() - 2 * heightSeparator)); l4bl_l5bl.add(Point(frameSize + l5b1Width / 2., sw.y_max() - 2.5 * heightSeparator + l5b1Height)); sw.attach(l4bl_l5bl); // Line 4: box left -> Line 5: box center Graph_lib::Marked_polyline l4bl_l5bc("^"); l4bl_l5bc.add(Point(frameSize + l4b1Width / 2., sw.y_max() - 2 * heightSeparator)); l4bl_l5bc.add(Point(sw.x_max() / 2. - 4 * frameSize, sw.y_max() - 2.5 * heightSeparator + l5b2Height)); sw.attach(l4bl_l5bc); // Line 4: box center -> Line 5: box center Graph_lib::Marked_polyline l4bc_l5bc("^"); l4bc_l5bc.add(Point(sw.x_max() / 2. - 4 * frameSize, sw.y_max() - 2 * heightSeparator)); l4bc_l5bc.add(Point(sw.x_max() / 2. - 4 * frameSize, sw.y_max() - 2.5 * heightSeparator + l5b2Height)); sw.attach(l4bc_l5bc); // Line 4: box center -> Line 5: box left Graph_lib::Marked_polyline l4bc_l5bl("^"); l4bc_l5bl.add(Point(sw.x_max() / 2. - 4 * frameSize, sw.y_max() - 2 * heightSeparator)); l4bc_l5bl.add(Point(frameSize + l5b1Width / 2., sw.y_max() - 2.5 * heightSeparator + l5b1Height)); sw.attach(l4bc_l5bl); // Line 4: box right -> Line 5: box center Graph_lib::Marked_polyline l4br_l5bc("^"); l4br_l5bc.add(Point(sw.x_max() - l4b3Width / 2. - frameSize, sw.y_max() - 2 * heightSeparator)); l4br_l5bc.add(Point(sw.x_max() / 2. - 4 * frameSize, sw.y_max() - 2.5 * heightSeparator + l5b2Height)); sw.attach(l4br_l5bc); // Line 4: box right -> Line 4: box center Graph_lib::Marked_polyline l4br_l4bc("<"); l4br_l4bc.add(Point(sw.x_max() - l4b3Width / 2. - frameSize, sw.y_max() - 2 * heightSeparator)); l4br_l4bc.add(Point(sw.x_max() - l4b3Width - frameSize, sw.y_max() - 2.1 * heightSeparator)); l4br_l4bc.add(Point(sw.x_max() / 2. - 4 * frameSize, sw.y_max() - 2 * heightSeparator)); sw.attach(l4br_l4bc); // Line 5: box right -> Line 5: box center Graph_lib::Marked_polyline l5br_l5bc("<"); l5br_l5bc.add(Point(sw.x_max() - l5b3Width / 2. - frameSize, sw.y_max() - 2.5 * heightSeparator)); l5br_l5bc.add(Point(sw.x_max() - l5b3Width - frameSize, sw.y_max() - 2.6 * heightSeparator)); l5br_l5bc.add(Point(sw.x_max() / 2. - 4 * frameSize, sw.y_max() - 2.5 * heightSeparator)); sw.attach(l5br_l5bc); sw.wait_for_button(); } catch(std::exception& e) { std::cerr << e.what() << std::endl; } catch(...) { std::cerr <<"Default exception!"<< std::endl; } } //-------------------------------------------------------------------------------------------------------------------- /* Function: max_line_length() This function finds the length of the longest string in a vector and returns it. static size_t max_line_length(std::vector<std::string> &lines) { size_t max = 0; for (auto it = lines.begin(); it != lines.end(); it++) { if (it->length() > max) { max = it->length(); } } return max; } */ //-------------------------------------------------------------------------------------------------------------------- /* Function: boxWithText() Use: void boxWithText(Simple_window& sw, int topLeftX, int topLeftY, const string& upLine, const string& line1, const string& line2 , const string& line3) This function draws a box with text either on top and/or three line in it, depending on the value of the last 4 pararameters. The first parameter passes the simple_window object to which the box and text will be attached. The second and third parameters are the top left coordinates of the box. Simple_window& boxWithText(Simple_window& sw, int topLeftX, int topLeftY, const string& upLine = "0", const string& line1 = "0", const string& line2 = "0", const string& line3 = "0") { const int frameSize = 1; const int textHeight = 20; // create box // boxWidth depends on the lengthiest string int boxWidth = 0; // boxHeight depends on how much of the strings have value != 0 int boxHeight = 0; vector<string> lines(3); lines[0] = line1; lines[1] = line2; lines[2] = line3; // box width determined from the longest string multiplied by a scaling factor const int scalingFactor = 1; boxWidth = max_line_length(lines) * scalingFactor; // box height determined on how many of the strings are != 0 for(size_t i = 0; i < lines.size(); ++i) { if (lines[i] != "0") { boxHeight += textHeight + frameSize; } } // frame between the last line and the bottom line of the box boxHeight += frameSize; cout << "box w: "<< boxWidth <<" boxh: "<< boxHeight; Graph_lib::Rectangle box(Point(topLeftX, topLeftY), boxWidth, boxHeight); box.set_fill_color(Color::yellow); sw.attach(box); // create text // case upLine: topLeftY - textHeight - frameSize if (upLine != "0") { Text l0(Point(topLeftX + frameSize, topLeftY - textHeight - frameSize), upLine); sw.attach(l0); } // case line1: topLeftY + texrHeight + frameSize if (line1 != "0") { Text l1(Point(topLeftX + frameSize, topLeftY + textHeight + frameSize), line1); sw.attach(l1); } // case line2: topLeftY + 2 * textHeight + 2 * frameSize if (line2 != "0") { Text l2(Point(topLeftX + frameSize, topLeftY + 2 * textHeight + 2 * frameSize), line2); sw.attach(l2); } // case line3: topLeftY + 3 * textHeight + 3 * frameSize if (line3 != "0") { Text l3(Point(topLeftX + frameSize, topLeftY + 3 * textHeight + 3 * frameSize), line3); sw.attach(l3); } } */
let el = document.getElementsByClassName('classname')[0];
require 'rails' module Discretion class Railtie < ::Rails::Railtie initializer 'discretion.insert_middleware' do |app| if defined?(Clearance::RackSession) app.config.middleware.insert_after( Clearance::RackSession, Discretion::Middleware, ) end end end end
#smallrnaseq #!/bin/bash #torun #chmod u+x smallrnaseq.sh #./smallrnaseq.sh /home/fb416/projects/fabian/FB37/ BASEPATH=${1} for filepath in $BASEPATH/seq/*.fastq do filename=$(basename $filepath .fastq) qsub -o $BASEPATH/log/fastqc_$filename.out -e $BASEPATH/log/fastqc_$filename.err -N fastqc_$filename -pe slots 1 -b y /home/fb416/projects/res/FastQC/fastqc $filepath -o $BASEPATH/out/ qsub -o $BASEPATH/log/wormgfpCDS$filename.out -e $BASEPATH/log/wormgfpCDS$filename.err -N wormgfpCDS$filename -pe slots 8 -b y /home/fb416/projects/res/bowtie -a -p 8 -v 0 -t --fullref --sam /home/fb416/projects/res/genomes/wormgfpCDS $BASEPATH/seq/$filename.fastq $BASEPATH/out/$filename.wormgfpCDS.sam --al $BASEPATH/out/$filename.wormgfpCDS.fq --un $BASEPATH/out/$filename.nowormgfpCDS.fq done
#! /bin/bash #SBATCH -o /home/hpc/pr63so/di69fol/workspace/SWEET_2016_01_16/benchmarks_performance/rexi_tests/2016_01_06_scalability_rexi_fd_run2/run_rexi_fd_par_m4096_t004_n0128_r0896_a1.txt ###SBATCH -e /home/hpc/pr63so/di69fol/workspace/SWEET_2016_01_16/benchmarks_performance/rexi_tests/2016_01_06_scalability_rexi_fd_run2/run_rexi_fd_par_m4096_t004_n0128_r0896_a1.err #SBATCH -J rexi_fd_par_m4096_t004_n0128_r0896_a1 #SBATCH --get-user-env #SBATCH --clusters=mpp2 #SBATCH --ntasks=896 #SBATCH --cpus-per-task=4 #SBATCH --exclusive #SBATCH --export=NONE #SBATCH --time=00:05:00 #declare -x NUMA_BLOCK_ALLOC_VERBOSITY=1 declare -x KMP_AFFINITY="granularity=thread,compact,1,0" declare -x OMP_NUM_THREADS=4 echo "OMP_NUM_THREADS=$OMP_NUM_THREADS" echo . /etc/profile.d/modules.sh module unload gcc module unload fftw module unload python module load python/2.7_anaconda_nompi module unload intel module load intel/16.0 module unload mpi.intel module load mpi.intel/5.1 module load gcc/5 cd /home/hpc/pr63so/di69fol/workspace/SWEET_2016_01_16/benchmarks_performance/rexi_tests/2016_01_06_scalability_rexi_fd_run2 cd ../../../ . local_software/env_vars.sh # force to use FFTW WISDOM data declare -x SWEET_FFTW_LOAD_WISDOM_FROM_FILE="FFTW_WISDOM_nofreq_T0" time -p mpiexec.hydra -genv OMP_NUM_THREADS 4 -envall -ppn 7 -n 896 ./build/rexi_fd_par_m_tno_a1 --initial-freq-x-mul=2.0 --initial-freq-y-mul=1.0 -f 1 -g 1 -H 1 -X 1 -Y 1 --compute-error 1 -t 50 -R 4 -C 0.3 -N 128 -U 0 -S 0 --use-specdiff-for-complex-array 0 --rexi-h 0.8 --timestepping-mode 1 --staggering 0 --rexi-m=4096 -C -5.0
# load the necessary library library(tidyverse) # sample list list <- c(1, 2, 3, 4, 5, 6, 7, 8) # calculate mean mean <- mean(list) # calculate standard deviation sd <- sd(list) # print the results print(paste("Mean: ", mean)) print(paste("Standard Deviation: ", sd))