text
stringlengths
27
775k
<br> <?php if($this->session->flashdata('reg_success')) { print '<div class="success-msg">'.$this->session->flashdata('reg_success').'</div>'; } ?> <div class="row justify-content-center"> <div class="col-lg-5 col-md-6 col-sm-8"> <div class="section-title"><i class="fas fa-user-plus"></i> Register here</div> <div class="reg-form-area"> <?= form_open('users/add_admin') ?> <div class="form-group"> <label><b>Name</b></label> <?= form_input(['name' => 'admin_name', 'value' => set_value('admin_name'), 'class' => 'form-control']) ?> <div class="text-danger"><?= form_error('admin_name')?></div> </div> <div class="form-group"> <label><b>Email</b></label> <?= form_input(['name' => 'email', 'value' => set_value('email'), 'class' => 'form-control']) ?> <div class="text-danger"><?= form_error('email')?></div> </div> <div class="form-group"> <label><b>Password</b></label> <?= form_password(['name' => 'password', 'value' => '', 'class' => 'form-control'])?> <div class="text-danger"><?= form_error('password')?></div> </div> <div class="form-group"> <label><b>Confirm Password</b></label> <?= form_password(['name' => 'cpassword', 'value' => '', 'class' => 'form-control'])?> <div class="text-danger"><?= form_error('cpassword')?></div> </div> <div class="form-group"> <?= form_submit(['name' => 'submit', 'value' => 'Register', 'class' => 'btn btn-primary login-btn'])?> </div> <?= form_close() ?> </div> </div> </div><br>
/** * Copyright (c) 2008-2010 Mark Logic Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * The use of the Apache License does not indicate that this project is * affiliated with the Apache Software Foundation. */ package com.marklogic.recordloader; import com.marklogic.ps.Utilities; /** * @author Michael Blakeley, Mark Logic Corporation * */ public class TranscodingFileLoader extends AbstractLoader { /* * (non-Javadoc) * * @see com.marklogic.recordloader.AbstractLoader#process() */ public void process() throws LoaderException { super.process(); // handle input as a single document, without parsing logger.fine("setting currentId = " + currentRecordPath); int size = 0; try { // we need the content object, hence the URI, before we can // check its existence currentUri = composeUri(currentRecordPath); content = contentFactory.newContent(currentUri); boolean skippingRecord = checkIdAndUri(currentRecordPath); // grab the entire document in the desired encoding byte[] bytes = Utilities.read(input, decoder).getBytes( config.getOutputEncoding()); if (null == bytes) { throw new LoaderException("null document: " + currentRecordPath); } size = bytes.length; if (0 == size) { throw new LoaderException("empty document: " + currentRecordPath); } if (!skippingRecord) { logger.finest("bytes = " + size); content.setBytes(bytes); insert(); } } catch (Exception e) { if (config.isFatalErrors()) { throw new FatalException(e); } event.stop(true); logger.logException(e); } finally { updateMonitor(size); cleanupInput(event.isError()); } } }
package co.netguru.videochatguru.util import android.util.Log internal object Logger { private const val PREFIX = "WebRTC:" var loggingEnabled = false fun d(tag: String, message: String) { if (loggingEnabled) Log.d("$PREFIX $tag", message) } fun e(tag: String, message: String) { if (loggingEnabled) Log.e("$PREFIX $tag", message) } }
set -eo nounset cd /sources test -f which-2.21.tar.gz || \ wget --no-check-certificate \ https://ftp.gnu.org/gnu/which/which-2.21.tar.gz rm -rf which-2.21 tar xf which-2.21.tar.gz pushd which-2.21 ./configure --prefix=/usr make make install #cat > /usr/bin/which << "EOF" ##!/bin/bash #type -pa "$@" | head -n 1 ; exit ${PIPESTATUS[0]} #EOF #chmod -v 755 /usr/bin/which #chown -v root:root /usr/bin/which popd rm -rf which-2.21
(defn get-banner [] (str " ____ _ _\n" "/ ___|| |_ __ _ _ __ | | __ _ _ __ ___ ___\n" "\\___ \\| __/ _` | '__| | | / _` | '_ \\ / _ \\/ __|\n" " ___) | || (_| | | | |__| (_| | | | | __/\\__ \\\n" "|____/ \\__\\__,_|_| |_____\\__,_|_| |_|\\___||___/\n")) (defproject starlanes "0.2.0-SNAPSHOT" :description "A Nostalgic Reimplementation of the old Star Lanes BASIC Game" :url "http://github.com/clojusc/clj-starlanes" :license {:name "BSD" :url "http://opensource.org/licenses/BSD-3-Clause"} :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/math.combinatorics "0.1.3"]] :plugins [[lein-kibit "0.1.2"] [lein-cloverage "1.0.6"] [jonase/eastwood "0.2.3"]] :aot [starlanes.trader] :main starlanes.trader :repl-options { :welcome ~(println (get-banner))} :test-selectors {:default (complement :integration) :integration :integration :all (constantly true)} :profiles { :1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]} :1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]} :1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} :dev { :dependencies [[org.clojure/tools.namespace "0.2.10"] [org.clojure/java.classpath "0.2.3"] [clj-http-fake "1.0.2"] [leiningen "2.6.1"]]} :debug { :dependencies [[org.clojure/clojure "1.8.0"]] :source-paths ["dev-resources/src"] :repl-options { :init-ns starlanes.debug}}} :aliases {"all" ["with-profile" "1.5:1.6:1.7:1.8"]})
#!/bin/bash KAFKA=/home/splice/kafka_2.10-0.10.0.1 javac -cp "$KAFKA/libs/*" SimpleProducer.java
package com.trafi.maas.account.ui.internal import com.trafi.ui.theme.internal.CurrentTheme import com.trafi.ui.theme.internal.SpacingScale import com.trafi.ui.theme.internal.type.dp class RequirementsViewConstants(theme: CurrentTheme) { val iconHeight = 150.dp val iconWidth = 150.dp val buttonsSpacing = SpacingScale.lg val contentSpacing = SpacingScale.xxxl val titleTextStyle = theme.typographyScale.headingXXL }
""" This is a program written in python for finding GCD of two numbers. This solution uses recursive approach as implementation. Recursive approach means a fuction calling itself for which a base condition is given so that the program knows where to terminate. """ #definition of functions to find GCD of 2 numbers. def gcd_of_nums(x,y): #choose the smaller number if x > y: t=x x=y y=t if(x==0): return y else: return gcd_of_nums(x,y%x) def main(): num1 = int(input("Enter 1st number: ")) num2 = int(input("Enter 2nd number: ")) print("The GCD is: ", gcd_of_nums(num1,num2)) if __name__ == "__main__": main() """ Output: Enter 1st number: 48 Enter 2nd number: 6 The GCD is: 6 Enter 1st number: 43 Enter 2nd number: 54 The GCD is: 1 """ print("\n")
var builderNode = require('../../utils/filterbuilder').BuilderNode; var FilterBuilder = require('../../utils/filterbuilder').FilterBuilder; var NexxusError = require('../../lib/NexxusError'); var chai = require('chai'); var expect = chai.expect; var assert = chai.assert; chai.should(); chai.use(require('chai-things')); module.exports = function() { describe('BuilderNode', function() { after(afterTest); it('Should throw an error because connector is not valid', function(done) { try { var bn = new builderNode('wtf'); assert.fail(undefined, NexxusError, 'Expected builderNode constructor to throw error'); } catch (e) { if (e instanceof NexxusError) { expect(e).to.have.property('code', '048'); } else { throw e; } try { var bn1 = new builderNode(); assert.fail(undefined, NexxusError, 'Expected builderNode constructor to throw error'); } catch (e1) { if (e1 instanceof NexxusError) { expect(e1).to.have.property('code', '048'); } else { throw e; } } } done(); }); it('Should have an empty builder with a valid connector', function(done) { try { var bn1 = new builderNode('and'); var bn2 = new builderNode('or'); expect(bn1).to.have.property('parent', null); expect(bn1).to.have.property('name', 'and'); expect(bn1.children).to.have.length(0); expect(bn2).to.have.property('parent', null); expect(bn2).to.have.property('name', 'or'); expect(bn2.children).to.have.length(0); } catch (e) { if (e instanceof NexxusError){ assert.fail(e, undefined, 'Expected builderNode constructor to not throw error: ' + e); } else { throw e; } } done(); }); it('Should throw an error because trying to add invalid filter', function(done) { try { var bn1 = new builderNode('and'); bn1.addFilter('qwop'); assert.fail(undefined, NexxusError, 'Expected buildNode.addFilter to throw error'); } catch (e) { expect(e).to.be.instanceof(NexxusError); expect(e).to.have.property('code', '048'); try { bn1 = new builderNode('and'); bn1.addFilter('is'); assert.fail(undefined, NexxusError, 'Expected buildNode.addFilter to throw error'); } catch (e1) { expect(e1).to.be.instanceof(NexxusError); expect(e1).to.have.property('code', '048'); } } done(); }); it('Should throw an error because trying to add invalid value', function(done) { try { var bn1 = new builderNode('and'); bn1.addFilter('is', 'string wut'); assert.fail(undefined, NexxusError, 'Expected buildNode.addFilter to throw error'); } catch (e) { expect(e).to.be.instanceof(NexxusError); expect(e).to.have.property('code', '048'); try { bn1 = new builderNode('and'); bn1.addFilter('range', 'wut'); assert.fail(undefined, NexxusError, 'Expected buildNode.addFilter to throw error'); } catch (e1) { expect(e1).to.be.instanceof(NexxusError); expect(e1).to.have.property('code', '048'); } } done(); }); it('Should add all supported filters to builder', function(done) { try { var bn1 = new builderNode('and'), filters = [ { is: {field: 'test'} }, { not: {is: {field: 'test'}} }, { exists: 'field' }, { range: {field: {gte: 0, lte: 1}} }, { in_array: {field: 'test'} }, { like: {field: 'test'} } ]; filters.forEach(function(f) { var name = Object.keys(f)[0]; bn1.addFilter(name, f[name]); }); expect(bn1.children).to.deep.equal(filters); } catch (e) { if (e instanceof NexxusError){ assert.fail(e, undefined, 'Expected builderNode.addFilter to not throw error: ' + e); } else { throw e; } } done(); }); it('Should fail adding a node because argument is not instanceof BuilderNode', function(done) { try { var bn1 = new builderNode('and'); bn1.addNode('string'); assert.fail(undefined, NexxusError, 'Expected builderNode.addNode to throw error'); } catch (e) { expect(e).to.be.instanceof(NexxusError); expect(e).to.have.property('code', '002'); } done(); }); it('Should add a valid builderNode', function(done) { try { var bn1 = new builderNode('and'); var bn2 = new builderNode('or'); bn1.addNode(bn2); expect(bn1.children).to.have.length(1); expect(bn2.parent).to.be.instanceof(builderNode); expect(bn2.parent).to.have.property('name', 'and'); } catch (e) { if (e instanceof NexxusError){ assert.fail(e, undefined, 'Expected builderNode constructor to not throw error: ' + e); } else { throw e; } } done(); }); it('Should fail removing a node because argument is not instanceof BuilderNode', function(done) { try { var bn1 = new builderNode('and'); bn1.removeNode('string'); assert.fail(undefined, NexxusError, 'Expected builderNode.addNode to throw error'); } catch (e) { expect(e).to.be.instanceof(NexxusError); expect(e).to.have.property('code', '002'); } done(); }); it('Should remove a valid builderNode', function(done) { try { var bn1 = new builderNode('and'); var bn2 = new builderNode('or'); bn1.addNode(bn2); var result = bn1.removeNode(bn2); expect(bn1.children).to.have.length(0); expect(bn2.parent).to.be.equal(null); expect(result).to.be.instanceof(builderNode); expect(result).to.have.property('name', 'or'); } catch (e) { if (e instanceof NexxusError){ assert.fail(e, undefined, 'Expected builderNode.removeNode to not throw error: ' + e); } else { throw e; } } done(); }); it('Should return an object representing the node', function(done) { try { var bn1 = new builderNode('and'); var result = bn1.toObject(); expect(result).to.be.deep.equal({and: []}); //testing a simple node with just 1 filter bn1.addFilter('is', {application_id: 1}); expect(bn1.toObject()).to.be.deep.equal( { and: [ { is: { application_id: 1 } } ] } ); //testing a simple node with multiple filters bn1.addFilter('range', {age: {gte: 18}}); expect(bn1.toObject()).to.be.deep.equal( { and: [ { is: { application_id: 1 } }, { range: { age: { gte: 18 } } } ] } ); //testing nested node with multiple filters var bn2 = new builderNode('or'); bn2.addFilter('is', {user_id: 1}); bn2.addFilter('is', {user_id: 2}); bn1.addNode(bn2); expect(bn1.toObject()).to.be.deep.equal( { and: [ { is: { application_id: 1 } }, { range: { age: { gte: 18 } } }, { or: [ { is: { user_id: 1 } }, { is: { user_id: 2 } } ] } ] } ); //testing triple nested node with filters var bn3 = new builderNode('and'); bn3.addFilter('is', {field: 'value'}); bn2.addNode(bn3); expect(bn1.toObject()).to.be.deep.equal( { and: [ { is: { application_id: 1 } }, { range: { age: { gte: 18 } } }, { or: [ { is: { user_id: 1 } }, { is: { user_id: 2 } }, { and: [ { is: { field: 'value' } } ] } ] } ] } ); } catch (e) { if (e instanceof NexxusError){ assert.fail(e, undefined, 'Expected builderNode.toObject to not throw error: ' + e); } else { throw e; } } done(); }); }); describe('FilterBuilder', function() { it('Should construct a FilterBuilder with no initial node supplied', function(done) { var fb = new FilterBuilder(); expect(fb.root).to.be.instanceof(builderNode); expect(fb.root).to.have.property('name', 'and'); expect(fb.root.children).to.have.length(0); expect(fb.pointer).to.be.equal(fb.root); done(); }); it('Should construct a FilterBuilder with initial node', function(done) { var fb = new FilterBuilder('or'); expect(fb.root).to.be.instanceof(builderNode); expect(fb.root).to.have.property('name', 'or'); expect(fb.root.children).to.have.length(0); expect(fb.pointer).to.be.equal(fb.root); done(); }); it('Should add an "and" node', function(done) { var fb = new FilterBuilder('or'); var initialPointer = fb.root; var returnValue = fb.and(); expect(fb.pointer).to.be.not.equal(initialPointer); expect(fb.pointer).to.have.property('name', 'and'); expect(fb.root.children).to.have.length(1); expect(fb).to.be.equal(returnValue); done(); }); it('Should add an "or" node', function(done) { var fb = new FilterBuilder('or'); var initialPointer = fb.root; var returnValue = fb.or(); expect(fb.pointer).to.be.not.equal(initialPointer); expect(fb.pointer).to.have.property('name', 'or'); expect(fb.root.children).to.have.length(1); expect(fb).to.be.equal(returnValue); done(); }); it('Should add filter to the curent pointer', function(done) { var fb = new FilterBuilder('or'); var returnedValue = fb.addFilter('is', {user_id: 1}); expect(returnedValue).to.be.equal(fb); returnedValue.addFilter('is', {user_id: 2}); expect(fb.root.children).to.have.length(2); expect(fb.root.toObject()).to.be.deep.equal({ or: [ { is: { user_id: 1 } }, { is: { user_id: 2 } } ] }); done(); }); it('Should return null because root node cannot be removed', function(done) { var fb = new FilterBuilder(); expect(fb.removeNode()).to.be.equal(null); expect(fb.root).to.be.equal(fb.pointer); done(); }); it('Should remove the current pointer node', function(done) { var fb = new FilterBuilder(); fb.and(); var insertedNode = fb.pointer; expect(fb.removeNode()).to.be.equal(insertedNode); expect(fb.root).to.be.equal(fb.pointer); done(); }); it('Should check if the filter builder is empty or not', function(done) { var fb = new FilterBuilder(); expect(fb.isEmpty()).to.be.eql(true); fb.and(); expect(fb.isEmpty()).to.be.eql(false); done(); }); it('Should end the current pointer and go back to parent', function(done) { var fb = new FilterBuilder(); expect(fb.end()).to.be.equal(fb); fb.and(); var insertedNode = fb.pointer; expect(fb.end()).to.be.equal(fb); expect(fb.root).to.be.equal(fb.pointer); done(); }); it('Should when trying to build the query because root is empty ', function(done) { try { var fb = new FilterBuilder(); var ret = fb.build(); assert.fail(ret, undefined, 'FilterBuilder.build should throw error'); } catch (e) { expect(e).to.be.instanceof(NexxusError); expect(e).to.have.property('code', '048'); done(); } }); it('Should construct the filter object', function(done) { var fb = new FilterBuilder(); fb.addFilter('is', {field: 'value'}). addFilter('exists', 'field'). or(). addFilter('like', {text: 'something'}). addFilter('range', {age: {gte: 18}}); expect(fb.build()).to.be.deep.equal({ and: [ { is: { field: 'value' } }, { exists: 'field' }, { or: [ { like: { text: 'something' } }, { range: { age: { gte: 18 } } } ] } ] }); done(); }); }); }
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1992 -- All Rights Reserved PROJECT: PC GEOS MODULE: FILE: visHermanClock.asm AUTHOR: Adam de Boor, Feb 4, 1992 ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- Adam 2/ 4/92 Initial revision DESCRIPTION: Implementation of the VisHermanClock object $Id: visHermanClock.asm,v 1.1 97/04/04 14:50:48 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ include clock.def include Internal/grWinInt.def idata segment VisHermanClockClass idata ends L_EYEBROW_LEFT equ 1 L_EYEBROW_TOP equ 0 L_EYEBROW_RIGHT equ 25 L_EYEBROW_BOTTOM equ 8 R_EYEBROW_LEFT equ 40 R_EYEBROW_TOP equ 0 R_EYEBROW_RIGHT equ 65 R_EYEBROW_BOTTOM equ 7 L_EYE_LEFT equ 0 L_EYE_TOP equ 6 L_EYE_RIGHT equ 32 L_EYE_BOTTOM equ 35 R_EYE_LEFT equ 38 R_EYE_TOP equ 7 R_EYE_RIGHT equ 70 R_EYE_BOTTOM equ 37 NOSE_LEFT equ 25 NOSE_TOP equ 27 NOSE_RIGHT equ 42 NOSE_BOTTOM equ 55 MUSTACHE_LEFT equ 6 MUSTACHE_TOP equ 51 MUSTACHE_RIGHT equ 59 MUSTACHE_BOTTOM equ 67 HermanCode segment resource PUPIL_WIDTH equ 5 pupilBitmap Bitmap < PUPIL_WIDTH, PUPIL_WIDTH, BMC_UNCOMPACTED, BMF_MONO shl offset BMT_FORMAT > byte 01110000b byte 11111000b byte 11111000b byte 11111000b byte 01110000b ; ; These hands are drawn at 12 o'clock, because that works with the minimal ; amount of translation, scaling, etc. ; if (L_EYE_BOTTOM-L_EYE_TOP) lt (L_EYE_RIGHT-L_EYE_LEFT) HOUR_HAND_LENGTH equ (L_EYE_BOTTOM-L_EYE_TOP)/4-PUPIL_WIDTH/2 else HOUR_HAND_LENGTH equ (L_EYE_RIGHT-L_EYE_LEFT)/4-PUPIL_WIDTH/2 endif if (R_EYE_BOTTOM-R_EYE_TOP) lt (R_EYE_RIGHT-R_EYE_LEFT) MINUTE_HAND_LENGTH equ (R_EYE_BOTTOM-R_EYE_TOP)/2-PUPIL_WIDTH/2 else MINUTE_HAND_LENGTH equ (R_EYE_RIGHT-R_EYE_LEFT)/2-PUPIL_WIDTH/2 endif HandStruct struct HS_edge word ; outer edge for the hand, whatever form it ; takes HS_center Point ; translation to get to the center of the ; eyeball HS_eyeball VisHermanBodyPart; region for wiping the eyeball out HS_pupil VisHermanBodyPart; part to draw for pupil HandStruct ends hourHand HandStruct < HOUR_HAND_LENGTH, < L_EYE_LEFT+(L_EYE_RIGHT-L_EYE_LEFT)/2, L_EYE_TOP+(L_EYE_BOTTOM-L_EYE_TOP)/2 >, VHBP_LEFT_EYE, VHBP_HOUR_PUPIL > minuteHand HandStruct < MINUTE_HAND_LENGTH, < R_EYE_LEFT+(R_EYE_RIGHT-R_EYE_LEFT)/2, R_EYE_TOP+(R_EYE_BOTTOM-R_EYE_TOP)/2 >, VHBP_RIGHT_EYE, VHBP_MINUTE_PUPIL > ; Regions for drawing the different parts of Herman. lEyebrowReg Rectangle < L_EYEBROW_LEFT, L_EYEBROW_TOP, L_EYEBROW_RIGHT, L_EYEBROW_BOTTOM > word -1, EOREGREC ; nothing till onscreen word 0, 12,21, EOREGREC word 1, 10,23, EOREGREC word 2, 8,24, EOREGREC word 3, 6,25, EOREGREC word 4, 4,25, EOREGREC word 5, 3,9,22,25, EOREGREC word 6, 2,7, EOREGREC word 7, 1,3, EOREGREC word 8, 1,2, EOREGREC word EOREGREC ; end of region rEyebrowReg Rectangle < R_EYEBROW_LEFT, R_EYEBROW_TOP, R_EYEBROW_RIGHT, R_EYEBROW_BOTTOM > word -1, EOREGREC ; nothing till onscreen word 0, 52,59, EOREGREC word 1, 49,63, EOREGREC word 2, 46,65, EOREGREC word 3, 44,65, EOREGREC word 4, 43,65, EOREGREC word 5, 42,47,61,64, EOREGREC word 6, 41,45, EOREGREC word 7, 40,43, EOREGREC word EOREGREC ; end of region lEyeReg Rectangle < L_EYE_LEFT, L_EYE_TOP, L_EYE_RIGHT, L_EYE_BOTTOM > word 5, EOREGREC ; nothing till onscreen word 6, 12,21, EOREGREC word 7, 8,24, EOREGREC word 8, 6,25, EOREGREC word 9, 4,26, EOREGREC word 10,3,27, EOREGREC word 11,2,28, EOREGREC word 12,2,29, EOREGREC word 13, 1,30, EOREGREC word 14, 1,31, EOREGREC word 15, 0,31, EOREGREC word 16, 0,31, EOREGREC word 18, 0,32, EOREGREC word 23, 0,32, EOREGREC word 26, 0,31, EOREGREC word 27, 1,31, EOREGREC word 28, 1,30, EOREGREC word 29,2,29, EOREGREC word 30,2,28, EOREGREC word 31,2,27, EOREGREC word 32,3,26, EOREGREC word 33,5,25, EOREGREC word 34,6,23, EOREGREC word 35,8,20, EOREGREC word EOREGREC ; end of region rEyeReg Rectangle < R_EYE_LEFT, R_EYE_TOP, R_EYE_RIGHT, R_EYE_BOTTOM > word 6, EOREGREC ; nothing till onscreen word 7, 50,59, EOREGREC word 8, 47,62, EOREGREC word 9, 45,63, EOREGREC word 10,44,65, EOREGREC word 11,43,66, EOREGREC word 12,42,67, EOREGREC word 13,41,68, EOREGREC word 14,40,68, EOREGREC word 15,40,69, EOREGREC word 16,39,69, EOREGREC word 18,39,69, EOREGREC word 23,38,70, EOREGREC word 26,38,70, EOREGREC word 27,38,69, EOREGREC word 28,39,69, EOREGREC word 29,39,68, EOREGREC word 30,40,68, EOREGREC word 31,40,67, EOREGREC word 32,41,66, EOREGREC word 33,42,65, EOREGREC word 34,43,64, EOREGREC word 35,45,63, EOREGREC word 36,47,60, EOREGREC word 37,50,55, EOREGREC word EOREGREC ; end of region noseReg Rectangle < NOSE_LEFT, NOSE_TOP, NOSE_RIGHT, NOSE_BOTTOM > word 26, EOREGREC ; nothing till onscreen word 27,31,37, EOREGREC word 28,31,38, EOREGREC word 29,30,38, EOREGREC word 31,29,39, EOREGREC word 34,28,39, EOREGREC word 38,27,40, EOREGREC word 42,26,41, EOREGREC word 44,25,41, EOREGREC word 51,25,42, EOREGREC word 52,26,41, EOREGREC word 53,27,41, EOREGREC word 54,29,40, EOREGREC word 55,32,36, EOREGREC word EOREGREC ; end of region nose1Reg Rectangle < 26,52,41,55 > word 51, EOREGREC word 52,26,41, EOREGREC word 53,27,41, EOREGREC word 54,29,40, EOREGREC word 55,32,36, EOREGREC word EOREGREC ; end of region nose2Reg Rectangle < 25,48,42,51 > word 47, EOREGREC word 51,25,42, EOREGREC word EOREGREC nose3Reg Rectangle < 25,45,42,47 > word 44, EOREGREC word 47,25,42, EOREGREC word EOREGREC nose4Reg Rectangle < 25,42,41,44 > word 41, EOREGREC word 42,26,41, EOREGREC word 44,25,41, EOREGREC word EOREGREC nose5Reg Rectangle < 26,39,41,41 > word 38, EOREGREC word 41,26,41, EOREGREC word EOREGREC nose6Reg Rectangle < 27,36,40,38 > word 35, EOREGREC word 38,27,40, EOREGREC word EOREGREC nose7Reg Rectangle < 27,33,40,35 > word 32, EOREGREC word 35,27,40, EOREGREC word EOREGREC nose8Reg Rectangle < 28,30,39,32 > word 29, EOREGREC word 31,29,39, EOREGREC word 32,28,39, EOREGREC word EOREGREC nose9Reg Rectangle < 30,27,38,29 > word 26, EOREGREC word 27,31,37, EOREGREC word 28,31,38, EOREGREC word 29,30,38, EOREGREC word EOREGREC mustacheReg Rectangle < MUSTACHE_LEFT, MUSTACHE_TOP, MUSTACHE_RIGHT, MUSTACHE_BOTTOM > word 50, EOREGREC ; nothing till onscreen word 51, 16,21, 45,46, EOREGREC word 52, 14,17, 46,49, EOREGREC word 53, 12,15, 20,22, 47,51, EOREGREC word 54, 10,14, 18,20, 24,24, 44,45, 49,52, EOREGREC word 55, 9,13, 17,19, 22,24, 44,47, 50,53, EOREGREC word 56, 9,12, 16,18, 21,23, 26,27, 42,42, 45,48, 52,54, EOREGREC word 57, 8,11, 15,17, 20,22, 26,27, 30,30, 34,34, 38,39, 42,43, 46,49, 53,55, EOREGREC word 58, 7,10, 14,17, 19,21, 26,27, 30,31, 34,34, 38,40, 43,44, 47,50, 54,56, EOREGREC word 59, 7,9, 13,16, 19,21, 25,27, 30,31, 34,35, 38,40, 43,45, 48,51, 54,57, EOREGREC word 60, 6,8, 13,15, 18,20, 25,27, 29,31, 34,35, 38,40, 43,45, 48,51, 55,58, EOREGREC word 61, 6,8, 12,15, 18,20, 25,26, 29,31, 34,35, 38,40, 44,46, 49,52, 55,58, EOREGREC word 62, 6,8, 12,14, 17,20, 24,26, 29,31, 34,35, 38,40, 44,46, 49,52, 56,59, EOREGREC word 63, 6,7, 12,14, 17,20, 24,26, 29,31, 33,35, 38,40, 44,47, 50,53, 56,59, EOREGREC word 64, 6,7, 12,14, 17,20, 24,26, 29,31, 33,35, 38,40, 44,47, 50,53, 57,58, EOREGREC word 65, 12,14, 17,20, 24,26, 29,31, 33,35, 38,41, 44,47, 50,53, EOREGREC word 66, 17,20, 24,26, 29,30, 33,35, 38,41, 45,46, EOREGREC word 67, 18,19, 24,25, 34,35, EOREGREC word EOREGREC ; end of region mustache10Reg Rectangle < 6,51,22,65 > word 50, EOREGREC word 51, 16,21, EOREGREC word 52, 14,17, EOREGREC word 53, 12,15, 20,22, EOREGREC word 54, 10,14, 18,20, EOREGREC word 55, 9,13, 17,19, EOREGREC word 56, 9,12, 16,18, EOREGREC word 57, 8,11, 15,17, EOREGREC word 58, 7,10, 14,17, EOREGREC word 59, 7,9, 13,16, EOREGREC word 60, 6,8, 13,15, EOREGREC word 61, 6,8, 12,15, EOREGREC word 62, 6,8, 12,14, EOREGREC word 64, 6,7, 12,14, EOREGREC word 65, 12,14, EOREGREC word EOREGREC mustache20Reg Rectangle < 18,54,27,67 > word 53, EOREGREC word 54, 24,24, EOREGREC word 55, 22,24, EOREGREC word 56, 21,23, 26,27, EOREGREC word 57, 20,22, 26,27, EOREGREC word 58, 19,21, 26,27, EOREGREC word 59, 19,21, 25,27, EOREGREC word 60, 18,20, 25,27, EOREGREC word 61, 18,20, 25,26, EOREGREC word 66, 17,20, 24,26, EOREGREC word 67, 18,19, 24,25, EOREGREC word EOREGREC mustache30Reg Rectangle < 29,57,35,67 > word 56, EOREGREC word 57, 30,30, 34,34, EOREGREC word 58, 30,31, 34,34, EOREGREC word 59, 30,31, 34,35, EOREGREC word 62, 29,31, 34,35, EOREGREC word 65, 29,31, 33,35, EOREGREC word 66, 29,30, 33,35, EOREGREC word 67, 34,35, EOREGREC word EOREGREC mustache40Reg Rectangle < 38,56,47,66 > word 55, EOREGREC word 56, 42,42, EOREGREC word 57, 38,39, 42,43, EOREGREC word 58, 38,40, 43,44, EOREGREC word 60, 38,40, 43,45, EOREGREC word 62, 38,40, 44,46, EOREGREC word 64, 38,40, 44,47, EOREGREC word 65, 38,41, 44,47, EOREGREC word 66, 38,41, 45,46, EOREGREC word EOREGREC mustache50Reg Rectangle < 44,51,59,65 > word 50, EOREGREC word 51, 45,46, EOREGREC word 52, 46,49, EOREGREC word 53, 47,51, EOREGREC word 54, 44,45, 49,52, EOREGREC word 55, 44,47, 50,53, EOREGREC word 56, 45,48, 52,54, EOREGREC word 57, 46,49, 53,55, EOREGREC word 58, 47,50, 54,56, EOREGREC word 59, 48,51, 54,57, EOREGREC word 60, 48,51, 55,58, EOREGREC word 61, 49,52, 55,58, EOREGREC word 62, 49,52, 56,59, EOREGREC word 63, 50,53, 56,59, EOREGREC word 64, 50,53, 57,58, EOREGREC word 65, 50,53, EOREGREC word EOREGREC regions nptr.Rectangle lEyebrowReg, ; VHBP_LEFT_EYEBROW rEyebrowReg, ; VHBP_RIGHT_EYEBROW lEyeReg, ; VHBP_LEFT_EYE rEyeReg, ; VHBP_RIGHT_EYE noseReg, ; VHBP_NOSE mustacheReg ; VHBP_MUSTACHE emptyRegion Rectangle < 0,0,0,0 > word EOREGREC noseRegions nptr.Rectangle nose1Reg, nose2Reg, nose3Reg, nose4Reg, nose5Reg, nose6Reg, nose7Reg, nose8Reg, nose9Reg mustacheRegions nptr.Rectangle mustache10Reg, mustache20Reg, mustache30Reg, mustache40Reg, mustache50Reg COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% VHCDraw %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw the current time in Herman CALLED BY: MSG_VIS_DRAW PASS: *ds:si = object cl = DrawFlags bp = gstate RETURN: nothing DESTROYED: ax, cx, dx, bp PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 2/ 4/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ VHCDraw method dynamic VisHermanClockClass, MSG_VIS_DRAW .enter mov di, bp call TimerGetDateAndTime ; ; Convert minutes to degrees by multiplying by 6 ; push dx ; save seconds in case 1-second interval clr dh mov ax, dx ; save minutes for additional ; hour-hand rotation shl dx ; *2 mov bx, dx shl dx ; *4 add dx, bx ; dx <- dl*6 ; ; Figure AM/PM ; ; bl <- part to fill, bh <- part to ; clear mov bx, VHBP_LEFT_EYEBROW or (VHBP_RIGHT_EYEBROW shl 8) cmp ch, 12 ; afternoon? jb convertHours ; no, fill left eyebrow for AM xchg bl, bh sub ch, 12 ; convert to 0-11 convertHours: ; ; Convert hours to degrees by multiplying by 30 = 16 + 8 + 4 + 2 ; shr ax ; divide minutes by 2 to get additional ; degrees of rotation (30 degrees in ; an hour...) mov cl, ch clr ch shl cx ; *2 add ax, cx shl cx ; *4 add ax, cx shl cx ; *8 add ax, cx shl cx ; *16 add cx, ax ; cx <- cl*30 ; ; cx and dx are the degrees of rotation, clockwise from north, for the ; hours and minutes hands, respectively. bl is the VisHermanBodyPart ; to fill with its proper color, and bh is the VHBP to fill with black. ; mov ax, VHC_USE_SET_COLOR push bx call VHCDrawReg ; draw filled eyebrow pop bx mov bl, bh ; draw blanked eyebrow mov ax, C_BLACK call VHCDrawReg ; ; Draw the minute hand. ; push cx mov_trash ax, dx ; ax <- degrees of rotation mov bx, offset minuteHand call VHCDrawHand ; ; Draw the hour hand ; mov bx, offset hourHand pop ax ; ax <- degress of rotation for hand call VHCDrawHand ; ; Draw the nose and mustache. ; pop dx mov bx, ds:[si] add bx, ds:[bx].VisHermanClock_offset cmp ds:[bx].VCI_interval, 60 ; 1-second interval? je drawSeconds mov ax, VHC_USE_SET_COLOR mov bl, VHBP_NOSE call VHCDrawReg mov ax, VHC_USE_SET_COLOR mov bl, VHBP_MUSTACHE call VHCDrawReg done: .leave ret drawSeconds: ; ; Draw the nose and mustache clipped appropriately, according to the ; tens or units portions of the seconds. ; mov al, dh aam ; ah <- seconds/10 ; al <- seconds%10 push ax mov ah, VHBP_NOSE mov bx, offset noseRegions mov dx, length noseRegions call VHCDrawPartiteReg pop ax mov al, ah mov ah, VHBP_MUSTACHE mov bx, offset mustacheRegions mov dx, length mustacheRegions call VHCDrawPartiteReg jmp done VHCDraw endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% VHCDrawPartiteReg %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw a region of Herman that is defined as a series of pieces, the first n of which are to be drawn in the body part's color, and the remaining m-n of which are to be drawn in black. You might recognize this as the code that draws the mustache and nose when displaying seconds. CALLED BY: VHCDraw PASS: al = 0-9/0-5 to index the array ah = VisHermanBodyPart being drawn cs:bx = array of 10/6 pointers to regions. [0..al] get drawn in part color, [al+1..dx] get drawn in black. dx = number of regions in the array *ds:si = VisHermanClock object di = gstate RETURN: nothing DESTROYED: ax, bx, cx, dx PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 2/ 8/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ VHCDrawPartiteReg proc near class VisHermanClockClass uses si, ds .enter ; ; We start drawing the filled in portions, so set the area color ; to the color for the body part. ; mov si, ds:[si] add si, ds:[si].VisHermanClock_offset push ax, bx mov bl, ah clr bh CheckHack <size ColorQuad eq 4> shl bx shl bx mov ax, ({dword}ds:[si].VHCI_colors[bx]).low mov bx, ({dword}ds:[si].VHCI_colors[bx]).high call GrSetAreaColor pop ax, bx ; ; Set up for first sequence of loops, where we draw in the body ; part's color... ; mov si, bx ; ds:si <- region table segmov ds, cs mov_trash cx, ax clr ch ; cx <- parts to draw in body part color jcxz firstPartDone partLoop: lodsw ; ds:ax <- region to draw... push si mov_trash si, ax ; ds:si <- region to draw clr ax ; draw region at (0,0) mov bx, ax call GrDrawRegion pop si dec dx ; reduce count of parts remaining loop partLoop je done ; => all parts drawn (dx decremented ; to 0, either because this is the ; second pass, or there are none to ; draw in black) firstPartDone: ; ; Switch to C_BLACK for the second set of regions, unless all regions ; already drawn, of course... ; mov cx, dx ; cx <- parts to draw in black mov ax, C_BLACK call GrSetAreaColor jmp partLoop done: .leave ret VHCDrawPartiteReg endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% VHCDrawReg %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw the region in the appropriate color, or whatever color is passed. CALLED BY: VHCDraw PASS: *ds:si = VisHermanClock object bl = VisHermanBodyPart to draw ax = color in which to draw the region, or VHC_USE_SET_COLOR di = gstate to use RETURN: nothing DESTROYED: ax, bx, bp PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 2/ 6/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ VHCDrawReg proc near uses ds, si class VisHermanClockClass .enter clr bh ; zero-extend for array indexing... ; ; Fetch the defined color for this part, if told to. ; push bx cmp ax, VHC_USE_SET_COLOR jne haveColor mov si, ds:[si] add si, ds:[si].VisHermanClock_offset CheckHack <size ColorQuad eq 4> shl bx shl bx mov ax, ({dword}ds:[si].VHCI_colors[bx]).low mov bx, ({dword}ds:[si].VHCI_colors[bx]).high haveColor: call GrSetAreaColor pop bx ; ; Fetch the region for this body part and draw it at 0,0 (all regions ; are defined to be window-relative). If beyond the defined regions, ; draw nothing (just wanted to get the color) ; segmov ds, cs assume ds:@CurSeg shl bx cmp bx, size regions jae done mov si, ds:[regions][bx] ; ds:si <- region (bounding ; rectangle of same) clr ax mov bx, ax call GrDrawRegion assume ds:dgroup done: .leave ret VHCDrawReg endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% VHCDrawHand %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw the hand described by the passed HandStruct and rotation CALLED BY: VHCDraw PASS: cs:bx = HandStruct describing the hand to draw *ds:si = VisHermanClock object di = gstate to use ax = degrees of rotation (clockwise from noon) RETURN: nothing DESTROYED: ax, bx, cx, dx PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 2/ 5/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ VHCDrawHand proc near uses si, ds class VisHermanClockClass .enter push ax ; ; Blank out the eyeball ; mov ax, VHC_USE_SET_COLOR push bx mov bx, cs:[bx].HS_eyeball call VHCDrawReg ; ; Set the proper pupil color (can't use VHCDrawReg to draw it b/c it's ; a bitmap, and it can't be drawn at 0,0 w/o applying a translation ; pop bx push bx mov ax, VHC_USE_SET_COLOR mov bx, cs:[bx].HS_pupil call VHCDrawReg segmov ds, cs pop si ; ds:si <- HandStruct ; ; Do all the transformations ourselves to avoid distortions in the ; pupil, as come about whether we use a bitmap or an ellipse. We ; figure the coordinate for the center of the pupil by the following ; formulae: ; X = Xcenter + cos(theta') * radius ; Y = Ycenter - sin(theta') * radius ; the subtraction for Y is caused by the Y axis being inverted from ; normal geometry. theta' is derived from our input theta, the ; degrees clockwise from 12, by ; theta' = |((360 - theta) - 270) % 360| ; as theta+90 shifts the origin of the rotation to 3, and you subtract ; that from 360 to go the opposite direction. Of course, angles are ; always 0-359, hence the absolute value of the modulus. ; pop ax mov dx, 360 sub dx, ax sub dx, 270 jge haveAngle add dx, 360 haveAngle: push dx ; ; dx.ax <- sin(theta') ; clr ax call GrQuickSine ; ; dx.cx <- sin(theta') [dx.cx] * radius [bx.ax] ; mov_trash cx, ax mov bx, ds:[si].HS_edge clr ax call GrMulWWFixed neg dx ; -sin(theta') pop ax ; recover degrees push dx ; save Y coord ; ; dx.ax <- cos(theta') ; mov_trash dx, ax clr cx call GrQuickCosine ; ; dx.cx <- cos(theta') [dx.cx] * radius [bx.ax] ; mov_trash cx, ax mov bx, ds:[si].HS_edge clr ax call GrMulWWFixed ; ; Now offset to the center of eyeball, and adjust so bitmap is centered ; on the final coordinate. ; mov ax, dx pop bx sub bx, PUPIL_WIDTH/2 sub ax, PUPIL_WIDTH/2 add ax, ds:[si].HS_center.P_x add bx, ds:[si].HS_center.P_y ; ; Draw the darn thing. ; mov si, offset pupilBitmap clr dx call GrFillBitmap .leave ret VHCDrawHand endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% VHCRecalcSize %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Figure how big we should be. Herman is always the same size, so this is simple. CALLED BY: MSG_VIS_RECALC_SIZE PASS: *ds:si = object RETURN: cx = desired width dx = desired height DESTROYED: ? PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 2/ 4/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ VHCRecalcSize method dynamic VisHermanClockClass, MSG_VIS_RECALC_SIZE .enter mov cx, HERMAN_WIDTH mov dx, HERMAN_HEIGHT .leave ret VHCRecalcSize endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% VHCSetInterval %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Note a change in the rate at which we're called CALLED BY: MSG_VC_SET_INTERVAL PASS: *ds:si = VisHermanClock object ds:di = VisHermanClockInstance cx = new interval (in ticks) RETURN: nothing DESTROYED: ? PSEUDO CODE/STRATEGY: let the superclass do its thing, but invalidate our image, as we need to get the nose-as-second-hand going or stopped right away. KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 2/ 8/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ VHCSetInterval method dynamic VisHermanClockClass, MSG_VC_SET_INTERVAL .enter mov di, offset VisHermanClockClass CallSuper MSG_VC_SET_INTERVAL mov cx, mask VOF_IMAGE_INVALID mov dl, VUM_NOW call VisClockMarkInvalid .leave ret VHCSetInterval endm HermanCode ends
using System.Globalization; using System.Resources; namespace System.Speech { internal static class SR { private static ResourceManager _resourceManager = new ResourceManager("ExceptionStringTable", typeof(SR).Assembly); internal static string Get(SRID id, params object[] args) { string text = _resourceManager.GetString(id.ToString()); if (string.IsNullOrEmpty(text)) { text = _resourceManager.GetString("Unavailable"); } else if (args != null && args.Length != 0) { text = string.Format(CultureInfo.InvariantCulture, text, args); } return text; } } }
#!/bin/bash # Script for Jenkins continuous integration testing of theano base echo "===== Testing theano core" # Get environment from worker, necessary for CUDA source ~/.bashrc # Test theano core PARTS="theano -e cuda -e gpuarray" THEANO_PARAM="${PARTS} --with-timer --timer-top-n 10" FLAGS="mode=FAST_RUN,init_gpu_device=gpu,floatX=float32" THEANO_FLAGS=${FLAGS} bin/theano-nose ${THEANO_PARAM}
const express = require('express'); const pushController = require('../controllers/push'); const router = express.Router(); // POST REQUESTS // POST => /push/tree router.post('/tree', pushController.postTree); // POST => /push/file router.post('/file', pushController.postFile); module.exports = router;
# encoding: utf-8 module Rubocop module Cop module Style # Checks for uses of if/then/else/end on a single line. class OneLineConditional < Cop include IfThenElse def offending_line(node) node.loc.expression.line unless node.loc.expression.source =~ /\n/ end def error_message 'Favor the ternary operator (?:) over if/then/else/end constructs.' end end end end end
--- toc: true layout: post title: "消失的日记本" date: 2020-12-24 tags: [日记] comments: true author: BobWU --- toc: true 因为软件被禁用,探索一下怎么使用在线编辑来做笔记 ## Title 2 > 写什么呢,索引? ``` dim kk as string dim bb ```
package fr.alchemy.utilities.task.actions; import java.util.function.Function; /** * A functional interface allowing the user to perform a certain type of action safely to the invoked element * and return the modified element. * * @version 0.2.0 * @since 0.1.0 * * @author GnosticOccultist */ @FunctionalInterface public interface SafeModifierAction<T, U> extends Function<T, U> { /** * Performs safely a modification to the provided element and return it. * * @param element The element to modify safely. * @return The modified element. */ U modify(T element) throws Exception; @Override default U apply(T element) { try { return modify(element); } catch (Exception ex) { ex.printStackTrace(); } return null; } }
module ActsAsApi module Adapters autoload :Mongoid, "acts_as_api/adapters/mongoid" end end
# AWS AMI for CSYE 6225 ## Team Information | Name | NEU ID | Email Address | | --- | --- | --- | | Vivek Dalal|001430934|dalal.vi@husky.neu.edu | |Mansi Raghuwanshi|001888977|raghuwanshi.m@husky.neu.edu | |Gaurang Davda|001826203|davda.g@husky.neu.edu| |Karan Barai|001832013|barai.k@husky.neu.edu| ## Validate Template ``` packer validate centos-ami-template.json ``` ## Build AMI ``` packer build \ -var 'aws_region=us-east-1' \ -var 'subnet_id=REDACTED' \ centos-ami-template.json ```
namespace AngleSharp.Services { using System; /// <summary> /// Defines the methods to perform an integrity check. /// </summary> public interface IIntegrityProvider { /// <summary> /// Checks if the given content satisfies the provided integrity /// attribute. /// </summary> /// <param name="content">The content to hash.</param> /// <param name="integrity">The value of the integrity attribute.</param> /// <returns>True if integrity is preserved, otherwise false.</returns> Boolean IsSatisfied(Byte[] content, String integrity); } }
package com.zhangteng.baselibrary.mvp.model import com.zhangteng.mvp.base.BaseModel import com.zhangteng.baselibrary.mvp.model.imodel.IBaseMvpDemoFragmentModel class BaseMvpDemoFragmentModel : BaseModel(), IBaseMvpDemoFragmentModel
#!/bin/sh python launch.py --nproc_per_node=4 supervised.py dataset=cifar10
#!/usr/bin/env bash # start up autotest (rq) workers which are managed by supervisor source /home/vagrant/markus-autotesting/server/venv/bin/activate supervisord -c /home/vagrant/markus-autotesting/server/supervisord.conf deactivate
import * as React from "react"; import { inject, observer } from "mobx-react"; import GlobalStore from "../../shared/store/GlobalStore"; const styles = require("./styles/stats.less"); interface StatsProps { store?: GlobalStore; } interface StatsState {} @inject("store") @observer export default class Stats extends React.Component<StatsProps, StatsState> { private commitsCountSpan: React.ReactDOM; private starsCountSpan: React.ReactDOM; private followersCountSpan: React.ReactDOM; constructor(props) { super(props); } animate = (span, value) => { const easeOutQuart = (t, b, c, d) => { return -c * ((t = t / d - 1) * t * t * t - 1) + b; }; const time = { total: 4000, start: performance.now() }; const tick = now => { const elapsed = now - time.start; const progress = easeOutQuart(elapsed, 0, 1, time.total); span.textContent = Math.round(progress * value).toLocaleString(); if (elapsed < time.total) { window.requestAnimationFrame(tick); } }; window.requestAnimationFrame(tick); }; refCommitsCountSpan = span => { this.commitsCountSpan = span; this.starsCountSpan = span; this.followersCountSpan = span; }; refStarsCountSpan = span => { this.starsCountSpan = span; }; refFollowersCountSpan = span => { this.followersCountSpan = span; }; componentDidMount() { const store = this.props.store as GlobalStore; const { profile, totalStars, totalCommits } = store; this.animate(this.commitsCountSpan, totalCommits); this.animate(this.starsCountSpan, totalStars); this.animate(this.followersCountSpan, profile.basicProfile.followers); } render() { const store = this.props.store as GlobalStore; const { profile, totalStars, totalCommits } = store; return ( <div className={styles.wrapper}> <div className={styles.stat}> <span> <span className={styles.count} ref={this.refCommitsCountSpan}> {totalStars} </span>Commits submitted </span> </div> <div className={styles.stat}> <span> <span className={styles.count} ref={this.refStarsCountSpan}> {totalCommits} </span>Stars gained </span> </div> <div className={styles.stat}> <span> <span className={styles.count} ref={this.refFollowersCountSpan}> {profile.basicProfile.followers} </span>Followers got </span> </div> </div> ); } }
# frozen_string_literal: true module Dynamodb module Api module Relation class FilterClause # :nodoc: attr_reader :expression attr_reader :values attr_reader :reserved_words def initialize(expression, values) @expression = expression @values = values @reserved_words = extract_reserved_words(@expression) end private def extract_reserved_words(expression) expression.scan(/\#\w+/) end end end end end
cask 'stereo-tool' do version '8.54' sha256 'e2fa88bdaa32517adb8b515ff30f6e00fbfb9b09dfce9e69665c9d5ec9f53d57' url 'http://www.stereotool.com/download/stereo_tool.zip' appcast 'https://www.stereotool.com/documentation/8.50/version_history/', checkpoint: '0f9934dee6dd8cb0cdad1954156d743750b5b4000f0f2a67065d9fe87a10e0a8' name 'Stereo Tool' homepage 'https://www.stereotool.com/' app 'stereo_tool.app' end
package com.mapbox.search.utils.bitmap import android.graphics.Bitmap import android.util.Base64 import java.io.ByteArrayOutputStream import kotlin.math.min import kotlin.math.roundToInt /** * Helper function to encode Bitmap in Base64 String. Useful for sending screenshots * over Events SDK, which doesn't support Bitmap encoding out of the box. */ internal fun Bitmap.encodeBase64(encodeOptions: BitmapEncodeOptions): String { val (scaledWidth, scaledHeight) = if (width <= height) { val scaledWidth: Int = min(width, encodeOptions.minSideSize) val scaledHeight = ((scaledWidth.toFloat() / width) * height).roundToInt() scaledWidth to scaledHeight } else { val scaledHeight: Int = min(height, encodeOptions.minSideSize) val scaledWidth = ((scaledHeight.toFloat() / height) * width).roundToInt() scaledWidth to scaledHeight } val scaled = Bitmap.createScaledBitmap(this, scaledWidth, scaledHeight, true) val stream = ByteArrayOutputStream() scaled.compress(Bitmap.CompressFormat.JPEG, encodeOptions.compressQuality, stream) return Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT) ?: "" }
use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::marker::PhantomData; use super::*; use crate::opset::Opset; use crate::value::{Membership, Raw}; use crate::impl_fuzzy_expr_ops; /// Fuzzy value expression. #[derive(Clone, Copy)] pub struct ExprValue<S: Opset> { membership: Membership<S>, phantom: PhantomData<S> } impl<S: Opset> ExprValue<S> { /// Creates from raw value. Panics if it's not a valid membership. pub fn new(raw: Raw) -> Self { Self { membership: Membership::new(raw), phantom: PhantomData } } /// Creates from raw value. pub fn try_new(raw: Raw) -> Option<Self> { Membership::try_new(raw).map(|raw| { Self { membership: raw, phantom: PhantomData } }) } /// Creates from valid membership. pub fn from_membership(membership: Membership<S>) -> Self { Self { membership, phantom: PhantomData } } /// Changes into tagged value. pub fn with_tag<T>(self, tag: T) -> ExprTagged<S, T> { ExprTagged::from_unnamed(self, tag) } } impl<S: Opset> Debug for ExprValue<S> { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "ExprValue({:?})", self.membership.to_string()) } } impl<S: Opset> Display for ExprValue<S> { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "{}", self.membership.to_string()) } } impl<S: Opset> Expr<S> for ExprValue<S> { #[inline] fn to_value(&self) -> Membership<S> { self.membership } } impl_fuzzy_expr_ops! { ExprValue<S> }
// build.rs use std::{ env, path::Path, process::{exit, Command}, }; use which::which; const LIBPNG_URL: &str = "https://deac-fra.dl.sourceforge.net/project/libpng/libpng16/1.6.37/libpng-1.6.37.tar.xz"; fn build_dep_check(tools: &[&str]) { for tool in tools { println!("Checking for build tool {}...", tool); if let Ok(path) = which(tool) { println!("Found build tool {}", path.to_str().unwrap()) } else { println!("ERROR: missing build tool {}", tool); exit(1); }; } } fn main() { if cfg!(windows) { println!("cargo:warning=Skipping libpng frida example on Windows"); exit(0); } let out_dir = env::var_os("OUT_DIR").unwrap(); let cwd = env::current_dir().unwrap().to_string_lossy().to_string(); let out_dir = out_dir.to_string_lossy().to_string(); let out_dir_path = Path::new(&out_dir); std::fs::create_dir_all(&out_dir).unwrap_or_else(|_| panic!("Failed to create {}", &out_dir)); println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=../libfuzzer_runtime/rt.c",); println!("cargo:rerun-if-changed=harness.cc"); build_dep_check(&["clang", "clang++", "wget", "tar", "make"]); let libpng = format!("{}/libpng-1.6.37", &out_dir); let libpng_path = Path::new(&libpng); let libpng_tar = format!("{}/libpng-1.6.37.tar.xz", &cwd); // Enforce clang for its -fsanitize-coverage support. let clang = match env::var("CLANG_PATH") { Ok(path) => path, Err(_) => "clang".to_string(), }; let clangpp = format!("{}++", &clang); std::env::set_var("CC", &clang); std::env::set_var("CXX", &clangpp); let ldflags = match env::var("LDFLAGS") { Ok(val) => val, Err(_) => "".to_string(), }; // println!("cargo:warning=output path is {}", libpng); if !libpng_path.is_dir() { if !Path::new(&libpng_tar).is_file() { println!("cargo:warning=Libpng not found, downloading..."); // Download libpng Command::new("wget") .arg("-c") .arg(LIBPNG_URL) .arg("-O") .arg(&libpng_tar) .status() .unwrap(); } Command::new("tar") .current_dir(&out_dir_path) .arg("xvf") .arg(&libpng_tar) .status() .unwrap(); Command::new(format!("{}/configure", &libpng)) .current_dir(&libpng_path) .args(&[ "--disable-shared", &format!("--host={}", env::var("TARGET").unwrap())[..], ]) .env("CC", &clang) .env("CXX", &clangpp) .env( "CFLAGS", "-O3 -g -D_DEFAULT_SOURCE -fPIC -fno-omit-frame-pointer", ) .env( "CXXFLAGS", "-O3 -g -D_DEFAULT_SOURCE -fPIC -fno-omit-frame-pointer", ) .env( "LDFLAGS", //format!("-g -fPIE -fsanitize=address {}", ldflags), format!("-g -fPIE {}", ldflags), ) .status() .unwrap(); Command::new("make") .current_dir(&libpng_path) .status() .unwrap(); } let status = cc::Build::new() .cpp(true) .get_compiler() .to_command() .current_dir(&cwd) .arg("-I") .arg(&libpng) //.arg("-D") //.arg("HAS_DUMMY_CRASH=1") .arg("-fPIC") .arg("-shared") .arg("-O3") //.arg("-fomit-frame-pointer") .arg(if env::var("CARGO_CFG_TARGET_OS").unwrap() == "android" { "-static-libstdc++" } else { "" }) .arg("-o") .arg(format!("{}/libpng-harness.so", &out_dir)) .arg("./harness.cc") .arg(format!("{}/.libs/libpng16.a", &libpng)) .arg("-l") .arg("z") .status() .unwrap(); assert!(status.success()); }
package $organization$.config import com.tremorvideo.lib.feature.flags.{Debug, FeatureFlagsConfig, Observe} import com.tremorvideo.lib.kafka.producer.TremorKafkaProducerConfig import com.tremorvideo.lib.metrics.MetricsReporter case class AppConfig( http: HttpConfig, metrics: MetricsReporter, consulDynamicConfig: ConsulDynamicConfig, appName: String, dataCenter: String, debug: Debug, observe: Observe, grpcServerPort: Int, observableStaticConfigProducer: TremorKafkaProducerConfig, observableDynamicConfigProducer: TremorKafkaProducerConfig, mysqlConfig: MySqlConfig, verticaConfig: VerticaConfig ) extends FeatureFlagsConfig case class MySqlConfig(databaseConfig: DatabaseConfig) case class VerticaConfig(databaseConfig: DatabaseConfig) case class ConsulDynamicConfig( consulHostname: String, consulPort: Int ) case class HttpConfig( host: String, port: Int, healthEndPoint: String )
$('#password').pwstrength({ //Override the default values of the ../plugins/jquery.pwstrength.js texts: ['seriously?', 'soft', 'that\'s something', 'good', 'hardcore'] });
package consumeUser import ( "context" "fmt" "io" "math/rand" "sync" "time" "github.com/mrpiggy97/sharedProtofiles/user" ) func ConsumeRegisterUsers(waiter *sync.WaitGroup, client user.UserServiceClient) { waiter.Add(1) //get stream streamContext, cancelFunc := context.WithTimeout( context.Background(), time.Second*5, ) stream, streamError := client.RegisterUsers(streamContext) if streamError != nil { panic(streamError) } //make requests for i := 0; i < 100; i++ { var request *user.RegisterUserRequest = &user.RegisterUserRequest{ Username: fmt.Sprintf("%v username", i), Password: fmt.Sprintf("%v", rand.Int63()), } //make request var requestError error = stream.Send(request) if requestError != nil { panic(requestError) } } stream.CloseSend() //consume stream for { response, resError := stream.Recv() if resError != nil && resError != io.EOF { panic(resError) } if resError == io.EOF { fmt.Println("finished consuming service RegisterUsers") break } fmt.Println("register users service ", response.String()) } defer waiter.Done() defer cancelFunc() }
const NUMBER_OF_LETTERS_IN_ALPHABET = 26; class Pangram { constructor(private readonly text: string) {} isPangram(): boolean { return this.countUniqueLetters() === NUMBER_OF_LETTERS_IN_ALPHABET; } private countUniqueLetters(): number { return new Set(this.text.toLowerCase().match(/[a-z]/g)).size; } } export default Pangram;
#pragma once namespace performance { #pragma region Types namespace types { /// <summary> /// A string implementation. /// Unsigned __int8 size should be a positive number greater than 0. /// </summary> template <unsigned __int8 size> struct string8 { char Characters[size]; /// <summary> /// Gets the size of this string. /// </summary> /// <returns></returns> unsigned register __int8 Size() { return (sizeof(Characters) / sizeof(char)); } }; }; #pragma endregion };
--- title: 源代码窗格 description: 源代码窗格 ms.assetid: 2d4ee4da-1340-473b-83dc-018e1d6910eb keywords: - 窗格 WDK Static Driver Verifier ms.date: 04/20/2017 ms.localizationpriority: medium ms.openlocfilehash: ee6d4829abe776ef17e33f425af0c82ba24d4fff ms.sourcegitcommit: 0cc5051945559a242d941a6f2799d161d8eba2a7 ms.translationtype: MT ms.contentlocale: zh-CN ms.lasthandoff: 04/23/2019 ms.locfileid: "63378019" --- # <a name="source-code-pane"></a>源代码窗格 **源代码**窗格中显示所有涉及的源代码文件中检测规则冲突。 本部分包括: [了解源代码窗格](understanding-the-source-code-pane.md) [使用源代码窗格](using-the-source-code-pane.md) [源代码窗格操作](source-code-pane-actions.md) [源的代码窗格中的文件](files-in-the-source-code-pane.md) [在源代码窗格中的颜色编码](color-coding-in-the-source-code-pane.md)
#!/bin/bash RED="\033[31m" YELLOW="\033[33m" BLUE="\033[94m" GREEN="\033[32m" NO_COLOR="\033[0m" CWD="$(pwd)" echo "pwd=$CWD" # Create the repo cd /tmp reponame=$(date +gitlint-test-%Y-%m-%d_%H-%M-%S) git init $reponame cd $reponame # Do some basic config git config user.name gïtlint-test-user git config user.email gitlint@test.com git config core.quotePath false git config core.precomposeUnicode true # Add a test commit echo "tëst 123" > test.txt git add test.txt # commit -m -> use multiple -m args to add multiple paragraphs (/n in strings are ignored) git commit -m "test cömmit title" -m "test cömmit body that has a bit more text" cd $CWD # Let the user know echo "" echo -e "Created $GREEN/tmp/${reponame}$NO_COLOR" echo "Hit key up to access 'cd /tmp/$reponame'" echo "(Run this script using 'source' for this to work)" history -s "cd /tmp/$reponame"
#!/usr/bin/env bash set -e # Install command-line tools using Homebrew. # Make sure we’re using the latest Homebrew. brew update # Upgrade any already-installed formulae. brew upgrade # Install GNU core utilities (those that come with macOS are outdated). # Don’t forget to add `$(brew --prefix coreutils)/libexec/gnubin` to `$PATH`. brew install coreutils # Install Fish. # Note: don’t forget to add `/brew/bin/bash` to `/etc/shells` before # running `chsh`. brew install fish # Switch to using brew-installed bash as default shell if ! fgrep -q '/brew/bin/fish' /etc/shells; then echo '/brew/bin/fish' | sudo tee -a /etc/shells; chsh -s /brew/bin/fish; fi; brew install neovim brew install git brew install tree brew install fzf brew install ag brew install heroku brew install openssl brew install telnet brew install wget brew install fd brew install rbenv brew install awscli brew install postgresql brew install ccrypt brew install # Remove outdated versions from the cellar. brew cleanup
#!/bin/bash if [ -n "$(uname -m | grep aarch64)" ]; then IMAGE_TAG=vosk_aarch64 elif [ -n "$(uname -m | grep armv7l)" ]; then IMAGE_TAG=vosk_armv7l else # NOTE: x86 32bit build not supported atm IMAGE_TAG=vosk_amd64 fi sudo docker run --rm --name=sepia-stt-vosk -p 20741:20741 -it sepia/stt-server:$IMAGE_TAG /bin/bash #-v share:/home/admin/share
require 'spec_helper_acceptance' describe 'iis_virtual_directory' do before(:all) do # Remove 'Default Web Site' to start from a clean slate remove_all_sites @site_name = SecureRandom.hex(10) create_site(@site_name, true) end after(:all) do remove_all_sites end context 'when configuring a virtual directory' do context 'with default parameters' do before(:all) do @virt_dir_name = SecureRandom.hex(10).to_s @manifest = <<-HERE file{ 'c:/foo': ensure => 'directory' }-> file{ 'c:/foo2': ensure => 'directory' }-> iis_virtual_directory { '#{@virt_dir_name}': ensure => 'present', sitename => '#{@site_name}', physicalpath => 'c:\\foo' } HERE end it_behaves_like 'an idempotent resource' context 'when puppet resource is run' do before(:all) do @result = resource('iis_virtual_directory', @virt_dir_name) end puppet_resource_should_show('ensure', 'present') context 'when capitalization of paths change' do before(:all) do @manifest = <<-HERE iis_virtual_directory { '#{@virt_dir_name}': ensure => 'present', sitename => '#{@site_name}', # Change capitalization to see if it breaks idempotency physicalpath => 'c:\\Foo' } HERE end it 'runs with no changes' do execute_manifest(@manifest, catch_changes: true) end end end context 'when physical path changes' do before(:all) do @manifest = <<-HERE iis_virtual_directory { '#{@virt_dir_name}': ensure => 'present', sitename => '#{@site_name}', physicalpath => 'c:\\foo2' } HERE end it_behaves_like 'an idempotent resource' context 'when puppet resource is run' do before(:all) do @result = resource('iis_virtual_directory', @virt_dir_name) end puppet_resource_should_show('physicalpath', 'c:\\foo2') end end after(:all) do remove_vdir(@virt_dir_name) end end context 'with a password wrapped in Sensitive()' do if get_puppet_version.to_i < 5 skip 'is skipped due to version being lower than puppet 5' else before(:all) do @virt_dir_name = SecureRandom.hex(10).to_s @manifest = <<-HERE file{ 'c:/foo': ensure => 'directory' }-> iis_virtual_directory { '#{@virt_dir_name}': ensure => 'present', sitename => '#{@site_name}', physicalpath => 'c:\\foo', user_name => 'user', password => Sensitive('#@\\\'454sdf'), } HERE end it_behaves_like 'an idempotent resource' context 'when puppet resource is run' do before(:all) do @result = resource('iis_virtual_directory', @virt_dir_name) end puppet_resource_should_show('ensure', 'present') puppet_resource_should_show('user_name', 'user') puppet_resource_should_show('password', '#@\\\'454sdf') end after(:all) do remove_vdir(@virt_dir_name) end end end context 'can remove virtual directory' do before(:all) do @virt_dir_name = SecureRandom.hex(10).to_s create_path('c:/foo') create_vdir(@virt_dir_name, 'foo', 'c:/foo') @manifest = <<-HERE iis_virtual_directory { '#{@virt_dir_name}': ensure => 'absent' } HERE end it_behaves_like 'an idempotent resource' context 'when puppet resource is run' do before(:all) do @result = resource('iis_virtual_directory', @virt_dir_name) end puppet_resource_should_show('ensure', 'absent') end after(:all) do remove_vdir(@virt_dir_name) end end context 'name allows slashes' do context 'simple case' do before(:all) do @virt_dir_name = SecureRandom.hex(10).to_s create_path('c:\inetpub\test_site') create_path('c:\inetpub\test_vdir') create_path('c:\inetpub\deeper') create_site(@site_name, true) @manifest = <<-HERE iis_virtual_directory{ "test_vdir": ensure => 'present', sitename => "#{@site_name}", physicalpath => 'c:\\inetpub\\test_vdir', }-> iis_virtual_directory { 'test_vdir\deeper': name => 'test_vdir\deeper', ensure => 'present', sitename => '#{@site_name}', physicalpath => 'c:\\inetpub\\deeper', } HERE end it_behaves_like 'an idempotent resource' after(:all) do remove_vdir(@virt_dir_name) end end end context 'with invalid' do context 'physicalpath parameter defined' do before(:all) do @virt_dir_name = SecureRandom.hex(10).to_s @manifest = <<-HERE iis_virtual_directory { '#{@virt_dir_name}': ensure => 'present', sitename => '#{@site_name}', physicalpath => 'c:\\wakka' } HERE end it_behaves_like 'a failing manifest' context 'when puppet resource is run' do before(:all) do @result = resource('iis_virtual_directory', @virt_dir_name) end puppet_resource_should_show('ensure', 'absent') end after(:all) do remove_vdir(@virt_dir_name) end end context 'physicalpath parameter not defined' do before(:all) do @virt_dir_name = SecureRandom.hex(10).to_s @manifest = <<-HERE iis_virtual_directory { '#{@virt_dir_name}': ensure => 'present', sitename => '#{@site_name}' } HERE end it_behaves_like 'a failing manifest' context 'when puppet resource is run' do before(:all) do @result = resource('iis_virtual_directory', @virt_dir_name) end puppet_resource_should_show('ensure', 'absent') end after(:all) do remove_vdir(@virt_dir_name) end end end end end
/// <reference path="../refs.d.ts" /> var fpxt; (function (fpxt) { (function (forms) { var Facebook = (function () { function Facebook() { this.extId = 'FACEBOOK'; } Facebook.prototype.setup = function (baseApiUrl, authKeys, objParams, onCompleted) { onCompleted(); }; Facebook.prototype.setupAuthPre = function (baseApiUrl, authKeys, objParams, onCompleted) { onCompleted(); }; Facebook.prototype.setupAuthPost = function (baseApiUrl, authKeys, objParams, onCompleted) { if ($('#txtFacebookAppId').val() != '' && $('#txtFacebookAppSecret').val() != '') { var bswitch = $('#chkFacebookOauthOption'); bswitch.bootstrapSwitch('toggleState'); } onCompleted(); }; Facebook.prototype.fill = function (baseApiUrl, authKeys, values) { $("#txtEventParamFacebookStatus").val(''); if (values == null) return; values.forEach(function (p) { switch (p.key) { case 'facebookstatus': $("#txtEventParamFacebookStatus").val(p.value); break; } }); }; Facebook.prototype.getProperties = function () { if ($("#txtEventParamFacebookStatus").val() == "") throw "Facebook status is required."; var ret = []; ret.push({ key: "facebookstatus", value: $("#txtEventParamFacebookStatus").val() }); return ret; }; return Facebook; })(); forms.Facebook = Facebook; })(fpxt.forms || (fpxt.forms = {})); var forms = fpxt.forms; })(fpxt || (fpxt = {})); //# sourceMappingURL=facebook.js.map
import React, { Component } from "react"; import PropTypes from "prop-types"; import { StaticQuery, graphql } from "gatsby"; import { scaleOrdinal } from "d3-scale"; import { withCaption, SelectProvider, SliderProvider } from "providers"; import { Legend, NarrowContainer, PieChart } from "story_components"; import COLORS from "utils/styles"; import { selectType, sliderType } from "utils/types"; class PureVotingPollWorkerAge extends Component { render() { const { data, selectOptions, sliderData, keyLabels, colorScale } = this.props; return ( <SliderProvider initialData={sliderData} fullWidthAt="medium" width="60%" render={([curYear]) => ( <SelectProvider width="100%" options={selectOptions} initialIndex={2} margin="0.75rem 0" render={([currentOption]) => { const { ages, year, state } = data.find( d => d.year === curYear && d.state === currentOption.label ); return ages.some(age => age > 0) ? ( <React.Fragment> <Legend title="Poll worker ages (years)" labels={colorScale .range() .map((color, i) => ({ color, text: keyLabels[i] }))} /> <NarrowContainer width="70%" fullWidthAt="medium"> <PieChart colorScale={colorScale} values={ages} textFill={COLORS.BLACK} /> </NarrowContainer> </React.Fragment> ) : ( <React.Fragment> <h4> No data available for {state} in {year}. </h4> <p>Please make another selection.</p> </React.Fragment> ); }} /> )} /> ); } } class VotingPollWorkerAge extends Component { cleanQuery = data => { return data.allVotingData20082016Csv.edges.map(({ node }) => ({ year: +node.year, state: node.state, num_jurisdictions: +node.num_jurisdictions, jurisdictions_with_age_info: +node.jurisdictions_with_age_info, poll_workers: +node.poll_workers, ages: [ +node.worker_age_group_1, +node.worker_age_group_2, +node.worker_age_group_3, +node.worker_age_group_4, +node.worker_age_group_5, +node.worker_age_group_6 ] })); }; getStateOptions = data => { const statesSet = new Set( data.allVotingData20082016Csv.edges.map(({ node }) => node.state) ); const options = Array.from(statesSet, (s, idx) => ({ label: s, value: idx })); return options; }; render() { return ( <StaticQuery query={query} render={data => ( <PureVotingPollWorkerAge data={this.cleanQuery(data)} selectOptions={[this.getStateOptions(data)]} /> )} /> ); } } PureVotingPollWorkerAge.propTypes = { colorScale: PropTypes.func.isRequired, data: PropTypes.arrayOf(PropTypes.object).isRequired, keyLabels: PropTypes.arrayOf(PropTypes.string).isRequired, sliderData: sliderType, selectOptions: selectType }; const MIN_YEAR = 2010; const MAX_YEAR = 2016; const STEP = 2; PureVotingPollWorkerAge.defaultProps = { colorScale: scaleOrdinal().range([ COLORS.RED, COLORS.ORANGE, COLORS.YELLOW, COLORS.GREEN, COLORS.BLUE, COLORS.PURPLE ]), data: [], keyLabels: ["<18", "18-25", "26-40", "41-60", "61-70", ">70"], sliderData: [ { min: MIN_YEAR, max: MAX_YEAR, step: STEP, initialValue: MIN_YEAR, color: COLORS.DARK_GRAY, tickCount: Math.round((MAX_YEAR - MIN_YEAR) / STEP) + 1, title: year => `Year: ${year}` } ], selectOptions: [] }; const query = graphql` query { allVotingData20082016Csv { edges { node { year state num_jurisdictions jurisdictions_with_age_info poll_workers worker_age_group_1 worker_age_group_2 worker_age_group_3 worker_age_group_4 worker_age_group_5 worker_age_group_6 } } } } `; export default withCaption(VotingPollWorkerAge); export { PureVotingPollWorkerAge };
/** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #pragma once #include <flashlight/flashlight.h> #include "libraries/common/Dictionary.h" #include "libraries/lm/LM.h" namespace w2l { struct ConvLMState { std::vector<int> tokens; int length; ConvLMState() : length(0) {} explicit ConvLMState(int size) : tokens(std::vector<int>(size)), length(size) {} }; class ConvLM : public LM { public: ConvLM( const std::string& modelPath, const std::string& tokenVocabPath, const Dictionary& usrTknDict, int lmMemory = 10000, int beamSize = 2500, int historySize = 49); LMStatePtr start(bool startWithNothing) override; std::pair<LMStatePtr, float> score( const LMStatePtr& state, const int usrTokenIdx) override; std::pair<LMStatePtr, float> finish(const LMStatePtr& state) override; int compareState(const LMStatePtr& state1, const LMStatePtr& state2) const override; void updateCache(std::vector<LMStatePtr> states) override; private: // This cache is also not thread-safe! int lmMemory_; int beamSize_; std::unordered_map<ConvLMState*, int> cacheIndices_; std::vector<std::vector<float>> cache_; std::vector<ConvLMState*> slot_; std::vector<int> batchedTokens_; Dictionary vocab_; std::shared_ptr<fl::Module> network_; int vocabSize_; int maxHistorySize_; std::vector<std::vector<float>> getLogProb( const std::vector<int>& input, const std::vector<int>& lastTokenPositions, int sampleSize = -1, int batchSize = 1); static ConvLMState* getRawState(const LMStatePtr& state); std::pair<LMStatePtr, float> scoreWithLmIdx( const LMStatePtr& state, const int tokenIdx); }; } // namespace w2l
This document contains information about how to create packages for debian and centos. But make sure you follow the [preparation steps](../devel/environment.md#prepare-the-environment) as packaging depends on that. After you create the package it is available at ``/leela/pkg/dist``. You can change using the ``distroot`` variable. # CLIENT LIBRARIES ## LIBLEELA Debian packages: ```.shell debian7.amd64 $ make -C /leela/pkg libleela.debian dist=debian7 arch=amd64 debian7.amd64 $ ls -1 /leela/pkg/dist/debian7/{arch}/libleela/ libleela-dev_{version}_{arch}.deb libleela_{version}.dsc libleela_{version}.tar.gz libleela_{version}_{arch}.changes libleela_{version}_{arch}.deb ``` Centos packages: ```.shell centos6.amd64 $ make -C /leela/pkg libleela.centos dist=centos6 arch=amd64 centos6.amd64 $ ls -1 /leela/pkg/dist/centos6/{arch}/libleela/ libleela-{version}.src.rpm libleela-{version}.{arch}.rpm libleela-devel-{version}.{arch}.rpm ``` ## LIBLEELA-PYTHON It requires ``libleela-devel`` installed to build properly. Debian packages: ```.bash debian7.amd64 $ gdebi /leela/pkg/dist/debian7/{arch}/libleela/libleela_*.deb debian7.amd64 $ gdebi /leela/pkg/dist/debian7/{arch}/libleela/libleela-dev_*.deb debian7.amd64 $ make -C /leela/pkg libleela-python.debian dist=debian7 arch=amd64 ``` Centos packages: ```.bash centos7.amd64 $ yum install /leela/pkg/dist/centos6/{arch}/libleela/libleela*.rpm centos7.amd64 $ make -C /leela/pkg libleela-python.centos dist=centos6 arch=amd64 centos7.amd64 $ ls -1 /leela/pkg/dist/centos6/{arch}/libleela-python libleela-python-{version}.src.rpm libleela-python-{version}.{arch}.rpm ``` ## LIBLEELA-RUBY There is no package. Users should install use the gem `leela_ruby`. The gem is at `src/libs/ruby/leela_ruby`. # CORE MODULES # BLACKBOX It requires ``libleela-devel`` installed to build properly and only debian packages are defined. ```.bash debian7.amd64 $ gdebi /leela/pkg/dist/debian7/{arch}/libleela/libleela_*.deb debian7.amd64 $ gdebi /leela/pkg/dist/debian7/{arch}/libleela/libleela-dev_*.deb debian7.amd64 $ make -C /leela/pkg leela-blackbox.debian dist=debian7 arch=amd64 ``` # FRONTEND ## WARPDRIVE It requires ``libleela-devel`` installed to build properly and only debian packages are defined. ```.bash debian7.amd64 $ gdebi /leela/pkg/dist/debian7/{arch}/libleela/libleela_*.deb debian7.amd64 $ gdebi /leela/pkg/dist/debian7/{arch}/libleela/libleela-dev_*.deb debian7.amd64 $ make -C /leela/pkg leela-warpdrive.debian dist=debian7 arch=amd64 debian7.amd64 $ ls -1 /leela/pkg/dist/debian7/amd64/leela-warpdrive/ leela-warpdrive_{version}.dsc leela-warpdrive_{version}.tar.gz leela-warpdrive_{version}_{arch}.changes leela-warpdrive_{version}_{arch}.deb ```
/// # Recoverable Errors with `Result` /// /// Most errors aren't serious enough to require the program to stop entirely. /// Sometimes, when a function fails, it's for a reason /// that you can easily interpret and respond to. /// For example, if you try to open a file and that operation falis /// because the file dosen't exist, you might want to create /// the file instead of terminating the process. /// /// The `Result` enum is defined as having two variants, /// -> `Ok` and `Err`, as follows: /// /// ``` /// emun Result<T, E> { /// Ok(T), /// Err(E), /// } /// ``` /// /// Where the `T` and `E` are generic type parameters. /// T: the type of the value that will be returned /// in a success case within the `Ok` variant /// E: the type of the erro that will be returned /// in a failure case within the `Err` variant use std::fs::File; use std::io::ErrorKind; fn main() { // 1. Let’s call a function that returns a Result value // because the function could fail. let f = File::open("hello.txt"); let f = match f { Ok(file) => file, //Err(error) => { // panic!("There was a problem opening the file: {:?}", error); //}, // Matching on Different Errors Err(error) => match error.kind() { ErrorKind::NotFound => match File::create("hello.txt") { Ok(fc) => fc, Err(e) => panic!("Tried to create file but there was a problem: {:?}", e), }, other_error => panic!("There was a problem opening the file: {:?}", other_error), }, }; // 2. `unwrap` and `expect` // 2-1. `unwrap`: // Is a shortcut method that is implemented just like the `match` expression // If the `Result` value is the ok variant, `unwrap` will return the value inside the `ok`. // If the `Result` is the Err variant, `unwrap` will call the `panic!` macro for us. //let f = File::open("hello2.txt").unwrap(); // 2-2. `expect`\ // Let us also choose the `panic!` error message. let f = File::open("hello3.txt").expect("Falied to open hello3.txt"); }
from src.internal.adapters.local_player import LocalPlayer from src.internal.app.interfaces.query_handler import QueryHandler class GetSkippedSongsHandler(QueryHandler): """ Returns all not-played songs from current playlist for refund """ player: LocalPlayer def __init__(self, local_player: LocalPlayer, **_kwargs): self.player = local_player def QueryName(self) -> str: return "GetSkippedSongs" def Execute(self) -> any: return self.player.SkippedSongs()
module API module V1 class Test < Grape::API resource 'test' do desc 'test GET method' get 'hello' do 'hello from Discounty GET' end desc 'test POST method' post 'hello' do 'hello from Discounty POST' end end end end end
main = do print (celToFahr 40) celToFahr :: Float -> Float celToFahr c = c * (9/5) + 32
package views import ( "html/template" "os" "path/filepath" "strings" ) type tplCache struct { tpl *template.Template err error } type file struct { viewExt string root string files map[string][]string } func (vf *file) visit(paths string, f os.FileInfo, err error) error { if f == nil { return err } if f.IsDir() || (f.Mode()&os.ModeSymlink) > 0 { return nil } if !strings.HasSuffix(strings.ToLower(paths), vf.viewExt) { return nil } replace := strings.NewReplacer("\\", "/") a := []byte(paths) a = a[len(vf.root):] file := strings.TrimLeft(replace.Replace(string(a)), "/") subDir := filepath.Dir(file) if _, ok := vf.files[subDir]; ok { vf.files[subDir] = append(vf.files[subDir], file) } else { m := make([]string, 1) m[0] = file vf.files[subDir] = m } return nil }
import styled from 'styled-components'; export const Title = styled.h1` color: #f00; background: #000; font-size: ${props => `${props.fontSize}px`}; span{ font-size: 12px; }; `; export const TitleSmall = styled(Title)` color: #00F; font-size: 16px `;
C @(#)swpanl.f 20.3 2/13/96 subroutine swpanl (m,n) include 'ipfinc/parametr.inc' include 'ipfinc/anlys.inc' save C entry swapan (m,n) kps = lstown(m) lstown(m) = lstown(n) lstown(n) = kps return entry swpan2 (m,n) kps = lstvlt(m) lstvlt(m) = lstvlt(n) lstvlt(n) = kps return end
from mayavi import mlab import numpy as np from scipy.special import sph_harm import os # Create a sphere r = 0.75 pi = np.pi cos = np.cos sin = np.sin phi, theta = np.mgrid[0:pi:101j, 0:2*pi:101j] x = r * sin(phi) * cos(theta) y = r * sin(phi) * sin(theta) z = r * cos(phi) mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 400)) mlab.clf() for l in range(0, 6): for m in range(-l, l+1): if m == 0: s = sph_harm(m, l, theta, phi).real if m > 0: s = np.sqrt(2)*((-1)**m)*(sph_harm(m, l, theta, phi).real) if m < 0: s = np.sqrt(2)*((-1)**m)*(sph_harm(np.abs(m), l, theta, phi).imag) n = s.clip(max=0) p = s.clip(min=0)*(-1) mlab.mesh(p*x - m, p*z - 1.5*l, p*y, color=(1, 0, 0), representation='surface') mlab.mesh(n*x - m, n*z - 1.5*l, n*y, color=(0, 0, 1), representation='surface') mlab.view(azimuth=0, elevation=0, distance=20, focalpoint=None, roll=None, reset_roll=True, figure=None) #mlab.show() mlab.savefig('picture.png', magnification=10)
package xyz.akko.yandroid.util.bean import java.io.Serializable data class YanderImgInfo( val actual_preview_height: Int, val actual_preview_width: Int, val approver_id: Any, val author: String, val change: Int, val created_at: Int, val creator_id: Int, val file_ext: String, val file_size: Int, val file_url: String, val frames: List<Any>, val frames_pending: List<Any>, val frames_pending_string: String, val frames_string: String, val has_children: Boolean, val height: Int, val id: Int, val is_held: Boolean, val is_note_locked: Boolean, val is_pending: Boolean, val is_rating_locked: Boolean, val is_shown_in_index: Boolean, val jpeg_file_size: Int, val jpeg_height: Int, val jpeg_url: String, val jpeg_width: Int, val last_commented_at: Int, val last_noted_at: Int, val md5: String, val parent_id: Int, val preview_height: Int, val preview_url: String, val preview_width: Int, val rating: String, val sample_file_size: Int, val sample_height: Int, val sample_url: String, val sample_width: Int, val score: Int, val source: String, val status: String, val tags: String, val updated_at: Int, val width: Int ):Serializable
#!/bin/sh set -e rm -fr build mkdir build cd build dependency_root="/Users/huangck/Documents/Work/CSR/2019-ER/ThirdPartyLibraries" pybind_root="${dependency_root}/pybind11_install" portage_root="${dependency_root}/Portage_install" thrust_root="${dependency_root}/Thrust/thrust" kokkos_root="${dependency_root}/Kokkos_install" cmake -Wno-dev \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_CXX_FLAGS="-lutil" \ -DCMAKE_CXX_COMPILER=clang++ \ -DENABLE_THRUST=True \ -DPORTAGE_DIR="${portage_root}" \ -DKokkos_DIR="${kokkos_root}" \ -DTHRUST_DIR="${thrust_root}" \ -Dpybind11_DIR="${pybind_root}" \ .. gmake VERBOSE=1
#!/bin/bash install_shottr() { brew_install_app "Shottr" "shottr" }
# QUICK START git clone https://github.com/justinbodnar/stocktuna.git cd stocktuna pip3 install -r requirements.txt wget https://stocktuna.com/datasets/kaggle-stock-etf-dataset.zip unzip kaggle-stock-etf-dataset.zip rm kaggle-stock-etf-dataset.zip mkdir models mkdir datasets python3 cli-menu.py OR pydoc3 stocktuna # CLI MENU OPTIONS 1. Create new data sets 2. Extend data set 3. List and analyze available data sets 4. Train a model on a data set 5. View a random data point and tag 6. Graph a random data point and tag (uses MatPlotLib) 6. Watch model make 10,000 predictions # MORE INFORMATION Read DATA.md for information about how the data is structured
// @alwaysStrict: true // @outFile: out.js // @fileName: a.ts module M { export function f() { var arguments = []; } } // @fileName: b.ts module M { export function f2() { var arguments = []; } }
package net.openid.appauthdemo.network import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import rx.Observable class NetworkClient { private val apiService: ApiService init { val baseUrl = "https://api.is74.ru" val httpLoggingInterceptor = HttpLoggingInterceptor() httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY val client = OkHttpClient.Builder() .addInterceptor(httpLoggingInterceptor) .build() val retrofit = Retrofit.Builder() .baseUrl(baseUrl) .client(client) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() apiService = retrofit.create(ApiService::class.java) } fun domofons(bearerToken: String): Observable<List<IntercomModel>> { return apiService.domofons(bearerToken) } fun openDomofon(id: Long, bearerToken: String): Observable<OpenIntercomStatus> { return apiService.openIntercom(id, bearerToken) } }
require 'app/lib/ebb.rb' $gtk.reset def tick args $e ||= Ebb.new $e.tick text_examples = [] line_examples = [] sprite_examples = [] text_examples << "blink: #{$e.blink}" text_examples << "blink(10): #{$e.blink(10)}" text_examples << "blink(20, 60): #{$e.blink(20, 60)}" $e.blink(100) do |on| text_examples << "blink with a block: #{on ? 'on' : 'off'}" end ## All float examples are rounded text_examples << "" text_examples << "wave: #{'%.2f' % $e.wave}" text_examples << "wave(0, 100, 240): #{'%.0f' % $e.wave(0, 100, 500)}" text_examples << "wave(0, 100, 240, :cos): #{'%.0f' % $e.wave(0, 100, 500, :cos)}" text_examples << "bounce: #{'%.2f' % $e.bounce}" text_examples << "" text_examples << "5 frames @ 1fps: #{ $e.frames([ "frame one", "frame two", "frame three", "frame four", "frame five" ], 1) }" text_examples << "5 frames @ 5fps: #{ $e.frames([ "frame one", "frame two", "frame three", "frame four", "frame five" ], 5) }" text_examples << "" text_examples << "reset transitions with spacebar" reset = args.inputs.keyboard.key_down.space text_examples << "transition: #{'%.2f' % $e.transition(:foo, 0, 1, 60, reset)}" text_examples << "transition(0,100,100): #{'%.0f' % $e.transition(:foo_2, 0, 100, 100, reset)}" line_examples << ["wave(0,200)", $e.wave(0, 200)] bounce = $e.bounce(0, 200) line_examples << ["b = bounce(0,200)", bounce ] delayed_bounce = $e.delay(:bounce, bounce, 100) line_examples << ["delay(:bounce, b, 100)", delayed_bounce] $e.delay(:bounce_2, bounce, 50) do |delayed| line_examples << ["delay(:bounce_b, b, 50) do...", delayed] end line_examples << ["fps(:bounce, b, 5)", $e.fps(:bounce, bounce, 5)] ## Sprite/combined examples # Orbit orbit_target = args.render_target(:orbit) orbit_x = $e.wave(0, 85, 60, :sin) orbit_y = $e.wave(0, 85, 60, :cos) orbit_target.solids << [orbit_x + 5, orbit_y + 5, 5, 5] $e.delay(:orbit_follower, [orbit_x,orbit_y], 3) do |delayed_coordinates| dx, dy = delayed_coordinates orbit_target.solids << [dx + 5, dy + 5, 5, 5, # 3fps loop of colors *$e.frames([[255, 0, 0], [0, 255, 0], [0, 0, 255] ], 3) ] end sprite_examples << ["'orbit' w/ delayed follower", :orbit] # Wave shot wave_shot_target = args.render_target(:wave_shot) wave_x = $e.transition(:wave_shot, 0, 200, 120, reset) $e.transition(:wave_height, 95, 5, 120, reset) do |height| wave_y = $e.bounce(0, height, 60) wave_shot_target.solids << [wave_x, wave_y, 5, 5] end sprite_examples << ["'bounce' (space to reset)", :wave_shot] 3 ### Render the examples line_examples.each_with_index do |example, i| args.outputs.solids << [ 500, 700 - i*60, example[1], 5, 20, 20, 20] args.outputs.labels << [ 500, 700 - i*60 - 3, example[0], 20, 20, 20] end text_examples.each_with_index do |example, i| args.outputs.labels << [ 10, 700 - i*20, example, 20, 20, 20] end sprite_examples.each_with_index do |example, i| args.outputs.borders << [ 950, 700 - (i+1)*200, 200, 100] args.outputs.sprites << { x: 950, y: 700 - (i+1)*200, w: 200, h: 100, path: example[1], source_x: 0, source_y: 0, source_w: 200, source_h: 100 } args.outputs.labels << [ 950, 700 - (i+1)*200 - 20, example[0], 20, 20, 20] end end
extern crate card_validate; use card_validate::{Validate, ValidateError}; fn visaelectron_numbers_valid() -> Vec<&'static str> { vec!["4917300800000000"] } fn maestro_numbers_valid() -> Vec<&'static str> { vec!["6759649826438453"] } fn forbrugsforeningen_numbers_valid() -> Vec<&'static str> { vec!["6007220000000004"] } fn dankort_numbers_valid() -> Vec<&'static str> { vec!["5019717010103742"] } fn visa_numbers_valid() -> Vec<&'static str> { vec![ "4539571147647251", "4532983409238819", "4485600412608021", "4916252910064718", "4916738103790259", ] } fn amex_numbers_valid() -> Vec<&'static str> { vec![ "343380440754432", "377156543570043", "340173808718013", "375801706141502", "372728319416034", ] } fn mastercard_numbers_valid() -> Vec<&'static str> { vec![ "5236313877109142", "5431604665471808", "5571788302926264", "5411516521560216", "5320524083396284", ] } fn discover_numbers_valid() -> Vec<&'static str> { vec![ "6011297718292606", "6011993225918523", "6011420510510997", "6011618637473995", "6011786207277235", ] } fn jcb_numbers_valid() -> Vec<&'static str> { vec!["3530111333300000", "3566002020360505"] } fn unionpay_numbers_valid() -> Vec<&'static str> { vec![ "6271136264806203568", "6236265930072952775", "6204679475679144515", "6216657720782466507", ] } fn dinersclub_numbers_valid() -> Vec<&'static str> { vec![ "30569309025904", "38520000023237", "36700102000000", "36148900647913", ] } fn gibberish_numbers_invalid() -> Vec<&'static str> { vec!["zduhehiudIHZHIUZHUI", "0292DYYEFYFEFYEFEFIUH"] } fn unknown_numbers_invalid() -> Vec<&'static str> { vec!["00002837743671762", "1136283774"] } fn known_numbers_invalid() -> Vec<&'static str> { vec!["424242424", "4242424242424244242424242", "523631387710914"] } fn numbers_invalid_luhn() -> Vec<&'static str> { vec!["5236313877109141", "6011420510510995"] } fn valid_mixture() -> Vec<&'static str> { let card_types = vec![ visaelectron_numbers_valid(), maestro_numbers_valid(), forbrugsforeningen_numbers_valid(), dankort_numbers_valid(), visa_numbers_valid(), amex_numbers_valid(), mastercard_numbers_valid(), discover_numbers_valid(), jcb_numbers_valid(), unionpay_numbers_valid(), dinersclub_numbers_valid(), ]; let mut mixture = Vec::new(); for card_type in card_types { for number in card_type { mixture.push(number); } } mixture } #[test] fn valid_card() { for number in valid_mixture() { assert_eq!(Validate::from(number).is_ok(), true); } } #[test] fn gibberish_invalid() { for number in gibberish_numbers_invalid() { assert_eq!( Validate::from(number) == Err(ValidateError::InvalidFormat), true ); } } #[test] fn unknown_invalid() { for number in unknown_numbers_invalid() { assert_eq!( Validate::from(number) == Err(ValidateError::UnknownType), true ); } } #[test] fn known_invalid() { for number in known_numbers_invalid() { assert_eq!( Validate::from(number) == Err(ValidateError::InvalidLength), true ); } } #[test] fn invalid_luhn() { for number in numbers_invalid_luhn() { assert_eq!( Validate::from(number) == Err(ValidateError::InvalidLuhn), true ); } } #[test] fn correct_visaelectron_card_name() { for number in visaelectron_numbers_valid() { let result = Validate::from(number).unwrap(); assert_eq!(result.card_type.name(), "visaelectron".to_string()); } } #[test] fn correct_maestro_card_name() { for number in maestro_numbers_valid() { let result = Validate::from(number).unwrap(); assert_eq!(result.card_type.name(), "maestro".to_string()); } } #[test] fn correct_forbrugsforeningen_card_name() { for number in forbrugsforeningen_numbers_valid() { let result = Validate::from(number).unwrap(); assert_eq!(result.card_type.name(), "forbrugsforeningen".to_string()); } } #[test] fn correct_dankort_card_name() { for number in dankort_numbers_valid() { let result = Validate::from(number).unwrap(); assert_eq!(result.card_type.name(), "dankort".to_string()); } } #[test] fn correct_visa_card_name() { for number in visa_numbers_valid() { let result = Validate::from(number).unwrap(); assert_eq!(result.card_type.name(), "visa".to_string()); } } #[test] fn correct_amex_card_name() { for number in amex_numbers_valid() { let result = Validate::from(number).unwrap(); assert_eq!(result.card_type.name(), "amex".to_string()); } } #[test] fn correct_mastercard_card_name() { for number in mastercard_numbers_valid() { let result = Validate::from(number).unwrap(); assert_eq!(result.card_type.name(), "mastercard".to_string()); } } #[test] fn correct_discover_card_name() { for number in discover_numbers_valid() { let result = Validate::from(number).unwrap(); assert_eq!(result.card_type.name(), "discover".to_string()); } } #[test] fn correct_jcb_card_name() { for number in jcb_numbers_valid() { let result = Validate::from(number).unwrap(); assert_eq!(result.card_type.name(), "jcb".to_string()); } } #[test] fn correct_unionpay_card_name() { for number in unionpay_numbers_valid() { let result = Validate::from(number).unwrap(); assert_eq!(result.card_type.name(), "unionpay".to_string()); } } #[test] fn correct_dinersclub_card_name() { for number in dinersclub_numbers_valid() { let result = Validate::from(number).unwrap(); assert_eq!(result.card_type.name(), "dinersclub".to_string()); } }
# daMi 使用 Vue + element-ui + Nodejs + MongoDB 仿小米官网
<?php $user = must_be_connected(); local_action($user); $fw->smarty->assign('menu_actif',"ballot-list"); $fw->include_css('ballot-list'); $fw->add_js('popper.min.js'); $fw->add_js('../plugins/sweetalert2/sweetalert2.min.js'); project_css_js($fw); $fw->include_js('ballot-list'); $fw->set_canonical('/ballot-list'); $fw->smarty->assign('ballot_list',sql($sql = " SELECT bal_ballot.*, ask_asker.*, bal_status.bstatus_lib, NOW() > ballot_start AS ballot_started, NOW() > ballot_start + INTERVAL ballot_duration_second SECOND AS ballot_finished, NOW() > ballot_start AND NOW() < ballot_start + INTERVAL ballot_duration_second SECOND AS ballot_running, DATE_FORMAT(ballot_start,'%d/%m/%Y %H:%i') AS ballot_start_fr, DATE_FORMAT(ballot_start + INTERVAL ballot_duration_second SECOND,'%d/%m/%Y %H:%i') AS ballot_end_fr, COUNT(DISTINCT question_id) AS nb_question, COUNT(DISTINCT vote_user_id) AS participation FROM bal_ballot INNER JOIN ask_asker ON ballot_asker_id = asker_id AND asker_active = '1' LEFT JOIN bal_status ON bstatus_id = ballot_bstatus_id LEFT JOIN bal_question ON question_ballot_id = ballot_id AND question_active = '1' LEFT JOIN bal_option ON option_question_id = question_id AND option_active = '1' LEFT JOIN vot_vote ON vote_option_id = option_id AND vote_active = '1' WHERE asker_user_id = '".for_db($user['user_id'])."' AND ballot_active = '1' GROUP BY ballot_id ORDER BY ballot_start DESC ")); $fw->smarty->display('ballot-list.tpl'); $fw->go(); function local_action($user){ if(gpost("action")=="delete_ballot"){ $delete_id = null; $res = [ "status" => "success", "message" => [] ]; if(!post_exists("ballot_id")){ $res["message"][] = "Impossible d'identifier la consultation"; }else{ $ballot_id = gpost("ballot_id"); $delete_id = $ballot_id; if(!is_numeric($ballot_id) || $ballot_id<=0){ $res["message"][] = "Impossible d'identifier la consultation"; }else{ $ballot_nb = intval(sql_unique(" SELECT COUNT(*) AS nb FROM bal_ballot INNER JOIN ask_asker ON asker_id = ballot_asker_id AND asker_active = '1' WHERE ballot_id = '".for_db($ballot_id)."' AND asker_user_id = '".for_db($user["user_id"])."' AND ballot_active = '1' ")); if($ballot_nb<=0){ $res["message"][] = "Opération impossible"; } } } if(count($res["message"])==0){ if(!is_null($delete_id) && is_numeric($delete_id) && $delete_id>0) { cp_delete_ballot($delete_id); } }else{ $res["status"] = "error"; } echo json_encode($res); exit(); } } ?>
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Open.Serialization.Json.Newtonsoft { public static class CamelCaseJson { public static JsonSerializerSettings Default(bool indent = false) { var options = RelaxedJson.Options(indent); options.ContractResolver = new CamelCasePropertyNamesContractResolver() { NamingStrategy = new CamelCaseNamingStrategy() { ProcessDictionaryKeys = false } }; return options; } public static JsonSerializerSettings Minimal(bool indent = false) { var options = Default(indent); options.NullValueHandling = NullValueHandling.Ignore; return options; } } }
require "spec_helper" RSpec.describe MarketplaceLandingPageController, type: :request do before(:each) do @community = FactoryGirl.create(:community) @user = create_admin_for(@community) @user.update(is_admin: true) end describe 'GET /' do it 'user not logged in' do get('/', headers: {host: "#{@community.ident}.lvh.me"}) expect(request).to render_template(:show) end it 'user logged in' do login_user(@user) get('/', headers: {host: "#{@community.ident}.lvh.me"}) expect(request).to redirect_to(homepage_without_locale_path) end end describe 'GET /landing-page' do it 'successful request' do get('/landing-page', headers: {host: "#{@community.ident}.lvh.me"}) expect(request).to render_template(:show) end end def login_user(user) allow_any_instance_of(ApplicationController).to receive(:current_person).and_return(user) end end
package com.vwo.mobile.models; import android.support.annotation.Keep; import android.support.annotation.NonNull; import android.text.TextUtils; import android.util.Patterns; import java.io.Serializable; import java.util.Locale; import java.util.regex.Pattern; /** * Created by aman on 16/09/17. */ @Keep public abstract class Entry implements Serializable { public static final String TYPE_GOAL = "goal"; public static final String TYPE_CUSTOM_DIMENSION = "custom_dimension"; public static final String TYPE_CAMPAIGN = "campaign"; private String url; private int retryCount; public Entry(@NonNull String url) { this.url = url; retryCount = 0; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getRetryCount() { return retryCount; } public void incrementRetryCount() { ++retryCount; } /** * A unique key for the given entry. * * @return {@link String} the unique key */ public abstract String getKey(); @Override public boolean equals(Object obj) { if (obj instanceof Entry) { String entryUrl = ((Entry) obj).getUrl(); return !TextUtils.isEmpty(entryUrl) && entryUrl.equals(this.url); } return super.equals(obj); } @Override public String toString() { return String.format(Locale.ENGLISH, "Url: %s\nRetryCount: %d\n", this.url, this.retryCount); } }
#!/bin/sh set -e # echo KUBECONFIG in a kubeconfig file for helm to authenticate with echo "$KUBECONFIG" > kubeconfig-file # point to our file from above export KUBECONFIG=kubeconfig-file # run the `command` specified in github sh -c "helm $*"
import m from 'mithril' import { Game } from '../index' export const ctrl = { end: () => { Game.isRunning = false Game.isOver = true }, goTo: { init() { Game.state = 'Init' m.redraw() }, intro() { Game.state = 'Intro' m.redraw() }, play() { Game.state = 'Play' m.redraw() }, }, }
<?php namespace Zilliqa; use Exception; use Zilliqa\DataType\ZilliqaQuantity; abstract class ZilliqaStatic { public static function getDefinition(): array { $schema_path = __DIR__ . '/../resources/zilliqa-schema.json'; return json_decode(file_get_contents($schema_path), true); } public static function hasHexPrefix(string $str): bool { return substr($str, 0, 2) === '0x'; } public static function ensureHexPrefix(string $str): string { if (self::hasHexPrefix($str)) { return $str; } return '0x' . $str; } /** * @throws Exception */ public static function convertCurrency(ZilliqaQuantity $quantity, string $from = 'zil', string $to = 'qa'): float { $convertTabe = [ 'zil' => 1000000000000, // 1e12 qa 'li' => 1000000, // 1e6 qa 'qa' => 1, ]; if (!isset($convertTabe[$from])) { throw new Exception('Unknown currency to convert from "' . $from . '"'); } if (!isset($convertTabe[$to])) { throw new Exception('Unknown currency to convert to "' . $to . '"'); } return $convertTabe[$to] * $quantity->val() / $convertTabe[$from]; } }
using System.Collections.Generic; using Poseidon.BackOffice.Common; using Poseidon.BackOffice.Common.ViewModels; using Poseidon.BackOffice.Core.ViewModels; namespace Poseidon.BackOffice.Core.DesignTime { public class DesignTimeBreadCrumbViewModel { public IEnumerable<ModuleViewModel> CurrentModules { get { var umsModule = new OfficeModule { Title = "User Module", Description = "This is the user management module.", IconFileName = "/Poseidon.BackOffice.Core;component/DesignTime/Resources/Ums.png", }; yield return new ModuleViewModel(umsModule, null); var userModule = new OfficeModule { Title = "Users", Description = "Manage all users", IconFileName = "/Poseidon.BackOffice.Core;component/DesignTime/Resources/User.png", //Parent = umsModule, }; yield return new ModuleViewModel(userModule, null); } } } }
import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:get/get.dart'; import '../../../../core/utils/color_palette.dart'; import '../../../../core/widgets/blocking_progress.dart'; import 'edit_note_controller.dart'; class EditNotePage extends GetView<EditNoteController> { @override Widget build(BuildContext context) { return Obx( () => WillPopScope( onWillPop: () => controller.saveNote(), child: BlockingProgress( isLoading: controller.isLoading.value, child: Scaffold( backgroundColor: controller.color.value.forBg(Get.isDarkMode), body: SafeArea( child: NotePageLayout(controller), ), appBar: AppBar( backgroundColor: controller.color.value.forBg(Get.isDarkMode), elevation: 0, actions: <Widget>[ Obx( () => IconButton( icon: Icon( controller.isPinned.value ? Icons.push_pin : Icons.push_pin_outlined, ), onPressed: () => controller.togglePinned(), ), ), IconButton( icon: Icon(Icons.palette_outlined), onPressed: () => controller.openColorPicker(), ), IconButton( icon: Icon(Icons.delete_outline), onPressed: () => controller.deleteNote(), ), ], ), ), ), ), ); } } class NotePageLayout extends StatelessWidget { final _focusNode = FocusNode(); final EditNoteController controller; NotePageLayout(this.controller); void _handleKeyEvent(RawKeyEvent event) { if (event.logicalKey == LogicalKeyboardKey.escape) { Get.back(); } } @override Widget build(BuildContext context) { FocusScope.of(context).requestFocus(_focusNode); return RawKeyboardListener( focusNode: _focusNode, onKey: _handleKeyEvent, child: Padding( padding: EdgeInsets.all(8), child: Column( children: <Widget>[ TextField( controller: controller.titleController, keyboardType: TextInputType.multiline, maxLines: null, decoration: InputDecoration.collapsed(hintText: 'Title'), style: TextStyle( fontSize: 25, ), ), SizedBox(height: 16), Expanded( child: TextField( controller: controller.messageController, keyboardType: TextInputType.multiline, maxLines: null, decoration: InputDecoration.collapsed(hintText: 'Message'), style: TextStyle( fontSize: 18, ), ), ), ], ), ), ); } }
from __future__ import unicode_literals from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from rest_framework_jwt.views import obtain_jwt_token from rest_framework_swagger.views import get_swagger_view from graphene_file_upload.django import FileUploadGraphQLView from graphene_django.views import GraphQLView schema_view = get_swagger_view(title="Collective Cetak API") urlpatterns = [ path("admin/", admin.site.urls), path("accounts/", include("allauth.urls")), path("api/", include("api.urls")), path("utils/", include("utils.urls")), path("document/", include("upload.urls")), path("account/", include("rest_auth.urls")), path("account/registration/", include("rest_auth.registration.urls")), path("account/token", obtain_jwt_token), path("graphql/", FileUploadGraphQLView.as_view(graphiql=True)), path("graphql/list/", GraphQLView.as_view(graphiql=True)), path("doc/", schema_view), path("email/", include("extensions.urls")), ] if settings.DEBUG: import debug_toolbar urlpatterns += [path("__debug__/", include(debug_toolbar.urls))]
package aula08; public class At01 { public static long fatorialNr(long num) { long aux = num; for (long i = num - 1; i > 0; i--) { aux *= i; } return aux; } public static long fatorialR(long num) { if (num == 0) { return 1; } else { return num * fatorialR(num - 1); } } public static void main(String[] args) { int num = 15; System.out.println(15 + "! = " + fatorialNr(num) + " - Fatorial Não Recursivo"); System.out.println(15 + "! = " + fatorialR(num) + " - Fatorial Recursivo"); } }
package com.litl.leveldb; public class DatabaseCorruptException extends LevelDBException { private static final long serialVersionUID = -2110293580518875321L; public DatabaseCorruptException() { } public DatabaseCorruptException(String error) { super(error); } }
Widget build(BuildContext context) { return Container( height: 56.0, padding: const EdgeInsets.symmetric(horizontal: 8.0), decoration: BoxDecoration(color: Colors.blue[500]), Row( IconButton( icon: Icon(Icons.menu), tooltip: 'Navigation menu', ), Expanded(title), IconButton( icon: Icon(Icons.search), tooltip: 'Search', ), ), ); }
import 'package:api_todo/src/models/todo_model.dart'; import 'package:api_todo/src/repositories/todo_repository.dart'; import 'package:flutter/cupertino.dart'; class Home_Controller { List<TodoModel> todos = []; final TodoRepository _repository; final state = ValueNotifier<HomeState>(HomeState.start); Home_Controller([TodoRepository repository]) : _repository = repository ?? TodoRepository(); Future start() async { state.value = HomeState.loading; try{ todos = await _repository.fetchTodos(); state.value = HomeState.success; } catch(e){ state.value = HomeState.error; } } } enum HomeState { start, loading, success, error }
module Schools module DFESignInAPI class NoOrganisationError < RuntimeError; end class Roles < Client attr_accessor :user_uuid, :organisation_uuid class << self def service_id ENV.fetch('DFE_SIGNIN_SCHOOL_EXPERIENCE_ADMIN_SERVICE_ID') end def role_id ENV.fetch('DFE_SIGNIN_SCHOOL_EXPERIENCE_ADMIN_ROLE_ID') end end def initialize(user_uuid, organisation_uuid) self.user_uuid = user_uuid self.organisation_uuid = organisation_uuid end def has_school_experience_role? roles.any? { |role| role['id'] == self.class.role_id } end private def roles @response ||= response unless @response.is_a?(Hash) && @response.has_key?('roles') fail APIResponseError, 'invalid response from roles API' end @response.fetch('roles') end def response super rescue Faraday::ResourceNotFound fail NoOrganisationError, "No organisation ID found for user #{user_uuid}" end def endpoint URI::HTTPS.build( host: Rails.configuration.x.dfe_sign_in_api_host, path: [ '/services', self.class.service_id, 'organisations', organisation_uuid, 'users', user_uuid ].join('/') ) end end end end
# OIFITS.jl The `OIFITS.jl` package provides support for OI-FITS data in Julia language. The support for the actual FITS files is provided by the [`FITSIO.jl`](https://github.com/JuliaAstro/FITSIO.jl) package. ## OI-FITS Summary OI-FITS is a standard to store optical interferometry data as a collection of data-blocks. In the first version of the standard (see [Ref. 1](#references)), the available data-blocks are: * `OI_TARGET` provides a list of observed targets; * `OI_ARRAY` describes a given array of stations; * `OI_WAVELENGTH` describes a given instrument (notably the effective wavelengths and bandwidths of its spectral channels); * `OI_VIS` contains complex visibility data; * `OI_VIS2` contains squared visibility (powerspectrum) data; * `OI_T3` contains triple product (bispectrum) data. These data-blocks, are stored as binary tables in a FITS data file. ## Installation OIFITS is a [registered Julia package](http://pkg.julialang.org/), the installation is as simple as: ```julia Pkg.add("OIFITS") Pkg.update() ``` The last command `Pkg.update()` may be unnecessary. ## Typical usage Loading an OI-FITS data file: ```julia using OIFITS master = OIFITS.load("testdata.oifits") ``` To iterate through all data-blocks: ```julia for db in master dbname = OIFITS.get_dbname(db) revn = OIFITS.get_revn(db) println("Data block is $dbname, revision $revn") end ``` To iterate through a sub-set of the data-blocks (here the complex visibility data, the powerspectrum data and the bispectrum data): ```julia for db in OIFITS.select(master, "OI_VIS", "OI_VIS2", "OI_T3") dbname = OIFITS.get_dbname(db) n = length(OIFITS.get_time(db)) println("Data block is $dbname, number of exposures is $n") end ``` ## Accessor functions Any OI-FITS field (keyword/column) of a given data-block can be retrieved via an accessor whose name has suffix `OIFITS.get_` followed by the name of the field (in lower case letters and with all non-letter and all non-digit letters replaced by the underscore character `'_'`). A notable exception is the revision number corresponding to the keyword "OI_REVN" which is retrieved with the method `OIFITS.get_revn()`. For instance: ```julia OIFITS.get_revn(db) # get the revison number of the format (OI_REVN) OIFITS.get_eff_wave(db) # get effective wavelengths (EFF_WAVE) OIFITS.get_eff_band(db) # get effective bandwidths (EFF_BAND) OIFITS.get_ucoord(db) # get the U coordinates of the data (UCOORD) ``` Of course, getting a given field must make sense. For instance, `OIFITS.get_eff_wave()` can be applied on any `OI_WAVELENGTH` data-blocks but also on data-blocks which contains interferometric data such as `OI_VIS`, `OI_VIS2`, `OI_T3`, *etc.* but not on other data-blocks like `OI_TARGET`. ## Reading data To load the contents of an OI-FITS file in memory, use: ```julia master = OIFITS.load(filename) ``` where `filename` is the name of the file and the returned value, `master`, contains all the OI-FITS data-blocks of the file. You may have the names of the data blocks printed as they get read with keyword `quiet=false`: ```julia master = OIFITS.load(filename, quiet=false) ``` If you already have a `FITS` handle to the data, you can use it as the argument to `OIFITS.load` in place of the file name. ## Constructors It is possible to build OI-FITS data-blocks individually. The general syntax is: ```julia OIFITS.new_XXX(KEY1=VAL1, KEY2=VAL2, ...) ``` where `XXX` is the type of the data-block and `KEYn=VALn` constructions give the fields of the data-block and their values. The names of the fields follow the same convention as for the field accessors. Available data-block constructors are: * `OIFITS.new_target` => `OI_TARGET` * `OIFITS.new_array` => `OI_ARRAY` * `OIFITS.new_wavelength` => `OI_WAVELENGTH` * `OIFITS.new_vis` => `OI_VIS` * `OIFITS.new_vis2` => `OI_VIS2` * `OIFITS.new_t3` => `OI_T3` When defining a new data-block, all mandatory fields must be provided. For instance, to create an `OI_WAVELENGTH` data-block: ```julia µm = 1e-6 # all values are in SI units in OI-FITS db = OIFITS.new_wavelength(insname="Amber", eff_wave=[1.4µm,1.6µm,1.8µm], eff_band=[0.2µm,0.2µm,0.2µm]) ``` Note that the revision number (`revn=...`) can be omitted; by default, the highest defined revision will be used. A consistent set of OI-FITS data-blocks is made of: exactly one `OI_TARGET` data-block, one or more `OI_WAVELENGTH` data-blocks, one or more `OI_ARRAY` data-blocks and any number of data-blocks with interferometric data (`OI_VIS`, `OI_VIS2` or `OI_T3`). These data-blocks must be stored in a container created by: ```julia master = OIFITS.new_master() ``` Then, call: ```julia OIFITS.attach(master, db) ``` to attach all data-block `db` to the OI-FITS container (in any order). Finally, you must call: ```julia OIFITS.update(master) ``` to update internal information such as links between data-blocks with interferometric data and the related instrument (`OI_WAVELENGTH` data-block) and array of stations (`OI_ARRAY` data-block). If you do not do that, then applying some accessors may not work, *e.g.* `OIFITS.get_eff_wave()` on a data-blocks with interferometric data. To read an OI-FITS data-block from the HDU of a FITS file: ```julia db = OIFITS.read_datablock(hdu) ``` where `hdu` is a `HDU` handle. The result may be `nothing` if the current HDU does not contain an OI-FITS data-block. ## Miscellaneous functions OI-FITS implements some useful functions which can be used to deal with FITS file (not just OI-FITS ones). These functions could be part of `FITSIO` package. ### Retrieving information from the header of a FITS HDU The header of a FITS HDU can be read with the function: ```julia fts = FITS(filename) hdr = FITSIO.read_header(fts[1]) ``` which returns an indexable and iterable object, here `hdr`. The keys of `hdr` are the FITS keywords of the header. For instance: ```julia keys(hdr) # yield an iterator on the keys of hdr collect(keys(hdr)) # yield all the keys of hdr haskey(hdr, key) # check whether key is present hdr[key] # retrieve the contents associated with the key ``` For commentary FITS keywords (`"HISTORY"` or `"COMMENT"`), there is no value, just a comment but there may be any number of these *commentary* keywords. Other keywords must be unique and thus have a scalar value. Use `get_comment` to retrieve the comment of a FITS keyword: ```julia get_comment(hdr, key)keys(hdr) # yield an iterator on the keys of hdr collect(keys(hdr)) # yield all the keys of hdr haskey(hdr, key) # check whether key is present hdr[key] # retrieve the contents associated with the key ``` *OIFITS* provides method `OIFITS.get_value()` and `OIFITS.get_comment()` method to retrieve the value and comment (respectively) of a FITS keyword with type checking and, optionaly, let you provide a default value if the keyword is absent: ```julia val = OIFITS.get_value(hdr, key) val = OIFITS.get_value(hdr, key, def) com = OIFITS.get_comment(hdr, key) com = OIFITS.get_comment(hdr, key, def) ``` To retrieve a value and make sure it has a specific type, the following methods are available: ```julia OIFITS.get_logical(hdr, "SIMPLE") OIFITS.get_integer(hdr, "BITPIX") OIFITS.get_real(hdr, "BSCALE") OIFITS.get_string(hdr, "XTENSION") ``` which throw an error if the keyword is not present and perform type checking and conversion if allowed. It is also possible to supply a default value to return if the keyword is not present: ```julia bscale = OIFITS.get_real(hdr, "BSCALE", 1.0) bzero = OIFITS.get_real(hdr, "BZERO", 0.0) xtension = OIFITS.get_string(hdr, "XTENSION", "IMAGE") ``` The function: ```julia OIFITS.get_hdutype(hdr) ``` returns the HDU type as a symbol, `:image_hdu` for an image, `:ascii_table` for an ASCII table, `:binary_table` for a binary table, and `:unknown` otherwise. For a FITS table, the function: ```julia OIFITS.get_dbtype(hdr) ``` returns the OI-FITS data-block type as a symbol like `:OI_TARGET`, `:OI_WAVELENGTH`, *etc.* ### Reading FITS tables In addition to the method `read(tbl::TableHDU, colname::ASCIIString)` provided by FITSIO for reading a specific column of a FITS table, the low-level function: ```julia OIFITS.read_column(ff::FITSFile, colnum::Integer) ``` returns a Julia array with the contents of the `colnum`-th column of the current HDU in FITS file handle `ff`. The current HDU must be a FITS table (an ASCII or a binary one). The last dimension of the result corresponds to the rows of the table. It is also possible to read all the table: ```julia OIFITS.read_table(ff::FITSFile) OIFITS.read_table(hdu::Union(TableHDU,ASCIITableHDU)) ``` or at high-level: ```julia read(hdu::Union(TableHDU,ASCIITableHDU)) ``` The result is a dictionary whose keys are the names of the columns (in uppercase letters and with trailing spaces removed). If a column has given units, the units are stored in the dictionary with suffix `".units"` appended to the column name. For instance, the units for column `"TIME"` are accessible with key `"TIME.units"`. ### FITS and Julia types conversion The functions `cfitsio_datatype()` and `fits_bitpix()` deal with conversion between CFITSIO type code or BITPIX value and actual Julia data types. They can be used as follows (assuming `T` is a Julia data type, while `code` and `bitpix` are integers): ```julia cfitsio_datatype(T) --------> code (e.g., TBYTE, TFLOAT, etc.) cfitsio_datatype(code) -----> T fits_bitpix(T) -------------> bitpix (e.g., BYTE_IMG, FLOAT_IMG, etc.) fits_bitpix(bitpix) --------> T ``` The functions `fits_get_coltype()` and `fits_get_eqcoltype()` yield the data type, repeat count and width in bytes of a given column, their prototypes are: ```julia (code, repcnt, width) = fits_get_coltype(ff::FITSFile, colnum::Integer) (code, repcnt, width) = fits_get_eqcoltype(ff::FITSFile, colnum::Integer) ``` with `colnum` the column number, `code` the CFITSIO column type (call `cfitsio_datatype(code)` to convert it to a Julia type) of the elements in this column, `repcnt` and `width` the repeat count and width of a cell in this column. The difference between `fits_get_coltype()` and `fits_get_eqcoltype()` is that the former yields the column type as it is stored in the file, while the latter yields the column type after automatic scaling by the values `"TSCALn"` and `"TZEROn"` keywods if present (with `n` the column number). Note that reading the column data with `fits_read_col()` or `fitsio_read_column()` automatically apply this kind of scaling. To retrieve the dimensions of the cells in a given column, call the function `fits_read_tdim()`, its prototype is: ```julia dims = fits_read_tdim(ff::FITSFile, colnum::Integer) ``` where `dims` is a vector of integer dimensions. ## Credits The developments of this package has received funding from the European Community's Seventh Framework Programme (FP7/2013-2016) under Grant Agreement 312430 (OPTICON). ## References 1. Pauls, T. A., Young, J. S., Cotton, W. D., & Monnier, J. D. "A data exchange standard for optical (visible/IR) interferometry." Publications of the Astronomical Society of the Pacific, vol. 117, no 837, p. 1255 (2005). [[pdf]](http://arxiv.org/pdf/astro-ph/0508185) 2. Duvert, G., Young, J., & Hummel, C. "OIFITS 2: the 2nd version of the Data Exchange Standard for Optical (Visible/IR) Interferometry." arXiv preprint [[arXiv:1510.04556v2.04556]](http://arxiv.org/abs/1510.04556v2).
### A Pluto.jl notebook ### # v0.12.4 using Markdown using InteractiveUtils # ╔═╡ f7e92500-194d-11eb-00c9-6f427ae012ac md"# The Basel Problem _Leonard Euler_ proved in 1741 that the following series $$\frac{1}{1} + \frac{1}{4} + \frac{1}{9} + \cdots$$ converges to $$\frac{\pi^2}{6} .$$ " # ╔═╡ 287ee380-194e-11eb-01fd-517dabec4f05 n = 1 : 500000000 # ╔═╡ 31d135f0-194e-11eb-105b-51bb3ea5d3d8 sequence = n .^ -2 # ╔═╡ b6920b1e-194e-11eb-200d-17bf72fdff3a π = sqrt(6 * sum(sequence)) # ╔═╡ Cell order: # ╟─f7e92500-194d-11eb-00c9-6f427ae012ac # ╠═b6920b1e-194e-11eb-200d-17bf72fdff3a # ╠═31d135f0-194e-11eb-105b-51bb3ea5d3d8 # ╠═287ee380-194e-11eb-01fd-517dabec4f05
package com.equalexperts.client.softwaredesignsystems.eatout import com.equalexperts.client.softwaredesignsystems.eatout.services.Location import com.equalexperts.client.softwaredesignsystems.eatout.services.Restaurant import org.osmdroid.util.GeoPoint import org.osmdroid.views.MapView import org.osmdroid.views.overlay.Marker fun Restaurant.toMarker(mapView: MapView): Marker { return Marker(mapView).apply { title = name subDescription = postcode position = GeoPoint(location.latitude, location.longitude) } } fun Marker.toRestaurant(): Restaurant { return Restaurant(title, subDescription, position.toLocation()) } private fun GeoPoint.toLocation(): Location { return Location(latitude, longitude) }
var $ = require('../lib/jquery-3.2.1.min.js'); var Vue = require('../lib/vue.js'); var pageBus = require('../common/bus.js'); var template= require('./currentview.html'); var loginview= require('./loginview.js'); var reset= require('./reset.js'); var currentview = { template: template, data: function() { return { currentView: 'loginview' } }, components: { reset: reset, loginview:loginview }, methods: { init:function(){ }, toggleTabs (tabName) { alert(1); this.currentView = tabName; }, showbox(){ $('.modal-out').addClass('show-box') }, }, created: function() {}, mounted: function() { this.init() } } if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) { define(function() { return currentview; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports.currentview = currentview; } else { window.currentview = currentview; }
require 'spec_helper' describe "client" do let(:api_user) { "sendgrid_user" } let(:api_key) { "password123" } let(:client) { SendGridWebApi::Client.new(api_user, api_key) } let(:client_invalid) { SendGridWebApi::Client.new("foo", "bar") } describe "intialise" do it "should return the correct base URL" do expect(client.base_url).to eql "https://api.sendgrid.com/api/" end it "should format the api request" do url = client.make_request_url("dummy.url", {foo: "bar"}) expect(url).to eql "dummy.url?api_key=#{api_key}&api_user=#{api_user}&foo=bar" end it "should fail with invalid credentials" do expect { client_invalid.bounce.get }.to raise_error(AuthenticationError) end it "shold fail when accessing with invalid method" do expect { client.bounce.send(:get_no_found) }.to raise_error(NoMethodError) end end describe "default api calls" do [:block, :bounce, :invalid_email, :spam_report].each do |rest_command| describe "#{rest_command.to_s}s" do it "should not raise error when invalid params" do VCR.use_cassette("#{rest_command.to_s}s_list_invalid_params") do json = client.bounce.get({invalid_param:"foobar"}) expect(json.count).to be > 0 end end it "should return the list of all #{rest_command.to_s}s" do VCR.use_cassette("client_#{rest_command.to_s}s_list") do json = client.send(rest_command).get expect(json.count).to be > 0 end end it "should return a filtered list of #{rest_command.to_s}s" do VCR.use_cassette("client_#{rest_command.to_s}s_filter_days") do json = client.send(rest_command).get({days:1}) expect(json.count).to be > 0 end end it "should return the count of #{rest_command.to_s}s" do VCR.use_cassette("client_#{rest_command.to_s}s_count") do json = client.send(rest_command).count expect(json["count"]).to be > 0 end end it "should delete the #{rest_command.to_s}" do VCR.use_cassette("client_#{rest_command.to_s}s_delete") do json = client.send(rest_command).delete({email: "user@exists.com"}) expect(json["message"]).to eql "success" end end it "should not delete the #{rest_command.to_s}" do VCR.use_cassette("client_#{rest_command.to_s}s_delete") do json = client.send(rest_command).delete({email: "user@notexists.com"}) expect(json["message"]).to eql "Email does not exist" end end end end end end
object DataTypes { def examples(): Unit = { println("DataType Examples") // variables can be declared with 'var' and can have implied type var myName = "James" var myAge = 39 println("My name is " + myName + " and I am " + myAge) // You can define the type var myLocation: String = "London" // 'var's are mutable myAge += 1 println("My age is now " + myAge) // 'vals' are constant val myHeight = 1.82 println("My height is " + myHeight) // This will cause an error because 'val's are constant //myHeight += 1 // All datatypes in Scala are objects and they include // (Get the max value with MaxValue) println("Byte = " + Byte.MinValue + " - " + Byte.MaxValue) println("Char = " + Char.MinValue + " - " + Char.MaxValue) println("Short = " + Short.MinValue + " - " + Short.MaxValue) println("Int = " + Int.MinValue + " - " + Int.MaxValue) println("Long = " + Long.MinValue + " - " + Long.MaxValue) println("Float = " + Float.MinValue + " - " + Float.MaxValue) println("Double = " + Double.MinValue + " - " + Double.MaxValue) var lgPrime = BigInt("622288097498926496141095869268883999563096063592498055290461") println("lgPrime = " + lgPrime) lgPrime += 1 println("lgPrime = " + lgPrime) var pi50 = BigDecimal("3.14159265358979323846264338327950288419716939937510") println("pi50 = " + pi50) pi50 += 0.00000000000000000000000000000000000000000000000001 println("pi50 = " + pi50) println("----------------------") } }
; void *tshc_aaddrcdown(void *aaddr) SECTION code_clib SECTION code_arch PUBLIC _tshc_aaddrcdown_fastcall EXTERN _zx_saddrcdown_fastcall defc _tshc_aaddrcdown_fastcall = _zx_saddrcdown_fastcall
<?php namespace uujia\framework\base\common\lib\Decrypt; /** * Class Aes * Date: 2020/10/6 * Time: 1:18 * * @package uujia\framework\base\common\lib\Decrypt */ class Aes { /** * @var string 加解密方法,可通过openssl_get_cipher_methods()获得 */ protected $_method; /** * @var string 加解密的密钥 */ protected $_secret_key; /** * @var string 加解密的向量,有些方法需要设置比如CBC */ protected $_iv; /** * @var int */ protected $_options; /** * 构造函数 * * @param string $key 密钥 * @param string $method 加密方式 * @param string $iv iv向量 * @param mixed $options 还不是很清楚 */ public function __construct($key = 'uujia.net', $method = 'AES-128-ECB', $iv = '', $options = 0) { // key是必须要设置的 $this->_secret_key = isset($key) ? $key : 'uujia.net'; $this->_method = $method; $this->_iv = $iv; $this->_options = $options; } /** * 加密方法,对数据进行加密,返回加密后的数据 * * @param string $data 要加密的数据 * * @return string */ public function encrypt($data) { return openssl_encrypt($data, $this->_method, $this->_secret_key, $this->_options, $this->_iv); } /** * 解密方法,对数据进行解密,返回解密后的数据 * * @param string $data 要解密的数据 * * @return string */ public function decrypt($data) { return openssl_decrypt($data, $this->_method, $this->_secret_key, $this->_options, $this->_iv); } /** * @return string */ public function getMethod(): string { return $this->_method; } /** * @param string $method * @return Aes */ public function setMethod(string $method) { $this->_method = $method; return $this; } /** * @return string */ public function getSecretKey(): string { return $this->_secret_key; } /** * @param string $secret_key * @return Aes */ public function setSecretKey(string $secret_key) { $this->_secret_key = $secret_key; return $this; } /** * @return string */ public function getIv(): string { return $this->_iv; } /** * @param string $iv * @return Aes */ public function setIv(string $iv) { $this->_iv = $iv; return $this; } /** * @return int */ public function getOptions(): int { return $this->_options; } /** * @param int $options * @return Aes */ public function setOptions(int $options) { $this->_options = $options; return $this; } }
MixServer === This is a forked repository from [Hivemall core](https://github.com/apache/incubator-hivemall). ## Build ``` $ mvn package -DskipTests ``` ## Run ``` $ mvn exec:java -Dexec.mainClass=hivemall.mix.server.MixServer ``` see [HIVEMALL-43](https://issues.apache.org/jira/browse/HIVEMALL-43)
#!/bin/bash # Executes commands in file placed by some other process on shared # NFS. The result is placed in the same file. The format of the file is: # {command text} # EOCommand # {command result text} # EOResult # Information is only appended to the file. Polling is done on the # EOCommand and EOResult tags to wait for complete info. initialize-teacher-notebooks() { teacherid="$1" shift if ! [ -d "/home/$teacherid" ]; then echo "No teacher with id=$studentid" return fi studentid="$*" if [ "$studentid" != "$teacherid" ]; then echo "Required first parameter should be the teacher id (i.e. $teacherid)" return fi echo "Deleting existing notebooks of $studentid." rm "/home/$studentid"/* -fr # TODO: rethink this echo "Initializing notebooks for $studentid." /srv/adapt-notebooks-for-user.sh "$studentid" echo "Done." } clear-notebooks() { teacherid="$1" shift if ! [ -d "/home/$teacherid" ]; then echo "No teacher with id=$studentid" return fi for studentid in "$@"; do if ! [ -d "/home/$studentid" ]; then echo "No student with id=$studentid" continue fi echo "Deleting existing notebooks of $studentid." rm "/home/$studentid"/* -fr # TODO: rethink this echo "Done." done } distribute-notebooks() { teacherid="$1" shift if ! [ -d "/home/$teacherid" ]; then echo "No teacher with id=$teacherid" return fi for studentid in "$@"; do if ! [ -d "/home/$studentid" ]; then echo "No student with id=$studentid" continue fi echo "Deleting existing notebooks of $studentid." rm "/home/$studentid"/* -fr # TODO: rethink this # Copy teacher notebooks to student container via NFS: echo "Copying notebooks..." cp -a "/home/$teacherid"/* "/home/$studentid/" chown -R "$studentid:$studentid" "/home/$studentid/" # Also make read-only copy: echo "Creating role_model directory..." rm -fr "/home/$studentid/role_model" ln -sf "/home/.others/$teacherid" "/home/$studentid/role_model" echo "Done." done } process-one-command() { set -x justcmd="${cmdtext/EOCommand/}" case "$justcmd" in fortesting*) bash <<<"${justcmd/fortesting/}" >>"$cmdfile" ;; distribute-notebooks*) read stripcmd teacherid sids <<<"$justcmd" distribute-notebooks $teacherid $sids >>"$cmdfile" ;; clear-notebooks*) read stripcmd teacherid sids <<<"$justcmd" clear-notebooks $teacherid $sids >>"$cmdfile" ;; initialize-teacher-notebooks*) read stripcmd teacherid sids <<<"$justcmd" initialize-teacher-notebooks $teacherid $sids >>"$cmdfile" ;; esac echo EOResult >>"$cmdfile" set +x } scan-for-commands() { shopt -s nullglob for cmdfile in /home/*/.commands/*-queued; do cmdtext="$(< "$cmdfile")" [[ "$cmdtext" == *EOCommand* ]] || continue # skip if client has not finished writing [[ "$cmdtext" == *EOResult* ]] && continue # skip if already processed process-one-command done } students-home-dir-hack() { # This is probably temporary and will be moved/rewritten when the design # stabilizes. # Make sure user directories have the symbolic links shopt -s nullglob for udir in /mnt/nfs/home/*; do userid="${udir##*/}" # skip known administrators and the teacher [ "$userid" = "potter" ] && continue [ "$userid" = "ubuntu" ] && continue [ -f "/jupyter/admin/$userid" ] && continue for link in textbook tools info; do if ! [ -h "$udir/$link" ]; then ln -s "/jupyter/admin/$link" "$udir/$link" 2>/dev/null chown -h "$userid:$userid" "$udir/$link" 2>/dev/null fi done for dir in private_info; do if ! [ -d "$udir/$dir" ]; then mkdir -p "$udir/$dir" 2>/dev/null chown -h "$userid:$userid" "$udir/$dir" 2>/dev/null fi done ipycfg="$udir/.ipython/profile_default/ipython_config.py" [ -f "$ipycfg" ] || { mkdir -p "${ipycfg%/*}" echo "c.InteractiveShellApp.matplotlib = 'inline'" >>"$ipycfg" chown -R "$userid:$userid" "$udir/.ipython" } # Hopefully this next one will be very temporary: # Make user dirs world writable so teacher can copy in notebooks with # simple unix commands. Do this every time so teacher can also # copy out new files that the student might put in. # TODO: avoid this, using groups, perhaps. ( # Put in exception to skip ssh related things that should not be world readable/writable # and also skip symbol links. if cd "$udir"; then shopt -s nullglob shopt -s dotglob for p in * ; do [ -L "$p" ] && continue [ "$p" = .ssh ] && continue [[ "$p" = *key* ]] && continue chmod -R a+wr "$p" done fi ) # the directory itself needs to be writable or else the jupyter server container does not launch # Note: no "-R" here chmod a+wr "$udir" done } if [ "$(whoami)" != root ]; then echo "Must be root" 1>&2 exit 1 fi while true; do scan-for-commands students-home-dir-hack sleep 5 done
using System; using System.Reflection; namespace GoPay.Common { public enum Currency { [CurrencyCode(203)] CZK, [CurrencyCode(978)] EUR, [CurrencyCode(985)] PLN, [CurrencyCode(348)] HUF, [CurrencyCode(840)] USD, [CurrencyCode(826)] GBP, [CurrencyCode(191)] HRK, [CurrencyCode(975)] BGN, [CurrencyCode(946)] RON } public static class CurrencyExtension { public static int GetCode(this Enum value) { FieldInfo fieldInfo = value.GetType().GetField(value.ToString()); var attribute = (CurrencyCode)fieldInfo.GetCustomAttribute(typeof(CurrencyCode)); return attribute.Code; } } public class CurrencyCode : Attribute { public int Code { get; set; } public CurrencyCode(int code) : base() { Code = code; } } }
# name-picker 给你的宝宝找一个心仪的名字吧! ## 使用 `scrapy crawl name` 抓取名字 `python app.py` 启动服务 访问 [http://www.renren.com:5000/](http://www.renren.com:5000/) 浏览页面
Write-Output 'EverGreen Install Started' New-Item -ItemType Directory 'C:\CustomizerArtifacts' | Out-Null Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force | Out-Null Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted | Out-Null Install-Module EverGreen -Scope CurrentUser -Force Write-Output 'EverGreen Installed'
import 'package:country_code_picker/country_localizations.dart'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:package_info/package_info.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:singlestore/screens/AppIntro/app_intro.dart'; import 'package:singlestore/screens/Cart/bloc/cart_bloc.dart'; import 'package:singlestore/screens/HomeContainer/home_container.dart'; import 'package:singlestore/screens/Onboarding/onboarding.dart'; import 'package:singlestore/screens/Store/store_page.dart'; import 'package:singlestore/screens/UpdateApp/update_app.dart'; import 'configs/api.dart'; import 'configs/navigator.dart'; SharedPreferences prefs; String userID; String appVersion = 'success'; PackageInfo packageInfo; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); packageInfo = await PackageInfo.fromPlatform(); prefs = await SharedPreferences.getInstance(); userID = prefs.getString('userID'); API.STORE_KEY = prefs.getString('storeKey'); if (prefs.getString('jwt') != null) API.JWT_AUTH = 'Bearer ' + prefs.getString('jwt'); // API.STORE_KEY = 'storeKey1'; logger.e(API.STORE_KEY); String url = API.BASE_URL + '/api/app/singlestore/appversionvalid'; var response; try { response = await Dio().get( url, queryParameters: { "appVersion": packageInfo.version, }, ); logger.e('app version : ${packageInfo.version}'); logger.e(response.data); appVersion = response.data['status']; logger.e('app version status : $appVersion'); } catch (e) {} runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( supportedLocales: [ Locale('en'), ], localizationsDelegates: [ CountryLocalizations.delegate, ], title: 'A2B', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.orangeAccent[500], visualDensity: VisualDensity.adaptivePlatformDensity, ), home: appVersion != 'success' ? UpdateApp() : API.JWT_AUTH.length < 8 ? AppIntro() : API.STORE_KEY == '' || API.STORE_KEY == null ? StorePage() : HomeContainerStateLess(), onGenerateRoute: NavRouter.generatedRoute, ); } }
(P) (Q) (R) (P=>Q) (Q=>R) (P=>R<P>) (P=>R<Q>) (P=>R<R>) (P=>R) (P=>R-WITH-LET<P>) (P=>R-WITH-LET<Q>) (P=>R-WITH-LET<R>) (P=>R-WITH-LET)
package com.raynigon.unit.api.kotlin import com.raynigon.unit.api.core.service.UnitsApiService.quantity import com.raynigon.unit.api.core.units.si.SISystemUnitsConstants.Metre import com.raynigon.unit.api.core.units.si.SISystemUnitsConstants.Watt import com.raynigon.unit.api.core.units.si.dimensionless.One import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import javax.measure.Quantity import javax.measure.UnconvertibleException import javax.measure.quantity.Speed import kotlin.math.sign import com.raynigon.unit.api.core.units.si.length.Metre as MetreUnit internal class QuantityOperatorsTest { @Test fun `comparison operator`() { val a = Metre(3) val b = Metre(4) val c = Metre(5) val d = Metre(4) assertTrue(a < b) assertFalse(a > b) assertTrue(c > b) assertFalse(c < b) assertTrue(b == d) assertTrue(b >= d) assertTrue(b <= d) assertTrue(a != b) // Definition 1: assertEquals(sign(a.compareTo(b).toDouble()), -sign(b.compareTo(a).toDouble())) // Definition 2: assertTrue(a < b && b < c) /* => */ assertTrue(a < c) // Definition 3: /* <p>Finally, the implementor must ensure that {@code x.compareTo(y)==0} * implies that {@code sgn(x.compareTo(z)) == sgn(y.compareTo(z))}, for * all {@code z}.*/ /* <p>It is strongly recommended, but <i>not</i> strictly required that * {@code (x.compareTo(y)==0) == (x.equals(y))}. Generally speaking, any * class that implements the {@code Comparable} interface and violates * this condition should clearly indicate this fact. The recommended * language is "Note: this class has a natural ordering that is * inconsistent with equals."*/ } @Test fun `invalid comparison fails`() { val a = Metre(3) as Quantity<*> val b = Watt(4) as Quantity<*> val c = a as Quantity<Speed> val d = b as Quantity<Speed> assertThrows(UnconvertibleException::class.java) { c < d } } @Test fun `math operators`() { val a = Metre(2) val b = Metre(4) val c = Metre(3) assertEquals(Metre(6), a + b) assertEquals(Metre(2), b - a) val result = b * c assertEquals(12, result.value.toInt()) assertEquals(MetreUnit().pow(2), result.unit) assertEquals(quantity(2, One()), b / a) } }
package edu.ucr.cs.riple; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import com.google.auto.service.AutoService; import com.google.errorprone.BugPattern; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Symbol; import javax.lang.model.element.ElementKind; @AutoService(BugChecker.class) @BugPattern( name = "NullAway", altNames = {"CheckNullabilityTypes"}, summary = "Nullability type error.", tags = BugPattern.StandardTags.LIKELY_ERROR, severity = WARNING) public class CSS extends BugChecker implements BugChecker.MethodInvocationTreeMatcher, BugChecker.AssignmentTreeMatcher, BugChecker.MemberSelectTreeMatcher { private final Config config; public CSS() { this.config = new Config(); } public CSS(ErrorProneFlags flags) { this.config = new Config(flags); } @Override public Description matchAssignment(AssignmentTree tree, VisitorState state) { if (config.fieldTrackerIsActive) { Symbol expressionSym = ASTHelpers.getSymbol(tree.getExpression()); if (expressionSym != null && expressionSym.getKind() == ElementKind.FIELD) { config.WRITER.saveFieldTrackerNode(tree.getExpression(), state); } } return Description.NO_MATCH; } @Override public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) { Symbol symbol = ASTHelpers.getSymbol(tree); if (config.fieldTrackerIsActive && symbol.getKind().equals(ElementKind.FIELD)) { config.WRITER.saveFieldTrackerNode(tree, state); } return Description.NO_MATCH; } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (config.methodTrackerIsActive) { config.WRITER.saveMethodTrackerNode(tree.getMethodSelect(), state); } return Description.NO_MATCH; } }
# validate.js validate.js is a lightweight JavaScript form validation library inspired by CodeIgniter. ## Features - Validate form fields from over a dozen rules - No dependencies - Customizable Messages - Supply your own validation callbacks for custom rules - Chainable customization methods for ease of declaration - Works in all major browsers, (even IE6!) - Modeled off the CodeIgniter form validation API - Multi-language support - Korean (<https://github.com/jnhwkim/validate.js>) - Multi-language support - Spanish (<https://github.com/tongilsoft/validate.js>) ## How to use var validator = new FormValidator('example_form', [{ name: 'req', display: 'required', rules: 'required' }, { name: 'alphanumeric', rules: 'alpha_numeric' }, { name: 'password', rules: 'required' }, { name: 'password_confirm', display: 'password confirmation', rules: 'required|matches[password]' }, { name: 'email', rules: 'valid_email' }, { name: 'minlength', display: 'min length', rules: 'min_length[8]' }], function(errors) { if (errors.length > 0) { // Show the errors } }); ## Documentation You can view everything at http://rickharrison.github.com/validate.js ## Plugins jQuery: https://github.com/magizh/validate_helper
package org.spekframework.spek2.integration import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import kotlin.test.assertEquals import kotlin.test.assertFailsWith object SetSpec: Spek({ describe("A set") { val set by memoized { mutableSetOf<String>() } context("is empty") { it("should have a size of 0") { assertEquals(0, set.size) } it("should throw when first is invoked") { assertFailsWith(NoSuchElementException::class) { set.first() } } } } })
# Q-learning applied to trading Here we present an approach for training an agent to behave optimally in a trading environment. We model such an environment with some simplifying assumptions: * There is only one opportunity to trade per day which must be done by paying the `close` price provided in historical market data. * An agent either has a long or short position in one security. The exact number of shares is made irrelevant by using cumulative returns. * No transaction costs are taken into account. ## Training To train an agent using the [Q-learning](https://en.wikipedia.org/wiki/Q-learning) method we first determine an indicative set of signals to represent the lucrative potential of changing stock prices. e.g. price momentum, volatility, moving average crossings are used. These values are encoded into a bitfield state value. The Q-learning algorithm is practically agnostic to the trading environment. The abstract state values are simply numbers (encoded bitfields) which the algorithm uses to track the perceived values of buying or selling while in any one state. An agent is tested using a cross-validated approach, whereby the market data is sliced into, e.g. 5, equally sized portions. The agent is trained on one portion and its performance is then tested against the remaining 4. This process is repeated until each slice acts as the training set. For each slice, training occurs over multiple "episodes". A single episode involves iterating through all records in a training set. ## Performance The performance is measured as the total return from applying the train and test procedure mentioned above. A total return of 1 means the agent has as much money at the end of trading as it did at the start. Results are presented here. With Q-learning the average return and deviation were just about 1. Compared to a randomized trading strategy the standard deviation is significantly lower. ### Q-learned returns histogram * `alpha` and `gamma` parameters varied in range [0.1, 0.9] * `epsilon` set to 0.1 * 500 unique stocks used, market data spanning 2000-2012 * Each stock trained and tested in 5-way cross-validated manner * Agent trained for 100 episodes for each training set * ~800k data points ![return](https://raw.githubusercontent.com/jlas/ml.q/master/rl/experiment/trade/results/return.png) * Data generated by running: ``` q trade.q q)runbatch[] ``` ### Random trading returns histogram * Long and short state chosen randomly * ~160k data points ![returnrand](https://raw.githubusercontent.com/jlas/ml.q/master/rl/experiment/trade/results/returnrand.png) * Data generated by running: ``` q trade.q q)randbatch[] ``` ### alpha & gamma The data suggests higher returns are produced with higher values of alpha and gamma. Experiments were conducted with the cross product of alpha and gamma values in the range [0.1, 0.9]. Average returns are plotted below with the log of standard deviation added as a band. ![alpha](https://raw.githubusercontent.com/jlas/ml.q/master/rl/experiment/trade/results/alpha.png) ![gamma](https://raw.githubusercontent.com/jlas/ml.q/master/rl/experiment/trade/results/gamma.png) ### Top 3 Runs ![topSPY](https://raw.githubusercontent.com/jlas/ml.q/master/rl/experiment/trade/results/topSPY.png) * Data generated by running: ``` q trade.q q)getreturns["SPY";3] ```
def show_description(path): if 'Simulation_1' in path: print('Simulation_1: Straight line drive on a wavey 2D surface') if 'Simulation_2' in path: print('Simulation_2: Left turn drive on a wavey 2D surface') if 'Simulation_3' in path: print('Simulation_3: Straight line drive on a two phase-shifted 2D surfaces') if 'Simulation_4' in path: print('Simulation_4: Straight line drive on a complex 3D surface (slow)') if 'Simulation_5' in path: print('Simulation_5: Complex path drive on a simplified 3D surface') if 'Simulation_6' in path: print('Simulation_6: Straight line drive on a wavey surface with obstacles (sphere based)') if 'Simulation_7' in path: print('Simulation_7: Straight line drive on a wavey surface with obstacles (STL based)')
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 Ragnar Svensson, Christian Murray ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; 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. (ns editor.util-test (:require [clojure.test :refer :all] [editor.util :as util])) (deftest natural-order (are [unsorted sorted] (= sorted (sort util/natural-order unsorted)) ;; edge cases [nil nil] [nil nil] ["" ""] ["" ""] ["a" ""] ["" "a"] ["1" "a"] ["1" "a"] ;; lexigraphically ["a" "b"] ["a" "b"] ["b" "a"] ["a" "b"] ;; case insensitive ["aa" "Ab"] ["aa" "Ab"] ["ab" "Aa"] ["Aa" "ab"] ;; numbers ["a1" "a"] ["a" "a1"] ["a1" "a10" "a2"] ["a1" "a2" "a10"] ["a2" "b" "a1"] ["a1" "a2" "b"] ;; really large numbers (these have one more digit than Long/MAX_VALUE) ["a10000000000000000001" "a10000000000000000000"] ["a10000000000000000000" "a10000000000000000001"])) (deftest join-words (is (= "" (util/join-words ", " " or " nil))) (is (= "" (util/join-words ", " " or " []))) (is (= "a" (util/join-words ", " " or " ["a"]))) (is (= "a or b" (util/join-words ", " " or " ["a" "b"]))) (is (= "a, b or c" (util/join-words ", " " or " ["a" "b" "c"]))) (is (= "a, b, c and d" (util/join-words ", " " and " ["a" "b" "c" "d"]))) (is (= "1 or 2 or :c" (util/join-words " or " " or " [1 2 :c]))))
package org.woehlke.computer.kurzweil.commons.model.fractal; import org.woehlke.computer.kurzweil.tabs.wator.WatorModel; import org.woehlke.computer.kurzweil.commons.model.turing.Point; import java.io.Serializable; import java.util.ArrayDeque; import java.util.Deque; //import java.util.logging.Logger; /** * Mandelbrot Set drawn by a Turing Machine. * * (C) 2006 - 2015 Thomas Woehlke. * https://thomas-woehlke.blogspot.com/2016/01/mandelbrot-set-drawn-by-turing-machine.html * @author Thomas Woehlke * * Created by tw on 16.12.2019. */ public class GaussianNumberPlane implements Serializable { private static final long serialVersionUID = 7526471155622776147L; public final static int YET_UNCOMPUTED = -1; private final static double complexWorldDimensionRealX = 3.2d; private final static double complexWorldDimensionImgY = 2.34d; private final static double complexCenterForMandelbrotRealX = -2.2f; private final static double complexCenterForMandelbrotImgY = -1.17f; private final static double complexCenterForJuliaRealX = -1.6d; private final static double complexCenterForJuliaImgY = -1.17d; private final Point worldDimensions; public volatile int zoomLevel; private volatile int[][] lattice; private volatile ComplexNumber complexNumberForJuliaSetC; private volatile ComplexNumber complexWorldDimensions; private volatile ComplexNumber complexCenterForMandelbrot; private volatile ComplexNumber complexCenterForJulia; private volatile Deque<ComplexNumber> complexCenterForZoomedMandelbrot = new ArrayDeque<>(); private volatile ComplexNumber zoomCenter; //public static Logger log = Logger.getLogger(GaussianNumberPlane.class.getName()); public GaussianNumberPlane(WatorModel model) { this.worldDimensions = model.getWorldDimensions(); this.lattice = new int[worldDimensions.getWidth()][worldDimensions.getHeight()]; this.complexWorldDimensions = new ComplexNumber( complexWorldDimensionRealX, complexWorldDimensionImgY ); this.complexCenterForMandelbrot = new ComplexNumber( complexCenterForMandelbrotRealX, complexCenterForMandelbrotImgY ); this.complexCenterForJulia = new ComplexNumber( complexCenterForJuliaRealX, complexCenterForJuliaImgY ); start(); } public void setModeZoom() { this.setZoomLevel(1); this.setZoomCenter(complexCenterForMandelbrot); } public synchronized void start(){ zoomLevel = 1; for(int y = 0;y < this.worldDimensions.getY(); y++){ for(int x=0; x < worldDimensions.getX(); x++){ lattice[x][y] = YET_UNCOMPUTED; } } } public synchronized int getCellStatusFor(int x,int y){ return (lattice[x][y])<0?0:lattice[x][y]; } private synchronized ComplexNumber getComplexNumberFromLatticeCoordsForJulia(Point turingPosition) { double realX = complexCenterForJulia.getReal() + (complexWorldDimensions.getReal()*turingPosition.getX())/worldDimensions.getX(); double imgY = complexCenterForJulia.getImg() + (complexWorldDimensions.getImg()*turingPosition.getY())/worldDimensions.getY(); return new ComplexNumber(realX,imgY); } private synchronized ComplexNumber getComplexNumberFromLatticeCoordsForMandelbrot(Point turingPosition) { double realX = ( complexCenterForMandelbrot.getReal() + ( complexWorldDimensions.getReal() * turingPosition.getX() ) / worldDimensions.getX() ); double imgY = ( complexCenterForMandelbrot.getImg() + ( complexWorldDimensions.getImg() * turingPosition.getY() ) / worldDimensions.getY() ); return new ComplexNumber(realX,imgY); } private synchronized ComplexNumber getComplexNumberFromLatticeCoordsForZoomedMandelbrot(Point turingPosition) { double realX = ( ( complexCenterForMandelbrot.getReal() / this.getZoomLevel() ) + getZoomCenter().getReal() + ( complexWorldDimensions.getReal() * turingPosition.getX() ) / ( worldDimensions.getX() * this.getZoomLevel() ) ); double imgY = ( ( complexCenterForMandelbrot.getImg() / this.getZoomLevel() ) + getZoomCenter().getImg() + ( complexWorldDimensions.getImg() * turingPosition.getY() ) / ( worldDimensions.getY() * this.getZoomLevel() ) ); return new ComplexNumber(realX,imgY); } public synchronized boolean isInZooomedMandelbrotSet(Point turingPosition) { ComplexNumber position = this.getComplexNumberFromLatticeCoordsForZoomedMandelbrot(turingPosition); lattice[turingPosition.getX()][turingPosition.getY()] = position.computeMandelbrotSet(); return position.isInMandelbrotSet(); } public synchronized boolean isInMandelbrotSet(Point turingPosition) { ComplexNumber position = this.getComplexNumberFromLatticeCoordsForMandelbrot(turingPosition); lattice[turingPosition.getX()][turingPosition.getY()] = position.computeMandelbrotSet(); return position.isInMandelbrotSet(); } public synchronized void fillTheOutsideWithColors(){ for(int y=0;y<worldDimensions.getY();y++){ for(int x=0;x<worldDimensions.getX();x++){ if(lattice[x][y] == YET_UNCOMPUTED){ this.isInMandelbrotSet(new Point(x, y)); } } } } private synchronized void computeTheJuliaSetForC(ComplexNumber c) { for(int y = 0; y < worldDimensions.getY(); y++) { for (int x = 0; x < worldDimensions.getX(); x++) { Point zPoint = new Point(x, y); ComplexNumber z = this.getComplexNumberFromLatticeCoordsForJulia(zPoint); lattice[x][y] = z.computeJuliaSet(c); } } } public synchronized void computeTheJuliaSetFor(Point pointFromMandelbrotSet) { ComplexNumber c = getComplexNumberFromLatticeCoordsForMandelbrot(pointFromMandelbrotSet); this.complexNumberForJuliaSetC = c; computeTheJuliaSetForC(c); } public void zoomIntoTheMandelbrotSet(Point zoomPoint) { //log.info("zoomIntoTheMandelbrotSet: "+ zoomPoint +" - old: "+this.getZoomCenter()); this.inceaseZoomLevel(); if(this.getZoomLevel() == 2){ ComplexNumber complexCenter = new ComplexNumber(this.complexCenterForMandelbrot); complexCenterForZoomedMandelbrot.push(complexCenter); this.setZoomCenter(getComplexNumberFromLatticeCoordsForMandelbrot(zoomPoint)); } else { this.setZoomCenter(getComplexNumberFromLatticeCoordsForZoomedMandelbrot(zoomPoint)); } complexCenterForZoomedMandelbrot.push(this.getZoomCenter()); //log.info("zoomPoint: "+ zoomPoint); //log.info("zoomCenterNew: " + this.getZoomCenter() + " - zoomLevel: "+ this.getZoomLevel()); for(int y = 0; y < worldDimensions.getY(); y++){ for(int x = 0; x < worldDimensions.getX(); x++){ Point p = new Point(x, y); this.isInZooomedMandelbrotSet(p); } } } public void zoomOutOfTheMandelbrotSet() { //log.info("zoomOutOfTheMandelbrotSet: " + this.getZoomCenter()); if(this.getZoomLevel()>1){ this.deceaseZoomLevel(); this.setZoomCenter(complexCenterForZoomedMandelbrot.pop()); } //log.info("zoomCenter: " + this.getZoomCenter() + " - zoomLevel: "+ this.getZoomLevel()); for(int y = 0; y < worldDimensions.getY(); y++){ for(int x = 0; x < worldDimensions.getX(); x++){ Point p = new Point(x, y); this.isInZooomedMandelbrotSet(p); } } } public void zoomIntoTheJuliaSetFor(Point zoomPoint) { ComplexNumber c = this.complexNumberForJuliaSetC; computeTheJuliaSetForC(c); } public void zoomOutOfTheJuliaSet() { } public synchronized int getZoomLevel() { return zoomLevel; } public synchronized void setZoomLevel(int zoomLevel) { this.zoomLevel = zoomLevel; } public synchronized int inceaseZoomLevel() { return zoomLevel *= 2; } public synchronized int deceaseZoomLevel() { return zoomLevel /= 2; } public synchronized ComplexNumber getZoomCenter() { return zoomCenter; } public synchronized void setZoomCenter(ComplexNumber zoomCenter) { this.zoomCenter = zoomCenter; } }
#!/bin/sh set -eu fn=$1 src=$2 date=$(git log --max-count=1 --format=%ad --date=format:%FT%TZ $src) sed -e '/^%%%/,/^%%%/s/\(^date[ ]*=[ ]*\).*/\1'$date'/' \ -e '/^%%%/,/^%%%/s/\(^value[ ]*=[ ]*\).*/\1"'$fn'"/' \ <$src >$src.stamp if ! diff -u $src $src.stamp then mv $src.stamp $src else rm $src.stamp fi
package de.htwg.se.uno package controller.controllerComponent import util.Invoker import model.gameComponent._ import util.Observable trait controllerInterface extends Observable { var game: gameInterface val invoker: Invoker def take(): Unit def place(ind: Int): Unit def next(): Unit def undo(): Unit def redo(): Unit def newG(p1: String, p2: String): Unit def WinG(p1: String, p2: String): Unit def colorChoose(color: String): Unit override def toString: String def load: Unit def save: Unit }
#!/bin/bash set -euo pipefail git pull origin master . ./venv/bin/activate python3 documentation_parser.py if git status --porcelain Versions | grep '^??' > /dev/null 2>&1; then git add 'Versions/*' version=$(git status --porcelain Versions | head -n1 | sed -Ee 's/.+-([0-9.]+)\..+/\1/') git commit -m "Add parsed documentation version $version" git push origin master fi