text
stringlengths
1
1.05M
"use strict"; function asBadStateSetsData(data) { return data; } ; /** バッドステート群 */ class BadStates { constructor(badStateSets) { this.badStateSets = badStateSets; this.badStateSetNames = Object.keys(this.badStateSets).sort((a, b) => this.badStateSets[a].index - this.badStateSets[b].index); } static fromData(badStateSets) { return new BadStates(Object.keys(badStateSets).reduce((sets, setName, index) => { sets[setName] = BadStateSet.fromData(setName, index, badStateSets[setName]); return sets; }, {})); } findSet(setName) { return this.badStateSets[setName]; } } /** バッドステートセット */ class BadStateSet { constructor(name, index, badStates) { /* available = (stage: number, challenge: number, progress: number) => this.badStates.filter((badState) => badState.isAvailable(stage, challenge, progress)); */ this.byProgress = (progress) => this.badStates[progress - 1]; this.name = name; this.index = index; this.badStates = badStates; } static fromData(name, index, badStates) { return new BadStateSet(name, index, badStates.map((badState, index) => new BadState(Object.assign({ setName: name, setIndex: index, progress: index + 1, name }, badState)))); } get maxProgress() { return this.badStates.length; } } /** バッドステート */ class BadState { constructor(param) { this.sensitivity = 0; this.hideSpeed = 100; this.prod = 100; this.sensation = 0; this.speak = []; this.speakInterval = 1000; this.trigger = []; this.periodDown = 1; this.endTrigger = []; this.danger = []; for (const name of Object.keys(param)) { if (param[name] != null) this[name] = param[name]; } } /** 追加効果発動が必要か */ get needTrigger() { return Boolean(this.stop || this.speak.length || this.sensation || this.trigger.length); } get displayName() { return this.name + (this.level == null ? "" : " " + this.level); } /*isAvailable = (stage: number, challenge: number, progress: number) => this.minStage <= stage && this.minChallenge <= challenge && progress === this.progress - 1; */ triggersNow() { return Math.random() * 100 < (this.prod || 100); } randomSpeak() { return this.speak.map((speakStep) => speakStep instanceof Array ? speakStep[Math.floor(Math.random() * speakStep.length)] : speakStep); } } const badStateDescriptionJa = { setName: "系列名", displayName: "名称", description: "説明", sensitivity: "感度", hideSpeed: "スピード", delay: "遅延", prod: "+効果発動条件", stop: "+効果: 行動不能", sensation: "+効果: 快感", trigger: "+効果: 誘発", period: "持続時間", endTrigger: "解消時誘発", count: "カウント", countActivate: "付与条件(累計回数)", activeCountActivate: "付与条件(付与以後回数)", danger: "危険性", stageDown: "バトル後解消", retryDown: "治療", }; class BadStateDescription { constructor(badState, bias = 1) { this.badState = badState; this.bias = bias; } get summary() { return [ this.description, this.delay, this.stop, this.period, this.sensitivity.join(" "), ].filter((str) => Boolean(str)).join(" "); } get setName() { return this.badState.setName; } get displayName() { return this.badState.displayName; } get description() { return this.badState.description; } get sensitivityObject() { if (typeof this.badState.sensitivity === "number") { if (this.badState.sensitivity === 0) return []; return [{ part: "all", rate: this.badState.sensitivity }]; } const descriptions = []; for (const part of PlayerSensitivity.parts) { const rate = this.badState.sensitivity[part]; if (rate) descriptions.push({ part, rate }); } return descriptions; } get sensitivity() { return this.sensitivityObject.map((desc) => `${PlayerSensitivity.ja(desc.part, true)}感度+${desc.rate}%`); } get hideSpeed() { if (this.badState.hideSpeed > 100) { return `通常の${float2(this.badState.hideSpeed / 100)}倍遅く隠れる`; } else if (this.badState.hideSpeed < 100) { return `通常の${float2(100 / this.badState.hideSpeed)}倍速く隠れる`; } return; } get delay() { if (this.badState.delay) return `反応が${this.biasFormula(this.badState.delay / 1000)}秒遅れる`; } get prod() { if (this.badState.needTrigger) return `${this.badState.cycle ? `${float2(this.badState.cycle / 1000)}秒に一回` : ""}${this.badState.prod || 100}%の確率で+効果発動`; } get stop() { if (this.badState.stop) return `+効果発動で${this.biasFormula(this.badState.stop / 1000)}秒動けなくなる`; } get sensation() { if (this.badState.sensation) return `+効果発動で${this.badState.sensation === 1 ? "等" : this.badState.sensation}倍の快感を得る`; } get trigger() { if (this.badState.trigger && this.badState.trigger.length) return `+効果発動で${this.badState.trigger.map(param => typeof param === "string" ? param : param.name).join(", ")}を誘発`; } get period() { if (this.badState.period) return `${this.biasFormula(this.badState.period / 1000)}秒で${this.badState.periodDown === true ? "" : `${this.badState.periodDown}段階`}解消`; } get endTrigger() { if (this.badState.endTrigger && this.badState.endTrigger.length) return `解消時${this.badState.endTrigger.join(", ")}を誘発`; } get count() { if (this.badState.count) return `誘発(付与されない場合も含む)されると${this.badState.setName}のカウントが${this.badState.count}回増える`; } get countActivate() { if (this.badState.countActivate && this.badState.countActivate.length) return this.badState.countActivate.map((condition) => `${condition.name}の累計カウントが${condition.count}回以上`).join("、") + "になると付与可能になる"; } get activeCountActivate() { if (this.badState.activeCountActivate && this.badState.activeCountActivate.length) return this.badState.activeCountActivate.map((condition) => `${condition.name}の付与以降カウントが${condition.count}回以上`).join("、") + "になると付与可能になる"; } get danger() { if (this.badState.danger && this.badState.danger.length) return `${this.badState.danger.join("、")}の危険がある`; } get stageDown() { if (this.badState.stageDown) return this.badState.stageDown === true ? "バトルを終わると解消する" : `バトルを終わると${this.badState.stageDown}段階解消する`; } get retryDown() { return this.badState.retryDown ? this.badState.retryDown === true ? "治療で完全に解消する" : `治療をうけると${this.badState.retryDown}段階解消する` : "治療不能"; } biasFormula(value) { return this.bias === 1 ? `${float2(value)}` : `${float2(value * this.bias)}`; } } BadStateDescription.ja = badStateDescriptionJa; function float2(value) { return Math.round(value * 100) / 100; }
<filename>src/main/java/net/kardexo/kardexotools/command/CommandBase.java package net.kardexo.kardexotools.command; import java.util.EnumSet; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket; import net.minecraft.network.protocol.game.ClientboundSetExperiencePacket; import net.minecraft.server.commands.TeleportCommand; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; public class CommandBase { public static CommandSyntaxException exception(String message) { return new SimpleCommandExceptionType(new TranslatableComponent(message)).create(); } public static int teleport(CommandSourceStack source, ServerPlayer player, ServerLevel level, BlockPos position) throws CommandSyntaxException { TeleportCommand.performTeleport(source, player, level, position.getX() + 0.5F, position.getY(), position.getZ() + 0.5F, EnumSet.noneOf(ClientboundPlayerPositionPacket.RelativeArgument.class), player.getYRot(), player.getXRot(), null); player.connection.send(new ClientboundSetExperiencePacket(player.experienceProgress, player.totalExperience, player.experienceLevel)); return 1; } }
#pragma once #include <QString> namespace FileUtils { QString getBaseName( QString sourceFile); QString getDirName( QString sourceFile); };
#!/bin/sh echo "fix: vulnerabilities : $(date --iso-8601=ns)"
#!/bin/bash echo "Não implementado ainda"
/* * (C) Copyright 2017-2018, by <NAME> and Contributors. * * JGraphT : a free Java graph-theory library * * This program and the accompanying materials are dual-licensed under * either * * (a) the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation, or (at your option) any * later version. * * or (per the licensee's choosing) * * (b) the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation. */ package org.jgrapht.generate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; import org.junit.*; /** * Tests for ComplementGraphGenerator * * @author <NAME> */ public class ComplementGraphGeneratorTest { @Test public void testEmptyGraph() { // Complement of a graph without edges is the complete graph Graph<Integer, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); Graphs.addAllVertices(g, Arrays.asList(0, 1, 2, 3)); ComplementGraphGenerator<Integer, DefaultEdge> cgg = new ComplementGraphGenerator<>(g); Graph<Integer, DefaultEdge> target = new SimpleWeightedGraph<>(DefaultEdge.class); cgg.generateGraph(target); assertTrue(GraphTests.isComplete(target)); // complement of a complement graph is the original graph ComplementGraphGenerator<Integer, DefaultEdge> cgg2 = new ComplementGraphGenerator<>(target); Graph<Integer, DefaultEdge> target2 = new SimpleWeightedGraph<>(DefaultEdge.class); cgg2.generateGraph(target2); assertTrue(target2.edgeSet().isEmpty()); assertTrue(target2.vertexSet().equals(g.vertexSet())); } @Test public void testUndirectedGraph() { Graph<Integer, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); Graphs.addAllVertices(g, Arrays.asList(0, 1, 2, 3)); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(0, 2); ComplementGraphGenerator<Integer, DefaultEdge> cgg = new ComplementGraphGenerator<>(g); Graph<Integer, DefaultEdge> target = new SimpleWeightedGraph<>(DefaultEdge.class); cgg.generateGraph(target); assertTrue(target.vertexSet().equals(new HashSet<>(Arrays.asList(0, 1, 2, 3)))); assertEquals(3, target.edgeSet().size()); assertTrue(target.containsEdge(0, 3)); assertTrue(target.containsEdge(2, 3)); assertTrue(target.containsEdge(1, 3)); } @Test public void testDirectedGraph() { Graph<Integer, DefaultEdge> g = new SimpleDirectedGraph<>(DefaultEdge.class); Graphs.addAllVertices(g, Arrays.asList(0, 1, 2)); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(0, 2); ComplementGraphGenerator<Integer, DefaultEdge> cgg = new ComplementGraphGenerator<>(g); Graph<Integer, DefaultEdge> target = new SimpleWeightedGraph<>(DefaultEdge.class); cgg.generateGraph(target); assertTrue(target.vertexSet().equals(new HashSet<>(Arrays.asList(0, 1, 2)))); assertEquals(3, target.edgeSet().size()); assertTrue(target.containsEdge(1, 0)); assertTrue(target.containsEdge(2, 1)); assertTrue(target.containsEdge(2, 0)); } @Test public void testGraphWithSelfLoops() { Graph<Integer, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); Graphs.addAllVertices(g, Arrays.asList(0, 1, 2)); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(0, 2); ComplementGraphGenerator<Integer, DefaultEdge> cgg = new ComplementGraphGenerator<>(g, true); Graph<Integer, DefaultEdge> target = new Pseudograph<>(DefaultEdge.class); cgg.generateGraph(target); assertTrue(target.vertexSet().equals(new HashSet<>(Arrays.asList(0, 1, 2)))); assertEquals(3, target.edgeSet().size()); for (Integer v : target.vertexSet()) assertTrue(target.containsEdge(v, v)); } }
package org.museautomation.ui.valuesource.parser; import org.museautomation.parsing.valuesource.antlr.*; import org.museautomation.core.*; import org.museautomation.core.values.*; import java.util.*; /** * @author <NAME> (see LICENSE.txt for license details) */ public class VSBuilder extends ValueSourceBaseListener { VSBuilder(MuseProject project) { _project = project; } public ValueSourceConfiguration getSource() { if (_error != null) return null; if (_parse_stack.peek() instanceof ValueSourceConfiguration) return (ValueSourceConfiguration) _parse_stack.pop(); return null; } @Override public void exitLiteral(ValueSourceParser.LiteralContext context) { String text = context.getText(); for (ValueSourceStringExpressionSupport support : getSupporters()) { ValueSourceConfiguration config = support.fromLiteral(text, _project); if (config != null) { _parse_stack.push(config); return; } } } @Override public void exitPrefixedExpression(ValueSourceParser.PrefixedExpressionContext context) { String prefix = context.getChild(0).getText(); for (ValueSourceStringExpressionSupport support : getSupporters()) { if (!_parse_stack.isEmpty()) { ValueSourceConfiguration config = support.fromPrefixedExpression(prefix, (ValueSourceConfiguration) _parse_stack.peek(), _project); if (config != null) { _parse_stack.pop(); _parse_stack.push(config); return; } } } _error = "No support found for prefixed expression: " + prefix + context.getChild(1).getText(); } @Override public void enterElementExpression(ValueSourceParser.ElementExpressionContext ctx) { _parse_stack.push(ParseStackMarker.ElementExpression); } @Override public void exitElementExpression(ValueSourceParser.ElementExpressionContext context) { String type_id = context.getChild(1).getText(); // pop the arguments off the stack Object stack_item = _parse_stack.pop(); List<ValueSourceConfiguration> arguments = new ArrayList<>(); while (!(stack_item.equals(ParseStackMarker.ElementExpression))) { if (stack_item instanceof ValueSourceConfiguration) arguments.add(0, (ValueSourceConfiguration)stack_item); // insert at beginning, since we are popping from a stack, to pass in correct order to the ExpressionSupport else _error = String.format("Did not expect to see a %s on the stack: %s", stack_item.getClass().getSimpleName(), stack_item.toString()); stack_item = _parse_stack.pop(); } for (ValueSourceStringExpressionSupport support : getSupporters()) { ValueSourceConfiguration config = support.fromElementExpression(type_id, arguments, _project); if (config != null) { _parse_stack.push(config); return; } } _error = String.format("No support found for element expression: %s", context.getText()); } @Override public void enterElementLookupExpression(ValueSourceParser.ElementLookupExpressionContext context) { _parse_stack.push(ParseStackMarker.ElementLookupExpression); } @Override public void exitElementLookupExpression(ValueSourceParser.ElementLookupExpressionContext context) { // pop the arguments off the stack Object stack_item = _parse_stack.pop(); List<ValueSourceConfiguration> arguments = new ArrayList<>(); while (!(stack_item.equals(ParseStackMarker.ElementLookupExpression))) { if (stack_item instanceof ValueSourceConfiguration) arguments.add(0, (ValueSourceConfiguration)stack_item); else if (stack_item instanceof String) arguments.add(0, ValueSourceConfiguration.forValue(stack_item)); else _error = String.format("Did not expect to see a %s on the stack: %s", stack_item.getClass().getSimpleName(), stack_item.toString()); stack_item = _parse_stack.pop(); } if (arguments.size() == 1) _error = "Must not use a literal and an expresssion. Pick one or the other and use for both page and element"; if (arguments.size() < 2) { arguments.add(0, ValueSourceConfiguration.forValue(context.getChild(1).getText())); arguments.add(1, ValueSourceConfiguration.forValue(context.getChild(3).getText())); } for (ValueSourceStringExpressionSupport support : getSupporters()) { ValueSourceConfiguration config = support.fromElementLookupExpression(arguments, _project); if (config != null) { _parse_stack.push(config); return; } } _error = String.format("No support found for element expression: %s", context.getText()); } @Override public void enterArgumentedExpression(ValueSourceParser.ArgumentedExpressionContext ctx) { _parse_stack.push(ParseStackMarker.ArgumentedExpression); } @Override public void exitArgumentedExpression(ValueSourceParser.ArgumentedExpressionContext context) { String function_name = context.getChild(0).getText(); // pop the arguments off the stack Object stack_item = _parse_stack.pop(); List<ValueSourceConfiguration> arguments = new ArrayList<>(); while (!(stack_item.equals(ParseStackMarker.ArgumentedExpression))) { if (stack_item instanceof ValueSourceConfiguration) arguments.add(0, (ValueSourceConfiguration)stack_item); else _error = String.format("Did not expect to see a %s on the stack: %s", stack_item.getClass().getSimpleName(), stack_item.toString()); stack_item = _parse_stack.pop(); } for (ValueSourceStringExpressionSupport support : getSupporters()) { ValueSourceConfiguration config = support.fromArgumentedExpression(function_name, arguments, _project); if (config != null) { _parse_stack.push(config); return; } } _error = String.format("No support found for function name '%s' in argumented expression: %s", function_name, context.getText()); } @Override public void exitBinaryExpression(ValueSourceParser.BinaryExpressionContext context) { String operator = context.getChild(1).getText(); ValueSourceConfiguration right = (ValueSourceConfiguration) _parse_stack.pop(); ValueSourceConfiguration left = (ValueSourceConfiguration) _parse_stack.pop(); for (ValueSourceStringExpressionSupport support : getSupporters()) { ValueSourceConfiguration config = support.fromBinaryExpression(left, operator, right, _project); if (config != null) { _parse_stack.push(config); return; } } _error = String.format("No support found for binary operator '%s' in expression: %s", operator, context.getText()); } @Override public void exitBooleanExpression(ValueSourceParser.BooleanExpressionContext context) { String operator = context.getChild(1).getText(); ValueSourceConfiguration right = (ValueSourceConfiguration) _parse_stack.pop(); ValueSourceConfiguration left = (ValueSourceConfiguration) _parse_stack.pop(); for (ValueSourceStringExpressionSupport support : getSupporters()) { ValueSourceConfiguration config = support.fromBooleanExpression(left, operator, right, _project); if (config != null) { _parse_stack.push(config); return; } } _error = String.format("No support found for boolean operator '%s' in expression: %s", operator, context.getText()); } @Override public void exitDotExpression(ValueSourceParser.DotExpressionContext context) { String operator = context.getChild(1).getText(); ValueSourceConfiguration right = (ValueSourceConfiguration) _parse_stack.pop(); ValueSourceConfiguration left = (ValueSourceConfiguration) _parse_stack.pop(); for (ValueSourceStringExpressionSupport support : getSupporters()) { ValueSourceConfiguration config = support.fromDotExpression(left, right, _project); if (config != null) { _parse_stack.push(config); return; } } _error = String.format("No support found for binary operator '%s' in expression: %s", operator, context.getText()); } @Override public void enterArrayExpression(ValueSourceParser.ArrayExpressionContext ctx) { _parse_stack.push(ParseStackMarker.ArrayExpression); } @Override public void exitArrayExpression(ValueSourceParser.ArrayExpressionContext context) { // pop the arguments off the stack Object stack_item = _parse_stack.pop(); List<ValueSourceConfiguration> arguments = new ArrayList<>(); while (!(stack_item.equals(ParseStackMarker.ArrayExpression))) { if (stack_item instanceof ValueSourceConfiguration) arguments.add(0, (ValueSourceConfiguration) stack_item); else _error = String.format("Did not expect to see a %s on the stack: %s", stack_item.getClass().getSimpleName(), stack_item.toString()); stack_item = _parse_stack.pop(); } for (ValueSourceStringExpressionSupport support : getSupporters()) { ValueSourceConfiguration config = support.fromArrayExpression(arguments, _project); if (config != null) { _parse_stack.push(config); return; } } _error = "No support found for array expression"; } @Override public void exitArrayItemExpression(ValueSourceParser.ArrayItemExpressionContext context) { String operator = context.getChild(1).getText(); ValueSourceConfiguration selector = (ValueSourceConfiguration) _parse_stack.pop(); ValueSourceConfiguration collection = (ValueSourceConfiguration) _parse_stack.pop(); for (ValueSourceStringExpressionSupport support : getSupporters()) { ValueSourceConfiguration config = support.fromArrayItemExpression(collection, selector, _project); if (config != null) { _parse_stack.push(config); return; } } _error = String.format("No support found for binary operator '%s' in expression: %s", operator, context.getText()); } private List<ValueSourceStringExpressionSupport> getSupporters() { if (_supporters == null) _supporters = _project.getClassLocator().getInstances(ValueSourceStringExpressionSupport.class); return _supporters; } private Stack _parse_stack = new Stack<>(); private MuseProject _project; private String _error = null; private List<ValueSourceStringExpressionSupport> _supporters; }
YUI.add('aui-boolean-data-editor-tests', function(Y) { var suite = new Y.Test.Suite('aui-boolean-data-editor'); suite.add(new Y.Test.Case({ name: 'AUI Boolean Data Editor Unit Tests', init: function() { this._container = Y.one('#container'); }, setUp: function() { this.createBooleanDataEditor({ editedValue: true, originalValue: true, checkedContent: 'Editor Checked', uncheckedContent: 'Editor Unchecked' }); }, tearDown: function() { this._booleanDataEditor && this._booleanDataEditor.destroy(); }, createBooleanDataEditor: function(config) { var content = Y.Node.create('<div id="content"></div>'); this._booleanDataEditor = new Y.BooleanDataEditor(config); content.append(this._booleanDataEditor.get('node')); this._container.append(content); }, 'should set the inner labels': function () { var editor = this._booleanDataEditor; Y.Assert.areEqual(editor.get('node').one('.button-switch-inner-label-left').getHTML(), ''); Y.Assert.areEqual(editor.get('node').one('.button-switch-inner-label-right').getHTML(), ''); editor.set('innerLabelLeft', 'left'); editor.set('innerLabelRight', 'right'); Y.Assert.areEqual(editor.get('node').one('.button-switch-inner-label-left').getHTML(), 'left'); Y.Assert.areEqual(editor.get('node').one('.button-switch-inner-label-right').getHTML(), 'right'); }, 'should update the ui according to the edited value': function() { var contentNode = this._booleanDataEditor.get('node').one('.boolean-data-editor-content'); Y.Assert.areEqual('Editor Checked', contentNode.get('text')); this._booleanDataEditor.set('editedValue', false); Y.Assert.areEqual('Editor Unchecked', contentNode.get('text')); this._booleanDataEditor.set('editedValue', true); Y.Assert.areEqual('Editor Checked', contentNode.get('text')); }, 'should update the ui with checkedContent': function () { var checkedNode, contentNode = this._booleanDataEditor.get('node').one('.boolean-data-editor-content'); this._booleanDataEditor.set('checkedContent', 'Editor Checked 2'); Y.Assert.areEqual('Editor Checked 2', contentNode.get('text')); checkedNode = Y.Node.create('<label class="myClass">Node Content</label>'); this._booleanDataEditor.set('checkedContent', checkedNode); Y.Assert.isNotNull(contentNode.one('.myClass')); Y.Assert.areEqual('Node Content', contentNode.get('text')); }, 'should not update the ui with checkedContent if editor is unchecked': function () { var contentNode = this._booleanDataEditor.get('node').one('.boolean-data-editor-content'); this._booleanDataEditor.set('editedValue', false); this._booleanDataEditor.set('checkedContent', 'Editor Checked 2'); Y.Assert.areEqual('Editor Unchecked', contentNode.get('text')); }, 'should not update the ui with invalid checkedContent': function () { var contentNode = this._booleanDataEditor.get('node').one('.boolean-data-editor-content'); this._booleanDataEditor.set('checkedContent', 42); Y.Assert.areEqual('Editor Checked', contentNode.get('text')); }, 'should update the ui with uncheckedContent': function () { var contentNode = this._booleanDataEditor.get('node').one('.boolean-data-editor-content'), uncheckedNode; this._booleanDataEditor.set('editedValue', false); this._booleanDataEditor.set('uncheckedContent', Y.Node.create('Editor Unchecked 2')); Y.Assert.areEqual('Editor Unchecked 2', contentNode.get('text')); uncheckedNode = Y.Node.create('<label class="myClass">Node Content</label>'); this._booleanDataEditor.set('uncheckedContent', uncheckedNode); Y.Assert.isNotNull(contentNode.one('.myClass')); Y.Assert.areEqual('Node Content', contentNode.get('text')); }, 'should not update the ui with uncheckedContent if editor is checked': function () { var contentNode = this._booleanDataEditor.get('node').one('.boolean-data-editor-content'); this._booleanDataEditor.set('uncheckedContent', 'Editor Unchecked 2'); Y.Assert.areEqual('Editor Checked', contentNode.get('text')); }, 'should not update the ui with invalid uncheckedContent': function () { var contentNode = this._booleanDataEditor.get('node').one('.boolean-data-editor-content'); this._booleanDataEditor.set('editedValue', false); this._booleanDataEditor.set('uncheckedContent', 42); Y.Assert.areEqual('Editor Unchecked', contentNode.get('text')); }, 'should update the ui when the edited value is udpated': function() { var editor = this._booleanDataEditor; editor.set('editedValue', false); Y.Assert.isTrue(editor.get('node').one('.button-switch-inner-label-left').hasClass('hide')); Y.Assert.isFalse(editor.get('node').one('.button-switch-inner-label-right').hasClass('hide')); Y.Assert.isFalse(editor.get('editedValue')); editor.set('editedValue', true); Y.Assert.isFalse(editor.get('node').one('.button-switch-inner-label-left').hasClass('hide')); Y.Assert.isTrue(editor.get('node').one('.button-switch-inner-label-right').hasClass('hide')); Y.Assert.isTrue(editor.get('editedValue')); }, 'should get edited value from the ui': function() { var editor = this._booleanDataEditor, button; button = Y.one('.button-switch'); button.simulate('click'); Y.Assert.isFalse(editor.get('editedValue')); button.simulate('click'); Y.Assert.isTrue(editor.get('editedValue')); }, 'should show content related to the checked state of the editor': function() { var editor = this._booleanDataEditor, button; editor.set('checkedContent', 'Editor Checked'); editor.set('uncheckedContent', 'Editor Unchecked'); button = Y.one('.button-switch'); Y.Assert.areEqual('Editor Checked', editor.get('node').one('.boolean-data-editor-content').getHTML()); button.simulate('click'); Y.Assert.areEqual('Editor Unchecked', editor.get('node').one('.boolean-data-editor-content').getHTML()); button.simulate('click'); Y.Assert.areEqual('Editor Checked', editor.get('node').one('.boolean-data-editor-content').getHTML()); }, 'should check if the form is valid': function() { var editor; editor = new Y.BooleanDataEditor(); Y.Assert.isTrue(editor.isValid()); editor.set('required', true); Y.Assert.isTrue(editor.isValid()); } })); Y.Test.Runner.add(suite); },'', { requires: [ 'aui-boolean-data-editor', 'node-event-simulate' ] });
const PreferenceIndicator = require('./PreferenceIndicator') const RequestHandler = require('./RequestHandler') const types = PreferenceIndicator.App.Externals.NekosLifeAPIRoutes const baseURI = 'https://nekos.life/api/v2' const NekosLifeAPIParser = type => { return new Promise((resolve, reject) => { const requestURI = `${baseURI}/img/${type}` RequestHandler(requestURI).then(rawdata => { const url = JSON.parse(rawdata).url resolve(url) }).catch(rejection => { console.error(rejection) reject('NekosLifeAPIParser: Could not parse URL: ', rejection) }) }) } module.exports = NekosLifeAPIParser
class Database: def connect(self, database_name): # Implement database connection logic here pass class Person(Database): def add_name(self, name): # Implement adding a new name to the database if self.name_exists(name): raise DuplicateNameError("Name already exists in the database") # Add the name to the database def get_name_by_id(self, person_id): # Implement retrieving the name by ID if not self.id_exists(person_id): raise NameNotFoundError("Name not found for the given ID") # Retrieve and return the name associated with the ID def update_name(self, person_id, new_name): # Implement updating the name by ID if not self.id_exists(person_id): raise NameNotFoundError("Name not found for the given ID") # Update the name associated with the ID def name_exists(self, name): # Check if the name already exists in the database pass def id_exists(self, person_id): # Check if the ID exists in the database pass class DuplicateNameError(Exception): pass class NameNotFoundError(Exception): pass
function convertArraytoDict(array) { const obj = {}; if (array.length % 2 !== 0) { throw new Error('array should have even elements'); } for (let i = 0; i < array.length; i+=2) { obj[array[i]] = array[i+1]; } return obj; }
SELECT product_name, SUM(units_sold) as total_sales FROM orders WHERE country = 'USA' GROUP BY product_name ORDER BY total_sales ASC LIMIT 5;
def aggregate(string): result = {} for char in string: if char not in result: result[char] = 1 else: result[char] += 1 return result
# Function to calculate the length of the list def circular_length(head): current = head counter = 0 while current is not None: counter += 1 current = current.next if current == head: break return counter # Driver code length = circular_length(first) print("Number of nodes in circular list:",length)
import React from 'react'; import { Link } from 'react-router-dom'; import Button from '@material-ui/core/Button'; import Box from '@material-ui/core/Box'; import Grid from '@material-ui/core/Grid'; function Header() { return ( <Grid container direction="row" justify="center" alignItems="center"> <Box p={2}> <Button data-testid="home" variant="outlined" to="/" component={Link} color="primary" size="large" > Home </Button> </Box> <Box p={2}> <Button data-testid="about" variant="outlined" to="/about" component={Link} color="primary" size="large" > About </Button> </Box> </Grid> ); } export default Header;
#!/bin/bash # From https://misc.flogisoft.com/bash/tip_colors_and_formatting # This program is free software. It comes without any warranty, to # the extent permitted by applicable law. You can redistribute it # and/or modify it under the terms of the Do What The Fuck You Want # To Public License, Version 2, as published by Sam Hocevar. See # http://sam.zoy.org/wtfpl/COPYING for more details. for fgbg in 38 48 ; do # Foreground / Background for color in {0..255} ; do # Colors # Display the color printf "\e[${fgbg};5;%sm %3s \e[0m" $color $color # Display 6 colors per lines if [ $((($color + 1) % 6)) == 4 ] ; then echo # New line fi done echo # New line done exit 0
let ax = 50; let bxv = 40; testIf(ax, bxv) function testIf(a, b) { var x; if (a>b) { x = a +b; } else { x = a*b; } return x; }
package cbim import ( "testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "sigs.k8s.io/controller-runtime/pkg/envtest/printer" //+kubebuilder:scaffold:imports ) // These tests use Ginkgo (BDD-style Go testing framework). Refer to // http://onsi.github.io/ginkgo/ to learn more about Ginkgo. func TestAPIs(t *testing.T) { RegisterFailHandler(Fail) RunSpecsWithDefaultAndCustomReporters(t, "V1Beta1 Suite", []Reporter{printer.NewlineReporter{}}) } var _ = Describe("GlobalSecondaryIndexIdentifier.ToString", func() { It("should exclude the default collection name", func() { // Arrange identifier := GlobalSecondaryIndexIdentifier{ ScopeName: "_default", CollectionName: "_default", Name: "my_index", } // Act result := identifier.ToString() // Assert Expect(result).To(Equal("my_index")) }) It("should return a dotted name", func() { // Arrange identifier := GlobalSecondaryIndexIdentifier{ ScopeName: "scope", CollectionName: "_default", Name: "my_index", } // Act result := identifier.ToString() // Assert Expect(result).To(Equal("scope._default.my_index")) }) }) var _ = Describe("ParseIndexIdentifierString", func() { It("should error on empty string", func() { // Act _, err := ParseIndexIdentifierString("") // Assert Expect(err).NotTo(BeNil()) }) It("should error on empty segment", func() { // Act _, err := ParseIndexIdentifierString("scope..name") // Assert Expect(err).NotTo(BeNil()) }) It("should error on two segments", func() { // Act _, err := ParseIndexIdentifierString("scope.name") // Assert Expect(err).NotTo(BeNil()) }) It("should error on four segments", func() { // Act _, err := ParseIndexIdentifierString("scope.collection.name.extra") // Assert Expect(err).NotTo(BeNil()) }) It("should return simple name in default collection", func() { // Act result, err := ParseIndexIdentifierString("name") // Assert Expect(result).To(Equal(GlobalSecondaryIndexIdentifier{ ScopeName: "_default", CollectionName: "_default", Name: "name", })) Expect(err).To(BeNil()) }) It("should return dotted name", func() { // Act result, err := ParseIndexIdentifierString("scope.collection.name") // Assert Expect(result).To(Equal(GlobalSecondaryIndexIdentifier{ ScopeName: "scope", CollectionName: "collection", Name: "name", })) Expect(err).To(BeNil()) }) })
<reponame>teamcarma/titanium_mobile /** * */ package org.appcelerator.titanium; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import android.os.Bundle; import org.appcelerator.titanium.TiLifecycle.OnLifecycleEvent; import org.appcelerator.titanium.TiLifecycle.OnWindowFocusChangedEvent; import android.app.Activity; /** * Represents that the current application's state. This class give android the ability to simulate the similar app state as ios. * @author wei.ding */ public class ApplicationState implements OnLifecycleEvent, OnWindowFocusChangedEvent { public static final ApplicationState INSTANCE = new ApplicationState(); public static enum State { INACTIVE, ACTIVE, BACKGROUND, SUSPENDED } public static interface StateListener { public void onStateChanged(State newState, State oldState); } private final Map<Long, State> activityStates; private final AtomicReference<State> currentState; private final CopyOnWriteArrayList<StateListener> listeners = new CopyOnWriteArrayList<StateListener>(); private ReentrantLock statesLock = new ReentrantLock(); public ApplicationState() { this(State.SUSPENDED); } /** * */ public ApplicationState(State state) { this.activityStates = new ConcurrentHashMap<Long, State>(); this.currentState = new AtomicReference<State>(state); } /* * (non-Javadoc) * @see org.appcelerator.titanium.TiLifecycle.OnLifecycleEvent#onCreate(android.app.Activity) */ public void onCreate(Activity activity, Bundle savedInstanceState) { this.statesLock.lock(); try { long activityHashCode = activity.hashCode(); this.activityStates.put(activityHashCode, State.INACTIVE); this.updateCurrentState(); } finally { this.statesLock.unlock(); } } /* * (non-Javadoc) * @see org.appcelerator.titanium.TiLifecycle.OnLifecycleEvent#onStart(android.app.Activity) */ public void onStart(Activity activity) { this.statesLock.lock(); try { long activityHashCode = activity.hashCode(); this.activityStates.put(activityHashCode, State.INACTIVE); this.updateCurrentState(); } finally { this.statesLock.unlock(); } } /* * (non-Javadoc) * @see org.appcelerator.titanium.TiLifecycle.OnLifecycleEvent#onResume(android.app.Activity) */ public void onResume(Activity activity) { this.statesLock.lock(); try { long activityHashCode = activity.hashCode(); this.activityStates.put(activityHashCode, State.ACTIVE); this.updateCurrentState(); } finally { this.statesLock.unlock(); } } /* * (non-Javadoc) * @see org.appcelerator.titanium.TiLifecycle.OnLifecycleEvent#onPause(android.app.Activity) */ public void onPause(Activity activity) { this.statesLock.lock(); try { long activityHashCode = activity.hashCode(); this.activityStates.put(activityHashCode, State.ACTIVE); this.updateCurrentState(); } finally { this.statesLock.unlock(); } } /* * (non-Javadoc) * @see org.appcelerator.titanium.TiLifecycle.OnLifecycleEvent#onStop(android.app.Activity) */ public void onStop(Activity activity) { this.statesLock.lock(); try { long activityHashCode = activity.hashCode(); this.activityStates.put(activityHashCode, State.BACKGROUND); this.updateCurrentState(); } finally { this.statesLock.unlock(); } } /* * (non-Javadoc) * @see org.appcelerator.titanium.TiLifecycle.OnLifecycleEvent#onDestroy(android.app.Activity) */ public void onDestroy(Activity activity) { this.statesLock.lock(); try { long activityHashCode = activity.hashCode(); this.activityStates.put(activityHashCode, State.SUSPENDED); this.updateCurrentState(); } finally { this.statesLock.unlock(); } } private void updateCurrentState() { if (this.activityStates.isEmpty()) { this.currentState.set(State.SUSPENDED); } State previousState = this.currentState.get(); Collection<State> states = this.activityStates.values(); if (states.contains(State.ACTIVE)) { this.currentState.set(State.ACTIVE); } else if (states.contains(State.INACTIVE)) { this.currentState.set(State.INACTIVE); } else if (states.contains(State.BACKGROUND)) { this.currentState.set(State.BACKGROUND); } else if (states.contains(State.SUSPENDED)) { this.currentState.set(State.SUSPENDED); } State currentState = this.currentState.get(); if (previousState != currentState) { for (StateListener listener : this.listeners) { listener.onStateChanged(currentState, previousState); } } for (Map.Entry<Long, State> entry : this.activityStates.entrySet()) { if (entry.getValue() == State.SUSPENDED) { this.activityStates.remove(entry.getKey()); } } } public State getCurrentState() { return this.currentState.get(); } public boolean addStateListener(StateListener listener) { if (listener == null) { return false; } return this.listeners.add(listener); } /** * @param listener * @return */ public boolean removeStateListener(StateListener listener) { if (listener == null) { return true; } return this.listeners.remove(listener); } /** * Gets state listeners. * @return */ public List<StateListener> getStateListeners() { if (this.listeners.isEmpty()) { return Collections.<StateListener> emptyList(); } List<StateListener> list = new ArrayList<StateListener>(this.listeners.size()); Collections.copy(list, this.listeners); return list; } /* * (non-Javadoc) * @see org.appcelerator.titanium.TiLifecycle.OnWindowFocusChangedEvent#onWindowFocusChanged(boolean) */ public void onWindowFocusChanged(boolean hasFocus) { // TODO } /** * Gets the state change event name from {@link TiC}. * @param newState * @param oldState * @return */ public static String getStateChangeEventName(State newState, State oldState) { switch (newState) { case ACTIVE: return TiC.EVENT_RESUMED; case BACKGROUND: return TiC.EVENT_PAUSED; case INACTIVE: return oldState == State.ACTIVE ? TiC.EVENT_PAUSE : TiC.EVENT_RESUME; case SUSPENDED: return TiC.EVENT_DESTROY; default: return null; } } }
<gh_stars>0 import immutables from collections import namedtuple from .datatypes import OutputReference, Block from .humans import human from .genesis import genesis_block_data PKBalance = namedtuple('PKBalance', ['value', 'output_references']) def uto_apply_transaction(unspent_transaction_outs, transaction, is_coinbase): with unspent_transaction_outs.mutate() as mutable_unspent_transaction_outs: # for coinbase we must skip the input-removal because the input references "thin air" rather than an output. if not is_coinbase: for input in transaction.inputs: # we don't explicitly check that the transaction is spendable; inadvertant violation of that expectation # will lead to an application-crash (which is preferable over the alternative: double-spending). del mutable_unspent_transaction_outs[input.output_reference] for i, output in enumerate(transaction.outputs): output_reference = OutputReference(transaction.hash(), i) mutable_unspent_transaction_outs[output_reference] = output return mutable_unspent_transaction_outs.finish() def uto_apply_block(unspent_transaction_outs, block): unspent_transaction_outs = uto_apply_transaction(unspent_transaction_outs, block.transactions[0], is_coinbase=True) for transaction in block.transactions[1:]: unspent_transaction_outs = uto_apply_transaction(unspent_transaction_outs, transaction, is_coinbase=False) return unspent_transaction_outs def pkb_apply_transaction(unspent_transaction_outs, public_key_balances, transaction, is_coinbase): with public_key_balances.mutate() as mutable_public_key_balances: # for coinbase we must skip the input-removal because the input references "thin air" rather than an output. if not is_coinbase: for input in transaction.inputs: previously_unspent_output = unspent_transaction_outs[input.output_reference] public_key = previously_unspent_output.public_key mutable_public_key_balances[public_key] = PKBalance( mutable_public_key_balances[public_key].value - previously_unspent_output.value, [to for to in mutable_public_key_balances[public_key].output_references if to != input.output_reference] ) for i, output in enumerate(transaction.outputs): output_reference = OutputReference(transaction.hash(), i) if output.public_key not in mutable_public_key_balances: mutable_public_key_balances[output.public_key] = PKBalance(0, []) mutable_public_key_balances[output.public_key] = PKBalance( mutable_public_key_balances[output.public_key].value + output.value, mutable_public_key_balances[output.public_key].output_references + [output_reference], ) return mutable_public_key_balances.finish() def pkb_apply_block(unspent_transaction_outs, public_key_balances, block): # unspent_transaction_outs is used as a "reference" only (for looking up outputs); note that we never have to update # that reference inside this function, because intra-block spending is invalid per the consensus. public_key_balances = pkb_apply_transaction( unspent_transaction_outs, public_key_balances, block.transactions[0], is_coinbase=True) for transaction in block.transactions[1:]: public_key_balances = pkb_apply_transaction(unspent_transaction_outs, public_key_balances, transaction, False) return public_key_balances class CoinState: def __init__(self, block_by_hash, unspent_transaction_outs_by_hash, block_by_height_by_hash, heads, current_chain_hash, public_key_balances_by_hash): self.block_by_hash = block_by_hash # block_hash -> (OutputReference -> Output) self.unspent_transaction_outs_by_hash = unspent_transaction_outs_by_hash # given a hash to a current head, return a dictionary in which you can look up by height. self.block_by_height_by_hash = block_by_height_by_hash self.heads = heads # hash=>block ... but restricted to blocks w/o children. self.current_chain_hash = current_chain_hash # block_hash -> (public_key -> (value, [OutputReference])) self.public_key_balances_by_hash = public_key_balances_by_hash def __repr__(self): if self.current_chain_hash is None: return "CoinState @ empty" return "CoinState @ %s (h. %s) w/ %s heads" % ( human(self.current_chain_hash), self.head().height, len(self.heads)) @classmethod def empty(cls): return cls( block_by_hash=immutables.Map(), unspent_transaction_outs_by_hash=immutables.Map(), block_by_height_by_hash=immutables.Map(), heads=immutables.Map(), current_chain_hash=None, public_key_balances_by_hash=immutables.Map(), ) @classmethod def zero(cls): e = cls.empty() return e.add_block_no_validation(Block.deserialize(genesis_block_data)) def add_block(self, block, current_timestamp): from skepticoin.consensus import validate_block_by_itself, validate_block_in_coinstate validate_block_by_itself(block, current_timestamp) validate_block_in_coinstate(block, self) return self.add_block_no_validation(block) def add_block_no_validation(self, block): if block.previous_block_hash == b'\00' * 32: unspent_transaction_outs = immutables.Map() public_key_balances = immutables.Map() else: unspent_transaction_outs = self.unspent_transaction_outs_by_hash[block.previous_block_hash] public_key_balances = self.public_key_balances_by_hash[block.previous_block_hash] public_key_balances = pkb_apply_block(unspent_transaction_outs, public_key_balances, block) # NOTE: ordering matters b/c we assign to unspent_transaction_outs; perhaps just distinguish? unspent_transaction_outs = uto_apply_block(unspent_transaction_outs, block) block_by_hash = self.block_by_hash.set(block.hash(), block) # TODO pruning of unspent_transaction_outs_by_hash on e.g. max delta-height; because it is used as part of # validation, such an approach implies a limit (to be implemented in validation) on how old a fork may be w.r.t. # the current height if it is to be considered at all. unspent_transaction_outs_by_hash = self.unspent_transaction_outs_by_hash.set( block.hash(), unspent_transaction_outs) public_key_balances_by_hash = self.public_key_balances_by_hash.set( block.hash(), public_key_balances) if block.previous_block_hash == b'\00' * 32: block_by_height_by_hash = immutables.Map({block.hash(): immutables.Map({0: block})}) else: block_by_height = self.block_by_height_by_hash[block.previous_block_hash] block_by_height = block_by_height.set(block.height, block) block_by_height_by_hash = self.block_by_height_by_hash.set(block.hash(), block_by_height) with self.heads.mutate() as mutable_heads: if block.previous_block_hash in mutable_heads: del mutable_heads[block.header.summary.previous_block_hash] mutable_heads[block.hash()] = block heads = mutable_heads.finish() if self.current_chain_hash is None or self.current_chain_hash == block.previous_block_hash: # base case / simple moving ahead current_chain_hash = block.hash() # what should be the current_chain_hash in the case of forks? # we compare total work, using striclty greater: this means that when there is a fork in the chain, ties are # broken based on first-come-first serve. I'm sure someone wrote a paper on how this is optimal. elif block.get_total_work() > self.block_by_hash[self.current_chain_hash].get_total_work(): current_chain_hash = block.hash() else: current_chain_hash = self.current_chain_hash # a fork, but the most recently added block is non-current return CoinState( block_by_hash=block_by_hash, unspent_transaction_outs_by_hash=unspent_transaction_outs_by_hash, block_by_height_by_hash=block_by_height_by_hash, heads=heads, current_chain_hash=current_chain_hash, public_key_balances_by_hash=public_key_balances_by_hash, ) def head(self): return self.block_by_hash[self.current_chain_hash] def by_height_at_head(self): # TODO just use 'at_head' return self.block_by_height_by_hash[self.current_chain_hash] @property def at_head(self): class AtHead: @property def unspent_transaction_outs(inner_self): return self.unspent_transaction_outs_by_hash[self.current_chain_hash] @property def block_by_height(inner_self): return self.block_by_height_by_hash[self.current_chain_hash] @property def public_key_balances(inner_self): return self.public_key_balances_by_hash[self.current_chain_hash] return AtHead() def forks(self): def _find_lca_with_main(block): # while block.hash() not in block_by_hash_by_hash ... we have no such datastructure yet, so instead: while (block.height not in self.by_height_at_head() or self.by_height_at_head()[block.height].hash() != block.hash()): block = self.block_by_hash[block.previous_block_hash] return block return [(head, _find_lca_with_main(head)) for head in self.heads.values()]
require('spec_helper') describe(Venue) do describe('#bands') do it('returns a venue') do new_venue = Venue.create({name: 'Suprise', city: 'Boise', state: 'ID'}) new_band = new_venue.bands.create({name: 'Fry'}) expect(new_venue.bands).to(eq([new_band])) end it('returns name of venue title cased') do new_venue = Venue.create({name: 'CrYstall BALLroom', city: 'Boise', state: 'ID'}) expect(new_venue.name).to(eq("Crystall Ballroom")) end end end
#!/bin/sh cdir=`pwd` #检查是否有git环境 command -v git >/dev/null 2>&1 || { echo "require git but it's not installed. Aborting." >&2; exit 1; } command -v ctags >/dev/null 2>&1 || { echo "require ctags but it's not installed. Aborting." >&2; exit 1; } #编译需要的vim源码git地址,git上面的7.4.xxx版本不能用 #git url(wget):https://github.com/vim/vim/archive/v7.4.144.tar.gz #ver=7.4.143 #vimver=v$ver.tar.gz #sourceurl=https://github.com/vim/vim/archive/$vimver #if [ ! -f $vimver ];then # echo "download the vim source" # #wget https://github.com/vim/vim/archive/v7.4.144.tar.gz # wget $sourceurl -O $vimver #fi # #tar -xzvf $vimver #mv "vim-$ver" vim74 #编译需要的vim源码git地址ftp://ftp.vim.org/pub/vim/unix/vim-7.4.tar.bz2 if [ ! -f vim-7.4.tar.bz2 ];then echo "download the vim source" wget ftp://ftp.vim.org/pub/vim/unix/vim-7.4.tar.bz2 fi tar -xjvf vim-7.4.tar.bz2 #编译需要的vimgdb地址 #git url(wget):https://codeload.github.com/larrupingpig/vimgdb-for-vim7.4/zip/master if [ ! -f vimgdb-for-vim7.4-master.zip ];then echo "download the vimgdm source" wget https://codeload.github.com/larrupingpig/vimgdb-for-vim7.4/zip/master -O vimgdb-for-vim7.4-master.zip fi unzip vimgdb-for-vim7.4-master.zip #打补丁 patch -p0 < vimgdb-for-vim7.4-master/vim74.patch echo y|sudo apt-get install python-dev echo y|sudo apt-get install libxt-dev cd $cdir/vim74/src sed -i "s/BINDIR = \/opt\/bin/BINDIR = \/usr\/bin/" Makefile sed -i "s/MANDIR = \/opt\/share\/man/MANDIR = \/usr\/share\/man\/man1/" Makefile sed -i "s/DATADIR = \/opt\/share/DATADIR = \/usr\/share\/vim/" Makefile echo y|sudo apt-get install libncurses5-dev ./configure --enable-gdb --prefix=/usr/local/vim74 --enable-multibyte --enable-fontset --enable-xim --enable-gui=auto --enable-pythoninterp=yes --enable-rubyinterp=dynamic --enable-rubyinterp --enable-perlinterp --enable-cscope --enable-sniff --with-x --with-features=huge --enable-luainterp=dynami --with-python-config-dir=/usr/lib/python2.7/config --with-feature=big if [ $? -eq 0 ];then echo "make vim source" make CFLAGS="-O2 -D_FORTIFY_SOURCE=1" else echo "config the vim option error" fi make install cp -rf $cdir/vimgdb-for-vim7.4-master/vimgdb_runtime/* ~/.vim echo "vim compile success" cd /usr/share/vim/vim/vim74/doc/ echo ":helptags ."|vim #安装bundle if [ ! -f ~/.vim/bundle/vundle/autoload/vundle.vim ];then echo "download bundle\n" git clone https://github.com/gmarik/vundle.git ~/.vim/bundle/vundle; fi cd $cdir #生成vim默认配置加载文件.vimrc vimconfname=.vimrc vimloadbundle=.vimrc.bundles.local if [ -f $vimconfname ];then rm -rf ./$vimconfname fi touch $vimconfname echo "if &compatible" >> $vimconfname echo " set nocompatible" >> $vimconfname echo "end" >> $vimconfname echo "filetype off" >> $vimconfname "echo "set rtp+=~/.vim/bundle/vundle/" >> $vimconfname "echo "call vundle#rc()" >> $vimconfname "echo "\" Let Vundle manage Vundle" >> $vimconfname "echo "Bundle 'gmarik/vundle'" >> $vimconfname echo "if filereadable(expand(\"~/.vimrc.bundles.local\"))" >> $vimconfname echo ' source ~/.vimrc.bundles.local' >> $vimconfname echo "endif" >> $vimconfname echo "filetype on" >> $vimconfname echo "set previewheight=10" >>$vimconfname echo "run macros/gdb_mappings.vim" >>$vimconfname echo "set asm=0" >>$vimconfname echo "set gdbprg=gdb" >>$vimconfname echo "set splitbelow" >>$vimconfname echo "set splitright" >>$vimconfname if [ -f ~/$vimconfname ];then mv ~/.vimrc ~/$".vimrc.$(date +"%Y%m%d%I%M%S").bak" fi cp ./$vimconfname ~/ #vim的配置文件,使用git中use_vim_as_ide项目配置[https://github.com/yangyangwithgnu/use_vim_as_ide] #https://codeload.github.com/yangyangwithgnu/use_vim_as_ide/zip/master if [ ! -f use_vim_as_ide-master.zip ];then echo "download the vim config file\n" wget https://codeload.github.com/yangyangwithgnu/use_vim_as_ide/zip/master -O use_vim_as_ide-master.zip fi unzip use_vim_as_ide-master.zip cd $cdir/use_vim_as_ide-master/ sed -i "s/^colorscheme solarized/\"colorscheme solarized/" .vimrc sed -i "s/set background=dark/set background=light/" .vimrc sed -i "s/^\"colorscheme phd/colorscheme phd/" .vimrc cp .vimrc ~/$vimloadbundle cp README.md ./../ #启动vim安装插件 vim +PluginInstall +qall #重新配置ycm,从git上下载ubuntu-fix版本 rm -rf ~/.vim/bundle/YouCompleteMe cd ~/.vim/bundle/ git clone https://git.oschina.net/viperauter/ubuntu-fix.git mv ubuntu-fix YouCompleteMe cd ~/.vim/bundle/YouCompleteMe/ command -v cmake>/dev/null 2>&1 || { echo y|apt-get install cmake } git submodule update --init --recursive ./install.py --clang-completer echo "auto config vim env success" #打开README vim README.md
package cyclops.async.reactive.futurestream.companion; import cyclops.async.reactive.futurestream.pipeline.Status; import cyclops.async.reactive.futurestream.pipeline.collector.Blocker; import cyclops.async.reactive.futurestream.threading.SequentialElasticPools; import cyclops.exception.ExceptionSoftener; import cyclops.container.control.Either; import cyclops.async.Future; import cyclops.async.reactive.futurestream.SimpleReact; import cyclops.reactive.collection.container.mutable.ListX; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; public interface Futures { public static <T, R> Future<R> tailRec(T initial, Function<? super T, ? extends Future<? extends Either<T, R>>> fn) { SimpleReact sr = SequentialElasticPools.simpleReact.nextReactor(); return Future.of(() -> { Future<? extends Either<T, R>> next[] = new Future[1]; next[0] = Future.ofResult(Either.left(initial)); boolean cont = true; do { cont = next[0].fold(p -> p.fold(s -> { next[0] = Future.narrowK(fn.apply(s)); return true; }, pr -> false), () -> false); } while (cont); return next[0].map(x -> x.orElse(null)); }, sr.getExecutor()) .flatMap(i -> i) .peek(e -> SequentialElasticPools.simpleReact.populate(sr)) .recover(t -> { SequentialElasticPools.simpleReact.populate(sr); throw ExceptionSoftener.throwSoftenedException(t); }); } /** * Block until a Quorum of results have returned as determined by the provided Predicate * * <pre> * {@code * * Future<ListX<Integer>> strings = Future.quorum(status -> status.getCompleted() >0, Future.of(()->1),Future.future(),Future.future()); * * * strings.getValue().size() * //1 * * } * </pre> * * @param breakout Predicate that determines whether the block should be continued or removed * @param fts Futures to wait on results from * @return Future which will be populated with a Quorum of results */ @SafeVarargs public static <T> Future<ListX<T>> quorum(Predicate<Status<T>> breakout, Future<T>... fts) { List<CompletableFuture<?>> list = Stream.of(fts) .map(Future::getFuture) .collect(Collectors.toList()); return Future.of(new Blocker<T>(list, Optional.empty()).nonBlocking(breakout)); } /** * Block until a Quorum of results have returned as determined by the provided Predicate * * <pre> * {@code * * Future<ListX<Integer>> strings = Future.quorum(status -> status.getCompleted() >0, Future.of(()->1),Future.future(),Future.future()); * * * strings.getValue().size() * //1 * * } * </pre> * * @param breakout Predicate that determines whether the block should be continued or removed * @param fts Futures to wait on results from * @param errorHandler Consumer to handle any exceptions thrown * @return Future which will be populated with a Quorum of results */ @SafeVarargs public static <T> Future<ListX<T>> quorum(Predicate<Status<T>> breakout, Consumer<Throwable> errorHandler, Future<T>... fts) { List<CompletableFuture<?>> list = Stream.of(fts) .map(Future::getFuture) .collect(Collectors.toList()); return Future.of(new Blocker<T>(list, Optional.of(errorHandler)).nonBlocking(breakout)); } }
from flask import Flask, request app = Flask(__name__) @app.route('/register', methods=['POST']) def register(): username = request.form.get('username') password = request.form.get('password') if not username or not password: return 'Missing required fields' hashed_password = generate_password_hash(password) user = User(username=username, password=hashed_password) db.session.add(user) db.session.commit() return 'Registered successfully!'
<gh_stars>1-10 #import <Cocoa/Cocoa.h> FOUNDATION_EXPORT double Pods_IdentifyUSBMassStorage_TestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_IdentifyUSBMassStorage_TestsVersionString[];
<reponame>Strunken001/Key-Distributors-Monitor import { TestBed } from '@angular/core/testing'; import { ProfilingServiceService } from './profiling-service.service'; describe('ProfilingServiceService', () => { beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: ProfilingServiceService = TestBed.get(ProfilingServiceService); expect(service).toBeTruthy(); }); });
<gh_stars>0 package config import ( "fmt" "io" "time" yaml "gopkg.in/yaml.v2" ) type duration time.Duration type Config struct { Targets []string `yaml:"targets"` Ping struct { Interval duration `yaml:"interval"` Timeout duration `yaml:"timeout"` History int `yaml:"history-size"` Size uint16 `yaml:"payload-size"` } `yaml:"ping"` } func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error { var s string if err := unmashal(&s); err != nil { return err } dur, err := time.ParseDuration(s) if err != nil { return fmt.Errorf("failed to decode duration: %w", err) } *d = duration(dur) return nil } // Duration is a convenience getter. func (d duration) Duration() time.Duration { return time.Duration(d) } // Set updates the underlying duration. func (d *duration) Set(dur time.Duration) { *d = duration(dur) } // FromYAML reads YAML from reader and unmarshals it to Config. func FromYAML(r io.Reader) (*Config, error) { c := &Config{} err := yaml.NewDecoder(r).Decode(c) if err != nil { return nil, fmt.Errorf("failed to decode YAML: %w", err) } return c, nil }
<filename>packages/dev-tools/intTest.d.ts export * from './lib/intTest';
#!/bin/bash for filename in "$@";do echo $filename awk 'BEGIN {FS=","} NR==5 || NR==9 {print $4}' $filename #awk 'BEGIN {FS=","} NR==1 || NR==5 || NR==9 {print $1,$4}' $filename # also show epoch #awk '(NR==1 || NR==6 || NR==21 || NR==81 || NR==201)' $filename # show complete line done
<gh_stars>0 import { VueEventing } from "src/index"; import { config } from "src/config"; describe("VueEventing", () => { it("should configure the eventing plugin", () => { expect(config.instanceMethods).toBeFalsy(); expect(config.emitIntegration).toBeFalsy(); VueEventing({ instanceMethods: true, emitIntegration: true, }); expect(config.instanceMethods).toBeTruthy(); expect(config.emitIntegration).toBeTruthy(); }); });
/** Create a JavaScript program to generate prime numbers up to a certain number */ function generatePrimes(max) { let sieve = [], i, j, primes = []; for (i = 2; i <= max; ++i) { if (!sieve[i]) { // i has not been marked -- it is prime primes.push(i); for (j = i << 1; j <= max; j += i) { sieve[j] = true; } } } return primes; } console.log(generatePrimes(10)); // [2,3,5,7];
#! /bin/sh pyFoamClearCase.py . rm -rf constant/polyMesh/sets/ blockMesh # funkyWarpMesh -expression "vector(pts().x,pts().y*(interpolateToPoint(1)+(pts().x-min(pts().x))/(max(pts().x)-min(pts().x))),pts().z)" # funkyWarpMesh -relative -overwrite -expression "vector(interpolateToPoint(0),pts().y*(pts().x-min(pts().x))/(max(pts().x)-min(pts().x)),interpolateToPoint(0))" funkyWarpMesh -dictExt bend -overwrite
<gh_stars>0 import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router'; // RxJS import { Observable } from 'rxjs'; import { filter, first, tap } from 'rxjs/operators'; // ngRx import { select, Store } from '@ngrx/store'; // Reducer import * as fromSkills from '../../reducers/skills/skills.reducer'; // Actions import { SkillsActions } from '../../actions/skills/index'; // Model import { Skill } from '../../models/skills/skill.model'; // Service import { SkillsService } from '../../services/skills/skills.service'; export class SkillResolver implements Resolve<Skill> { constructor( private store: Store<fromSkills.SkillsState>, private skillsService: SkillsService ) {} resolve( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<Skill> { const skillId = route.params.id; return this.store.pipe( select(fromSkills.selectSkillById(skillId)), tap(skill => { if (!skill) { this.store.dispatch(new SkillsActions.GetSkill({ skillId })); } }), filter(skill => !!skill), first() ); } }
<reponame>Surfndez/mcs-lite-app<gh_stars>0 import constants from 'react-constants'; export default constants([ 'PUSHTOAST', 'DROPTOAST', ]);
/* * File created on Mar 8, 2019 * * Copyright (c) 2019 <NAME>, Jr * and others as noted * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.soulwing.jwt.api.jose4j; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import org.jmock.Expectations; import org.jmock.Sequence; import org.jmock.auto.Mock; import org.jmock.integration.junit4.JUnitRuleMockery; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.soulwing.jwt.api.Claims; import org.soulwing.jwt.api.JWE; import org.soulwing.jwt.api.JWS; import org.soulwing.jwt.api.JWTGenerator; import org.soulwing.jwt.api.exceptions.JWTConfigurationException; /** * Unit tests for {@link Jose4jGenerator}. * * @author <NAME> */ public class Jose4jGeneratorTest { private static final String PAYLOAD = "payload"; private static final String SIGNED_PAYLOAD = "signedPayload"; private static final String ENCRYPTED_PAYLOAD = "encryptedPayload"; @Rule public final JUnitRuleMockery context = new JUnitRuleMockery(); @Rule public final ExpectedException expectedException = ExpectedException.none(); @Mock private JWE encryptionOperator; @Mock private JWS signatureOperator; @Mock private Claims claims; @Test(expected = JWTConfigurationException.class) public void testBuildWithNoConfiguration() throws Exception { Jose4jGenerator.builder().build(); } @Test public void testBuildWithNoSignatureOperator() throws Exception { expectedException.expect(JWTConfigurationException.class); expectedException.expectMessage("signature"); Jose4jGenerator.builder() .encryption(encryptionOperator) .build(); } @Test public void testBuildWithNullEncryptionOperator() throws Exception { Jose4jGenerator.builder() .encryption(null) .signature(signatureOperator) .build(); } @Test public void testGenerate() throws Exception { final Sequence sequence = context.sequence("generatorSequence"); context.checking(new Expectations() { { oneOf(claims).toJson(); inSequence(sequence); will(returnValue(PAYLOAD)); oneOf(signatureOperator).sign(PAYLOAD); inSequence(sequence); will(returnValue(SIGNED_PAYLOAD)); oneOf(encryptionOperator).encrypt(SIGNED_PAYLOAD); inSequence(sequence); will(returnValue(ENCRYPTED_PAYLOAD)); } }); final JWTGenerator generator = Jose4jGenerator.builder() .encryption(encryptionOperator) .signature(signatureOperator) .build(); assertThat(generator.generate(claims), is(equalTo(ENCRYPTED_PAYLOAD))); } @Test public void testGenerateSignatureOnly() throws Exception { final Sequence sequence = context.sequence("generatorSequence"); context.checking(new Expectations() { { oneOf(claims).toJson(); inSequence(sequence); will(returnValue(PAYLOAD)); oneOf(signatureOperator).sign(PAYLOAD); inSequence(sequence); will(returnValue(SIGNED_PAYLOAD)); } }); final JWTGenerator generator = Jose4jGenerator.builder() .signature(signatureOperator) .build(); assertThat(generator.generate(claims), is(equalTo(SIGNED_PAYLOAD))); } }
func countPairs(nums: [Int], target: Int) -> Int { var count = 0 var numSet = Set<Int>() for num in nums { let complement = target - num if numSet.contains(complement) { count += 1 } numSet.insert(num) } return count }
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class MinDiffIndexFromAvgTest { @Test public void test_no_data() { int expected=-1; int[] data={}; int actual=MyArray.getMinDifferenceIndexFromAvg(data); Assertions.assertEquals(expected,actual,"Nem jol hatarozta meg az atlaghoz legkozelebb eso szam sorszamat!."); } @Test public void test_first() { int expected=0; int[] data={2,1,3,1,3,1,3,1,3,4}; int actual=MyArray.getMinDifferenceIndexFromAvg(data); Assertions.assertEquals(expected,actual,"Nem jol hatarozta meg az atlaghoz legkozelebb eso szam sorszamat!."); } @Test public void test_last() { int expected=9; int[] data={4,1,3,1,3,1,3,1,3,2}; int actual=MyArray.getMinDifferenceIndexFromAvg(data); Assertions.assertEquals(expected,actual,"Nem jol hatarozta meg az atlaghoz legkozelebb eso szam sorszamat!."); } @Test public void test_middle() { int expected=7; int[] data={4,4,4,4,1,2,1,3,1,3,1,3,2}; int actual=MyArray.getMinDifferenceIndexFromAvg(data); Assertions.assertEquals(expected,actual,"Nem jol hatarozta meg az atlaghoz legkozelebb eso szam sorszamat!."); } @Test public void test_samedistance() { int expected=0; int[] data={1,2,1,2,1,2,1,2}; int actual=MyArray.getMinDifferenceIndexFromAvg(data); Assertions.assertEquals(expected,actual,"Nem jol hatarozta meg az atlaghoz legkozelebb eso szam sorszamat!."); } }
<reponame>davidkarlsen/Hystrix<filename>hystrix-contrib/hystrix-javanica/src/test/java/com/netflix/hystrix/contrib/javanica/test/spring/command/jdk/CommandJdkProxyTest.java<gh_stars>0 package com.netflix.hystrix.contrib.javanica.test.spring.command.jdk; import com.netflix.hystrix.contrib.javanica.test.spring.command.CommandTest; import com.netflix.hystrix.contrib.javanica.test.spring.conf.AopJdkConfig; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {AopJdkConfig.class, CommandTest.CommandTestConfig.class}) public class CommandJdkProxyTest extends CommandTest { }
<gh_stars>0 /*--------------------------------------------------------------------------------------------- * Copyright (c) <NAME>. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { promises as fsPromise } from "fs"; import * as JSONC from "jsonc-parser"; import MqttConfig from "./handlers/mqttManager/MqttConfig"; import WebRequestConfig from "./handlers/webRequest/WebRequestConfig"; import * as log from "./Log"; import triggerSchema from "./schemas/triggerConfiguration.schema.json"; import validateJsonAgainstSchema from "./schemaValidator"; import Trigger from "./Trigger"; import ITriggerConfigJson from "./types/ITriggerConfigJson"; export default class TriggerManager { public Ready: Promise<boolean>; public get triggers(): Trigger[] { return this._triggers; } private _triggers: Trigger[]; /** * Loads a trigger configuration file * @param configFilePath The path to the configuration file * @returns The unvalidated raw JSON */ private async loadConfigurationFile(configFilePath: string): Promise<string> { if (!configFilePath) { throw new Error( `[Trigger Manager] No configuration file was specified. Make sure the trigger secret in the docker-compose.yaml points to a configuration file.`, ); } let rawConfig: string; try { rawConfig = await fsPromise.readFile(configFilePath, "utf-8"); } catch (e) { throw new Error(`[Trigger Manager] Unable to load configuration file ${configFilePath}: ${e.message}`); } if (!rawConfig) { throw new Error(`[Trigger Manager] Unable to load configuration file ${configFilePath}.`); } return rawConfig; } /** * Takes a raw JSON string and converts it to an ITriggerConfigJson * @param rawConfig The raw JSON in a string * @returns An ITriggerConfigJson from the parsed JSON */ private parseConfigFile(rawConfig: string): ITriggerConfigJson { let parseErrors: JSONC.ParseError[]; const triggerConfig = JSONC.parse(rawConfig, parseErrors) as ITriggerConfigJson; // This extra level of validation really shouldn't be necessary since the // file passed schema validation. Still, better safe than crashy. if (parseErrors && parseErrors.length > 0) { throw new Error( `[Trigger Manager] Unable to load configuration file: ${parseErrors .map(error => log.error("Trigger manager", `${error?.error}`)) .join("\n")}`, ); } return triggerConfig; } /** * Takes a path to a configuration file and loads all of the triggers from it. * @param configFilePath The path to the configuration file */ public async loadTriggers(configFilePath: string): Promise<void> { const rawConfig = await this.loadConfigurationFile(configFilePath); const triggerConfigJson = this.parseConfigFile(rawConfig); if (!(await validateJsonAgainstSchema(triggerSchema, triggerConfigJson))) { throw new Error("[Trigger Manager] Invalid configuration file."); } log.info("Trigger manager", `Loaded configuration from ${configFilePath}`); this._triggers = triggerConfigJson.triggers.map(triggerJson => { log.info("Trigger manager", `Loaded configuration for ${triggerJson.name}`); const configuredTrigger = new Trigger({ cooldownTime: triggerJson.cooldownTime, enabled: triggerJson.enabled ?? true, // If it isn't specified then enable the camera name: triggerJson.name, threshold: { minimum: triggerJson?.threshold?.minimum ?? 0, // If it isn't specified then just assume always trigger. maximum: triggerJson?.threshold?.maximum ?? 100, // If it isn't specified then just assume always trigger. }, watchPattern: triggerJson.watchPattern, watchObjects: triggerJson.watchObjects, }); // Set up the handlers if (triggerJson.handlers.webRequest) { configuredTrigger.webRequestHandlerConfig = new WebRequestConfig(triggerJson.handlers.webRequest); } if (triggerJson.handlers.mqtt) { configuredTrigger.mqttConfig = new MqttConfig(triggerJson.handlers.mqtt); } return configuredTrigger; }); } /** * Start all registered triggers watching for changes. */ public startWatching(): void { this._triggers.map(trigger => trigger.startWatching()); } /** * Stops all registered triggers from watching for changes. */ public async stopWatching(): Promise<void[]> { return Promise.all(this._triggers.map(trigger => trigger.stopWatching())); } }
<reponame>nicolasleger/dkdeploy-core require 'erb' require 'capistrano/i18n' require 'dkdeploy/i18n' include Capistrano::DSL namespace :apache do desc 'Render .htaccess to web root from erb template(s)' task :htaccess do |_, args| local_web_root_path = ask_array_variable(args, :local_web_root_path, 'questions.local_web_root_path') run_locally do apache_configuration_path = File.join 'config', 'etc', 'apache2', 'conf' htaccess_file_path = File.join apache_configuration_path, '.htaccess.erb' destination_htaccess_file_path = File.join local_web_root_path, '.htaccess' if File.exist? htaccess_file_path info I18n.t('tasks.apache.htaccess.render', scope: :dkdeploy) htaccess_template = ERB.new File.read(htaccess_file_path) # write the new htaccess file content to the target .htaccess file File.open(destination_htaccess_file_path, 'w') do |io| io.write htaccess_template.result(binding) end end end end end
#!/bin/bash # YouTube-DL Config Install Script # Nefari0uss SCRIPT_LOCATION=$(readlink -f "$0") # Get the path of this file. SCRIPT_DIR=$(dirname "$SCRIPT_LOCATION") # Get the path of the folder the file is current in. CONFIG_DIR=$HOME/.config/youtube-dl FILES=(config) NAME="youtube-dl" #printf 'Script %s\n' $SCRIPT #printf 'Script Dir %s\n' $SCRIPT_DIR printf "\nInstalling %s config.\n" "$NAME" if [ ! -d "$CONFIG_DIR" ]; then printf "Creating %s folder under %s.\n" "$NAME" "$CONFIG_DIR" mkdir -p "$CONFIG_DIR" fi for i in "${FILES[@]}" do #printf "$i\n" if [ -a "$CONFIG_DIR"/"$i" ]; then printf "Removing %s from the config directory.\n" "$i" rm "$CONFIG_DIR"/"$i" fi printf "Making symb link for %s.\n" "$i" ln -s "$SCRIPT_DIR"/"$i" "$CONFIG_DIR"/"$i" printf "\n" done printf "%s installation complete.\n" "$NAME"
export const FETCH_COMPOSITION_REQUESTED = 'FETCH_COMPOSITION_REQUESTED' export const FETCH_COMPOSITION_SUCCEEDED = 'FETCH_COMPOSITION_SUCCEEDED' export const FETCH_COMPOSITION_FAILED = 'FETCH_COMPOSITION_FAILED' export function fetchCompositionRequested(entityName, notation) { return { type: FETCH_COMPOSITION_REQUESTED, entityName, notation } }
/* * gyro.h * * Created on: Nov 22, 2020 * Author: Théo */ #ifndef SENSORS_GYRO_H_ #define SENSORS_GYRO_H_ #include "stm32f1xx_hal.h" #include "sensors.h" /* Default I2C address */ #define MPU6050_I2C_ADDR 0xD0 typedef enum gyros_e{ GYRO_MPU6050, GYRO_COUNT }gyros_e; typedef struct gyro_t{ //Properties related to the hardware configuration I2C_HandleTypeDef * hi2c ; gyros_e name ; sensor_connectivity_e connectivity ; //Angle x float x ; float x_raw ; //Angle y float y ; float y_raw ; //Angle z float z ; float z_raw ; //Rapport (degrees/s / bit) float sensi ; }gyro_t; sensor_init_e GYRO_init(gyro_t * gyro, gyros_e name, I2C_HandleTypeDef * hi2c, sensor_connectivity_e connectivity); sensor_end_e GYRO_update(gyro_t * gyro); #endif /* SENSORS_GYRO_H_ */
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package topologycache import ( "fmt" "testing" discovery "k8s.io/api/discovery/v1" ) func TestGetTotalEndpoints(t *testing.T) { testCases := []struct { name string si *SliceInfo expectedTotal int }{{ name: "empty", si: &SliceInfo{}, expectedTotal: 0, }, { name: "empty slice", si: &SliceInfo{ ToCreate: []*discovery.EndpointSlice{sliceWithNEndpoints(0)}, }, expectedTotal: 0, }, { name: "multiple slices", si: &SliceInfo{ ToCreate: []*discovery.EndpointSlice{sliceWithNEndpoints(15), sliceWithNEndpoints(8)}, }, expectedTotal: 23, }, { name: "slices for all", si: &SliceInfo{ ToCreate: []*discovery.EndpointSlice{sliceWithNEndpoints(15), sliceWithNEndpoints(8)}, ToUpdate: []*discovery.EndpointSlice{sliceWithNEndpoints(2)}, Unchanged: []*discovery.EndpointSlice{sliceWithNEndpoints(100), sliceWithNEndpoints(90)}, }, expectedTotal: 215, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { actualTotal := tc.si.getTotalEndpoints() if actualTotal != tc.expectedTotal { t.Errorf("Expected %d, got %d", tc.expectedTotal, actualTotal) } }) } } // helpers func sliceWithNEndpoints(n int) *discovery.EndpointSlice { endpoints := []discovery.Endpoint{} for i := 0; i < n; i++ { endpoints = append(endpoints, discovery.Endpoint{Addresses: []string{fmt.Sprintf("10.1.2.%d", i)}}) } return &discovery.EndpointSlice{ Endpoints: endpoints, } }
<filename>app/src/main/java/demo/sap/safetyandroid/viewmodel/EntityViewModelFactory.java package demo.sap.safetyandroid.viewmodel; import android.app.Application; import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider; import android.os.Parcelable; import demo.sap.safetyandroid.viewmodel.devicesettype.DeviceSetTypeViewModel; import demo.sap.safetyandroid.viewmodel.devicetagsettype.DeviceTagSetTypeViewModel; import demo.sap.safetyandroid.viewmodel.deviceuserviewsettype.DeviceUserViewSetTypeViewModel; import demo.sap.safetyandroid.viewmodel.ephemeralidinfectedsettype.EphemeralIDInfectedSetTypeViewModel; import demo.sap.safetyandroid.viewmodel.ephemeralidsettype.EphemeralIDSetTypeViewModel; import demo.sap.safetyandroid.viewmodel.eventsettype.EventSetTypeViewModel; import demo.sap.safetyandroid.viewmodel.historydevicesstatustype.HistoryDevicesStatusTypeViewModel; import demo.sap.safetyandroid.viewmodel.historydevicesstatusparameterstype.HistoryDevicesStatusParametersTypeViewModel; import demo.sap.safetyandroid.viewmodel.infectedsettype.InfectedSetTypeViewModel; import demo.sap.safetyandroid.viewmodel.proximitydetectedsettype.ProximityDetectedSetTypeViewModel; import demo.sap.safetyandroid.viewmodel.realtimeroomstatustype.RealTimeRoomStatusTypeViewModel; import demo.sap.safetyandroid.viewmodel.realtimeroomstatusparameterstype.RealTimeRoomStatusParametersTypeViewModel; import demo.sap.safetyandroid.viewmodel.tagsettype.TagSetTypeViewModel; /** * Custom factory class, which can create view models for entity subsets, which are * reached from a parent entity through a navigation property. */ public class EntityViewModelFactory implements ViewModelProvider.Factory { // application class private Application application; // name of the navigation property private String navigationPropertyName; // parent entity private Parcelable entityData; /** * Creates a factory class for entity view models created following a navigation link. * * @param application parent application * @param navigationPropertyName name of the navigation link * @param entityData parent entity */ public EntityViewModelFactory(Application application, String navigationPropertyName, Parcelable entityData) { this.application = application; this.navigationPropertyName = navigationPropertyName; this.entityData = entityData; } @Override public <T extends ViewModel> T create(Class<T> modelClass) { T retValue = null; switch(modelClass.getSimpleName()) { case "DeviceSetTypeViewModel": retValue = (T) new DeviceSetTypeViewModel(application, navigationPropertyName, entityData); break; case "DeviceTagSetTypeViewModel": retValue = (T) new DeviceTagSetTypeViewModel(application, navigationPropertyName, entityData); break; case "DeviceUserViewSetTypeViewModel": retValue = (T) new DeviceUserViewSetTypeViewModel(application, navigationPropertyName, entityData); break; case "EphemeralIDInfectedSetTypeViewModel": retValue = (T) new EphemeralIDInfectedSetTypeViewModel(application, navigationPropertyName, entityData); break; case "EphemeralIDSetTypeViewModel": retValue = (T) new EphemeralIDSetTypeViewModel(application, navigationPropertyName, entityData); break; case "EventSetTypeViewModel": retValue = (T) new EventSetTypeViewModel(application, navigationPropertyName, entityData); break; case "HistoryDevicesStatusTypeViewModel": retValue = (T) new HistoryDevicesStatusTypeViewModel(application, navigationPropertyName, entityData); break; case "HistoryDevicesStatusParametersTypeViewModel": retValue = (T) new HistoryDevicesStatusParametersTypeViewModel(application, navigationPropertyName, entityData); break; case "InfectedSetTypeViewModel": retValue = (T) new InfectedSetTypeViewModel(application, navigationPropertyName, entityData); break; case "ProximityDetectedSetTypeViewModel": retValue = (T) new ProximityDetectedSetTypeViewModel(application, navigationPropertyName, entityData); break; case "RealTimeRoomStatusTypeViewModel": retValue = (T) new RealTimeRoomStatusTypeViewModel(application, navigationPropertyName, entityData); break; case "RealTimeRoomStatusParametersTypeViewModel": retValue = (T) new RealTimeRoomStatusParametersTypeViewModel(application, navigationPropertyName, entityData); break; case "TagSetTypeViewModel": retValue = (T) new TagSetTypeViewModel(application, navigationPropertyName, entityData); break; } return retValue; } }
export function getListBuslineCompany(city) { return { type: '@home/EVENT_DATA_SUCCESS_REQUEST', payload: city, }; } export function functionsuccess(data) { return { type: '@home/EVENT_DATA_SUCCESS', payload: data }; }
#!/bin/sh if ! [ -x "$(command -v hub)" ]; then echo 'Github hub is not installed. Install from https://github.com/github/hub' >&2 exit 1 fi echo "Version you want to release?" read -r VERSION CURRENTBRANCH="$(git rev-parse --abbrev-ref HEAD)" if [ ! -d "build" ]; then echo "Build directory not found. Aborting." exit 1 fi # Create a release branch. BRANCH="${VERSION}" git checkout -b $BRANCH # Force add build directory and commit. git add build/. --force git add . git commit -m "Adding /build directory to release" --no-verify git push origin $BRANCH # Create the new release. hub release create -m $VERSION -m "Release of version $VERSION." -t $BRANCH "v${VERSION}" git checkout $CURRENTBRANCH git branch -D $BRANCH git push origin --delete $BRANCH echo "GitHub release complete."
import {Component, OnInit} from '@angular/core'; import {ProductInbound, ProductInboundControllerService} from '../../../service/rest'; import {LocalDataSource} from 'ng2-smart-table'; import {NbSearchService} from '@nebular/theme'; import {Router} from '@angular/router'; import {ServiceUtil} from '../../../service/util/service-util'; @Component({ selector: 'ngx-inventory-inbound-main', templateUrl: './inventory-inbound-main.component.html', styleUrls: ['./inventory-inbound-main.component.scss'] }) export class InventoryInboundMainComponent implements OnInit { productInbounds: Array<ProductInbound> = []; settings = { hideSubHeader: true, actions: false, columns: { id: { title: 'Inbound#', type: 'number', }, date: { title: 'Inbound Date', type: 'string', }, statusDescription: { title: 'Status', type: 'string', }, itemCount: { title: 'Item Count', type: 'number', addable: false, editable: false, }, }, }; source: LocalDataSource = new LocalDataSource(); constructor(private productInboundControllerService: ProductInboundControllerService, private searchService: NbSearchService, private router: Router) { this.searchService.onSearchSubmit() .subscribe((data: any) => { console.log('Search', data.term); this.source.setFilter([ { field: 'name', search: data.term } ], false); }); } ngOnInit(): void { this.fetchProductInbound(); } fetchProductInbound() { this.productInboundControllerService.getAllProductInboundsUsingGET().subscribe(response => { console.log('Product Inbound Data :', response); response.productInboundList.forEach(productInbound => { productInbound.statusDescription = ServiceUtil.getStatusDescription(productInbound.status); productInbound.itemCount = productInbound.productInboundItems.length; this.productInbounds.push(productInbound); }); this.source.load(this.productInbounds); }); } onUserRowSelect(event): void { console.log(event); this.router.navigate(['/pages/inventory/inbound-view'], {queryParams: {id: event.data.id}}); } resetFilter(): void { this.source.setFilter([]); } }
=begin #RadioManager #RadioManager OpenAPI spec version: 2.0 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.3.0 =end require 'spec_helper' require 'json' # Unit tests for RadioManagerClient::UserApi # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'UserApi' do before do # run before each test @instance = RadioManagerClient::UserApi.new end after do # run after each test end describe 'test an instance of UserApi' do it 'should create an instance of UserApi' do expect(@instance).to be_instance_of(RadioManagerClient::UserApi) end end # unit tests for delete_user_by_id # Remove user from station by Id # Remove user from station by Id # @param id id of User # @param [Hash] opts the optional parameters # @return [Success] describe 'delete_user_by_id test' do it "should work" do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end # unit tests for get_user_by_id # Get user by id # Get user by id # @param id id of User # @param [Hash] opts the optional parameters # @return [UserResult] describe 'get_user_by_id test' do it "should work" do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end # unit tests for invite_user_by_mail # Invite user by mail # Invite user by mail # @param data Data **(Required)** # @param [Hash] opts the optional parameters # @return [InviteUserSuccess] describe 'invite_user_by_mail test' do it "should work" do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end # unit tests for list_users # Get all users. # List all users. # @param [Hash] opts the optional parameters # @option opts [Integer] :page Current page *(Optional)* # @option opts [Integer] :role_id Search on Role ID *(Optional)* # @option opts [Integer] :limit Results per page *(Optional)* # @option opts [String] :order_by Field to order the results *(Optional)* # @option opts [String] :order_direction Direction of ordering *(Optional)* # @return [UserResults] describe 'list_users test' do it "should work" do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
<reponame>AriaPahlavan/Android-Apps<gh_stars>1-10 package com.example; /** * Created by apahlavan1 on 1/6/2016. */ public class Enemy { private int hitPoints; private int lives; public Enemy(int hitPoints, int lives) { this.hitPoints = hitPoints; this.lives = lives; } public void setHitPoints(int hitPoints) { this.hitPoints = hitPoints; } public void setLives(int lives) { this.lives = lives; } public int getLives() { return lives; } public int getHitPoints() { return hitPoints; } public void takeDamage(int damage){ int currHitPoints = getHitPoints(); int remainingHitPoints; if(currHitPoints > damage) { remainingHitPoints = currHitPoints - damage; } else remainingHitPoints = 0; setHitPoints(remainingHitPoints); System.out.println("I took " + damage + " points damage, and have " + remainingHitPoints + " left."); } }
package org.brapi.test.BrAPITestServer.model.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name="additional_info") public class AdditionalInfoEntity extends BrAPIBaseEntity{ @Column private String key; @Column private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
<filename>src/main/java/bootcamp/mercado/usuario/autenticacao/TokenParser.java package bootcamp.mercado.usuario.autenticacao; import bootcamp.mercado.usuario.Usuario; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class TokenParser { @Value("${orange.ecommerce-treino.secret}") private String secret; @Value("${orange.ecommerce-treino.expiration}") private String expiration; @Value("${orange.ecommerce-treino.issuer}") private String issuer; public Token parse(Usuario usuario) { return new Token(usuario, secret, expiration, issuer); } public Token parse(String token) { try { return new Token(token, secret); } catch (Exception e) { return null; } } }
<gh_stars>0 package io.cattle.platform.core.dao.impl; import com.netflix.config.DynamicBooleanProperty; import io.cattle.platform.archaius.util.ArchaiusUtil; import io.cattle.platform.core.addon.Register; import io.cattle.platform.core.constants.AccountConstants; import io.cattle.platform.core.constants.AgentConstants; import io.cattle.platform.core.constants.CommonStatesConstants; import io.cattle.platform.core.dao.AgentDao; import io.cattle.platform.core.dao.ClusterDao; import io.cattle.platform.core.dao.GenericResourceDao; import io.cattle.platform.core.dao.HostDao; import io.cattle.platform.core.model.Agent; import io.cattle.platform.core.model.Credential; import io.cattle.platform.core.model.Host; import io.cattle.platform.core.model.Instance; import io.cattle.platform.core.model.StoragePool; import io.cattle.platform.core.model.tables.records.AgentRecord; import io.cattle.platform.core.model.tables.records.CredentialRecord; import io.cattle.platform.core.model.tables.records.HostRecord; import io.cattle.platform.core.model.tables.records.StoragePoolRecord; import io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao; import io.cattle.platform.object.ObjectManager; import io.cattle.platform.object.util.DataAccessor; import io.cattle.platform.util.resource.UUID; import org.apache.commons.lang3.StringUtils; import org.jooq.Condition; import org.jooq.Configuration; import org.jooq.Record1; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static io.cattle.platform.core.model.tables.AgentTable.*; import static io.cattle.platform.core.model.tables.CredentialTable.*; import static io.cattle.platform.core.model.tables.HostTable.*; import static io.cattle.platform.core.model.tables.InstanceTable.*; import static io.cattle.platform.core.model.tables.StoragePoolTable.*; public class AgentDaoImpl extends AbstractJooqDao implements AgentDao { public static final DynamicBooleanProperty ALLOW_SIMULATORS = ArchaiusUtil.getBoolean("allow.simulators"); Long startTime = null; ClusterDao clusterDao; GenericResourceDao resourceDao; ObjectManager objectManager; public AgentDaoImpl(Configuration configuration, ClusterDao clusterDao, GenericResourceDao resourceDao, ObjectManager objectManager) { super(configuration); this.clusterDao = clusterDao; this.resourceDao = resourceDao; this.objectManager = objectManager; } @Override public Instance getInstanceByAgent(Long agentId) { if (agentId == null) { return null; } return create() .selectFrom(INSTANCE) .where(INSTANCE.AGENT_ID.eq(agentId) .and(INSTANCE.REMOVED.isNull()) .and(INSTANCE.STATE.notIn(CommonStatesConstants.ERROR, CommonStatesConstants.ERRORING, CommonStatesConstants.REMOVING))) .fetchAny(); } @Override public boolean areAllCredentialsActive(Agent agent) { List<Long> authedRoleAccountIds = DataAccessor.fieldLongList(agent, AgentConstants.FIELD_AUTHORIZED_ROLE_ACCOUNTS); if (agent.getAccountId() == null) { return false; } Set<Long> accountIds = new HashSet<>(); accountIds.add(agent.getAccountId()); for (Long aId : authedRoleAccountIds) { accountIds.add(aId); } List<? extends Credential> creds = create() .selectFrom(CREDENTIAL) .where(CREDENTIAL.STATE.eq(CommonStatesConstants.ACTIVE) .and(CREDENTIAL.ACCOUNT_ID.in(accountIds))) .fetch(); Set<Long> credAccountIds = new HashSet<>(); for (Credential cred : creds) { credAccountIds.add(cred.getAccountId()); } return accountIds.equals(credAccountIds); } @Override public Agent findNonRemovedByUri(String uri) { return create() .selectFrom(AGENT) .where( AGENT.URI.eq(uri) .and(AGENT.REMOVED.isNull())) .fetchAny(); } @Override public Map<String, Host> getHosts(Agent agent) { List<? extends Host> hostList = create() .select(HOST.fields()) .from(HOST) .where( HOST.AGENT_ID.eq(agent.getId()) .and(HOST.REMOVED.isNull())) .fetchInto(HostRecord.class); return groupByReportedUUid(agent, hostList); } public Map<String, Host> groupByReportedUUid(Agent agent, List<? extends Host> hostList) { Map<String,Host> hosts = new HashMap<>(); for ( Host host : hostList ) { hosts.put(host.getUuid(), host); if (StringUtils.isNotBlank(host.getExternalId())) { hosts.put(host.getExternalId(), host); if (host.getExternalId().equals(AgentConstants.defaultUuid(agent, Host.class))) { hosts.put("DEFAULT", host); } } } return hosts; } @Override public Map<String, StoragePool> getStoragePools(long agentId) { Map<String,StoragePool> pools = new HashMap<>(); List<? extends StoragePool> poolList = create() .select(STORAGE_POOL.fields()) .from(STORAGE_POOL) .where( STORAGE_POOL.AGENT_ID.eq(agentId) .and(STORAGE_POOL.REMOVED.isNull())) .fetchInto(StoragePoolRecord.class); for ( StoragePool pool : poolList ) { String uuid = pool.getExternalId(); if ( uuid == null ) { uuid = pool.getUuid(); } pools.put(uuid, pool); } return pools; } @Override public Agent getHostAgentForDelegate(long agentId) { List<? extends Agent> result = create().select(AGENT.fields()) .from(AGENT) .join(HOST) .on(HOST.AGENT_ID.eq(AGENT.ID)) .join(INSTANCE) .on(INSTANCE.HOST_ID.eq(HOST.ID)) .where(INSTANCE.AGENT_ID.eq(agentId)) .fetchInto(AgentRecord.class); return result.size() == 0 ? null : result.get(0); } @Override public String getAgentState(long agentId) { Record1<String> r = create().select(AGENT.STATE) .from(AGENT) .where(AGENT.ID.eq(agentId) .and(AGENT.REMOVED.isNull())).fetchAny(); return r == null ? null : r.value1(); } @Override public List<? extends Agent> findAgentsToRemove() { if (startTime == null) { startTime = System.currentTimeMillis(); } if ((System.currentTimeMillis() - startTime) <= (HostDao.HOST_REMOVE_START_DELAY.get() * 1000)) { return Collections.emptyList(); } List<? extends Agent> agents = create().select(AGENT.fields()) .from(AGENT) .leftOuterJoin(HOST) .on(HOST.AGENT_ID.eq(AGENT.ID)) .where(HOST.ID.isNull().or(HOST.REMOVED.isNotNull()) .and(AGENT.STATE.eq(AgentConstants.STATE_DISCONNECTED))) .fetchInto(AgentRecord.class); // This is purging old pre-1.2 agent delegates List<? extends Agent> oldAgents = create().select(AGENT.fields()) .from(AGENT) .where(AGENT.REMOVED.isNull().and(AGENT.URI.like("delegate%"))) .fetchInto(AgentRecord.class); List<Agent> result = new ArrayList<>(agents); result.addAll(oldAgents); return result; } @Override public Host getHost(Agent agent, String externalId) { if ("DEFAULT".equals(externalId)) { externalId = AgentConstants.defaultUuid(agent, Host.class); } return create() .select(HOST.fields()) .from(HOST) .where( HOST.AGENT_ID.eq(agent.getId()) .and(HOST.EXTERNAL_ID.eq(externalId)) .and(HOST.REMOVED.isNull())) .fetchAnyInto(HostRecord.class); } @Override public List<? extends Agent> findAgentsToPing() { Condition c = AGENT.STATE.eq(CommonStatesConstants.ACTIVE); for (String prefix : AgentConstants.AGENT_IGNORE_PREFIXES) { c = c.and(AGENT.URI.notLike(prefix + "%")); } return create() .select(AGENT.fields()) .from(AGENT) .where(c) .fetchInto(AgentRecord.class); } @Override public Agent findAgentByExternalId(String externalId, long clusterId) { return create().select(AGENT.fields()) .from(AGENT) .where(AGENT.CLUSTER_ID.eq(clusterId) .and(AGENT.EXTERNAL_ID.eq(externalId)) .and(AGENT.REMOVED.isNull())) .fetchAnyInto(AgentRecord.class); } @Override public Credential findAgentCredentailByExternalId(String externalId, long clusterId) { return create().select(CREDENTIAL.fields()) .from(CREDENTIAL) .join(AGENT) .on(AGENT.ACCOUNT_ID.eq(CREDENTIAL.ACCOUNT_ID)) .where(CREDENTIAL.STATE.eq(CommonStatesConstants.ACTIVE) .and(AGENT.CLUSTER_ID.eq(clusterId)) .and(AGENT.EXTERNAL_ID.eq(externalId)) .and(AGENT.REMOVED.isNull())) .fetchAnyInto(CredentialRecord.class); } @Override public Agent createAgentForRegistration(Register register, long clusterId) { Agent agent = objectManager.findAny(Agent.class, AGENT.EXTERNAL_ID, register.getKey(), AGENT.CLUSTER_ID, clusterId, AGENT.REMOVED, null); if (agent != null) { return agent; } long accountId = clusterDao.getOwnerAcccountIdForCluster(clusterId); String format = "event://%s"; if (register.isSimulated() && ALLOW_SIMULATORS.get()) { format = "sim://%s"; } return resourceDao.createAndSchedule(Agent.class, AGENT.KIND, AccountConstants.REGISTERED_AGENT_KIND, AGENT.URI, String.format(format, UUID.randomUUID().toString()), AGENT.RESOURCE_ACCOUNT_ID, accountId, AGENT.CLUSTER_ID, clusterId, AGENT.EXTERNAL_ID, register.getKey()); } }
package com.tracy.competition.utils import java.io.{ByteArrayOutputStream, IOException} import java.nio.charset.StandardCharsets import java.util import com.tracy.competition.domain.entity.{Team, User} import org.apache.poi.hpsf.{DocumentSummaryInformation, SummaryInformation} import org.apache.poi.hssf.usermodel.{HSSFCell, HSSFCellStyle, HSSFRow, HSSFSheet, HSSFWorkbook} import org.apache.poi.ss.usermodel.{FillPatternType, IndexedColors} import org.springframework.http.{HttpHeaders, HttpStatus, MediaType, ResponseEntity} /** * @author Tracy * @date 2021/2/9 12:40 */ object POIUtils { //导出 def userExcel(list: util.List[User]): ResponseEntity[Array[Byte]] = { //1. 创建一个 Excel 文档 val workbook = new HSSFWorkbook //2. 创建文档摘要 workbook.createInformationProperties() //3. 获取并配置文档信息 val docInfo: DocumentSummaryInformation = workbook.getDocumentSummaryInformation //文档类别 docInfo.setCategory("报名信息") //4. 获取文档摘要信息 val summInfo: SummaryInformation = summaryInfo(workbook.getSummaryInformation) //5. 创建样式 //创建标题行的样式 val headerStyle: HSSFCellStyle = headStyleSetting(workbook.createCellStyle) val sheet: HSSFSheet = sheetParams(workbook.createSheet("报名信息表")) //6. 创建标题行 val r0: HSSFRow = sheet.createRow(0) //设置行值 val c0: HSSFCell = r0.createCell(0) c0.setCellValue("序号") c0.setCellStyle(headerStyle) val c1: HSSFCell = r0.createCell(1) c1.setCellStyle(headerStyle) c1.setCellValue("姓名") val c2: HSSFCell = r0.createCell(2) c2.setCellStyle(headerStyle) c2.setCellValue("学校") val c3: HSSFCell = r0.createCell(3) c3.setCellStyle(headerStyle) c3.setCellValue("学院") val c4: HSSFCell = r0.createCell(4) c4.setCellStyle(headerStyle) c4.setCellValue("年级") val c5: HSSFCell = r0.createCell(5) c5.setCellStyle(headerStyle) c5.setCellValue("班级") val c6: HSSFCell = r0.createCell(6) c6.setCellStyle(headerStyle) c6.setCellValue("性别") val c7: HSSFCell = r0.createCell(7) c7.setCellStyle(headerStyle) c7.setCellValue("联系电话") for (i <- 0 until list.size) { val user: User = list.get(i) val row: HSSFRow = sheet.createRow(i + 1) row.createCell(0).setCellValue(i + 1) row.createCell(1).setCellValue(user.getName) row.createCell(2).setCellValue(user.getCollege.getUniversity.getUniversityName) row.createCell(3).setCellValue(user.getCollege.getCollegeName) row.createCell(4).setCellValue(user.getPeriod.toDouble) row.createCell(5).setCellValue(user.getUserClassName) row.createCell(6).setCellValue(user.getSex) row.createCell(7).setCellValue(user.getPhone) } packageResponseEntity(workbook) } def teamExcel(teamList: util.List[Team]): ResponseEntity[Array[Byte]] = { val workbook = new HSSFWorkbook workbook.createInformationProperties() val docInfo: DocumentSummaryInformation = workbook.getDocumentSummaryInformation docInfo.setCategory("队伍报名信息") val summInfo: SummaryInformation = summaryInfo(workbook.getSummaryInformation) val headerStyle: HSSFCellStyle = headStyleSetting(workbook.createCellStyle) val sheet: HSSFSheet = sheetParams(workbook.createSheet("报名信息表")) val r0: HSSFRow = sheet.createRow(0) val c0: HSSFCell = r0.createCell(0) c0.setCellValue("序号") c0.setCellStyle(headerStyle) val c1: HSSFCell = r0.createCell(1) c1.setCellStyle(headerStyle) c1.setCellValue("队伍名") val c2: HSSFCell = r0.createCell(2) c2.setCellStyle(headerStyle) c2.setCellValue("姓名") val c3: HSSFCell = r0.createCell(3) c3.setCellStyle(headerStyle) c3.setCellValue("学校") val c4: HSSFCell = r0.createCell(4) c4.setCellStyle(headerStyle) c4.setCellValue("学院") val c5: HSSFCell = r0.createCell(5) c5.setCellStyle(headerStyle) c5.setCellValue("年级") val c6: HSSFCell = r0.createCell(6) c6.setCellStyle(headerStyle) c6.setCellValue("班级") val c7: HSSFCell = r0.createCell(7) c7.setCellStyle(headerStyle) c7.setCellValue("性别") val c8: HSSFCell = r0.createCell(8) c8.setCellStyle(headerStyle) c8.setCellValue("联系电话") //当前行,默认1, 0为表头 var nowLine = 1 for (i <- 0 until teamList.size) { val team: Team = teamList.get(i) System.out.println(team) val row: HSSFRow = sheet.createRow(nowLine) row.createCell(0).setCellValue(i + 1) row.createCell(1).setCellValue(team.getTeamName) row.createCell(2).setCellValue(team.getCaptain.getName) row.createCell(3).setCellValue(team.getCaptain.getCollege.getUniversity.getUniversityName) row.createCell(4).setCellValue(team.getCaptain.getCollege.getCollegeName) row.createCell(5).setCellValue(team.getCaptain.getPeriod.toDouble) row.createCell(6).setCellValue(team.getCaptain.getUserClassName) row.createCell(7).setCellValue(team.getCaptain.getSex) row.createCell(8).setCellValue(team.getCaptain.getPhone) //行自加 nowLine += 1 //队伍成员标题行 val rr0: HSSFRow = sheet.createRow(nowLine) //设置行值,从1开始,代表成员偏移一格 val cc1: HSSFCell = rr0.createCell(1) cc1.setCellValue("成员序号") cc1.setCellStyle(headerStyle) val cc2: HSSFCell = rr0.createCell(2) cc2.setCellStyle(headerStyle) cc2.setCellValue("姓名") val cc3: HSSFCell = rr0.createCell(3) cc3.setCellStyle(headerStyle) cc3.setCellValue("学校") val cc4: HSSFCell = rr0.createCell(4) cc4.setCellStyle(headerStyle) cc4.setCellValue("学院") val cc5: HSSFCell = rr0.createCell(5) cc5.setCellStyle(headerStyle) cc5.setCellValue("年级") val cc6: HSSFCell = rr0.createCell(6) cc6.setCellStyle(headerStyle) cc6.setCellValue("班级") val cc7: HSSFCell = rr0.createCell(7) cc7.setCellStyle(headerStyle) cc7.setCellValue("性别") val cc8: HSSFCell = rr0.createCell(8) cc8.setCellStyle(headerStyle) cc8.setCellValue("联系电话") nowLine += 1 for (j <- 1 until team.getUsers.size) { val user: User = team.getUsers.get(j) val row1: HSSFRow = sheet.createRow(nowLine) row1.createCell(1).setCellValue(j) row1.createCell(2).setCellValue(user.getName) row1.createCell(3).setCellValue(user.getCollege.getUniversity.getUniversityName) row1.createCell(4).setCellValue(user.getCollege.getCollegeName) row1.createCell(5).setCellValue(user.getPeriod.toDouble) row1.createCell(6).setCellValue(user.getUserClassName) row1.createCell(7).setCellValue(user.getSex) row1.createCell(8).setCellValue(user.getPhone) nowLine += 1 } } packageResponseEntity(workbook) } /** * 摘要信息初始化 * @param summInfo summaryInformation * @return */ private def summaryInfo(summInfo: SummaryInformation): SummaryInformation = { //文档标题 summInfo.setTitle("报名信息") //文档作者 summInfo.setAuthor("admin") // 文档备注 summInfo.setComments("本文档由竞赛管理系统导出") summInfo } /** * 设置头参数 * @param headerStyle headerStyle * @return */ private def headStyleSetting(headerStyle: HSSFCellStyle): HSSFCellStyle = { headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index) headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND) headerStyle } /** * 设置列参数 * @param sheet sheet * @return */ private def sheetParams(sheet: HSSFSheet): HSSFSheet = { //设置列的宽度 sheet.setColumnWidth(0, 5 * 256) sheet.setColumnWidth(1, 10 * 256) sheet.setColumnWidth(2, 20 * 256) sheet.setColumnWidth(3, 20 * 256) sheet.setColumnWidth(4, 10 * 256) sheet.setColumnWidth(5, 20 * 256) sheet.setColumnWidth(6, 5 * 256) sheet.setColumnWidth(7, 15 * 256) sheet } /** * 将workbook封装至http响应体 * * @param workbook workbook * @return */ private def packageResponseEntity(workbook: HSSFWorkbook): ResponseEntity[Array[Byte]] = { val baos = new ByteArrayOutputStream val headers = new HttpHeaders try { headers.setContentDispositionFormData("attachment", new String("报名表.xls".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)) headers.setContentType(MediaType.APPLICATION_OCTET_STREAM) workbook.write(baos) } catch { case e: IOException => e.printStackTrace() } new ResponseEntity[Array[Byte]](baos.toByteArray, headers, HttpStatus.CREATED) } }
<filename>app/src/main/java/com/qtimes/pavilion/events/ApkInstallEvent.java<gh_stars>0 package com.qtimes.pavilion.events; /** * Author: JackHou * Date: 2020/5/9. */ public class ApkInstallEvent { private long downLoadId; public ApkInstallEvent(long mDownLoadId) { downLoadId = mDownLoadId; } public long getDownLoadId() { return downLoadId; } public void setDownLoadId(long mDownLoadId) { downLoadId = mDownLoadId; } }
#!/bin/sh set -e echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # Use filter instead of exclude so missing patterns don't throw errors. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Copies the dSYM of a vendored framework install_dsym() { local source="$1" if [ -r "$source" ]; then echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DWARF_DSYM_FOLDER_PATH}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DWARF_DSYM_FOLDER_PATH}" fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current file archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" stripped="" for arch in $archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/JYMemoryWatch/JYMemoryWatch.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/JYMemoryWatch/JYMemoryWatch.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi
<gh_stars>10-100 package io.iftech.sparkudf.spark; import io.iftech.sparkudf.Decoder; import io.iftech.sparkudf.converter.Converter; import io.iftech.sparkudf.converter.SparkConverter; import java.util.List; import org.apache.spark.sql.Row; import org.apache.spark.sql.api.java.UDF4; import scala.collection.JavaConverters; import scala.collection.mutable.WrappedArray; public class DecodeContractEventUDF implements UDF4<byte[], WrappedArray<String>, String, String, Row> { @Override public Row call( final byte[] data, final WrappedArray<String> topicsHex, final String eventABI, final String eventName ) throws Exception { List<Object> values = new Decoder<>(new SparkConverter()) .decodeEvent( data, JavaConverters.seqAsJavaList(topicsHex), eventABI, eventName ); return values == null ? null : Row.fromSeq(Converter.convertListToSeq(values)); } }
from rest_framework.permissions import BasePermission, SAFE_METHODS, IsAdminUser class CustomPermission(BasePermission): def has_permission(self, request, view): if request.method in SAFE_METHODS: return True # Allow safe methods for all users else: return request.user and IsAdminUser().has_permission(request, view)
#!/usr/bin/env python # -*- coding:UTF -*- x = 42 def callf(func): #本身也有环境 print("callf本身的x is %d" % x) return func()
<reponame>komura-c/supabase<filename>studio/components/interfaces/App/PortalToast.tsx import dynamic from 'next/dynamic' import { Toaster, ToastBar, toast } from 'react-hot-toast' import { Button, IconX } from '@supabase/ui' const PortalRootWithNoSSR = dynamic( // @ts-ignore () => import('@radix-ui/react-portal').then((portal) => portal.Root), { ssr: false } ) const PortalToast = () => ( // @ts-ignore <PortalRootWithNoSSR className="portal--toast"> <Toaster position="top-right" toastOptions={{ className: 'bg-bg-primary-light dark:bg-bg-primary-dark text-typography-body-strong-light dark:text-typography-body-strong-dark border dark:border-dark', style: { padding: '8px', paddingLeft: '16px', paddingRight: '16px', fontSize: '0.875rem', }, error: { duration: 8000, }, }} > {(t) => ( <ToastBar toast={t} style={t.style}> {({ icon, message }) => ( <> {icon} {message} {t.type !== 'loading' && ( <div className="ml-4"> <Button className="!p-1" type="text" onClick={() => toast.dismiss(t.id)}> <IconX size={14} strokeWidth={2} /> </Button> </div> )} </> )} </ToastBar> )} </Toaster> </PortalRootWithNoSSR> ) export default PortalToast
def sort_dict_of_dicts_by_score(data): # get items from dict items = list(data.items()) # sort list by score items.sort(key=lambda x: x[1]['score']) # return sorted list of dicts return [dict(name=i[0], **i[1]) for i in items]
import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic; import java.util.Set; @SupportedAnnotationTypes({"com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty", "com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper"}) @SupportedSourceVersion(SourceVersion.RELEASE_8) public class JacksonXmlAnnotationProcessor extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (Element element : roundEnv.getElementsAnnotatedWith(JacksonXmlProperty.class)) { if (element.getKind() == ElementKind.FIELD) { JacksonXmlProperty annotation = element.getAnnotation(JacksonXmlProperty.class); String fieldName = element.getSimpleName().toString(); String xmlElementName = annotation.localName(); boolean isAttribute = annotation.isAttribute(); // Generate XML element name based on the field name and annotation String xmlElement = "<" + xmlElementName; if (isAttribute) { xmlElement += " " + fieldName + "=\"" + fieldName + "\""; } xmlElement += "/>"; processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Generated XML element: " + xmlElement); } } for (Element element : roundEnv.getElementsAnnotatedWith(JacksonXmlElementWrapper.class)) { if (element.getKind() == ElementKind.FIELD) { JacksonXmlElementWrapper annotation = element.getAnnotation(JacksonXmlElementWrapper.class); String wrapperName = annotation.localName(); boolean useWrapping = annotation.useWrapping(); // Generate XML wrapper element based on the annotation String xmlWrapper = "<" + wrapperName + " useWrapping=\"" + useWrapping + "\">"; xmlWrapper += "</" + wrapperName + ">"; processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Generated XML wrapper element: " + xmlWrapper); } } return true; } }
// openseadragon-overlays-manager.js // Draw // proposal: // test: // /** * @constructor * OpenSeadragon Overlays Manage Plugin 0.0.1 based on canvas overlay plugin. * A OpenSeadragon plugin that provides a way to mange multiple overlays. * @param {Object} [options] * Allows configurable properties to be entirely specified by passing an options object to the constructor. * @param {Object} options.viewer * A instance of viewer in Openseadragon. * @param {Object} [zIndex=100] * specifies the z-order of a positioned element */ (function($){ if (!$) { $ = require('openseadragon'); if (!$) { throw new Error('OpenSeadragon is missing.'); } } // check version if (!$.version || $.version.major < 2) { throw new Error('This version of OpenSeadragonScalebar requires ' + 'OpenSeadragon version 2.2.0+'); } $.Viewer.prototype.overlaysManager = function(options) { if (!this.omanager) { options = options || {}; options.viewer = this; this.omanager = new $.OverlaysManager(options); } else { //this.omanager.updateOptions(options); } }; $.OverlaysManager = function(options) { this._viewer = options.viewer; this.overlays = []; this.events = { highlight:this.highlight.bind(this), click:this.pathClick.bind(this), updateView:this.updateView.bind(this), zooming:this._zooming.bind(this), panning:this._panning.bind(this), drawing:this._drawing.bind(this) } // -- create container div, and hover, display canvas -- // this._containerWidth = 0; this._containerHeight = 0; // create container div this._div = document.createElement( 'div'); this._div.style.position = 'absolute'; this._div.style.left = 0; this._div.style.top = 0; this._div.style.width = '100%'; this._div.style.height = '100%'; this._div.style.display = 'none'; this._div.style.transformOrigin = '0 0'; this._div.style.transform = 'scale(1,1)'; this._div.style.display = 'none'; this._div.style.display = 'none'; this._div.style.zIndex = options.zIndex || 100; this._viewer.canvas.appendChild(this._div); // create display_canvas this._display_ = document.createElement('canvas'); this._display_.style.position = 'absolute'; this._display_.style.top = 0; this._display_.style.left = 0; this._display_ctx_ = this._display_.getContext('2d'); this._div.appendChild(this._display_); // create hover_canvas this._hover_ = document.createElement('canvas'); this._hover_.style.position = 'absolute'; this._hover_.style.top = 0; this._hover_.style.left = 0; this._hover_ctx_ = this._hover_.getContext('2d'); this._div.appendChild(this._hover_); this._center = this._viewer.viewport.getCenter(true); this._interval = null; this.updateView(); //this._viewer.addHandler('update-viewport',this.updateView.bind(this)); this._viewer.addHandler('open',this.updateView.bind(this)); this._viewer.addHandler('resize',this.updateView.bind(this)); this._viewer.addHandler('pan',this.events.panning); this._viewer.addHandler('zoom',this.events.zooming); this._viewer.addHandler('animation-finish', this.events.drawing); this._div.addEventListener('mousemove', this.events.highlight); this._div.addEventListener('click', this.events.click); } $.OverlaysManager.prototype = { _zooming:function(e){ if(!this.hasShowOverlay()) return; if(!e.refPoint || e.zoom > this._viewer.viewport.getMaxZoom() || e.zoom < this._viewer.viewport.getMinZoom()) return; if(e.refPoint === true){ e.refPoint = this._viewer.viewport.getCenter(true); } const viewportPoint = this._viewer.viewport.viewportToViewerElementCoordinates(e.refPoint); var viewportZoom = this._viewer.viewport.getZoom(); var zoom = this._viewer.viewport.viewportToImageZoom(e.zoom); var scale = viewportZoom/this._zoom; if(scale == 1 || Math.abs(1 - scale) < 0.01) return; this._div.style.transformOrigin = `${viewportPoint.x}px ${viewportPoint.y}px`; this._div.style.transform = `scale(${scale},${scale})`; }, _panning:function(e){ if(!this.hasShowOverlay()) return; let dx = this._center.x - e.center.x; let dy = this._center.y - e.center.y; const distance = this._viewer.viewport.deltaPixelsFromPoints(new $.Point(dx,dy), true); if(Math.abs(distance.x) < 0.01 && Math.abs(distance.y) < 0.01) return; let top = parseFloat(this._div.style.top); let left = parseFloat(this._div.style.left); this._div.style.top = `${top + distance.y}px`; this._div.style.left = `${left + distance.x}px`; this._center = e.center; }, _drawing:function(e){ if(!this.hasShowOverlay()) return; // debound if there are a if(this.events['async']){ clearTimeout(this._interval); this._interval = setTimeout(function(){ this.events['async'](this.events.updateView); }.bind(this),800); return; } this.updateView(); }, /** * @private * highlight the path if cursor on the path * @param {Event} e the event */ highlight:function(e){ this._div.style.cursor = 'default'; DrawHelper.clearCanvas(this._hover_); const point = new OpenSeadragon.Point(e.clientX, e.clientY); const img_point = this._viewer.viewport.windowToImageCoordinates(point); for(let i = 0;i<this.overlays.length;i++){ const layer = this.overlays[i]; if(!layer.isShow) continue; if($.isArray(layer.data)){ for(let j = 0;j < layer.data.length;j++){ const path = layer.data[j].geometry.path; const style = layer.data[j].properties.style; if(layer.hoverable&&path.contains(img_point.x,img_point.y)){ this.resize(); this.highlightPath = path; this.highlightStyle = style; this.highlightLayer = layer; this.highlightLayer.data.selected = j; this.drawOnCanvas(this.drawOnHover,[this._hover_ctx_,this._div,path,style]); return; }else{ this.highlightPath = null; this.highlightStyle = null; if(this.highlightLayer) { this.highlightLayer.data.selected = null; this.highlightLayer = null; } } } } if(!layer.data.geometries) continue; const features = layer.data.geometries.features; for(let j = 0;j < features.length;j++){ const path = features[j].geometry.path; const style = features[j].properties.style; this.subIndex = null; if(layer.hoverable&&path.contains(img_point.x,img_point.y)){ this.resize(); this.highlightPath = path; this.highlightStyle = style; this.highlightLayer = layer; this.highlightLayer.data.selected = j; this.drawOnCanvas(this.drawOnHover,[this._hover_ctx_,this._div,path,style]); return; }else{ this.highlightPath = null; this.highlightStyle = null; this.highlightLayer = null; } } } }, /** * @private * pathClick * @param {Event} e the event */ pathClick:function(e){ if(this.highlightLayer&&this.highlightLayer.clickable) this._viewer.raiseEvent('canvas-lay-click',{position:{x:e.clientX, y:e.clientY},data:this.highlightLayer?this.highlightLayer.data:null}); }, /** * setOverlays * add a collection of overlays by geting the data collection * @param {Array} overlays the collection of data of the overlays */ setOverlays:function(overlays){ if(!$.isArray(overlays)) return; for(let i = 0;i<overlays.length;i++){ this.addOverlay(overlays[i]); } }, /** * @private * resize the canvas and redraw marks on the proper place */ resize: function() { this._div.style.top = 0; this._div.style.left = 0; this._div.style.transformOrigin = '0 0'; this._div.style.transform = 'scale(1,1)'; this._center = this._viewer.viewport.getCenter(true); this._zoom = this._viewer.viewport.getZoom(true); if (this._containerWidth !== this._viewer.container.clientWidth) { this._containerWidth = this._viewer.container.clientWidth; this._div.setAttribute('width', this._containerWidth); this._hover_.setAttribute('width', this._containerWidth); this._display_.setAttribute('width', this._containerWidth); } if (this._containerHeight !== this._viewer.container.clientHeight) { this._containerHeight = this._viewer.container.clientHeight; this._div.setAttribute('height', this._containerHeight); this._hover_.setAttribute('height', this._containerHeight); this._display_.setAttribute('height', this._containerHeight); } this._viewportOrigin = new $.Point(0, 0); var boundsRect = this._viewer.viewport.getBounds(true); this._viewportOrigin.x = boundsRect.x; this._viewportOrigin.y = boundsRect.y * this.imgAspectRatio; this._viewportWidth = boundsRect.width; this._viewportHeight = boundsRect.height * this.imgAspectRatio; var image1 = this._viewer.world.getItemAt(0); this.imgWidth = image1.source.dimensions.x; this.imgHeight = image1.source.dimensions.y; this.imgAspectRatio = this.imgWidth / this.imgHeight; }, /** * @private * drawOnCanvas draw marks on canvas * @param {Canvas} ctx a canvas' 2d context that the marks draw on * @param {Function} drawFuc [description] * @return {[type]} [description] */ drawOnCanvas:function(drawFuc,args){ var viewportZoom = this._viewer.viewport.getZoom(true); var image1 = this._viewer.world.getItemAt(0); var zoom = image1.viewportToImageZoom(viewportZoom); var x=((this._viewportOrigin.x/this.imgWidth-this._viewportOrigin.x )/this._viewportWidth)*this._containerWidth; var y=((this._viewportOrigin.y/this.imgHeight-this._viewportOrigin.y )/this._viewportHeight)*this._containerHeight; DrawHelper.clearCanvas(args[0].canvas); args[0].translate(x,y); args[0].scale(zoom,zoom); drawFuc.apply(this,args); //this.drawOnDisplay(this._display_ctx_); args[0].setTransform(1, 0, 0, 1, 0, 0); }, /** * hasShowOverlay determine that there is a overlay to show or not * @return {Boolean} return true if has overlay to show. Otherwise, return false. */ hasShowOverlay:function(){ return this.overlays.some(lay => lay.isShow == true); }, /** * @private * drawOnDisplay draw marks on display canvas * @param {Canvas} ctx a canvas' 2d context that the marks draw on */ drawOnDisplay:function(ctx){ for (var i = 0; i < this.overlays.length; i++) { const layer = this.overlays[i]; if(layer.isShow) layer.onDraw(ctx); } }, /** * @private * drawOnHover draw marks on hover canvas * @param {Canvas} ctx a canvas' 2d context that the marks draw on * @param {Path/Path2D} path the data of a path/marks * @param {Object} style the style of drawing */ drawOnHover:function(ctx,div,path,style){ div.style.cursor = 'point'; ctx.lineJoin = 'round'; ctx.lineCap = 'round'; ctx.fillStyle = hexToRgbA(style.color,0.5); ctx.strokeStyle = style.color; ctx.lineWidth = style.lineWidth; if(style.isFill ==undefined || style.isFill){ path.fill(this._hover_ctx_); }else{ const imagingHelper = this._viewer.imagingHelper; const lineWidth = (imagingHelper.physicalToDataX(2) - imagingHelper.physicalToDataX(0))>> 0; ctx.lineWidth = lineWidth; path.stroke(this._hover_ctx_); } }, /** * updateView update all canvas according to the current states of the osd'viewer */ updateView:function(){ this.resize(); if(this.hasShowOverlay()) { this._div.style.display = 'block'; }else{ this._div.style.display = 'none'; return; }; this.drawOnCanvas(this.drawOnDisplay,[this._display_ctx_]); if(this.highlightPath&& this.highlightLayer&& this.highlightLayer.hoverable)this.drawOnCanvas(this.drawOnHover,[this._hover_ctx_,this._div,this.highlightPath,this.highlightStyle]); }, /** * * addOverlay add a new over lay * @param {Object} options * allows configurable properties to be entirely specified by passing an options object to the constructor. * @param {String} options.id * the overlay's id * @param {Object} options.data * the data that is used to describe the overlay * @param {object} options.renderer * the renderer to render the overlay * */ addOverlay:function(options){ // id, data, render if(this.overlays.find(layer => layer.id == options.id)){ console.warn('duplicate overlay ID'); return; } options.viewer = this._viewer const lay = new Overlay(options) this.overlays.push(lay); // TODO redraw return lay; }, /** * remove a overlay from the manager * @param {String} id overlay's id * @return {Boolean} true - remove success. false - remove fail */ removeOverlay:function(id){ const index = this.overlays.findIndex(layer => layer.id == id); if (index > -1) { this.overlays.splice(index, 1); this.updateView(); //const sort = this.overlays.map(layer=>layer.id); //this.setSort(sort.reverse()); return true; } return false; }, /** * get Overlay by id * @param {String} id the overlay's id * @return {Object} */ getOverlay:function(id){ return this.overlays.find(layer => layer.id == id); }, sort:function(){ // for (var i = data.length - 1; i >= 0; i--) { // const id = data[i]; // const layer = this.getOverlayer(id); // const index = data.length - i; // layer.index = index; // } }, clearOverlays:function(){ this.overlays = []; }, clearCanvas:function(){ DrawHelper.clearCanvas(this._display_); DrawHelper.clearCanvas(this._hover_); }, clear:function(){ this.clearCanvas(); this.clearOverlays(); }, /** * Function to destroy the instance of OverlayManager and clean up everything created by OverlayManager. * * Example: * var omanger = OverlayManager({ * [...] * }); * * //when you are done with the omanger: * omanger.destroy(); * omanger = null; //important * */ destroy:function(){ for(const key in this){ this[key] = null; } } } $.extend( $.OverlaysManager.prototype, $.EventSource.prototype); /** * @constructor * Overlay a instance of overlay. * @param {Object} options * allows configurable properties to be entirely specified by passing an options object to the constructor. * @param {Object} options.id * the overlay's id * @param {Object} options.data * the data that is used to describe the overlay * @param {Object} options.render * the render that is used to render the overlay */ var Overlay = function(options){ this.className = 'Overlay' if(!options){ console.error(`${this.className}: No Options.`); return; } if(!options.id){ console.error(`${this.className}: No ID.`); return; } if(!options.data){ console.error(`${this.className}: No Data.`); return; } if(!options.render || typeof options.render !== 'function'){ console.error(`${this.className}: No Render or Illegal.`); return; } this.id = options.id; this.data = options.data; this.render = options.render; //this.clickable = options.clickable || true; //this.hoverable = options.hoverable || true; this.viewer = options.viewer; if(options.clickable!=null && options.clickable == false){ this.clickable = options.clickable }else{ this.clickable = true; } if(options.hoverable!=null && options.hoverable == false){ this.hoverable = options.hoverable }else{ this.hoverable = true; } if(options.isShow!=null && options.isShow == false){ this.isShow = options.isShow }else{ this.isShow = true; } //this.isShow = options.isShow || true; } Overlay.prototype = { /** * onDraw draw overlay * @param {2DContext} ctx * the context that is used to draw shapes * @param {[type]} data * the data that is used to describe the overlay */ onDraw:function( ctx, data){ if(data) this.data = data; this.render( ctx, this.data); } } })(OpenSeadragon)
#!/bin/bash ############################################################### # Created by Richard Tirtadji # Auto installer for Debian 10 + HA Supervised # Install Docker ESPHome ############################################################### TZONE=$1 while [[ $TZONE = "" ]]; do read -p "Write your timezone eg, Asia/Jakarta: " TZONE done # open port 6052 & 6123 for HA #ufw allow 6052 #ufw allow 6123 #service ufw restart # Making Directory for docker container mkdir /usr/share/hassio/homeassistant/esphome docker run -d --name="esphome" --net=host -p 6052:6052 -p 6123:6123 -e TZ=$TZONE -v /usr/share/hassio/homeassistant/esphome:/config esphome/esphome:latest
MStatus processInputPlugs(const std::vector<std::string>& inputPlugs, const std::vector<double>& inputValues) { std::unordered_set<std::string> expectedPlugs = {"plug1", "plug2", "plug3"}; // Replace with actual expected plug names for (const auto& plug : inputPlugs) { if (expectedPlugs.find(plug) == expectedPlugs.end()) { return MS::kUnknownParameter; // Unexpected plug encountered } } // Process input plugs here // ... return MS::kSuccess; // All input plugs processed successfully }
function getUsers(){ return fetch('/users') .then(response => response.json()) .then(data => data); }
#!/usr/bin/env bash milestone="$1" echo "Setting milestone to ${milestone}" gh "${ISSUE_KIND}" -R "${GH_REPOSITORY}" edit "${ISSUE_NUMBER}" --milestone "${milestone}"
<gh_stars>1-10 /* test6007.Quick.cpp */ //---------------------------------------------------------------------------------------- // // Project: CCore 2.00 // // Tag: Target/LIN64utf8 // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2015 <NAME>. All rights reserved. // //---------------------------------------------------------------------------------------- #include <CCore/test/test.h> #include <CCore/inc/base/Quick.h> #include <CCore/inc/math/UIntSlowMulAlgo.h> #include <CCore/inc/Random.h> namespace App { namespace Private_6007 { template <class UInt> class Engine : NoCopy { Random random; using Algo1 = Quick::UIntMulFunc<UInt> ; using Algo2 = Math::UIntSlowMulFunc<UInt> ; private: UInt next() { return random.next_uint<UInt>(); } public: Engine() {} void test1() { UInt a=next(); UInt b=next(); typename Algo1::Mul mul1(a,b); typename Algo2::Mul mul2(a,b); if( mul1.hi!=mul2.hi || mul1.lo!=mul2.lo ) { Printf(Exception,"test1 failed"); } } void test2() { UInt hi=next(); UInt lo=next(); UInt den=next(); if( hi>=den ) return; if( Algo1::Div(hi,lo,den) != Algo2::Div(hi,lo,den) ) { Printf(Exception,"test2 failed"); } } void test3() { UInt hi=next(); UInt lo=next(); UInt den=next(); if( hi>=den ) return; if( Algo1::Mod(hi,lo,den) != Algo2::Mod(hi,lo,den) ) { Printf(Exception,"test3 failed"); } } void test4() { UInt a=next(); UInt b=next(); UInt den=next(); typename Algo1::Mul mul(a,b); if( mul.hi>=den ) return; if( Algo1::MulDiv(a,b,den) != Algo2::MulDiv(a,b,den) ) { Printf(Exception,"test4 failed"); } } void test5() { UInt hi=next(); UInt lo=next(); UInt den=next(); if( hi>=den ) return; typename Algo1::DivMod divmod1(hi,lo,den); typename Algo2::DivMod divmod2(hi,lo,den); if( divmod1.div!=divmod2.div || divmod1.mod!=divmod2.mod ) { Printf(Exception,"test5 failed"); } } void test6() { UInt a=next(); UInt b=next(); UInt mod=next(); if( !mod ) return; a%=mod; b%=mod; if( Algo1::ModMul(a,b,mod) != Algo2::ModMul(a,b,mod) ) { Printf(Exception,"test6 failed"); } } void test7() { UInt s=next(); UInt a=next(); UInt b=next(); UInt mod=next(); if( !mod ) return; s%=mod; a%=mod; b%=mod; if( Algo1::ModMac(s,a,b,mod) != Algo2::ModMac(s,a,b,mod) ) { Printf(Exception,"test7 failed"); } } void step() { test1(); test2(); test3(); test4(); test5(); test6(); test7(); } void run(ulen count=10'000'000) { for(; count ;count--) { if( (count%1'000'000)==0 ) Printf(Con,"#;\n",count); step(); } } }; } // namespace Private_6007 using namespace Private_6007; /* Testit<6007> */ template<> const char *const Testit<6007>::Name="Test6007 Quick"; template<> bool Testit<6007>::Main() { Engine<uint64> engine; engine.run(); return true; } } // namespace App
function longestString(str1, str2) { if (str1.length >= str2.length) { console.log(str1); } else { console.log(str2); } } longestString(str1, str2);
package com.netcracker.ncstore.exception; /** * Should be used when parameters for new product are invalid. * Should always have a message explaining the cause; */ public class ProductServiceValidationException extends RuntimeException { public ProductServiceValidationException(String message) { super(message); } public ProductServiceValidationException(String message, Throwable cause) { super(message, cause); } }
<reponame>ES-UFABC/UFABCplanner import { Request, Response } from 'express'; import { validateInput } from 'infra/http/errors/validation'; import { container } from 'tsyringe'; import { GetClassesBySubjectIdDTO } from '../dtos/GetClassesBySubjectId.dto'; import { GetClassesBySubjectIdService } from '../services/GetClassesBySubjectIdService'; export class GetClassesBySubjectIdController { async execute(request: Request, response: Response) { const { id } = request.params; const getClassesBySubjectIdDTO = await validateInput(GetClassesBySubjectIdDTO, { id }); const classes = await container.resolve(GetClassesBySubjectIdService).handle(getClassesBySubjectIdDTO); return response.json(classes).send(); } }
import copy original_dict = {'a': 1, 'b': 2} shallow_copy_dict = copy.copy(original_dict)
<filename>src/app/models/disenio/nivel-centro-votacion.ts import { CentroVotacion } from './centro-votacion'; export class NivelCentroVotacion { id_nivel_centro_votacion: number; centroVotacion: CentroVotacion; id_nivel: number; }
<gh_stars>10-100 package facade.amazonaws import scala.scalajs.js @js.native trait Response[T <: js.Object] extends js.Object { val error: Error = js.native val data: T = js.native val request: Request[T] = js.native def hasNextPage(): Boolean = js.native def nextPage(): Request[T] = js.native }
export { default as escapeRegex } from './escapeRegex' export { default as getPlainText } from './getPlainText' export { default as applyChangeToValue } from './applyChangeToValue' export { default as findStartOfMentionInPlainText, } from './findStartOfMentionInPlainText' export { default as getMentions } from './getMentions' export { default as getSuggestionHtmlId } from './getSuggestionHtmlId' export { default as countSuggestions } from './countSuggestions' export { default as getEndOfLastMention } from './getEndOfLastMention' export { default as mapPlainTextIndex } from './mapPlainTextIndex' export { default as readConfigFromChildren } from './readConfigFromChildren' export { default as spliceString } from './spliceString' export { default as makeMentionsMarkup } from './makeMentionsMarkup' export { default as iterateMentionsMarkup } from './iterateMentionsMarkup' export { default as getSubstringIndex } from './getSubstringIndex' export { default as isNumber } from './isNumber' export { default as merge } from './merge' export { default as omit } from './omit' export { default as keys } from './keys' export { default as defaultStyle } from './defaultStyle'
<filename>lynxdef.h // // Copyright (c) 2004 <NAME> // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from // the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ////////////////////////////////////////////////////////////////////////////// // Handy - An Atari Lynx Emulator // // Copyright (c) 1996,1997 // // <NAME> // ////////////////////////////////////////////////////////////////////////////// // Generic lyynx definition header file // ////////////////////////////////////////////////////////////////////////////// // // // This header file provides the definition of all of the useful hardware // // addreses within the Lynx. // // // // <NAME> // // August 1997 // // // ////////////////////////////////////////////////////////////////////////////// // Revision History: // // ----------------- // // // // 01Aug1997 KW Document header added & class documented. // // // ////////////////////////////////////////////////////////////////////////////// #define TMPADR 0xfc00 #define TMPADRL 0xfc00 #define TMPADRH 0xfc01 #define TILTACUM 0xfc02 #define TILTACUML 0xfc02 #define TILTACUMH 0xfc03 #define HOFF 0xfc04 #define HOFFL 0xfc04 #define HOFFH 0xfc05 #define VOFF 0xfc06 #define VOFFL 0xfc06 #define VOFFH 0xfc07 #define VIDBAS 0xfc08 #define VIDBASL 0xfc08 #define VIDBASH 0xfc09 #define COLLBAS 0xfc0a #define COLLBASL 0xfc0a #define COLLBASH 0xfc0b #define VIDADR 0xfc0c #define VIDADRL 0xfc0c #define VIDADRH 0xfc0d #define COLLADR 0xfc0e #define COLLADRL 0xfc0e #define COLLADRH 0xfc0f #define SCBNEXT 0xfc10 #define SCBNEXTL 0xfc10 #define SCBNEXTH 0xfc11 #define SPRDLINE 0xfc12 #define SPRDLINEL 0xfc12 #define SPRDLINEH 0xfc13 #define HPOSSTRT 0xfc14 #define HPOSSTRTL 0xfc14 #define HPOSSTRTH 0xfc15 #define VPOSSTRT 0xfc16 #define VPOSSTRTL 0xfc16 #define VPOSSTRTH 0xfc17 #define SPRHSIZ 0xfc18 #define SPRHSIZL 0xfc18 #define SPRHSIZH 0xfc19 #define SPRVSIZ 0xfc1a #define SPRVSIZL 0xfc1a #define SPRVSIZH 0xfc1b #define STRETCH 0xfc1c #define STRETCHL 0xfc1c #define STRETCHH 0xfc1d #define TILT 0xfc1e #define TILTL 0xfc1e #define TILTH 0xfc1f #define SPRDOFF 0xfc20 #define SPRDOFFL 0xfc20 #define SPRDOFFH 0xfc21 #define SPRVPOS 0xfc22 #define SPRVPOSL 0xfc22 #define SPRVPOSH 0xfc23 #define COLLOFF 0xfc24 #define COLLOFFL 0xfc24 #define COLLOFFH 0xfc25 #define VSIZACUM 0xfc26 #define VSIZACUML 0xfc26 #define VSIZACUMH 0xfc27 #define HSIZOFF 0xfc28 #define HSIZOFFL 0xfc28 #define HSIZOFFH 0xfc29 #define VSIZOFF 0xfc2a #define VSIZOFFL 0xfc2a #define VSIZOFFH 0xfc2b #define SCBADR 0xfc2c #define SCBADRL 0xfc2c #define SCBADRH 0xfc2d #define PROCADR 0xfc2e #define PROCADRL 0xfc2e #define PROCADRH 0xfc2f #define MATHD 0xfc52 #define MATHC 0xfc53 #define MATHB 0xfc54 #define MATHA 0xfc55 #define MATHP 0xfc56 #define MATHN 0xfc57 #define MATHH 0xfc60 #define MATHG 0xfc61 #define MATHF 0xfc62 #define MATHE 0xfc63 #define MATHM 0xfc6c #define MATHL 0xfc6d #define MATHK 0xfc6e #define MATHJ 0xfc6f #define SPRCTL0 0xfc80 #define SPRCTL1 0xfc81 #define SPRCOLL 0xfc82 #define SPRINIT 0xfc83 #define SUZYHREV 0xfc88 #define SUZYSREV 0xfc89 #define SUZYBUSEN 0xfc90 #define SPRGO 0xfc91 #define SPRSYS 0xfc92 #define JOYSTICK 0xfcb0 #define SWITCHES 0xfcb1 #define RCART0 0xfcb2 #define RCART1 0xfcb3 #define LEDS 0xfcc0 #define PPORTSTAT 0xfcc2 #define PPORTDATA 0xfcc3 #define HOWIE 0xfcc4 #define TIM0BKUP 0xfd00 #define TIM0CTLA 0xfd01 #define TIM0CNT 0xfd02 #define TIM0CTLB 0xfd03 #define TIM1BKUP 0xfd04 #define TIM1CTLA 0xfd05 #define TIM1CNT 0xfd06 #define TIM1CTLB 0xfd07 #define TIM2BKUP 0xfd08 #define TIM2CTLA 0xfd09 #define TIM2CNT 0xfd0a #define TIM2CTLB 0xfd0b #define TIM3BKUP 0xfd0c #define TIM3CTLA 0xfd0d #define TIM3CNT 0xfd0e #define TIM3CTLB 0xfd0f #define TIM4BKUP 0xfd10 #define TIM4CTLA 0xfd11 #define TIM4CNT 0xfd12 #define TIM4CTLB 0xfd13 #define TIM5BKUP 0xfd14 #define TIM5CTLA 0xfd15 #define TIM5CNT 0xfd16 #define TIM5CTLB 0xfd17 #define TIM6BKUP 0xfd18 #define TIM6CTLA 0xfd19 #define TIM6CNT 0xfd1a #define TIM6CTLB 0xfd1b #define TIM7BKUP 0xfd1c #define TIM7CTLA 0xfd1d #define TIM7CNT 0xfd1e #define TIM7CTLB 0xfd1f #define AUD0VOL 0xfd20 #define AUD0SHFTFB 0xfd21 #define AUD0OUTVAL 0xfd22 #define AUD0L8SHFT 0xfd23 #define AUD0TBACK 0xfd24 #define AUD0CTL 0xfd25 #define AUD0COUNT 0xfd26 #define AUD0MISC 0xfd27 #define AUD1VOL 0xfd28 #define AUD1SHFTFB 0xfd29 #define AUD1OUTVAL 0xfd2a #define AUD1L8SHFT 0xfd2b #define AUD1TBACK 0xfd2c #define AUD1CTL 0xfd2d #define AUD1COUNT 0xfd2e #define AUD1MISC 0xfd2f #define AUD2VOL 0xfd30 #define AUD2SHFTFB 0xfd31 #define AUD2OUTVAL 0xfd32 #define AUD2L8SHFT 0xfd33 #define AUD2TBACK 0xfd34 #define AUD2CTL 0xfd35 #define AUD2COUNT 0xfd36 #define AUD2MISC 0xfd37 #define AUD3VOL 0xfd38 #define AUD3SHFTFB 0xfd39 #define AUD3OUTVAL 0xfd3a #define AUD3L8SHFT 0xfd3b #define AUD3TBACK 0xfd3c #define AUD3CTL 0xfd3d #define AUD3COUNT 0xfd3e #define AUD3MISC 0xfd3f #define ATTEN_A 0xFD40 // #define ATTEN_B 0xFD41 #define ATTEN_C 0xFD42 // Lynx2 Regs see macros/handy.equ #define ATTEN_D 0xFD43 #define MPAN 0xFD44 // #define MSTEREO 0xfd50 #define INTRST 0xfd80 #define INTSET 0xfd81 #define MAGRDY0 0xfd84 #define MAGRDY1 0xfd85 #define AUDIN 0xfd86 #define SYSCTL1 0xfd87 #define MIKEYHREV 0xfd88 #define MIKEYSREV 0xfd89 #define IODIR 0xfd8a #define IODAT 0xfd8b #define SERCTL 0xfd8c #define SERDAT 0xfd8d #define SDONEACK 0xfd90 #define CPUSLEEP 0xfd91 #define DISPCTL 0xfd92 #define PBKUP 0xfd93 #define DISPADR 0xfd94 #define DISPADRL 0xfd94 #define DISPADRH 0xfd95 #define Mtest0 0xfd9c #define Mtest1 0xfd9d #define Mtest2 0xfd9e #define GREEN0 0xfda0 #define GREEN1 0xfda1 #define GREEN2 0xfda2 #define GREEN3 0xfda3 #define GREEN4 0xfda4 #define GREEN5 0xfda5 #define GREEN6 0xfda6 #define GREEN7 0xfda7 #define GREEN8 0xfda8 #define GREEN9 0xfda9 #define GREENA 0xfdaa #define GREENB 0xfdab #define GREENC 0xfdac #define GREEND 0xfdad #define GREENE 0xfdae #define GREENF 0xfdaf #define BLUERED0 0xfdb0 #define BLUERED1 0xfdb1 #define BLUERED2 0xfdb2 #define BLUERED3 0xfdb3 #define BLUERED4 0xfdb4 #define BLUERED5 0xfdb5 #define BLUERED6 0xfdb6 #define BLUERED7 0xfdb7 #define BLUERED8 0xfdb8 #define BLUERED9 0xfdb9 #define BLUEREDA 0xfdba #define BLUEREDB 0xfdbb #define BLUEREDC 0xfdbc #define BLUEREDD 0xfdbd #define BLUEREDE 0xfdbe #define BLUEREDF 0xfdbf #define MMAPCTL 0xfff9 #define CPUNMI 0xfffa #define CPUNMIL 0xfffa #define CPUNMIH 0xfffb #define CPURESET 0xfffc #define CPURESETL 0xfffc #define CPURESETH 0xfffd #define CPUINT 0xfffe #define CPUINTL 0xfffe #define CPUINTH 0xffff
<filename>exoskeleton/src/main/java/com/wangxy/exoskeleton/api/BaiduTranslateUtil.java package com.wangxy.exoskeleton.api; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.wangxy.exoskeleton.api.translate.TransApi; public class BaiduTranslateUtil { // 在平台申请的APP_ID 详见 http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer private static final String APP_ID = "20200518000460986"; private static final String SECURITY_KEY = "<KEY>"; static TransApi api = new TransApi(APP_ID, SECURITY_KEY); public static void main(String[] args) { //TransApi api = new TransApi(APP_ID, SECURITY_KEY); String query = "高度600米"; System.out.println(api.getTransResult(query, "auto", "en")); } public static TransApi getApi() { return api; } public static void setApi(TransApi api) { BaiduTranslateUtil.api = api; } public static String translate4PrdUpt(String cnWord,String sourceLang,String targetLang) { String transResult = getApi().getTransResult(cnWord, sourceLang, targetLang); JSONObject transResultJson = JSONObject.parseObject(transResult); JSONArray resultArray = transResultJson.getJSONArray("trans_result"); String targetLangWord = resultArray.getJSONObject(0).getString("dst"); return targetLangWord; } }
<gh_stars>0 #include "extensions/common/tap/admin.h" #include "envoy/admin/v2alpha/tap.pb.h" #include "envoy/admin/v2alpha/tap.pb.validate.h" #include "common/buffer/buffer_impl.h" namespace Envoy { namespace Extensions { namespace Common { namespace Tap { // Singleton registration via macro defined in envoy/singleton/manager.h SINGLETON_MANAGER_REGISTRATION(tap_admin_handler); AdminHandlerSharedPtr AdminHandler::getSingleton(Server::Admin& admin, Singleton::Manager& singleton_manager, Event::Dispatcher& main_thread_dispatcher) { return singleton_manager.getTyped<AdminHandler>( SINGLETON_MANAGER_REGISTERED_NAME(tap_admin_handler), [&admin, &main_thread_dispatcher] { return std::make_shared<AdminHandler>(admin, main_thread_dispatcher); }); } AdminHandler::AdminHandler(Server::Admin& admin, Event::Dispatcher& main_thread_dispatcher) : admin_(admin), main_thread_dispatcher_(main_thread_dispatcher) { const bool rc = admin_.addHandler("/tap", "tap filter control", MAKE_ADMIN_HANDLER(handler), true, true); RELEASE_ASSERT(rc, "/tap admin endpoint is taken"); } AdminHandler::~AdminHandler() { const bool rc = admin_.removeHandler("/tap"); ASSERT(rc); } Http::Code AdminHandler::handler(absl::string_view, Http::HeaderMap&, Buffer::Instance& response, Server::AdminStream& admin_stream) { if (attached_request_.has_value()) { // TODO(mattlklein123): Consider supporting concurrent admin /tap streams. Right now we support // a single stream as a simplification. return badRequest(response, "An attached /tap admin stream already exists. Detach it."); } if (admin_stream.getRequestBody() == nullptr) { return badRequest(response, "/tap requires a JSON/YAML body"); } envoy::admin::v2alpha::TapRequest tap_request; try { MessageUtil::loadFromYamlAndValidate(admin_stream.getRequestBody()->toString(), tap_request); } catch (EnvoyException& e) { return badRequest(response, e.what()); } ENVOY_LOG(debug, "tap admin request for config_id={}", tap_request.config_id()); if (config_id_map_.count(tap_request.config_id()) == 0) { return badRequest( response, fmt::format("Unknown config id '{}'. No extension has registered with this id.", tap_request.config_id())); } for (auto config : config_id_map_[tap_request.config_id()]) { config->newTapConfig(std::move(*tap_request.mutable_tap_config()), this); } admin_stream.setEndStreamOnComplete(false); admin_stream.addOnDestroyCallback([this] { for (auto config : config_id_map_[attached_request_.value().config_id_]) { ENVOY_LOG(debug, "detach tap admin request for config_id={}", attached_request_.value().config_id_); config->clearTapConfig(); attached_request_ = absl::nullopt; } }); attached_request_.emplace(tap_request.config_id(), &admin_stream); return Http::Code::OK; } Http::Code AdminHandler::badRequest(Buffer::Instance& response, absl::string_view error) { ENVOY_LOG(debug, "handler bad request: {}", error); response.add(error); return Http::Code::BadRequest; } void AdminHandler::registerConfig(ExtensionConfig& config, const std::string& config_id) { ASSERT(!config_id.empty()); ASSERT(config_id_map_[config_id].count(&config) == 0); config_id_map_[config_id].insert(&config); } void AdminHandler::unregisterConfig(ExtensionConfig& config) { ASSERT(!config.adminId().empty()); std::string admin_id(config.adminId()); ASSERT(config_id_map_[admin_id].count(&config) == 1); config_id_map_[admin_id].erase(&config); if (config_id_map_[admin_id].empty()) { config_id_map_.erase(admin_id); } } void AdminHandler::submitBufferedTrace( std::shared_ptr<envoy::data::tap::v2alpha::BufferedTraceWrapper> trace) { ENVOY_LOG(debug, "admin submitting buffered trace to main thread"); main_thread_dispatcher_.post([this, trace]() { if (attached_request_.has_value()) { ENVOY_LOG(debug, "admin writing buffered trace to response"); Buffer::OwnedImpl json_trace{MessageUtil::getJsonStringFromMessage(*trace, true, true)}; attached_request_.value().admin_stream_->getDecoderFilterCallbacks().encodeData(json_trace, false); } }); } } // namespace Tap } // namespace Common } // namespace Extensions } // namespace Envoy
<reponame>beamka/Polyclinic package ua.clinic.services; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ua.clinic.jpa.Group; import ua.clinic.jpa.User; import ua.clinic.repository.UgroupRepository; import ua.clinic.repository.UserRepository; import ua.clinic.utils.EntityIdGenerator; import java.util.List; /** * Created by <NAME> on 08.03.2017. */ @Service public class UgroupService { private static final Logger logger = LoggerFactory.getLogger(UgroupService.class); @Autowired UserRepository userRepository; @Autowired UgroupRepository ugroupRepository; public Group newGroup(Group inData) { Long newId; do { newId = EntityIdGenerator.random(); } while (ugroupRepository.findOne(newId) != null); inData.setIdgroup(newId); Group outData = ugroupRepository.save(inData); logger.debug("##### New group's groupname: " + outData.getGroupname() + " ID: " + outData.getIdgroup()); return outData; } public void createDefoultGroups() { logger.debug(">>>>> createDefoultGroups >>>>>"); Group guest = new Group(Long.valueOf(1), "guest", "New registered user"); ugroupRepository.save(guest); Group patient = new Group(Long.valueOf(2), "patient", "patient"); ugroupRepository.save(patient); Group doctor = new Group(Long.valueOf(3), "doctor", "doctor"); ugroupRepository.save(doctor); Group admin = new Group(Long.valueOf(4), "admin", "admin"); ugroupRepository.save(admin); } public List<Group> getAllUgroup() { return ugroupRepository.findAll(); } public Group getGroupById(Long id) { Group group = ugroupRepository.findOne(id); return group; } public List<User> getUserByGroupname(String group_name) { Group group = ugroupRepository.findByGroupname(group_name); List<User> users = group.getUsers(); return users; } public void delUgroup(Long id) { logger.info("##### delUgroup ID = " + id); Group group = ugroupRepository.findOne(id); if (group != null) { logger.debug("Deleting users %s with id %s", group.getGroupname(), group.getIdgroup()); ugroupRepository.delete(id); } } }
<reponame>anotheria/moskito-control package org.moskito.control.plugins.monitoring.mail; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import net.anotheria.util.StringUtils; import org.apache.http.HttpStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sun.misc.BASE64Encoder; import javax.ws.rs.core.MediaType; /** * Trigger external api to send mail. * * @author ynikonchuk */ public class MonitoringSendMailTask { private static final Logger log = LoggerFactory.getLogger(MonitoringSendMailTask.class); private final MonitoringMailConfig config; private final Client client; public MonitoringSendMailTask(MonitoringMailConfig config) { this.config = config; this.client = Client.create(); this.client.setConnectTimeout(5000); this.client.setReadTimeout(10000); } /** * Executes task. */ public Result execute() { MonitoringMailSendEndpointConfig sendConfig = config.getSendMailConfig(); if (sendConfig == null) { log.debug("no sendEndpointConfig for: " + config.getName()); return new Result(false, config); } log.info("execute(). config: " + sendConfig.getApiEndpoint()); boolean success = executeSendMail(sendConfig); return new Result(success, config); } private boolean executeSendMail(MonitoringMailSendEndpointConfig config) { try { WebResource resource = client.resource(config.getApiEndpoint()); // set auth if needed setBasicAuthHeader(resource, config); setAuthHeader(resource, config); ClientResponse response = resource .type(MediaType.APPLICATION_JSON_TYPE) .post(ClientResponse.class, new SendMailRequest(config.getEmail())); if (log.isDebugEnabled()) { log.debug("status: " + response.getStatus()); } boolean successResponse = response.getStatus() == HttpStatus.SC_OK; if (!successResponse) { log.error("failed to send mail. response: {}", response.getEntity(String.class)); } return successResponse; } catch (Exception e) { log.error("executeSendMail(). endpoint: {}, failed: {}", config.getApiEndpoint(), e.getMessage(), e); return false; } } private static class SendMailRequest { private String email; public SendMailRequest() { } public SendMailRequest(String email) { this.email = email; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } public static class Result { private final boolean success; private final MonitoringMailConfig config; public Result(boolean success, MonitoringMailConfig config) { this.success = success; this.config = config; } public boolean isSuccess() { return success; } public MonitoringMailConfig getConfig() { return config; } @Override public String toString() { return "Result{" + "success=" + success + ", config=" + config + '}'; } } private void setBasicAuthHeader(WebResource resource, MonitoringMailSendEndpointConfig config) { if (StringUtils.isEmpty(config.getBasicAuthName())) { return; } String basicAuthVal = getBasicAuthVal(config); resource.header("Authorization", "Basic " + basicAuthVal); } private void setAuthHeader(WebResource resource, MonitoringMailSendEndpointConfig config) { if (StringUtils.isEmpty(config.getAuthHeaderName())) { return; } resource.header(config.getAuthHeaderName(), config.getAuthHeaderValue()); } private String getBasicAuthVal(MonitoringMailSendEndpointConfig config) { String authString = config.getBasicAuthName() + ":" + config.getBasicAuthPass(); return new BASE64Encoder().encode(authString.getBytes()); } }
#!/bin/bash # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. JAVA_VERSION="1.7" RED="\033[0;31m" GREEN="\033[0;32m" BLUE="\033[0;35m" ENDCOLOR="\033[0m" error() { echo -e "$RED""$*""$ENDCOLOR" exit 1 } success() { echo -e "$GREEN""$*""$ENDCOLOR" } info() { echo -e "$BLUE""$*""$ENDCOLOR" } PACKAGE_VERSION=$(cat package.json \ | grep version \ | head -1 \ | awk -F: '{ print $2 }' \ | sed 's/[",]//g' \ | tr -d '[[:space:]]') success "Preparing version $PACKAGE_VERSION" repo_root=$(pwd) rm -rf android ./gradlew :ReactAndroid:installArchives || error "Couldn't generate artifacts" success "Generated artifacts for Maven" npm install success "Killing any running packagers" lsof -i :8081 | grep LISTEN lsof -i :8081 | grep LISTEN | /usr/bin/awk '{print $2}' | xargs kill info "Start the packager in another terminal by running 'npm start' from the root" info "and then press any key." info "" read -n 1 ./gradlew :RNTester:android:app:installJscDebug || error "Couldn't build RNTester Android" info "Press any key to run RNTester in an already running Android emulator/device" info "" read -n 1 adb shell am start -n com.facebook.react.uiapp/.RNTesterActivity success "Installing CocoaPods dependencies" rm -rf RNTester/Pods (cd RNTester && pod install) info "Press any key to open the workspace in Xcode, then build and test manually." info "" read -n 1 open "RNTester/RNTesterPods.xcworkspace" info "When done testing RNTester app on iOS and Android press any key to continue." info "" read -n 1 success "Killing packager" lsof -i :8081 | grep LISTEN lsof -i :8081 | grep LISTEN | /usr/bin/awk '{print $2}' | xargs kill npm pack PACKAGE=$(pwd)/react-native-$PACKAGE_VERSION.tgz success "Package bundled ($PACKAGE)" node scripts/set-rn-template-version.js "file:$PACKAGE" success "React Native version changed in the template" project_name="RNTestProject" cd /tmp/ rm -rf "$project_name" node "$repo_root/cli.js" init "$project_name" --template "$repo_root" info "Double checking the versions in package.json are correct:" grep "\"react-native\": \".*react-native-$PACKAGE_VERSION.tgz\"" "/tmp/${project_name}/package.json" || error "Incorrect version number in /tmp/${project_name}/package.json" grep -E "com.facebook.react:react-native:\\+" "${project_name}/android/app/build.gradle" || error "Dependency in /tmp/${project_name}/android/app/build.gradle must be com.facebook.react:react-native:+" success "New sample project generated at /tmp/${project_name}" info "Test the following on Android:" info " - Disable Fast Refresh. It might be enabled from last time (the setting is stored on the device)" info " - Verify 'Reload JS' works" info "" info "Press any key to run the sample in Android emulator/device" info "" read -n 1 cd "/tmp/${project_name}" && npx react-native run-android info "Test the following on iOS:" info " - Disable Fast Refresh. It might be enabled from last time (the setting is stored on the device)" info " - Verify 'Reload JS' works" info " - Test Chrome debugger by adding breakpoints and reloading JS. We don't have tests for Chrome debugging." info " - Disable Chrome debugging." info " - Enable Fast Refresh, change a file (index.js) and save. The UI should refresh." info " - Disable Fast Refresh." info "" info "Press any key to open the project in Xcode" info "" read -n 1 open "/tmp/${project_name}/ios/${project_name}.xcworkspace" cd "$repo_root" info "Next steps:" info " - https://github.com/facebook/react-native/blob/master/Releases.md"
#include <TF1.h> #include <triumf/bnmr/nuclei.hpp> #include <triumf/bnmr/slr/bi_exp.hpp> #include <triumf/bnmr/slr/cbrt_exp.hpp> #include <triumf/bnmr/slr/exp.hpp> #include <triumf/bnmr/slr/gauss_dist_exp.hpp> #include <triumf/bnmr/slr/magnesium_31/exp.hpp> #include <triumf/bnmr/slr/sq_exp.hpp> #include <triumf/bnmr/slr/sqrt_exp.hpp> #include <triumf/bnmr/slr/str_exp.hpp> // for lithium-8 constexpr double t_min = 0.0; constexpr double t_max = 16.0; constexpr double t_pulse = 4.0; // for magnesium-31 constexpr double t_min_31mg = 0.0; constexpr double t_max_31mg = 4.0; constexpr double t_pulse_31mg = 1.0; // TF1 f_pulsed_exp("f_pulsed_exp", triumf::bnmr::slr::pulsed_exp<double>, t_min, t_max, 4); TF1 f_pulsed_bi_exp("f_pulsed_bi_exp", triumf::bnmr::slr::pulsed_bi_exp<double>, t_min, t_max, 6); TF1 f_pulsed_str_exp("f_pulsed_str_exp", triumf::bnmr::slr::pulsed_str_exp<double>, t_min, t_max, 5); TF1 f_pulsed_sqrt_exp("f_pulsed_sqrt_exp", triumf::bnmr::slr::pulsed_sqrt_exp<double>, t_min, t_max, 4); TF1 f_pulsed_cbrt_exp("f_pulsed_cbrt_exp", triumf::bnmr::slr::pulsed_cbrt_exp<double>, t_min, t_max, 4); TF1 f_pulsed_sq_exp("f_pulsed_sq_exp", triumf::bnmr::slr::pulsed_sq_exp<double>, t_min, t_max, 4); TF1 f_pulsed_gauss_dist_exp("f_pulsed_gauss_dist_exp", triumf::bnmr::slr::pulsed_gauss_dist_exp<double>, t_min, t_max, 5); TF1 f_pulsed_exp_31mg("f_pulsed_exp_31mg", triumf::bnmr::slr::magnesium_31::pulsed_exp<double>, t_min_31mg, t_max_31mg, 4); void bnmr_slr() { // f_pulsed_exp.SetNpx(1000); f_pulsed_exp.SetParName(0, "Nuclear lifetime (s)"); f_pulsed_exp.SetParName(1, "Pulse length (s)"); f_pulsed_exp.SetParName(2, "Initial asymmetry"); f_pulsed_exp.SetParName(3, "SLR rate (1/s)"); f_pulsed_exp.FixParameter( 0, triumf::bnmr::nuclei::lithium_8<double>::lifetime()); f_pulsed_exp.FixParameter(1, t_pulse); f_pulsed_exp.SetParameter(2, 0.15); f_pulsed_exp.SetParameter(3, 1.0); f_pulsed_exp.SetParLimits(2, 0.00, 0.30); f_pulsed_exp.SetParLimits( 3, 0.0, 100.0 / triumf::bnmr::nuclei::lithium_8<double>::lifetime()); // f_pulsed_bi_exp.SetNpx(1000); f_pulsed_bi_exp.SetParName(0, "Nuclear lifetime (s)"); f_pulsed_bi_exp.SetParName(1, "Pulse length (s)"); f_pulsed_bi_exp.SetParName(2, "Initial asymmetry"); f_pulsed_bi_exp.SetParName(3, "Fraction (slow)"); f_pulsed_bi_exp.SetParName(4, "SLR rate (slow) (1/s)"); f_pulsed_bi_exp.SetParName(5, "SLR rate (fast) (1/s)"); f_pulsed_bi_exp.FixParameter( 0, triumf::bnmr::nuclei::lithium_8<double>::lifetime()); f_pulsed_bi_exp.FixParameter(1, t_pulse); f_pulsed_bi_exp.SetParameter(2, 0.15); f_pulsed_bi_exp.SetParameter(3, 0.75); f_pulsed_bi_exp.SetParameter(4, 0.10); f_pulsed_bi_exp.SetParameter(5, 0.10); f_pulsed_bi_exp.SetParLimits(2, 0.00, 0.30); f_pulsed_bi_exp.SetParLimits(3, 0.0, 1.0); f_pulsed_bi_exp.SetParLimits( 4, 0.0, 100.0 / triumf::bnmr::nuclei::lithium_8<double>::lifetime()); f_pulsed_bi_exp.SetParLimits( 5, 0.0, 100.0 / triumf::bnmr::nuclei::lithium_8<double>::lifetime()); // f_pulsed_str_exp.SetNpx(1000); f_pulsed_str_exp.SetParName(0, "Nuclear lifetime (s)"); f_pulsed_str_exp.SetParName(1, "Pulse length (s)"); f_pulsed_str_exp.SetParName(2, "Initial asymmetry"); f_pulsed_str_exp.SetParName(3, "SLR rate (1/s)"); f_pulsed_str_exp.SetParName(4, "Beta"); f_pulsed_str_exp.FixParameter( 0, triumf::bnmr::nuclei::lithium_8<double>::lifetime()); f_pulsed_str_exp.FixParameter(1, t_pulse); f_pulsed_str_exp.SetParameter(2, 0.15); f_pulsed_str_exp.SetParameter(3, 1.0); f_pulsed_str_exp.SetParameter(4, 0.75); f_pulsed_str_exp.SetParLimits(2, 0.00, 0.30); f_pulsed_str_exp.SetParLimits( 3, 0.0, 100.0 / triumf::bnmr::nuclei::lithium_8<double>::lifetime()); f_pulsed_str_exp.SetParLimits(4, 0.0, 1.0); // f_pulsed_sqrt_exp.SetNpx(1000); f_pulsed_sqrt_exp.SetParName(0, "Nuclear lifetime (s)"); f_pulsed_sqrt_exp.SetParName(1, "Pulse length (s)"); f_pulsed_sqrt_exp.SetParName(2, "Initial asymmetry"); f_pulsed_sqrt_exp.SetParName(3, "SLR rate (1/s)"); f_pulsed_sqrt_exp.FixParameter( 0, triumf::bnmr::nuclei::lithium_8<double>::lifetime()); f_pulsed_sqrt_exp.FixParameter(1, t_pulse); f_pulsed_sqrt_exp.SetParameter(2, 0.15); f_pulsed_sqrt_exp.SetParameter(3, 1.0); f_pulsed_sqrt_exp.SetParLimits(2, 0.00, 0.30); f_pulsed_sqrt_exp.SetParLimits( 3, 0.0, 100.0 / triumf::bnmr::nuclei::lithium_8<double>::lifetime()); // f_pulsed_cbrt_exp.SetNpx(1000); f_pulsed_cbrt_exp.SetParName(0, "Nuclear lifetime (s)"); f_pulsed_cbrt_exp.SetParName(1, "Pulse length (s)"); f_pulsed_cbrt_exp.SetParName(2, "Initial asymmetry"); f_pulsed_cbrt_exp.SetParName(3, "SLR rate (1/s)"); f_pulsed_cbrt_exp.FixParameter( 0, triumf::bnmr::nuclei::lithium_8<double>::lifetime()); f_pulsed_cbrt_exp.FixParameter(1, t_pulse); f_pulsed_cbrt_exp.SetParameter(2, 0.15); f_pulsed_cbrt_exp.SetParameter(3, 1.0); f_pulsed_cbrt_exp.SetParLimits(2, 0.00, 0.30); f_pulsed_cbrt_exp.SetParLimits( 3, 0.0, 100.0 / triumf::bnmr::nuclei::lithium_8<double>::lifetime()); // f_pulsed_sq_exp.SetNpx(1000); f_pulsed_sq_exp.SetParName(0, "Nuclear lifetime (s)"); f_pulsed_sq_exp.SetParName(1, "Pulse length (s)"); f_pulsed_sq_exp.SetParName(2, "Initial asymmetry"); f_pulsed_sq_exp.SetParName(3, "SLR rate (1/s)"); f_pulsed_sq_exp.FixParameter( 0, triumf::bnmr::nuclei::lithium_8<double>::lifetime()); f_pulsed_sq_exp.FixParameter(1, t_pulse); f_pulsed_sq_exp.SetParameter(2, 0.15); f_pulsed_sq_exp.SetParameter(3, 1.0); f_pulsed_sq_exp.SetParLimits(2, 0.00, 0.30); f_pulsed_sq_exp.SetParLimits( 3, 0.0, 100.0 / triumf::bnmr::nuclei::lithium_8<double>::lifetime()); // f_pulsed_gauss_dist_exp.SetNpx(1000); f_pulsed_gauss_dist_exp.SetParName(0, "Nuclear lifetime (s)"); f_pulsed_gauss_dist_exp.SetParName(1, "Pulse length (s)"); f_pulsed_gauss_dist_exp.SetParName(2, "Initial asymmetry"); f_pulsed_gauss_dist_exp.SetParName(3, "SLR rate (1/s)"); f_pulsed_gauss_dist_exp.SetParName(4, "SLR sigma (1/s)"); f_pulsed_gauss_dist_exp.FixParameter( 0, triumf::bnmr::nuclei::lithium_8<double>::lifetime()); f_pulsed_gauss_dist_exp.FixParameter(1, t_pulse); f_pulsed_gauss_dist_exp.SetParameter(2, 0.15); f_pulsed_gauss_dist_exp.SetParameter(3, 1.0); f_pulsed_gauss_dist_exp.SetParameter(4, 0.01); f_pulsed_gauss_dist_exp.SetParLimits(2, 0.00, 0.30); f_pulsed_gauss_dist_exp.SetParLimits( 3, 0.0, 100.0 / triumf::bnmr::nuclei::lithium_8<double>::lifetime()); f_pulsed_gauss_dist_exp.SetParLimits( 4, 0.00, 10.0 / triumf::bnmr::nuclei::lithium_8<double>::lifetime()); // f_pulsed_exp_31mg.SetNpx(1000); f_pulsed_exp_31mg.SetParName(0, "Nuclear lifetime (s)"); f_pulsed_exp_31mg.SetParName(1, "Pulse length (s)"); f_pulsed_exp_31mg.SetParName(2, "Initial asymmetry"); f_pulsed_exp_31mg.SetParName(3, "SLR rate (1/s)"); f_pulsed_exp_31mg.FixParameter( 0, triumf::bnmr::nuclei::magnesium_31<double>::lifetime()); f_pulsed_exp_31mg.FixParameter(1, t_pulse_31mg); f_pulsed_exp_31mg.SetParameter(2, 0.15); f_pulsed_exp_31mg.SetParameter(3, 1.0); f_pulsed_exp_31mg.SetParLimits(2, 0.00, 0.30); f_pulsed_exp_31mg.SetParLimits( 3, 0.0, 100.0 / triumf::bnmr::nuclei::magnesium_31<double>::lifetime()); }
<gh_stars>0 import React, { PureComponent, ReactNode } from "react"; import CalendarContainer from "./CalendarView/CalendarContainer"; import SearchContainer from "./SearchView/SearchContainer"; import ToolbarContainer from "./ToolbarContainer"; export interface StateProps { searchKey: string; } type Props = StateProps; export default class Sidebar extends PureComponent<Props, {}> { render(): ReactNode { const { searchKey } = this.props; return ( <div className="sidebar"> <ToolbarContainer /> {searchKey === "" ? <CalendarContainer /> : <SearchContainer />} </div> ); } }
<gh_stars>0 import * as mc from "mailchimp-api"; const client = new mc.Mailchimp("apikey", true); client.campaigns.list( { limit: 50 }, result => { result.data.forEach(campaign => { if (campaign.emails_sent) { console.log(campaign); } }); }, onError); client.lists.list( { limit: 50 }, result => { result.data.forEach(list => { client.lists.members( { id: list.id }, members => { console.log(list, members.data); }, onError); }); }, onError); function onError(err: mc.Mailchimp.RequestError) { console.error(`An error with code ${err.code} and status ${err.status} occured`, err); }
function foo(x,y,z) { let a = x + y + z; let b = a * x * y * z; return Math.sqrt(b); }
#!/bin/bash echo "Installing Pycharm community..." sudo snap install pycharm-community --classic echo "Pycharm installation complete!."
package wildfarm.animals.abstractbases; import wildfarm.animals.AnimalType; import wildfarm.animals.interfaces.Animal; import wildfarm.foods.Food; public abstract class AnimalImpl implements Animal { private String animalName; private String animalType; private Double animalWeight; private Integer foodEaten; public AnimalImpl(String name, String type, Double weight) { setAnimalName(name); setAnimalType(type); setAnimalWeight(weight); this.foodEaten = 0; } protected String getAnimalName() { return animalName; } protected String getAnimalType() { return animalType; } protected Double getAnimalWeight() { return animalWeight; } protected Integer getFoodEaten() { return foodEaten; } private void setAnimalName(String name) { if(name == null || name.trim().isEmpty()) { throw new IllegalArgumentException("Name cannot be empty or null!"); } this.animalName = name; } private void setAnimalType(String type) { if(type == null) { throw new IllegalArgumentException("Animal type cannot be Null!"); } if(!AnimalType.valueOf(type.toUpperCase()).getTypeName().equals(type)) { throw new IllegalArgumentException("Wrong Animal Type!"); } this.animalType = type; } private void setAnimalWeight(Double weight) { if(weight == null || weight <= 0) { throw new IllegalArgumentException("Weight cannot be null, 0 or negative number!"); } this.animalWeight = weight; } protected void increaseFoodEaten(Food foodEaten) { if(foodEaten == null) { throw new IllegalArgumentException("Food eaten cannot be null!"); } if(foodEaten.getQuantity() == null) { throw new IllegalArgumentException("Food eaten cannot be null!"); } if(0 > foodEaten.getQuantity()) { throw new IllegalArgumentException("Food eaten must be a positive Number!"); } this.foodEaten += foodEaten.getQuantity(); } }
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by <NAME>, <EMAIL>, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * import os.path from shutil import copyfile class Qorts(RPackage): """The QoRTs software package is a fast, efficient, and portable multifunction toolkit designed to assist in the analysis, quality control, and data management of RNA-Seq and DNA-Seq datasets. Its primary function is to aid in the detection and identification of errors, biases, and artifacts produced by high-throughput sequencing technology.""" homepage = "https://github.com/hartleys/QoRTs" url = "https://github.com/hartleys/QoRTs/releases/download/v1.2.42/QoRTs_1.2.42.tar.gz" version('1.2.42', '7d46162327b0da70bfe483fe2f2b7829') depends_on('java', type='run') resource( name='QoRTs.jar', url='https://github.com/hartleys/QoRTs/releases/download/v1.2.42/QoRTs.jar', md5='918df4291538218c12caa3ab98c535e9', placement='jarfile', expand=False ) @run_after('install') def install_jar(self): install_tree(join_path(self.stage.source_path, 'jarfile'), self.prefix.bin) # Set up a helper script to call java on the jar file, # explicitly codes the path for java and the jar file. script_sh = join_path(os.path.dirname(__file__), "QoRTs.sh") script = self.prefix.bin.QoRTs copyfile(script_sh, script) set_executable(script) # Munge the helper script to explicitly point to java and the # jar file. java = self.spec['java'].prefix.bin.java kwargs = {'backup': False} filter_file('^java', java, script, **kwargs) filter_file('QoRTs.jar', join_path(self.prefix.bin, 'QoRTs.jar'), script, **kwargs)
<reponame>PiterM/mama-gatsby import React from 'react'; import IndexPage from '../components/IndexPage/IndexPage'; import Helmet from 'react-helmet'; const App: React.FC = ({ pageContext: { data } }: any) => { const faviconUrl = require(__dirname + '/../images/favicon.ico').default; const thumbnailImageUrl = require('/src/images/thumbnail/joannamarkiewicz.pl.jpg').default; return ( <> <Helmet title="<NAME> - choreograf i instruktor tańca" meta={[ { name: 'description', content: 'Instruktor baletu w Olsztynie' }, { name: 'keywords', content: '<NAME>, choreograf, instruktor tańca, balet, instruktor baletu, taniec, ognisko baletowe, olsztyn, baletnice, dziewczynki', }, { property: 'og:title', content: '<NAME> - choreograf i instruktor tańca', }, { property: 'og:description', content: 'Choreograf i instruktor tańca z Olsztyna', }, { property: 'og:image', content: thumbnailImageUrl, }, { property: 'og:url', content: 'https://joannamarkiewicz.pl' }, { property: 'og:site_name', content: 'Choreograf i instruktor tańca z Olsztyna', }, { property: 'og:type', content: 'website' }, ]} link={[ { rel: 'icon', type: 'image/x-icon', href: faviconUrl, }, ]} /> <IndexPage data={data} />; </> ); }; export default App;
#!/bin/sh vpn="$(nmcli -t -f name,type connection show --order name --active 2>/dev/null | grep vpn | head -1 | cut -d ':' -f 1)" if [ -n "$vpn" ]; then echo "$vpn" else echo " --- " fi
package io.dronefleet.mavlink.uavionix; import io.dronefleet.mavlink.annotations.MavlinkEntryInfo; import io.dronefleet.mavlink.annotations.MavlinkEnum; /** * Transceiver RF control flags for ADS-B transponder dynamic reports */ @MavlinkEnum public enum UavionixAdsbOutRfSelect { /** * */ @MavlinkEntryInfo(0) UAVIONIX_ADSB_OUT_RF_SELECT_STANDBY, /** * */ @MavlinkEntryInfo(1) UAVIONIX_ADSB_OUT_RF_SELECT_RX_ENABLED, /** * */ @MavlinkEntryInfo(2) UAVIONIX_ADSB_OUT_RF_SELECT_TX_ENABLED }
// CSS content processing function function processCssContent(cssContent) { // Invoke processors based on content type const absoluteUrlProcessorSpy = jest.fn(); const relativeUrlProcessorSpy = jest.fn(); const integrityProcessorSpy = jest.fn(); const styleUrlProcessorSpy = jest.fn(); // Simulate the invocation of processors based on content type absoluteUrlProcessorSpy(cssContent); integrityProcessorSpy(cssContent); // Assert the expected processor invocations expect(absoluteUrlProcessorSpy).toHaveBeenCalled(); expect(relativeUrlProcessorSpy).not.toHaveBeenCalled(); expect(integrityProcessorSpy).toHaveBeenCalled(); expect(styleUrlProcessorSpy).not.toHaveBeenCalled(); } // Example usage const testCssContent = 'test buffer'; processCssContent(testCssContent);
import React from 'react'; import ReactDOM from 'react-dom'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import App from './App'; import rootReducer from './reducers'; const store = createStore(rootReducer); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
require "mobility/arel" require_relative "./active_record/backend" require_relative "./active_record/dirty" require_relative "./active_record/cache" require_relative "./active_record/query" require_relative "./active_record/uniqueness_validation" module Mobility =begin Plugin for ActiveRecord models. =end module Plugins module ActiveRecord extend Plugin requires :active_record_backend, include: :after requires :active_record_dirty requires :active_record_cache requires :active_record_query requires :active_record_uniqueness_validation included_hook do |klass| unless active_record_class?(klass) name = klass.name || klass.to_s raise TypeError, "#{name} should be a subclass of ActiveRecord::Base to use the active_record plugin" end end private def active_record_class?(klass) klass < ::ActiveRecord::Base end end register_plugin(:active_record, ActiveRecord) end end
/* * Copyright 2013 The Polymer Authors. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ (function(scope) { // copy own properties from 'api' to 'prototype, with name hinting for 'super' function extend(prototype, api) { if (prototype && api) { // use only own properties of 'api' Object.getOwnPropertyNames(api).forEach(function(n) { // acquire property descriptor var pd = Object.getOwnPropertyDescriptor(api, n); if (pd) { // clone property via descriptor Object.defineProperty(prototype, n, pd); // cache name-of-method for 'super' engine if (typeof pd.value == 'function') { // hint the 'super' engine prototype[n].nom = n; } // TODO(sjmiles): sharing a function only works if the function // only ever has one name } }); } return prototype; } // exports scope.extend = extend; })(Polymer);
if (( $+commands[kubectl] )); then __KUBECTL_COMPLETION_FILE="${ZSH_CACHE_DIR}/kubectl_completion" if [[ ! -f $__KUBECTL_COMPLETION_FILE || ! -s $__KUBECTL_COMPLETION_FILE ]]; then kubectl completion zsh >! $__KUBECTL_COMPLETION_FILE fi [[ -f $__KUBECTL_COMPLETION_FILE ]] && source $__KUBECTL_COMPLETION_FILE unset __KUBECTL_COMPLETION_FILE fi function get_k8s_secret() { secret=$1 namespace=$2 if [ -z "$namespace" ] then kubectl get secret $secret -o json | jq .data | jq -r 'to_entries[] | "\(.key): \(.value | @base64d)\n"' else kubectl get secret $secret -n $namespace -o json | jq .data | jq -r 'to_entries[] | "\(.key): \(.value | @base64d)\n"' fi } function k8s_yaml_to_json() { kubectl create --dry-run=client -o json -f $1 | \ jq -s '{kind: "List", apiVersion: "v1", metadata: {}, items: .}' | \ jq "del( .items[].status, .items[].metadata.annotations.\"deployment.kubernetes.io/revision\", .items[].metadata.annotations.\"kubectl.kubernetes.io/last-applied-configuration\", .items[].metadata.annotations.\"field.cattle.io/publicEndpoints\", .items[].metadata.creationTimestamp, .items[].metadata.resourceVersion, .items[].metadata.selfLink, .items[].metadata.uid, .items[].metadata.generation, .items[].spec.template.metadata.creationTimestamp)" } # This command is used a LOT both below and in daily life alias k=kubectl # Kubectx alias ktx=kubectx alias kns=kubens # Execute a kubectl command against all namespaces alias kca='_kca(){ k "$@" --all-namespaces; unset -f _kca; }; _kca' # Apply a YML file alias kaf='k apply -f' # Drop into an interactive terminal on a container alias keti='k exec -ti' # Manage configuration quickly to switch contexts between local, dev ad staging. alias kcuc='k config use-context' alias kcsc='k config set-context' alias kcdc='k config delete-context' alias kccc='k config current-context' # List all contexts alias kcgc='k config get-contexts' # General aliases alias kdel='k delete' alias kdelf='kdel -f' alias kg='k get' alias kd='k describe' alias ke='k edit' alias kp='k patch' alias ks='k scale' alias kr='k replace' alias kro='k rollout' # Pod management. alias kgp='k get pods' alias kgpa='kgp --all-namespaces' alias kgpw='kgp --watch' alias kgpaw='kgpa --watch' alias kgpwide='kgp -o wide' alias kgpawide='kgpa -o wide' alias kep='ke pods' alias kdp='kd pods' alias kdelp='kdel pods' alias kgpi='kgp --output=custom-columns="NAME:.metadata.name,STATUS:.status.phase,AGE:.status.startTime,IMAGE:.spec.containers[*].image"' # get pod by label: kgpl "app=myapp" -n myns alias kgpl='kgp -l' alias kgpal='kgpa -l' # get pod by namespace: kgpn kube-system" alias kgpn='kgp -n' # Service management. alias kgs='k get svc' alias kgsa='kgs --all-namespaces' alias kgsw='kgs --watch' alias kgsaw='kgsa --watch' alias kgswide='kgs -o wide' alias kgsawide='kgsa -o wide' alias kes='ke svc' alias kds='kd svc' alias kdels='kdel svc' # Ingress management alias kgi='k get ingress' alias kgia='kgi --all-namespaces' alias kei='ke ingress' alias kdi='kd ingress' alias kdeli='kdel ingress' # Namespace management alias kgns='k get namespaces' alias kens='ke namespace' alias kdns='kd namespace' alias kdelns='kdel namespace' alias kcn='kcsc --current --namespace' # ConfigMap management alias kgcm='k get configmaps' alias kgcma='kgcm --all-namespaces' alias kecm='ke configmap' alias kdcm='kd configmap' alias kdelcm='kdel configmap' # Secret management alias kgsec='k get secret' alias kgsecd='get_k8s_secret' alias kgseca='kgsec --all-namespaces' alias kdsec='kd secret' alias kdelsec='kdel secret' # Deployment management. alias kgd='k get deployment' alias kgda='kgd --all-namespaces' alias kgdw='kgd --watch' alias kgdaw='kgda --watch' alias kgdwide='kgd -o wide' alias kgdawide='kgda -o wide' alias ked='ke deployment' alias kdd='kd deployment' alias kdeld='kdel deployment' alias ksd='ks deployment' alias krsd='kro status deployment' alias kgdi='k get deploy --output=custom-columns="NAME:.metadata.name,IMAGE:.spec.template.spec.containers[*].image"' kres(){ kubectl set env $@ REFRESHED_AT=$(date +%Y%m%d%H%M%S) } # Rollout management. alias kgrs='k get rs' alias kgrsa='kgrs --all-namespaces' alias krh='kro history' alias kru='kro undo' alias krrd='kro restart deployment' alias krrss='kro restart statefulset' # Statefulset management. alias kgss='k get statefulset' alias kgssa='kgss --all-namespaces' alias kgssw='kgss --watch' alias kgssaw='kgssa --watch' alias kgsswide='kgss -o wide' alias kgssawide='kgssa -o wide' alias kess='ke statefulset' alias kdss='kd statefulset' alias kdelss='kdel statefulset' alias ksss='k scale statefulset' alias krsss='kro status statefulset' alias kgssi='kgss --output=custom-columns="NAME:.metadata.name,IMAGE:.spec.template.spec.containers[*].image"' # Port forwarding alias kpf="kubectl port-forward" # Tools for accessing all information alias kga='k get all' alias kgaa='kga --all-namespaces' # Logs alias kl='k logs' alias kl1h='kl --since 1h' alias kl1m='kl --since 1m' alias kl1s='kl --since 1s' alias klf='kl -f' alias klfa='klf --all-containers' alias klf1h='klf --since 1h' alias klf1m='klf --since 1m' alias klf1s='klf --since 1s' # File copy alias kcp='k cp' # Node Management alias kgno='k get nodes' alias kgnowide='kgno -o wide' alias kgnow='kgno --watch' alias keno='ke node' alias kdno='kd node' alias kdelno='kdel node' # PV management. alias kgpv='k get pv' alias kgpva='kgpv --all-namespaces' alias kgpvw='kgpv --watch' alias kgpvaw='kgpva --watch' alias kepv='ke pv' alias kdpv='kd pv' alias kdelpv='kdel pv' # PVC management. alias kgpvc='k get pvc' alias kgpvca='kgpvc --all-namespaces' alias kgpvcw='kgpvc --watch' alias kgpvcaw='kgpvca --watch' alias kepvc='ke pvc' alias kdpvc='kd pvc' alias kdelpvc='kdel pvc' # PV management. alias kgpv='k get pv' alias kgpva='kgpv -A' # Service account management. alias kdsa="kd sa" alias kdelsa="kdel sa" # DaemonSet management. alias kgds='k get daemonset' alias kgdsw='kgds --watch' alias keds='ke daemonset' alias kdds='kd daemonset' alias kdelds='kdel daemonset' # CronJob management. alias kgcj='k get cronjob' alias kecj='ke cronjob' alias kdcj='kd cronjob' alias kdelcj='kdel cronjob' # Delete all resources (run as "kdela --context <CONTEXT> -n <NAMESPACE> -l <KEY=VALUE>") alias kdela='kdel configmap,secret,deployment,statefulset,daemonset,service,ingress,job,cronjob,pod,replicaset' alias kdelapurge='kdel configmap,secret,deployment,statefulset,daemonset,service,ingress,job,cronjob,pod,replicaset,persistentvolumeclaim' ############################################### # KJ, KJX and KY syntax colors ############################################### # Get the plugin dir plugin_dir=$(dirname $0) # Only run if the user actually has kubectl installed if (( ${+_comps[kubectl]} )); then kj() { kubectl "$@" -o json | jq; } kjx() { kubectl "$@" -o json | fx; } ky() { kubectl "$@" -o yaml | yh; } compdef kj=kubectl compdef kjx=kubectl compdef ky=kubectl fi # Load the syntax aliases if (( $+commands[jq] )); then source "${plugin_dir}/kj_aliases.zsh" fi if (( $+commands[fx] )); then source "${plugin_dir}/kjx_aliases.zsh" fi if (( $+commands[yh] )); then source "${plugin_dir}/ky_aliases.zsh" fi # The syntax aliases files were created with: # cat ~/.oh-my-zsh/plugins/kubectl/kubectl.plugin.zsh | grep -E "^alias kg" | grep -E -v 'output|wide|watch|get_k8s_secret' | sed -e 's/alias kg/alias kjg/g' -e "s/='k/='kj/g" > ~/.oh-my-zsh/plugins/kubectl/kj_aliases.zsh # cat ~/.oh-my-zsh/plugins/kubectl/kubectl.plugin.zsh | grep -E "^alias kg" | grep -E -v 'output|wide|watch|get_k8s_secret' | sed -e 's/alias kg/alias kjxg/g' -e "s/='k/='kjx/g" > ~/.oh-my-zsh/plugins/kubectl/kjx_aliases.zsh # cat ~/.oh-my-zsh/plugins/kubectl/kubectl.plugin.zsh | grep -E "^alias kg" | grep -E -v 'output|wide|watch|get_k8s_secret' | sed -e 's/alias kg/alias kyg/g' -e "s/='k/='ky/g" > ~/.oh-my-zsh/plugins/kubectl/ky_aliases.zsh
package amora.converter import scala.collection.mutable.ListBuffer import scala.util.Failure import scala.util.Success import scala.util.Try import org.objectweb.asm.ClassReader import org.objectweb.asm.ClassVisitor import org.objectweb.asm.FieldVisitor import org.objectweb.asm.MethodVisitor import org.objectweb.asm.Opcodes import amora.converter.{ protocol ⇒ h } import amora.converter.protocol.{ Attachment ⇒ a } final class ClassfileConverter(addAttachment: h.Hierarchy ⇒ Unit) { private val found = ListBuffer[h.Hierarchy]() def convert(bytecode: Array[Byte]): Try[Seq[h.Hierarchy]] = { this.found.clear() val found = Try { val r = new ClassReader(bytecode) val v = new CVisitor r.accept(v, 0) this.found } found match { case Success(found) ⇒ Success(found.toList) case Failure(f) ⇒ Failure(new RuntimeException(s"Conversion of bytecode failed. See underlying issue for more information.", f)) } } private class CVisitor extends ClassVisitor(Opcodes.ASM5) { var owner: h.Decl = h.Root override def visit(version: Int, access: Int, name: String, signature: String, superName: String, interfaces: Array[String]): Unit = { val d = mkDecl(name) d.addAttachments(a.Class) owner = d found += d } override def visitField(access: Int, name: String, desc: String, signature: String, value: AnyRef): FieldVisitor = { val d = h.Decl(name, owner) d.addAttachments(a.Var) addAttachment(d) found += d super.visitField(access, name, desc, signature, value) } override def visitMethod(access: Int, name: String, desc: String, signature: String, exceptions: Array[String]): MethodVisitor = { if (name == "<init>") null else { val d = h.Decl(name, owner) d.addAttachments(a.Def, a.JvmSignature(desc)) addAttachment(d) found += d new MVisitor(d) } } } private class MVisitor(owner: h.Decl) extends MethodVisitor(Opcodes.ASM5) { override def visitParameter(name: String, access: Int) = { val d = h.Decl(name, owner) d.addAttachments(a.Var, a.Param) addAttachment(d) found += d } } /** * Packages are part of the name, divided by slashes. They are split into a * `Decl` hierarchy. */ private def mkDecl(name: String) = { val parts = name.split('/') val d = h.Decl(parts.head, h.Root) addAttachment(d) parts.tail.foldLeft(d) { (a, b) ⇒ val d = h.Decl(b, a) addAttachment(d) d } } }
#!/bin/bash #SBATCH --account=def-dkulic #SBATCH --mem=8000M # memory per node #SBATCH --time=23:00:00 # time (DD-HH:MM) #SBATCH --output=/project/6001934/lingheng/Double_DDPG_Job_output/continuous_RoboschoolHumanoid-v1_doule_ddpg_hardcopy_action_noise_seed2_run0_%N-%j.out # %N for node name, %j for jobID module load qt/5.9.6 python/3.6.3 nixpkgs/16.09 gcc/7.3.0 boost/1.68.0 cuda cudnn source ~/tf_cpu/bin/activate python ./ddpg_discrete_action.py --env RoboschoolHumanoid-v1 --random-seed 2 --exploration-strategy action_noise --summary-dir ../Double_DDPG_Results_no_monitor/continuous/RoboschoolHumanoid-v1/doule_ddpg_hardcopy_action_noise_seed2_run0 --continuous-act-space-flag --target-hard-copy-flag
def common_elements(arr1, arr2): result = [] for i, x in enumerate(arr1): if x in arr2: result.append(x) return result array1 = [1, 2, 3, 4, 5] array2 = [2, 3, 4, 5, 6] print(common_elements(array1, array2))
from fuzzywuzzy import fuzz def fuzzy_match(str1, str2): return fuzz.ratio(str1, str2)