text
stringlengths
27
775k
// Copyright (c) 2019 Georg Brandl. Licensed under the Apache License, // Version 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> // or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at // your option. This file may not be copied, modified, or distributed except // according to those terms. use ngc::parse; #[test] fn test_parse() { let src = r#"; Try to exercise as much of the syntax as possible. ; comments anywhere, line numbers, and block deletion /G1 X1 0(a)(b) Y2(a);rest /(a) (a)N1 G#1 X-[10] (a) ; number formats #1=+1. (a) #2=1.5 #3=-.5 ; expressions G[[1+ 2]/ 3*4--5] G+SIN[0] G[ATAN[1]/[2]] G[1 LE 2] ; parameter references #1=[1+2] #<de pth>=1 #<de(a) pth>=2 #[1 ]=3 #-#2=[+ 5] #SIN [0]=7 ; LCNC doesn't like this. # 10 = EXISTS[#<blub>] "#; let parsed = r#"/ G1 X10 Y2 G#1 X-10 #1=1 #2=1.5 #3=-0.5 G[[[[1 + 2] / 3] * 4] - -5] GSIN[0] GATAN[1]/[2] G[1 LE 2] #1=[1 + 2] #<depth>=1 #<de(a)pth>=2 #1=3 #-#2=5 #[SIN[0]]=7 #10=EXISTS[#<blub>] "#; let prog = parse::parse("testfile", src).unwrap(); // make sure we count lines correctly assert_eq!(prog.blocks[0].lineno, 4); println!("{:#?}", prog); assert_eq!(prog.to_string(), parsed.replace("\n", " \n")); } #[test] fn test_invalid() { for snippet in &[ "$", // invalid characters "GG", // missing values "O10", // O-words are unsupported "(", // unclosed comments "(\n)", // comments spanning lines "G(a)1", // comments between letter/value "G1(a)2", // comments within the value "G[1(a)+2]", // comments within an expression "G[1;]", // line comments within expression "G[TEST[x]]", // invalid function "#1.2=5", // fractional parameter number "#1=EXISTS[5]", // invalid EXISTS argument ] { assert!(parse::parse("testfile", snippet).is_err()); } }
//! Compiled peephole optimizations. use crate::error::Result; use crate::instruction_set::InstructionSet; use crate::integer_interner::IntegerInterner; use crate::linear::{Action, MatchOp, MatchResult}; use crate::optimizer::PeepholeOptimizer; use crate::paths::PathInterner; use peepmatic_automata::Automaton; use serde::{Deserialize, Serialize}; #[cfg(feature = "construct")] use std::fs; #[cfg(feature = "construct")] use std::path::Path; /// A compiled set of peephole optimizations. /// /// This is the compilation result of the `peepmatic` crate, after its taken a /// bunch of optimizations written in the DSL and lowered and combined them. #[derive(Debug, Serialize, Deserialize)] pub struct PeepholeOptimizations { /// The instruction paths referenced by the peephole optimizations. pub paths: PathInterner, /// Not all integers we're matching on fit in the `u32` that we use as the /// result of match operations. So we intern them and refer to them by id. pub integers: IntegerInterner, /// The underlying automata for matching optimizations' left-hand sides, and /// building up the corresponding right-hand side. pub automata: Automaton<MatchResult, MatchOp, Box<[Action]>>, } impl PeepholeOptimizations { /// Deserialize a `PeepholeOptimizations` from bytes. pub fn deserialize(serialized: &[u8]) -> Result<Self> { let peep_opt: Self = bincode::deserialize(serialized)?; Ok(peep_opt) } /// Serialize these peephole optimizations out to the file at the given path. /// /// Requires that the `"construct"` cargo feature is enabled. #[cfg(feature = "construct")] pub fn serialize_to_file(&self, path: &Path) -> Result<()> { let file = fs::File::create(path)?; bincode::serialize_into(file, self)?; Ok(()) } /// Create a new peephole optimizer instance from this set of peephole /// optimizations. /// /// The peephole optimizer instance can be used to apply these peephole /// optimizations. When checking multiple instructions for whether they can /// be optimized, it is more performant to reuse a single peephole optimizer /// instance, rather than create a new one for each instruction. Reusing the /// peephole optimizer instance allows the reuse of a few internal /// allocations. pub fn optimizer<'peep, 'ctx, I>(&'peep self, instr_set: I) -> PeepholeOptimizer<'peep, 'ctx, I> where I: InstructionSet<'ctx>, { PeepholeOptimizer { peep_opt: self, instr_set, right_hand_sides: vec![], actions: vec![], backtracking_states: vec![], } } }
--- title: Gamesplanet description: Buy games & digital codes with Bitcoin. homepage: https://gamesplanet.com/ twitter: ---
namespace Menees.RpnCalc { #region Using Directives using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using Menees.RpnCalc.Internal; #endregion public class EntryLineParser { #region Private Data Members private const char NULL = '\0'; // These are listed in the order we want to try them. private static readonly RpnValueType[] AmbiguousValueTypes = { // Try as Integer first because TimeSpan will parse // an integer as a number of days. That's not what // we want normally. Also, integer must come before // double since every sub-15-digit integer would parse // as a double. RpnValueType.Integer, // TimeSpans can use culture-specific separators, // but they shouldn't conflict with a Double's format. RpnValueType.TimeSpan, RpnValueType.Double, }; private readonly Calculator calc; // If you add a member here, add it to the Reset() method too. private readonly List<Token> tokens = new(); private readonly List<Value> values = new(); private int position; private ParseStates states; private string? errorMessage; private string entryLine = string.Empty; private int entryLineLength; #endregion #region Constructors public EntryLineParser(Calculator calc) { this.calc = calc; } public EntryLineParser(Calculator calc, string entryLine) : this(calc) { this.EntryLine = entryLine; } #endregion #region ParseStates [Flags] private enum ParseStates { None = 0, // We were able to completely parse all the tokens // (although the last one may not have an ending delimiter). Complete = 1, // The last token begins with '(' but doesn't end with ')'. InComplex = 2, // The last token begins with '"' but doesn't end with '"'. InDateTime = 4, // Last token appears to be a Fraction, TimeSpan, Integer, or Double. // Might be incomplete (e.g., 1_2_, 3:12:, 1.23e-). InNegatableScalarValue = 8, // Note: We don't need an Error state because // it's really just the lack of the Complete state, // and we have an ErrorMessage member for it too. } #endregion #region Public Properties public string EntryLine { get { return this.entryLine; } set { this.entryLine = value ?? string.Empty; this.entryLineLength = this.entryLine.Length; // Reset all members before we start tokenizing. this.Reset(); // Split the entry line into tokens (i.e., text, positions, and type hints). this.Tokenize(); // Try to parse the tokens into values. this.Parse(); // Setting state flags in one method is a lot simpler than trying to // redetermine the states whenever each state property is invoked. this.SetStates(); } } public IList<string> Tokens { get { IList<string> result = (from t in this.tokens select t.Text).ToList(); return result; } } public IList<Value> Values { get { return this.values.AsReadOnly(); } } public bool IsEntryLineComplete { get { return this.states.HasFlag(ParseStates.Complete); } } public bool InComplex { get { return this.states.HasFlag(ParseStates.InComplex); } } public bool InDateTime { get { return this.states.HasFlag(ParseStates.InDateTime); } } public bool InNegatableScalarValue { get { return this.states.HasFlag(ParseStates.InNegatableScalarValue); } } public bool HasError { get { return !string.IsNullOrEmpty(this.errorMessage); } } public string ErrorMessage { get { return this.errorMessage ?? string.Empty; } } #endregion #region Public Methods public bool GetErrorLocation(out int start, out int length) { bool result = false; start = this.entryLineLength; length = 0; // Assume that the first unparsed token is the one with the error // since that's where then Parse() method stops processing. int valueCount = this.values.Count; if (this.HasError && valueCount < this.tokens.Count) { Token errorToken = this.tokens[valueCount]; start = errorToken.StartPosition; length = errorToken.Text.Length; result = true; } return result; } #endregion #region Private Methods private static bool ContainsFractionValueSeparator(string text) { // Look for '_' and '/' because FractionValue can parse them both. // However, we have to be a little careful to avoid ambiguities with // dates, which also use '/'. But everywhere in this class, I've made // sure to look for dates before dealing with fractions. bool result = text.Contains(FractionValue.EntrySeparator) || text.Contains(FractionValue.DisplaySeparator); return result; } private void Reset() { this.states = ParseStates.None; this.tokens.Clear(); this.values.Clear(); this.errorMessage = null; this.position = 0; } private void Tokenize() { if (!string.IsNullOrWhiteSpace(this.entryLine)) { char ch = this.SkipWhitespace(); while (ch != NULL) { int tokenStartPosition = this.position - 1; RpnValueType? tokenValueType = null; string tokenText; if (ch == ComplexValue.StartDelimiter) { tokenText = this.ReadToEndDelimiter(ch, ComplexValue.EndDelimiter); tokenValueType = RpnValueType.Complex; } else if (ch == DateTimeValue.StartDelimiter) { tokenText = this.ReadToEndDelimiter(ch, DateTimeValue.EndDelimiter); tokenValueType = RpnValueType.DateTime; } else if ((ch == BinaryValue.Prefix) || (ch == '0' && this.PeekChar() == 'x')) { // Ignore whitespace between the '#' prefix and the digits. if (ch == BinaryValue.Prefix && char.IsWhiteSpace(this.PeekChar())) { this.SkipWhitespace(); this.UngetChar(); } tokenText = this.ReadToWhitespace(ch); tokenValueType = RpnValueType.Binary; } else { // It could be a fraction, timespan, integer, double, or junk. // We'll let the Parse method figure that out. tokenText = this.ReadToWhitespace(ch); } if (!string.IsNullOrEmpty(tokenText)) { this.tokens.Add(new Token(tokenText, tokenStartPosition, tokenValueType)); } ch = this.SkipWhitespace(); } } } private char GetChar() { char ch = this.PeekChar(); if (ch != NULL) { this.position++; } return ch; } private void UngetChar() { if (this.position > 0) { this.position--; } } private char PeekChar() => this.position < this.entryLineLength ? this.entryLine[this.position] : NULL; private char SkipWhitespace() { char ch; do { ch = this.GetChar(); } while (ch != NULL && char.IsWhiteSpace(ch)); return ch; } private string ReadToEndDelimiter(char ch, char endDelimiter) { StringBuilder sb = new(); sb.Append(ch); while ((ch = this.GetChar()) != NULL && ch != endDelimiter) { sb.Append(ch); } if (ch == endDelimiter) { sb.Append(ch); } return sb.ToString(); } private string ReadToWhitespace(char ch) { StringBuilder sb = new(); sb.Append(ch); while ((ch = this.GetChar()) != NULL && !char.IsWhiteSpace(ch)) { sb.Append(ch); } return sb.ToString(); } private void Parse() { foreach (Token token in this.tokens) { string text = token.Text; Debug.Assert(!string.IsNullOrEmpty(text), "Token.Text should always be non-empty."); int startingValueCount = this.values.Count; if (token.ValueType.HasValue) { // Handles: Complex, DateTime, Binary if (Value.TryParse(token.ValueType.Value, text, this.calc, out Value? value)) { this.values.Add(value); } } else if (ContainsFractionValueSeparator(text)) { // Handles: Fraction if (FractionValue.TryParse(text, out FractionValue? value)) { this.values.Add(value); } } else { // Handles: TimeSpan, Integer, Double foreach (RpnValueType type in AmbiguousValueTypes) { if (Value.TryParse(type, text, this.calc, out Value? value)) { this.values.Add(value); break; // Quit the inner c_ambiguousValueTypes loop. } } } // If we weren't able to parse the current token, then stop. // The GetErrorLocation() method depends on this behavior. if (startingValueCount == this.values.Count) { // Use the same "helpful" error message that the HP48 uses. this.errorMessage = Resources.EntryLineParser_InvalidSyntax; break; // Quit the outer this.tokens loop. } } } private void SetStates() { int tokenCount = this.tokens.Count; if (tokenCount == this.values.Count) { // We were able to completely parse all the tokens // (although the last one may not have an ending delimiter). this.states |= ParseStates.Complete; } if (tokenCount > 0) { Token lastToken = this.tokens[tokenCount - 1]; string text = lastToken.Text; char firstChar = text[0]; char lastChar = text[text.Length - 1]; if (firstChar == ComplexValue.StartDelimiter && lastChar != ComplexValue.EndDelimiter) { // The last token begins with '(' but doesn't end with ')'. this.states |= ParseStates.InComplex; } else if (firstChar == DateTimeValue.StartDelimiter && lastChar != DateTimeValue.EndDelimiter) { // The last token begins with '"' but doesn't end with '"'. this.states |= ParseStates.InDateTime; } else if (!char.IsWhiteSpace(this.entryLine[this.entryLineLength - 1])) { // The entry line doesn't end with whitespace, so assume the // caret position is at the end of the last token. Then try to // determine if the last value or token is a negatable scalar. if (this.IsEntryLineComplete) { // We have a parsed entry line, so we'll use the last value's type. Value lastValue = this.values[this.values.Count - 1]; RpnValueType type = lastValue.ValueType; if (type == RpnValueType.Integer || type == RpnValueType.Double || type == RpnValueType.Fraction || type == RpnValueType.TimeSpan) { this.states |= ParseStates.InNegatableScalarValue; } } else { // The entry line is incomplete. This can happen for inputs // like "1_2_", "3:12:", and "1.23e-". Check if the last token // appears to be a Fraction or TimeSpan. I don't know a // good, safe way to determine if they've entered the start // of a double value that currently can't be parsed, so we // just won't return this state in that case. if (ContainsFractionValueSeparator(text) || text.Contains(TimeSpanValue.FieldSeparator)) { this.states |= ParseStates.InNegatableScalarValue; } } } } } #endregion #region Private Types #region Token private sealed class Token { #region Constructors public Token(string text, int startPos, RpnValueType? type) { this.Text = text; this.StartPosition = startPos; this.ValueType = type; } #endregion #region Public Properties public string Text { get; private set; } public int StartPosition { get; private set; } public RpnValueType? ValueType { get; private set; } #endregion } #endregion #endregion } }
import { TypeApiItem } from './TypeApiItem'; import { TypeActionData } from './TypeActionData'; import { TypeApiRequestGenerator } from './TypeApiRequestGenerator'; import { TypeApiResponseGenerator } from './TypeApiResponseGenerator'; export type TypeApiGenerator<TApi extends TypeApiItem> = { [TApiName in keyof TApi]: TypeActionData & (( requestParams: TypeApiRequestGenerator<TApi, TApiName> ) => Promise<TypeApiResponseGenerator<TApi, TApiName>>); };
<?php /** * Copyright (c) 2015, Chris Harris. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @author Chris Harris <[email protected]> * @copyright Copyright (c) 2015 Chris Harris * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License */ namespace Curly\Parser; use ReflectionClass; /** * A token stores meaningful character strings that are found when peforming lexical analysis. * * A token should consists of a name by which it can be identified and an optional value. The name of * a token does not have to be unique amongst other tokens. The name of a token is simply used to hint * what value is stored by the token. The value stored by a token can be of any type, but it's most * likely that a token is used to stored a sequence of characters found with a lexer. * * @author Chris Harris <[email protected]> * @version 1.0.0 */ class Token implements TokenInterface { /** * Tokens types */ const T_UNKNOWN = 1; const T_TEXT = 2; const T_OPEN_TAG = 3; const T_CLOSE_TAG = 4; const T_OPEN_PRINT_TAG = 5; const T_CLOSE_PRINT_TAG = 6; const T_OPERATOR = 7; const T_INTEGER = 8; const T_FLOAT = 9; const T_STRING = 10; const T_BOOLEAN = 11; const T_NULL = 12; const T_IDENTIFIER = 13; const T_VARIABLE = 14; const T_OPEN_BRACKET = 15; const T_CLOSE_BRACKET = 16; const T_OPEN_PARENTHESIS = 16; const T_CLOSE_PARENTHESIS = 17; const T_OPEN_BRACE = 18; const T_CLOSE_BRACE = 19; const T_PERIOD = 20; const T_COMMA = 21; const T_PIPELINE = 22; const T_SEMICOLON = 23; const T_COLON = 24; const T_ASSIGN = 25; /** * The token type. * * @var mixed */ private $type; /** * The value stored by this token. * * @var mixed */ private $value; /** * The line number of the value. * * @var int */ private $lineNumber = -1; /** * Construct a new token. * * @param mixed $type The token type. * @param mixed $value The value for this token. * @param int $lineNumber (optional) the line number of the value. */ public function __construct($type, $value, $lineNumber = -1) { $this->setType($type); $this->setValue($value); $this->setLineNumber($lineNumber); } /** * Set the type of this token. The type is simply used to hint the parser what value is stored by the token. * * @param mixed $type the token type. * @throws InvalidArgumentException if the given argument is not a string. */ private function setType($type) { $this->type = $type; } /** * {@inheritDoc} */ public function getType() { return $this->type; } /** * The value to hold by this token. * * @param mixed $value the token value. */ private function setValue($value) { $this->value = $value; } /** * {@inheritDoc} */ public function getValue() { return $this->value; } /** * Set the line number of the value. * * @param int $position the line number of the value. * @throws InvalidArgumentException if the given position is not a numeric value. */ private function setLineNumber($lineNumber) { if (!is_numeric($lineNumber)) { throw new \InvalidArgumentException(sprintf( '%s: expects a numeric argument; received "%s"', __METHOD__, (is_object($lineNumber) ? get_class($lineNumber) : gettype($lineNumber)) )); } $this->lineNumber = (int) $lineNumber; } /** * {@inheritDoc} */ public function getLineNumber() { return $this->lineNumber; } /** * {@inheritDoc} */ public function equals($obj) { if ($obj instanceof self) { return ($obj->getType() === $this->getType() && $obj->getValue() === $this->getValue()); } return false; } /** * {@inheritDoc} */ public static function getLiteral($type, $strict = false) { static $reflClass; if ($reflClass === null) { $reflClass = new ReflectionClass(get_called_class()); } $constants = $reflClass->getConstants(); foreach ($constants as $name => $value) { $matches = ($strict) ? ($type === $value) : ($type == $value); if ($matches) { return $name; } } return null; } }
<?php /** * MediatorTest.php * PHP version 5.4 * 2015-09-29 * * @package Foundry\Masonry * @category Tests * @author Daniel Mason <[email protected]> * @copyright 2015 The Foundry Visionmongers */ namespace Foundry\Masonry\Tests\PhpUnit\Core; use Foundry\Masonry\Core\Mediator; use Foundry\Masonry\Core\Task; use Foundry\Masonry\Tests\PhpUnit\TestCase; use Foundry\Masonry\Interfaces\WorkerInterface; use Foundry\Masonry\Interfaces\Task\DescriptionInterface; use React\Promise\Promise; /** * Class MediatorTest * * @package Foundry\Masonry * @coversDefaultClass \Foundry\Masonry\Core\Mediator */ class MediatorTest extends TestCase { /** * @return WorkerInterface|\PHPUnit_Framework_MockObject_MockObject */ protected function getMockWorker() { return $this->getMockBuilder('\Foundry\Masonry\Interfaces\WorkerInterface') ->disableOriginalConstructor() ->getMock(); } /** * @return DescriptionInterface|\PHPUnit_Framework_MockObject_MockObject */ protected function getMockDescription() { return $this->getMockBuilder('\Foundry\Masonry\Interfaces\Task\DescriptionInterface') ->disableOriginalConstructor() ->getMock(); } /** * @test * @covers ::addWorker * @return void */ public function testAddWorker() { $worker = $this->getMockWorker(); $mediator = new Mediator(); $this->assertSame( $mediator, $mediator->addWorker($worker) ); $this->assertSame( [$worker], $this->getObjectAttribute($mediator, 'workers') ); } /** * @test * @covers ::process * @uses \Foundry\Masonry\Core\Mediator::addWorker * @uses \Foundry\Masonry\Core\Task * @return void */ public function testProcess() { $promise = new Promise(function () { return true; }); $description = $this->getMockDescription(); $task = new Task($description); $worker = $this->getMockWorker(); $worker->expects($this->once()) ->method('process') ->with($task) ->will($this->returnValue($promise)); $worker->expects($this->once()) ->method('getDescriptionTypes') ->will($this->returnValue([get_class($description)])); $mediator = new Mediator(); $mediator->addWorker($worker); $this->assertSame( $promise, $mediator->process($task) ); } /** * @test * @covers ::process * @uses \Foundry\Masonry\Core\Task * @expectedException \Foundry\Masonry\Core\Exception\NoWorkerFound * @return void */ public function testProcessNoWorkers() { $description = $this->getMockDescription(); $task = new Task($description); $mediator = new Mediator(); $mediator->process($task); } /** * @test * @covers ::process * @uses \Foundry\Masonry\Core\Task * @uses \Foundry\Masonry\Core\Mediator::addWorker * @expectedException \Foundry\Masonry\Core\Exception\NoWorkerFound * @return void */ public function testProcessNoValidWorker() { $description = $this->getMockDescription(); $task = new Task($description); $worker = $this->getMockWorker(); $worker->expects($this->once()) ->method('getDescriptionTypes') ->will($this->returnValue(['SomeOtherTaskDescription'])); $mediator = new Mediator(); $mediator->addWorker($worker); $mediator->process($task); } }
@{ ViewBag.Title = "TimeLine"; Layout = "~/Views/Shared/_amChartLayout.cshtml"; } <script src="https://www.amcharts.com/lib/4/plugins/timeline.js"></script> <script src="https://www.amcharts.com/lib/4/plugins/bullets.js"></script> <div class="row pt-3 px-4"> <div class="col-md-12"> <div class="card"> <div class="card-header"> Simple Time Line </div> <div class="card-body"> <div id="chartdiv" style=" width: 100%;height:500px"></div> </div> </div> </div> </div> <script> am4core.ready(function () { // Themes begin am4core.useTheme(am4themes_animated); // Themes end var chart = am4core.create("chartdiv", am4plugins_timeline.SerpentineChart); chart.curveContainer.padding(100, 20, 50, 20); chart.levelCount = 3; chart.yAxisRadius = am4core.percent(20); chart.yAxisInnerRadius = am4core.percent(2); chart.maskBullets = false; var colorSet = new am4core.ColorSet(); chart.dateFormatter.inputDateFormat = "yyyy-MM-dd HH:mm"; chart.dateFormatter.dateFormat = "HH"; chart.data = [{ "category": "", "start": "2019-01-10 06:00", "end": "2019-01-10 07:00", "color": colorSet.getIndex(15), "text": "I will have\na healthy day today!", "textDisabled": false, "icon": "/wp-content/uploads/assets/timeline/timeline0.svg" }, { "category": "", "start": "2019-01-10 07:00", "end": "2019-01-10 08:00", "color": colorSet.getIndex(14), "icon": "/wp-content/uploads/assets/timeline/timeline1.svg" }, { "category": "", "start": "2019-01-10 08:00", "end": "2019-01-10 09:00", "color": colorSet.getIndex(13), "icon": "/wp-content/uploads/assets/timeline/timeline2.svg" }, { "category": "", "start": "2019-01-10 09:00", "end": "2019-01-10 10:00", "color": colorSet.getIndex(12), "icon": "/wp-content/uploads/assets/timeline/timeline2.svg" }, { "category": "", "start": "2019-01-10 10:00", "end": "2019-01-10 12:00", "color": colorSet.getIndex(11), "icon": "/wp-content/uploads/assets/timeline/timeline2.svg" }, { "category": "", "start": "2019-01-10 12:00", "end": "2019-01-10 13:00", "color": colorSet.getIndex(10), "icon": "/wp-content/uploads/assets/timeline/timeline1.svg" }, { "category": "", "start": "2019-01-10 13:00", "end": "2019-01-10 14:00", "color": colorSet.getIndex(9), "text": "One beer doesn't count.", "textDisabled": false, "icon": "/wp-content/uploads/assets/timeline/timeline3.svg" }, { "category": "", "start": "2019-01-10 14:00", "end": "2019-01-10 16:00", "color": colorSet.getIndex(8), "icon": "/wp-content/uploads/assets/timeline/timeline2.svg" }, { "category": "", "start": "2019-01-10 16:00", "end": "2019-01-10 17:00", "color": colorSet.getIndex(7), "icon": "/wp-content/uploads/assets/timeline/timeline4.svg" }, { "category": "", "start": "2019-01-10 17:00", "end": "2019-01-10 20:00", "color": colorSet.getIndex(6), "icon": "/wp-content/uploads/assets/timeline/timeline2.svg" }, { "category": "", "start": "2019-01-10 20:00", "end": "2019-01-10 20:30", "color": colorSet.getIndex(5), "icon": "/wp-content/uploads/assets/timeline/timeline3.svg" }, { "category": "", "start": "2019-01-10 20:30", "end": "2019-01-10 21:30", "color": colorSet.getIndex(4), "icon": "/wp-content/uploads/assets/timeline/timeline3.svg" }, { "category": "", "start": "2019-01-10 21:30", "end": "2019-01-10 22:00", "color": colorSet.getIndex(3), "icon": "/wp-content/uploads/assets/timeline/dance.svg" }, { "category": "", "start": "2019-01-10 22:00", "end": "2019-01-10 23:00", "color": colorSet.getIndex(2), "icon": "/wp-content/uploads/assets/timeline/timeline5.svg" }, { "category": "", "start": "2019-01-10 23:00", "end": "2019-01-11 00:00", "color": colorSet.getIndex(1), "icon": "/wp-content/uploads/assets/timeline/timeline6.svg" }, { "category": "", "start": "2019-01-11 00:00", "end": "2019-01-11 01:00", "color": colorSet.getIndex(0), "text": "Damn...", "textDisabled": false, "icon": "/wp-content/uploads/assets/timeline/timeline7.svg" }]; chart.fontSize = 10; chart.tooltipContainer.fontSize = 10; var categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis()); categoryAxis.dataFields.category = "category"; categoryAxis.renderer.grid.template.disabled = true; categoryAxis.renderer.labels.template.paddingRight = 25; categoryAxis.renderer.minGridDistance = 10; var dateAxis = chart.xAxes.push(new am4charts.DateAxis()); dateAxis.renderer.minGridDistance = 70; dateAxis.baseInterval = { count: 30, timeUnit: "minute" }; dateAxis.renderer.tooltipLocation = 0; dateAxis.renderer.line.strokeDasharray = "1,4"; dateAxis.renderer.line.strokeOpacity = 0.5; dateAxis.tooltip.background.fillOpacity = 0.2; dateAxis.tooltip.background.cornerRadius = 5; dateAxis.tooltip.label.fill = new am4core.InterfaceColorSet().getFor("alternativeBackground"); dateAxis.tooltip.label.paddingTop = 7; dateAxis.endLocation = 0; dateAxis.startLocation = -0.5; var labelTemplate = dateAxis.renderer.labels.template; labelTemplate.verticalCenter = "middle"; labelTemplate.fillOpacity = 0.4; labelTemplate.background.fill = new am4core.InterfaceColorSet().getFor("background"); labelTemplate.background.fillOpacity = 1; labelTemplate.padding(7, 7, 7, 7); var series = chart.series.push(new am4plugins_timeline.CurveColumnSeries()); series.columns.template.height = am4core.percent(15); series.dataFields.openDateX = "start"; series.dataFields.dateX = "end"; series.dataFields.categoryY = "category"; series.baseAxis = categoryAxis; series.columns.template.propertyFields.fill = "color"; // get color from data series.columns.template.propertyFields.stroke = "color"; series.columns.template.strokeOpacity = 0; series.columns.template.fillOpacity = 0.6; var imageBullet1 = series.bullets.push(new am4plugins_bullets.PinBullet()); imageBullet1.locationX = 1; imageBullet1.propertyFields.stroke = "color"; imageBullet1.background.propertyFields.fill = "color"; imageBullet1.image = new am4core.Image(); imageBullet1.image.propertyFields.href = "icon"; imageBullet1.image.scale = 0.5; imageBullet1.circle.radius = am4core.percent(100); imageBullet1.dy = -5; var textBullet = series.bullets.push(new am4charts.LabelBullet()); textBullet.label.propertyFields.text = "text"; textBullet.disabled = true; textBullet.propertyFields.disabled = "textDisabled"; textBullet.label.strokeOpacity = 0; textBullet.locationX = 1; textBullet.dy = - 100; textBullet.label.textAlign = "middle"; chart.scrollbarX = new am4core.Scrollbar(); chart.scrollbarX.align = "center" chart.scrollbarX.width = am4core.percent(75); chart.scrollbarX.opacity = 0.5; var cursor = new am4plugins_timeline.CurveCursor(); chart.cursor = cursor; cursor.xAxis = dateAxis; cursor.yAxis = categoryAxis; cursor.lineY.disabled = true; cursor.lineX.strokeDasharray = "1,4"; cursor.lineX.strokeOpacity = 1; dateAxis.renderer.tooltipLocation2 = 0; categoryAxis.cursorTooltipEnabled = false; var label = chart.createChild(am4core.Label); label.text = "Another unlucky day in the office." label.isMeasured = false; label.y = am4core.percent(40); label.x = am4core.percent(50); label.horizontalCenter = "middle"; label.fontSize = 20; }); // end am4core.ready() </script>
package org.tools4j.fix import java.util.Arrays /** * User: ben * Date: 13/06/2017 * Time: 6:49 AM */ class SplitString(private val splitValues: Array<String>?) : Iterable<String> { fun allElementsOnwards(indexIncludingAndOnwards: Int, delimiter: String): String? { if (splitValues!!.size <= indexIncludingAndOnwards) { return null } else if (splitValues.size == indexIncludingAndOnwards + 1) { return splitValues[indexIncludingAndOnwards] } else { val sb = StringBuilder() for (i in indexIncludingAndOnwards until splitValues.size) { if (sb.length > 0) { sb.append(delimiter) } sb.append(splitValues[i]) } return sb.toString() } } operator fun get(index: Int): String { return splitValues!![index] } override fun iterator(): Iterator<String> { if (splitValues == null) { throw NullPointerException("Please call split() before calling iterator().") } return Arrays.asList(*splitValues).iterator() } fun values(): Array<String>? { return splitValues } fun indexOf(value: String): Int { for (i in splitValues!!.indices) { if (splitValues[i] == value) { return i } } throw IllegalStateException("Value: " + value + " is not an element of array: " + Arrays.toString(splitValues)) } operator fun contains(value: String): Boolean { for (i in splitValues!!.indices) { if (splitValues[i] == value) { return true } } return false } fun equalsArray(expected: Array<String>): Boolean { return if(expected.isEmpty() && splitValues!!.isEmpty()){ true } else { Arrays.equals(splitValues, expected) } } override fun toString(): String { return "SplitString{" + Arrays.toString(splitValues) + '}'.toString() } }
package com.temp.cube.model; import com.temp.cube.enums.Color; import com.temp.cube.enums.CubeTurnEnum; import com.temp.cube.enums.Direction; import com.temp.cube.enums.SideTurnEnum; import com.temp.cube.output.OutputManager; import com.temp.cube.turn.TurnFactory; /** * 整个立方体的抽象 */ public class Cube { /** * 前面的一面,初始面 */ private Side frontSide; /** * 右边的一面, y转体后正对 */ private Side rightSide; /** * 后面的一面, y2转体后正对 */ private Side backSide; /** * 左边的一面, y'转体后正对 */ private Side leftSide; /** * 底下的一面, z转体后正对 */ private Side downSide; /** * 顶上的一面, z'转体后正对 */ private Side upSide; /** * 屏蔽隐藏默认构造 */ private Cube() {} /** * 初始化 */ public static Cube init(Side frontSide, Side rightSide, Side backSide, Side leftSide, Side downSide, Side upSide) { Cube cube = new Cube(); cube.frontSide = frontSide; cube.rightSide = rightSide; cube.backSide = backSide; cube.leftSide = leftSide; cube.downSide = downSide; cube.upSide = upSide; return cube; } /** * 以完成状态作为初始化, 默认按照国际标准: 白顶绿前 */ public static Cube init() { Side frontSide = Side.initWithOneColor(Color.GREEN); Side rightSide = Side.initWithOneColor(Color.RED); Side backSide = Side.initWithOneColor(Color.BLUE); Side leftSide = Side.initWithOneColor(Color.ORANGE); Side downSide = Side.initWithOneColor(Color.YELLOW); Side upSide = Side.initWithOneColor(Color.WHITE); return Cube.init(frontSide, rightSide, backSide, leftSide, downSide, upSide); } public void turn(SideTurnEnum sideTurnEnum, Direction direction) { TurnFactory.getTurn(sideTurnEnum).turn(this, direction); } public void turn(CubeTurnEnum cubeTurnEnum, Direction direction) { TurnFactory.getTurn(cubeTurnEnum).turn(this, direction); } public void output() { OutputManager.useDefaultOutput().output(this); } public Side getFrontSide() { return frontSide; } public Side getRightSide() { return rightSide; } public Side getBackSide() { return backSide; } public Side getLeftSide() { return leftSide; } public Side getDownSide() { return downSide; } public Side getUpSide() { return upSide; } public void setFrontSide(Side frontSide) { this.frontSide = frontSide; } public void setRightSide(Side rightSide) { this.rightSide = rightSide; } public void setBackSide(Side backSide) { this.backSide = backSide; } public void setLeftSide(Side leftSide) { this.leftSide = leftSide; } public void setDownSide(Side downSide) { this.downSide = downSide; } public void setUpSide(Side upSide) { this.upSide = upSide; } }
/* * Copyright 2017 The Hyve * * 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.radarbase.android.data import org.radarbase.android.data.serialization.SerializationFactory import org.radarbase.android.util.ChangeRunner import org.radarbase.android.util.SafeHandler import org.radarbase.data.AvroRecordData import org.radarbase.data.Record import org.radarbase.data.RecordData import org.radarbase.topic.AvroTopic import org.radarbase.util.BackedObjectQueue import org.radarbase.util.QueueFile import org.slf4j.LoggerFactory import java.io.File import java.io.IOException import java.util.* import java.util.concurrent.ExecutionException /** * Caches measurement on a BackedObjectQueue. Internally, all data is first cached on a local queue, * before being written in batches to the BackedObjectQueue, using a single-threaded * ExecutorService. Data is retrieved and removed from the queue in a blocking way using that same * ExecutorService. Sent messages are not kept, they are immediately removed. * * @param K measurement key type * @param V measurement value type */ class TapeCache<K: Any, V: Any> /** * TapeCache to cache measurements with * @param topic Kafka Avro topic to write data for. * @throws IOException if a BackedObjectQueue cannot be created. */ @Throws(IOException::class) constructor( override val file: File, override val topic: AvroTopic<K, V>, override val readTopic: AvroTopic<Any, Any>, private val handler: SafeHandler, override val serialization: SerializationFactory, config: CacheConfiguration, ) : DataCache<K, V> { private val measurementsToAdd = mutableListOf<Record<K, V>>() private val serializer = serialization.createSerializer(topic) private val deserializer = serialization.createDeserializer(readTopic) private var queueFile: QueueFile private var queue: BackedObjectQueue<Record<K, V>, Record<Any, Any>> private val queueFileFactory = config.queueFileType private var addMeasurementFuture: SafeHandler.HandlerFuture? = null private val configCache = ChangeRunner(config) override var config get() = handler.compute { configCache.value } set(value) = handler.execute { configCache.applyIfChanged(value.copy()) { queueFile.maximumFileSize = it.maximumSize } } private val maximumSize: Long get() = config.maximumSize.takeIf { it <= Int.MAX_VALUE } ?: Int.MAX_VALUE.toLong() init { queueFile = try { queueFileFactory.generate(Objects.requireNonNull(file), maximumSize) } catch (ex: IOException) { logger.error("TapeCache {} was corrupted. Removing old cache.", file, ex) if (file.delete()) { queueFileFactory.generate(file, maximumSize) } else { throw ex } } this.queue = BackedObjectQueue(queueFile, serializer, deserializer) } @Throws(IOException::class) override fun getUnsentRecords(limit: Int, sizeLimit: Long): RecordData<Any, Any?>? { logger.debug("Trying to retrieve records from topic {}", topic.name) return try { handler.compute { try { getValidUnsentRecords(limit, sizeLimit) ?.let { (key, values) -> AvroRecordData(readTopic, key, values) } } catch (ex: IOException) { fixCorruptQueue(ex) null } catch (ex: IllegalStateException) { fixCorruptQueue(ex) null } } } catch (ex: InterruptedException) { logger.warn("getUnsentRecords was interrupted, returning an empty list", ex) Thread.currentThread().interrupt() null } catch (ex: ExecutionException) { logger.warn("Failed to retrieve records for topic {}", topic, ex) val cause = ex.cause if (cause is RuntimeException) { throw cause } else { throw IOException("Unknown error occurred", ex) } } } private fun getValidUnsentRecords(limit: Int, sizeLimit: Long): Pair<Any, List<Any>>? { var currentKey: Any? = null lateinit var records: List<Record<Any, Any>?> while (currentKey == null) { records = queue.peek(limit, sizeLimit) if (records.isEmpty()) return null val nullSize = records.indexOfFirst { it != null } .takeIf { it != -1 } ?: records.size if (nullSize > 0) { queue -= nullSize records = records.subList(nullSize, records.size) } currentKey = records.firstOrNull()?.key } val differentKeyIndex = records.indexOfFirst { it?.key != currentKey } if (differentKeyIndex > 0) { records = records.subList(0, differentKeyIndex) } return Pair(currentKey, records.mapNotNull { it?.value }) } @Throws(IOException::class) override fun getRecords(limit: Int): RecordData<Any, Any>? { return getUnsentRecords(limit, maximumSize)?.let { records -> AvroRecordData<Any, Any>(records.topic, records.key, records.filterNotNull()) } } override val numberOfRecords: Long get() = handler.compute { queue.size.toLong() } @Throws(IOException::class) override fun remove(number: Int) { return handler.execute { val actualNumber = number.coerceAtMost(queue.size) if (actualNumber > 0) { logger.debug("Removing {} records from topic {}", actualNumber, topic.name) queue -= actualNumber } } } override fun addMeasurement(key: K, value: V) { val record = Record(key, value) require(serializer.canSerialize(record)) { "Cannot send invalid record to topic $topic with {key: $key, value: $value}" } handler.execute { measurementsToAdd += record if (addMeasurementFuture == null) { addMeasurementFuture = handler.delay(config.commitRate, ::doFlush) } } } @Throws(IOException::class) override fun close() { flush() queue.close() } override fun flush() { try { handler.await { addMeasurementFuture?.runNow() } } catch (e: InterruptedException) { logger.warn("Did not wait for adding measurements to complete.") } catch (ex: ExecutionException) { logger.warn("Failed to execute flush task", ex) } } override fun triggerFlush() { handler.execute { addMeasurementFuture?.runNow() } } private fun doFlush() { addMeasurementFuture = null if (measurementsToAdd.isEmpty()) { return } try { logger.info("Writing {} records to file in topic {}", measurementsToAdd.size, topic.name) queue += measurementsToAdd } catch (ex: IOException) { logger.error("Failed to add records", ex) throw RuntimeException(ex) } catch (ex: IllegalStateException) { logger.error("Queue {} is full, not adding records", topic.name) } catch (ex: IllegalArgumentException) { logger.error("Failed to validate all records; adding individual records instead", ex) try { logger.info("Writing {} records to file in topic {}", measurementsToAdd.size, topic.name) for (record in measurementsToAdd) { try { queue += record } catch (ex2: IllegalArgumentException) { logger.error("Failed to write individual record {}", record, ex) } } } catch (illEx: IllegalStateException) { logger.error("Queue {} is full, not adding records", topic.name) } catch (ex2: IOException) { logger.error("Failed to add record", ex) throw RuntimeException(ex) } } finally { measurementsToAdd.clear() } } @Throws(IOException::class) private fun fixCorruptQueue(ex: Exception) { logger.error("Queue {} was corrupted. Removing cache.", topic.name, ex) try { queue.close() } catch (ioex: IOException) { logger.warn("Failed to close corrupt queue", ioex) } if (file.delete()) { queueFile = queueFileFactory.generate(file, maximumSize) queue = BackedObjectQueue(queueFile, serializer, deserializer) } else { throw IOException("Cannot create new cache.") } } companion object { private val logger = LoggerFactory.getLogger(TapeCache::class.java) } }
using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace SpaceShipSurvival { public class ShopController : MonoBehaviour { [SerializeField] private GameObject _upgradeButtonPrefab; [SerializeField] private Transform _upgradeButtonsParent; [SerializeField] private Button _shopButton; [SerializeField] private GameObject _shopPanel; private bool _showingPanel = false; [SerializeField] private Upgrades.Upgrades _upgrades; private void Awake() { RoundController.Instance.RoundChangeState += RoundChangeState; _shopPanel.SetActive(false); GenerateButtonUpgrades(); } public void GenerateButtonUpgrades() { foreach (var upgrade in _upgrades.upgrades) { GameObject newUpgradeButton = Instantiate(_upgradeButtonPrefab, _upgradeButtonsParent); newUpgradeButton.GetComponentsInChildren<Image>()[1].sprite = upgrade.icon; Button button = newUpgradeButton.GetComponent<Button>(); button.onClick.AddListener(() => { upgrade.Upgrading(); //Actualitzar el text de la ui al nou preu. }); } } public void RoundChangeState(bool roundActive) { if (roundActive) { _shopButton.interactable = false; _shopPanel.SetActive(false); _showingPanel = false; } else { _shopButton.interactable = true; } } public void ShowShopPanel() { _showingPanel = !_showingPanel; _shopPanel.SetActive(_showingPanel); } } }
What do we mean by menu? A set of options, a selection using buttons. • Add a simple hero card, which we can add to later in the sequence, as the default • Get the current weather for Seattle. o https://graphical.weather.gov/xml/rest.php  listZipCodeList, ndfdBrowserClientByDay • Can the weather service handle ZIP codes? (easier than using geocoordinates). Need to add a static'ish call to the weather service in the "normal" path.
package user type User struct { Id string `json:"id"` Name string `json:"name"` } func (this *User) String() string { return "User(id: " + this.Id + ", Name: " + this.Name + ")" }
// pyCstruct_ptrtype.c // This file is generated by Shroud nowrite-version. Do not edit. // Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and // other Shroud Project Developers. // See the top-level COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) // #include "pystructmodule.h" #define NO_IMPORT_ARRAY #define PY_ARRAY_UNIQUE_SYMBOL SHROUD_STRUCT_ARRAY_API #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include "numpy/arrayobject.h" // splicer begin class.Cstruct_ptr.impl.include // splicer end class.Cstruct_ptr.impl.include #ifdef __cplusplus #define SHROUD_UNUSED(param) #else #define SHROUD_UNUSED(param) param #endif #if PY_MAJOR_VERSION >= 3 #define PyInt_AsLong PyLong_AsLong #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyString_FromString PyUnicode_FromString #define PyString_FromStringAndSize PyUnicode_FromStringAndSize #endif // splicer begin class.Cstruct_ptr.impl.C_definition // splicer end class.Cstruct_ptr.impl.C_definition // splicer begin class.Cstruct_ptr.impl.additional_methods // splicer end class.Cstruct_ptr.impl.additional_methods static void PY_Cstruct_ptr_tp_del (PY_Cstruct_ptr *self) { // splicer begin class.Cstruct_ptr.type.del PY_SHROUD_release_memory(self->idtor, self->obj); self->obj = NULL; // Python objects for members. Py_XDECREF(self->cfield_obj); Py_XDECREF(self->const_dvalue_obj); // Python objects for members. Py_XDECREF(self->cfield_dataobj); Py_XDECREF(self->const_dvalue_dataobj); // splicer end class.Cstruct_ptr.type.del } // ---------------------------------------- // Function: Cstruct_ptr +name(Cstruct_ptr_ctor) // Attrs: +intent(ctor) // Exact: py_default // ---------------------------------------- // Argument: char * cfield // Attrs: +intent(in) // Requested: py_ctor_char_*_numpy // Match: py_ctor_char_* // ---------------------------------------- // Argument: const double * const_dvalue // Attrs: +intent(in) // Requested: py_ctor_native_*_numpy // Match: py_ctor_native_* static int PY_Cstruct_ptr_tp_init( PY_Cstruct_ptr *self, PyObject *args, PyObject *kwds) { // splicer begin class.Cstruct_ptr.method.cstruct_ptr_ctor STR_SHROUD_converter_value SHValue_cfield = {NULL, NULL, NULL, NULL, 0}; SHValue_cfield.name = "cfield"; STR_SHROUD_converter_value SHValue_const_dvalue = {NULL, NULL, NULL, NULL, 0}; SHValue_const_dvalue.name = "const_dvalue"; char *SHT_kwlist[] = { "cfield", "const_dvalue", NULL }; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&:Cstruct_ptr_ctor", SHT_kwlist, STR_SHROUD_get_from_object_char, &SHValue_cfield, STR_SHROUD_get_from_object_double_numpy, &SHValue_const_dvalue)) return -1; self->obj = malloc(sizeof(Cstruct_ptr)); if (self->obj == NULL) { PyErr_NoMemory(); return -1; } self->idtor = 2; // post_call - initialize fields Cstruct_ptr *SH_obj = self->obj; SH_obj->cfield = (char *) SHValue_cfield.data; self->cfield_obj = SHValue_cfield.obj; // steal reference SH_obj->const_dvalue = (double *) SHValue_const_dvalue.data; self->const_dvalue_obj = SHValue_const_dvalue.obj; // steal reference return 0; // splicer end class.Cstruct_ptr.method.cstruct_ptr_ctor } // splicer begin class.Cstruct_ptr.impl.after_methods // splicer end class.Cstruct_ptr.impl.after_methods // Requested: py_descr_char_*_numpy // Match: py_descr_char_* static PyObject *PY_Cstruct_ptr_cfield_getter(PY_Cstruct_ptr *self, void *SHROUD_UNUSED(closure)) { if (self->obj->cfield == NULL) { Py_RETURN_NONE; } PyObject * rv = PyString_FromString(self->obj->cfield); return rv; } // Requested: py_descr_char_*_numpy // Match: py_descr_char_* static int PY_Cstruct_ptr_cfield_setter(PY_Cstruct_ptr *self, PyObject *value, void *SHROUD_UNUSED(closure)) { STR_SHROUD_converter_value cvalue; Py_XDECREF(self->cfield_dataobj); if (STR_SHROUD_get_from_object_char(value, &cvalue) == 0) { self->obj->cfield = NULL; self->cfield_dataobj = NULL; return -1; } self->obj->cfield = (char *) cvalue.data; self->cfield_dataobj = cvalue.dataobj; // steal reference return 0; } // Exact: py_descr_native_*_numpy static PyObject *PY_Cstruct_ptr_const_dvalue_getter(PY_Cstruct_ptr *self, void *SHROUD_UNUSED(closure)) { if (self->obj->const_dvalue == NULL) { Py_RETURN_NONE; } if (self->const_dvalue_obj != NULL) { Py_INCREF(self->const_dvalue_obj); return self->const_dvalue_obj; } npy_intp dims[1] = { 1 }; PyObject *rv = PyArray_SimpleNewFromData(1, dims, NPY_DOUBLE, (double *) self->obj->const_dvalue); if (rv != NULL) { Py_INCREF(rv); self->const_dvalue_obj = rv; } return rv; } // Exact: py_descr_native_*_numpy static int PY_Cstruct_ptr_const_dvalue_setter(PY_Cstruct_ptr *self, PyObject *value, void *SHROUD_UNUSED(closure)) { STR_SHROUD_converter_value cvalue; Py_XDECREF(self->const_dvalue_obj); if (STR_SHROUD_get_from_object_double_numpy(value, &cvalue) == 0) { self->obj->const_dvalue = NULL; self->const_dvalue_obj = NULL; // XXXX set error return -1; } self->obj->const_dvalue = (double *) cvalue.data; self->const_dvalue_obj = cvalue.obj; // steal reference return 0; } static PyGetSetDef PY_Cstruct_ptr_getset[] = { {(char *)"cfield", (getter)PY_Cstruct_ptr_cfield_getter, (setter)PY_Cstruct_ptr_cfield_setter, NULL, NULL}, {(char *)"const_dvalue", (getter)PY_Cstruct_ptr_const_dvalue_getter, (setter)PY_Cstruct_ptr_const_dvalue_setter, NULL, NULL}, // splicer begin class.Cstruct_ptr.PyGetSetDef // splicer end class.Cstruct_ptr.PyGetSetDef {NULL} /* sentinel */ }; static PyMethodDef PY_Cstruct_ptr_methods[] = { // splicer begin class.Cstruct_ptr.PyMethodDef // splicer end class.Cstruct_ptr.PyMethodDef {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */ }; static char Cstruct_ptr__doc__[] = "virtual class" ; /* static */ PyTypeObject PY_Cstruct_ptr_Type = { PyVarObject_HEAD_INIT(NULL, 0) "cstruct.Cstruct_ptr", /* tp_name */ sizeof(PY_Cstruct_ptr), /* tp_basicsize */ 0, /* tp_itemsize */ /* Methods to implement standard operations */ (destructor)NULL, /* tp_dealloc */ (printfunc)NULL, /* tp_print */ (getattrfunc)NULL, /* tp_getattr */ (setattrfunc)NULL, /* tp_setattr */ #if PY_MAJOR_VERSION >= 3 NULL, /* tp_reserved */ #else (cmpfunc)NULL, /* tp_compare */ #endif (reprfunc)NULL, /* tp_repr */ /* Method suites for standard classes */ NULL, /* tp_as_number */ NULL, /* tp_as_sequence */ NULL, /* tp_as_mapping */ /* More standard operations (here for binary compatibility) */ (hashfunc)NULL, /* tp_hash */ (ternaryfunc)NULL, /* tp_call */ (reprfunc)NULL, /* tp_str */ (getattrofunc)NULL, /* tp_getattro */ (setattrofunc)NULL, /* tp_setattro */ /* Functions to access object as input/output buffer */ NULL, /* tp_as_buffer */ /* Flags to define presence of optional/expanded features */ Py_TPFLAGS_DEFAULT, /* tp_flags */ Cstruct_ptr__doc__, /* tp_doc */ /* Assigned meaning in release 2.0 */ /* call function for all accessible objects */ (traverseproc)NULL, /* tp_traverse */ /* delete references to contained objects */ (inquiry)NULL, /* tp_clear */ /* Assigned meaning in release 2.1 */ /* rich comparisons */ (richcmpfunc)NULL, /* tp_richcompare */ /* weak reference enabler */ 0, /* tp_weaklistoffset */ /* Added in release 2.2 */ /* Iterators */ (getiterfunc)NULL, /* tp_iter */ (iternextfunc)NULL, /* tp_iternext */ /* Attribute descriptor and subclassing stuff */ PY_Cstruct_ptr_methods, /* tp_methods */ NULL, /* tp_members */ PY_Cstruct_ptr_getset, /* tp_getset */ NULL, /* tp_base */ NULL, /* tp_dict */ (descrgetfunc)NULL, /* tp_descr_get */ (descrsetfunc)NULL, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)PY_Cstruct_ptr_tp_init, /* tp_init */ (allocfunc)NULL, /* tp_alloc */ (newfunc)NULL, /* tp_new */ (freefunc)NULL, /* tp_free */ (inquiry)NULL, /* tp_is_gc */ NULL, /* tp_bases */ NULL, /* tp_mro */ NULL, /* tp_cache */ NULL, /* tp_subclasses */ NULL, /* tp_weaklist */ (destructor)PY_Cstruct_ptr_tp_del, /* tp_del */ 0, /* tp_version_tag */ #if PY_MAJOR_VERSION >= 3 (destructor)NULL, /* tp_finalize */ #endif };
package com.lacolinares.jetpicexpress.util.navigation import android.app.Activity import androidx.compose.animation.* import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.tween import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.runtime.Composable import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavBackStackEntry import androidx.navigation.NavDeepLink import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.compose.NamedNavArgument import androidx.navigation.compose.navArgument import com.google.accompanist.navigation.animation.AnimatedNavHost import com.google.accompanist.navigation.animation.composable import com.google.accompanist.navigation.animation.rememberAnimatedNavController import com.lacolinares.jetpicexpress.presentation.ui.about.AboutScreen import com.lacolinares.jetpicexpress.presentation.ui.editimage.EditImageScreen import com.lacolinares.jetpicexpress.presentation.ui.editimage.EditImageViewModel import com.lacolinares.jetpicexpress.presentation.ui.home.HomeScreen import com.lacolinares.jetpicexpress.presentation.ui.savedimage.SavedImageScreen import com.lacolinares.jetpicexpress.presentation.ui.splash.SplashScreen import com.lacolinares.jetpicexpress.presentation.ui.viewimages.ViewImagesScreen import com.lacolinares.jetpicexpress.presentation.ui.viewimages.ViewImagesViewModel import com.lacolinares.jetpicexpress.util.FileHelper private const val PARAM_IMAGE_NAME = "imgName" @ExperimentalFoundationApi @ExperimentalMaterialApi @OptIn(ExperimentalAnimationApi::class) @Composable fun Navigation( activity: Activity, fileHelper: FileHelper, ) { val navController = rememberAnimatedNavController() val navigator = AppNavigator( activity = activity, navController = navController ) AnimatedNavHost( navController = navController, startDestination = Screen.SplashScreen.route ) { customComposable(Screen.SplashScreen.route) { SplashScreen(navigator = navigator) } customComposable(Screen.HomeScreen.route) { HomeScreen(navigator = navigator) } customComposable(Screen.AboutScreen.route){ AboutScreen(navigator = navigator) } customComposable(Screen.ViewImagesScreen.route) { val viewImagesViewModel = hiltViewModel<ViewImagesViewModel>() ViewImagesScreen(viewModel = viewImagesViewModel, navigator = navigator, fileHelper = fileHelper) } customComposable(Screen.EditImageScreen.route) { val editImageViewModel = hiltViewModel<EditImageViewModel>() EditImageScreen(viewModel = editImageViewModel, navigator = navigator) } customComposable( route = "${Screen.SavedFilterImageScreen.route}/{$PARAM_IMAGE_NAME}", arguments = listOf( navArgument(PARAM_IMAGE_NAME) { type = NavType.StringType defaultValue = "empty" } ) ) { entry -> val imageName = entry.arguments?.getString(PARAM_IMAGE_NAME).orEmpty() SavedImageScreen(savedImageName = imageName, navigator = navigator, fileHelper = fileHelper) } } } @ExperimentalAnimationApi private fun NavGraphBuilder.customComposable( route: String, arguments: List<NamedNavArgument> = emptyList(), deepLinks: List<NavDeepLink> = emptyList(), content: @Composable (NavBackStackEntry) -> Unit ) { val offSetX = 300 composable( route = route, arguments = arguments, deepLinks = deepLinks, enterTransition = { _, _ -> slideInHorizontally( initialOffsetX = { offSetX }, animationSpec = tween( durationMillis = offSetX, easing = FastOutSlowInEasing ) ) + fadeIn(animationSpec = tween(offSetX)) }, exitTransition = { _, _ -> slideOutHorizontally( targetOffsetX = { -offSetX }, animationSpec = tween( durationMillis = offSetX, easing = FastOutSlowInEasing ) ) + fadeOut(animationSpec = tween(offSetX)) }, popEnterTransition = { _, _ -> slideInHorizontally( initialOffsetX = { -offSetX }, animationSpec = tween( durationMillis = 300, easing = FastOutSlowInEasing ) ) + fadeIn(animationSpec = tween(offSetX)) }, popExitTransition = { _, _ -> slideOutHorizontally( targetOffsetX = { offSetX }, animationSpec = tween( durationMillis = offSetX, easing = FastOutSlowInEasing ) ) + fadeOut(animationSpec = tween(offSetX)) } ) { content.invoke(it) } }
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; using Split.Models; namespace split.Migrations { [DbContext(typeof(SplitContext))] [Migration("20200304072331_InitialMigration")] partial class InitialMigration { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Npgsql:Enum:categorytype", "income,expense") .HasAnnotation("Npgsql:PostgresExtension:uuid-ossp", "'uuid-ossp', '', ''") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn) .HasAnnotation("ProductVersion", "2.1.4-rtm-31024") .HasAnnotation("Relational:MaxIdentifierLength", 63); modelBuilder.Entity("Split.Models.Account", b => { b.Property<Guid>("AccountId") .ValueGeneratedOnAdd() .HasColumnName("accountId") .HasDefaultValueSql("uuid_generate_v4()"); b.Property<string>("AccountName") .IsRequired() .HasColumnName("accountName") .HasColumnType("character varying(20)"); b.Property<int>("AccountType") .HasColumnName("accountType"); b.Property<decimal?>("Balance") .HasColumnName("balance") .HasColumnType("money"); b.Property<DateTime>("CreatedOn") .ValueGeneratedOnAdd() .HasColumnName("createdOn") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<decimal?>("Limit") .HasColumnName("limit") .HasColumnType("money"); b.Property<DateTime>("ModifiedOn") .ValueGeneratedOnAdd() .HasColumnName("modifiedOn") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<Guid>("UserId") .HasColumnName("userId"); b.HasKey("AccountId"); b.HasIndex("UserId"); b.ToTable("Account"); }); modelBuilder.Entity("Split.Models.Category", b => { b.Property<Guid>("CategoryId") .ValueGeneratedOnAdd() .HasColumnName("categoryId") .HasDefaultValueSql("uuid_generate_v4()"); b.Property<string>("CategoryName") .IsRequired() .HasColumnName("categoryName") .HasColumnType("character varying(25)"); b.Property<int>("CategoryType") .HasColumnName("categoryType"); b.Property<DateTime>("CreatedOn") .ValueGeneratedOnAdd() .HasColumnName("createdOn") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<DateTime>("ModifiedOn") .ValueGeneratedOnAdd() .HasColumnName("modifiedOn") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<Guid>("UserId") .HasColumnName("userId"); b.HasKey("CategoryId"); b.HasIndex("UserId"); b.ToTable("Category"); }); modelBuilder.Entity("Split.Models.SplitPayment", b => { b.Property<Guid>("SplitPaymentId") .ValueGeneratedOnAdd() .HasColumnName("splitPaymentId") .HasDefaultValueSql("uuid_generate_v4()"); b.Property<decimal>("Amount") .HasColumnName("amount") .HasColumnType("money"); b.Property<DateTime>("CreatedOn") .ValueGeneratedOnAdd() .HasColumnName("createdOn") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<DateTime>("ModifiedOn") .ValueGeneratedOnAdd() .HasColumnName("modifiedOn") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<Guid>("PayeeId") .HasColumnName("payeeId"); b.Property<Guid>("TransactionId") .HasColumnName("transactionId"); b.HasKey("SplitPaymentId"); b.HasIndex("PayeeId"); b.HasIndex("TransactionId"); b.ToTable("SplitPayment"); }); modelBuilder.Entity("Split.Models.Transaction", b => { b.Property<Guid>("TransactionId") .ValueGeneratedOnAdd() .HasColumnName("transactionId") .HasDefaultValueSql("uuid_generate_v4()"); b.Property<Guid?>("AccountInId") .HasColumnName("accountInId"); b.Property<Guid?>("AccountOutId") .HasColumnName("accountOutId"); b.Property<decimal?>("Amount") .HasColumnName("amount") .HasColumnType("money"); b.Property<Guid?>("CategoryId") .HasColumnName("categoryId"); b.Property<DateTime>("CreatedOn") .ValueGeneratedOnAdd() .HasColumnName("createdOn") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<bool>("IsShared") .HasColumnName("isShared"); b.Property<DateTime>("ModifiedOn") .ValueGeneratedOnAdd() .HasColumnName("modifiedOn") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<DateTime>("TransactionDate") .ValueGeneratedOnAdd() .HasColumnName("transactionDate") .HasColumnType("date") .HasDefaultValueSql("CURRENT_DATE"); b.Property<Guid?>("TransactionPartyId") .HasColumnName("transactionPartyId"); b.Property<Guid?>("UserId") .HasColumnName("userId"); b.HasKey("TransactionId"); b.HasIndex("AccountInId"); b.HasIndex("AccountOutId"); b.HasIndex("CategoryId"); b.HasIndex("TransactionPartyId"); b.HasIndex("UserId"); b.ToTable("Transaction"); }); modelBuilder.Entity("Split.Models.TransactionParty", b => { b.Property<Guid>("TransactionPartyId") .ValueGeneratedOnAdd() .HasColumnName("transactionPartyId") .HasDefaultValueSql("uuid_generate_v4()"); b.Property<DateTime>("CreatedOn") .ValueGeneratedOnAdd() .HasColumnName("createdOn") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<Guid?>("DefaultCategoryId") .HasColumnName("defaultCategoryId"); b.Property<DateTime>("ModifiedOn") .ValueGeneratedOnAdd() .HasColumnName("modifiedOn") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<string>("TransactionPartyName") .IsRequired() .HasColumnName("transactionPartyName") .HasColumnType("character varying(25)"); b.Property<Guid?>("UserId") .HasColumnName("userId"); b.HasKey("TransactionPartyId"); b.HasIndex("DefaultCategoryId"); b.HasIndex("UserId"); b.ToTable("TransactionParty"); }); modelBuilder.Entity("Split.Models.User", b => { b.Property<Guid>("UserId") .ValueGeneratedOnAdd() .HasColumnName("userId") .HasDefaultValueSql("uuid_generate_v4()"); b.Property<bool?>("ConfirmedEmail") .ValueGeneratedOnAdd() .HasColumnName("confirmedEmail") .HasDefaultValueSql("false"); b.Property<DateTime>("CreatedOn") .ValueGeneratedOnAdd() .HasColumnName("createdOn") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<string>("Email") .IsRequired() .HasColumnName("email") .HasColumnType("character varying(50)"); b.Property<string>("FirstName") .HasColumnName("firstName") .HasColumnType("character varying(50)"); b.Property<bool?>("IsRegistered") .ValueGeneratedOnAdd() .HasColumnName("isRegistered") .HasDefaultValueSql("true"); b.Property<DateTime?>("LastLogin") .HasColumnName("lastLogin") .HasColumnType("timestamp with time zone"); b.Property<string>("LastName") .HasColumnName("lastName") .HasColumnType("character varying(50)"); b.Property<DateTime>("ModifiedOn") .ValueGeneratedOnAdd() .HasColumnName("modifiedOn") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<byte[]>("PasswordHash") .HasColumnName("passwordHash"); b.Property<byte[]>("PasswordSalt") .HasColumnName("passwordSalt"); b.HasKey("UserId"); b.HasIndex("Email") .IsUnique() .HasName("User_email_key"); b.ToTable("User"); }); modelBuilder.Entity("Split.Models.UserContact", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("id") .HasDefaultValueSql("uuid_generate_v4()"); b.Property<Guid?>("ContactId") .HasColumnName("contactId"); b.Property<DateTime>("CreatedOn") .ValueGeneratedOnAdd() .HasColumnName("createdOn") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<DateTime>("ModifiedOn") .ValueGeneratedOnAdd() .HasColumnName("modifiedOn") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("CURRENT_TIMESTAMP"); b.Property<string>("Name") .HasColumnName("name") .HasColumnType("character varying(30)"); b.Property<Guid?>("UserId") .HasColumnName("userId"); b.HasKey("Id"); b.HasIndex("ContactId"); b.HasIndex("UserId"); b.ToTable("UserContact"); }); modelBuilder.Entity("Split.Models.Account", b => { b.HasOne("Split.Models.User", "User") .WithMany("Account") .HasForeignKey("UserId") .HasConstraintName("Account_userId_fkey") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Split.Models.Category", b => { b.HasOne("Split.Models.User", "User") .WithMany("Category") .HasForeignKey("UserId") .HasConstraintName("Category_userId_fkey") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Split.Models.SplitPayment", b => { b.HasOne("Split.Models.User", "Payee") .WithMany("SplitPayment") .HasForeignKey("PayeeId") .HasConstraintName("SplitPayment_payeeId_fkey") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Split.Models.Transaction", "Transaction") .WithMany("SplitPayment") .HasForeignKey("TransactionId") .HasConstraintName("SplitPayment_transactionId_fkey") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Split.Models.Transaction", b => { b.HasOne("Split.Models.Account", "AccountIn") .WithMany("TransactionAccountIn") .HasForeignKey("AccountInId") .HasConstraintName("Transaction_accountInId_fkey"); b.HasOne("Split.Models.Account", "AccountOut") .WithMany("TransactionAccountOut") .HasForeignKey("AccountOutId") .HasConstraintName("Transaction_accountOutId_fkey"); b.HasOne("Split.Models.Category", "Category") .WithMany("Transaction") .HasForeignKey("CategoryId") .HasConstraintName("Transaction_categoryId_fkey") .OnDelete(DeleteBehavior.SetNull); b.HasOne("Split.Models.TransactionParty", "TransactionParty") .WithMany("Transaction") .HasForeignKey("TransactionPartyId") .HasConstraintName("Transaction_transactionPartyId_fkey") .OnDelete(DeleteBehavior.SetNull); b.HasOne("Split.Models.User", "User") .WithMany("Transaction") .HasForeignKey("UserId") .HasConstraintName("Transaction_userId_fkey") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Split.Models.TransactionParty", b => { b.HasOne("Split.Models.Category", "DefaultCategory") .WithMany("TransactionParty") .HasForeignKey("DefaultCategoryId") .HasConstraintName("TransactionParty_defaultCategoryId_fkey") .OnDelete(DeleteBehavior.SetNull); b.HasOne("Split.Models.User", "User") .WithMany("TransactionParty") .HasForeignKey("UserId") .HasConstraintName("TransactionParty_userId_fkey") .OnDelete(DeleteBehavior.SetNull); }); modelBuilder.Entity("Split.Models.UserContact", b => { b.HasOne("Split.Models.User", "Contact") .WithMany("UserContactContact") .HasForeignKey("ContactId") .HasConstraintName("UserContact_contactId_fkey") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Split.Models.User", "User") .WithMany("UserContactUser") .HasForeignKey("UserId") .HasConstraintName("UserContact_userId_fkey") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
#include "ComboBox.h" bool comboSelectItem(QComboBox* combo, const QVariant& value) { int n = combo->count(); for (int i = 0; i < n; i++) { if (combo->itemData(i) == value) { combo->setCurrentIndex(i); return true; } } return false; } QVariant comboSelectedItem(const QComboBox* combo) { int selected = combo->currentIndex(); return (selected < 0 ? QVariant() : combo->itemData(selected)); }
#!/bin/bash SESSION_BUS="org.workrave.Workrave" METHOD_ROOT="/org/workrave/Workrave" CORE_INTERFACE="$METHOD_ROOT/Core org.workrave.CoreInterface" CONTROL_INTERFACE="$METHOD_ROOT/UI org.workrave.ControlInterface" APPLET_INTERFACE="$METHOD_ROOT/UI org.workrave.AppletInterface" CONFIG_INTERFACE="$METHOD_ROOT/Core org.workrave.ConfigInterface" try() { if [ -z "$1" ]; then exit fi if ! ret=$(qdbus $SESSION_BUS $@) ; then kdialog --error "$(echo "$ERROR\n$@")" clean_up kill $$ fi echo $ret } seconds_to_readable() { local secs="$1" h=$((secs/3600)) m=$((secs%3600/60)) s=$((secs%60)) if [ "$h" -gt 0 ]; then printf "%02d:" "$h" fi printf "%02d:%02d" "$m" "$s" } progress() { local _status=$1 local _total=$2 local _progress=$(((_status*100/_total*100)/100)) local _done=$(((_progress*4)/10)) local _left=$((40-_done)) _done=$(printf "%${_done}s") _left=$(printf "%${_left}s") printf "[${_done// /=}${_left// / }]" } restbreak_limit="$(try "$CONFIG_INTERFACE.GetInt" "timers/rest_break/limit" |tr -d [:blank:][:alpha:])" restbreak_current="$(try "$CORE_INTERFACE.GetTimerElapsed" "restbreak")" next_restbreak=$((restbreak_limit - restbreak_current)) if [ $restbreak_current -gt 0 -a $restbreak_current -lt $restbreak_limit ]; then echo "$(progress $restbreak_current $restbreak_limit) $(seconds_to_readable "$next_restbreak")" else echo "Break time!" fi
package com.github.prologdb.async import io.kotlintest.matchers.beGreaterThanOrEqualTo import io.kotlintest.matchers.should import io.kotlintest.matchers.shouldBe import io.kotlintest.matchers.shouldThrow import io.kotlintest.specs.FreeSpec import java.util.* import java.util.concurrent.CompletableFuture import kotlin.concurrent.thread class WorkableFutureTest : FreeSpec({ "immediate return" { val hasRun = CompletableFuture<Unit>() val future = WorkableFutureImpl(RANDOM_PRINCIPAL) { hasRun.complete(Unit) "foobar" } hasRun.isDone shouldBe false future.step() hasRun.isDone shouldBe true future.isDone shouldBe true future.get() shouldBe "foobar" } "immediate throw" { val hasRun = CompletableFuture<Unit>() val future = WorkableFutureImpl(RANDOM_PRINCIPAL) { hasRun.complete(Unit) throw Exception("Faiiilleeeed!!!") } hasRun.isDone shouldBe false future.step() hasRun.isDone shouldBe true shouldThrow<Exception> { future.get() } } "wait for another future step-by-step successfully" { val hasStarted = CompletableFuture<Unit>() val returnedAfterWait = CompletableFuture<Unit>() val waitingOn = CompletableFuture<String>() val future = WorkableFutureImpl(RANDOM_PRINCIPAL) { hasStarted.complete(Unit) val result = await(waitingOn) returnedAfterWait.complete(Unit) result } // initial state future.isDone shouldBe false hasStarted.isDone shouldBe false returnedAfterWait.isDone shouldBe false // test that await(T) suspends future.step() future.isDone shouldBe false hasStarted.isDone shouldBe true returnedAfterWait.isDone shouldBe false // test that step() does not resume the coroutine // unless its completed future.step() future.isDone shouldBe false returnedAfterWait.isDone shouldBe false // test that await() correctly forwards the result // of the awaited future val value = "Hello World!!" waitingOn.complete(value) // unless step() is called again, the future should // not move ahead future.isDone shouldBe false returnedAfterWait.isDone shouldBe false future.step() // completion future.isDone shouldBe true returnedAfterWait.isDone shouldBe true future.get() shouldBe value } "wait for another future step-by-step exceptionally" { val hasStarted = CompletableFuture<Unit>() val waitingOn = CompletableFuture<String>() val future = WorkableFutureImpl(RANDOM_PRINCIPAL) { hasStarted.complete(Unit) try { await(waitingOn) Unit } catch (ex: Throwable) { ex } } future.step() future.isDone shouldBe false hasStarted.isDone shouldBe true future.step() future.isDone shouldBe false waitingOn.isCompletedExceptionally shouldBe false val error = Exception("faiiil!") waitingOn.completeExceptionally(error) future.isDone shouldBe false future.isCancelled shouldBe false future.step() future.isDone shouldBe true future.isCancelled shouldBe false future.get() shouldBe error } "await exception should not complete the future" { val waitingOn = CompletableFuture<Unit>() val caught = CompletableFuture<Throwable>() val future = WorkableFutureImpl(RANDOM_PRINCIPAL) { try { await(waitingOn) } catch (ex: Throwable) { caught.complete(ex) } "All fine" } val error = Exception("faaaaaaiiiilllllllll") future.step() waitingOn.completeExceptionally(error) future.step() caught.isDone shouldBe true caught.get() shouldBe error future.get() shouldBe "All fine" } "await completed does not suspend" { val waitingOn = CompletableFuture<Unit>() waitingOn.complete(Unit) val future = WorkableFutureImpl(RANDOM_PRINCIPAL) { await(waitingOn) "Done" } future.step() future.isDone shouldBe true future.get() shouldBe "Done" } "get waits on await future" { val waitingOn = CompletableFuture<Unit>() val future = WorkableFutureImpl(RANDOM_PRINCIPAL) { await(waitingOn) "Done" } val earliestStart = System.currentTimeMillis() thread { Thread.sleep(200) waitingOn.complete(Unit) } future.get() shouldBe "Done" val completedAt = System.currentTimeMillis() (completedAt - earliestStart) should beGreaterThanOrEqualTo(200L) } "await workable future" { val stepOneCompleted = CompletableFuture<Unit>() val blockerAfterStepOne = CompletableFuture<String>() val principal = RANDOM_PRINCIPAL val waitingOn = WorkableFutureImpl(principal) { stepOneCompleted.complete(Unit) await(blockerAfterStepOne) } val future = WorkableFutureImpl(principal) { await(waitingOn) } future.isDone shouldBe false future.step() future.isDone shouldBe false stepOneCompleted.isDone shouldBe false future.step() future.isDone shouldBe false stepOneCompleted.isDone shouldBe true waitingOn.isDone shouldBe false future.step() future.isDone shouldBe false waitingOn.isDone shouldBe false blockerAfterStepOne.complete("Fuzz") future.isDone shouldBe false waitingOn.isDone shouldBe false future.step() future.isDone shouldBe true future.get() shouldBe "Fuzz" } "finally" - { "on error" { val finallyExecutions = mutableListOf<Int>() val workableFuture = launchWorkableFuture(UUID.randomUUID()) { val completedFuture1 = CompletableFuture<Unit>() completedFuture1.complete(Unit) val erroredFuture1 = CompletableFuture<Unit>() erroredFuture1.completeExceptionally(Exception("ERROR!")) await(completedFuture1) finally { finallyExecutions.add(1) } finally { finallyExecutions.add(2) } awaitAndFinally(erroredFuture1) { finallyExecutions.add(3) } finally { finallyExecutions.add(4) } } shouldThrow<Exception> { workableFuture.get() } finallyExecutions shouldBe listOf(3, 2, 1) } "on success" { val finallyExecutions = mutableListOf<Int>() val workableFuture = launchWorkableFuture(UUID.randomUUID()) { val completedFuture1 = CompletableFuture<Unit>() completedFuture1.complete(Unit) finally { finallyExecutions.add(1) } awaitAndFinally(completedFuture1) { finallyExecutions.add(2) } finally { finallyExecutions.add(3) } } workableFuture.get() finallyExecutions shouldBe listOf(3, 2, 1) } } "folding" { val principal = RANDOM_PRINCIPAL val foldable = buildLazySequence<Int>(principal) { yield(1) yield(2) yield(3) yield(5) yield(102) } val future = WorkableFutureImpl(principal) { foldRemaining(foldable, 0, Int::plus) + 4 } future.step() shouldBe false future.step() shouldBe false future.step() shouldBe false future.step() shouldBe false future.step() shouldBe false future.step() shouldBe false future.step() shouldBe true future.get() shouldBe 1 + 2 + 3 + 5 + 102 + 4 } })
import execa from 'execa' import fs from 'fs-extra' import Listr from 'listr' import ncu from 'npm-check-updates' import { IProjectJson } from '..' import { writeToDest } from './copy' export const run = async ( srcDir: string, destDir: string, result: IProjectJson, isWorkSpace: boolean = false, spaceName: string = '' ) => { if (isWorkSpace) { const tasks = new Listr([ { title: 'copy templates to workspaces', task: async () => { await writeToDest(srcDir, destDir, result, spaceName) }, }, { title: 'update pkgs to latest version', task: async () => { const newPkg = await ncu.run({ packageData: fs.readFileSync(`${destDir}/package.json`, 'utf-8'), jsonAll: true, }) fs.writeJSONSync(`${destDir}/package.json`, newPkg, { spaces: 2, encoding: 'utf-8', }) }, }, ]) try { await tasks.run() } catch (errs) { console.log(errs) } } else { const tasks = new Listr([ { title: 'generate project', task: async () => { await writeToDest(srcDir, destDir, result) }, }, { title: 'update pkgs to latest version', task: async () => { const newPkg = await ncu.run({ packageData: fs.readFileSync(`${destDir}/package.json`, 'utf-8'), jsonAll: true, }) fs.writeJSONSync(`${destDir}/package.json`, newPkg, { spaces: 2, encoding: 'utf-8', }) }, }, { title: 'Install package dependencies with Yarn', task: (ctx, task) => execa('yarn', { cwd: destDir, }).catch(() => { ctx.yarn = false task.skip( 'Yarn not available, install it via `npm install -g yarn`' ) }), }, { title: 'Install package dependencies with npm', enabled: ctx => ctx.yarn === false, task: () => execa('npm', ['install'], { cwd: destDir, }), }, ]) try { await tasks.run() } catch (errs) { console.log(errs) } } }
<?php declare(strict_types=1); namespace GabrielDeTassigny\Blog\Tests\Controller\Admin; use GabrielDeTassigny\Blog\Controller\Admin\BlogInfoController; use GabrielDeTassigny\Blog\Service\Authentication\AdminAuthenticator; use GabrielDeTassigny\Blog\Service\BlogInfoService; use Phake; use Phake_IMock; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ServerRequestInterface; use Teapot\HttpException; use Teapot\StatusCode; use Twig\Environment; class BlogInfoControllerTest extends TestCase { private const BLOG_TITLE = 'Blog Title'; private const BLOG_DESCRIPTION = 'blog description'; private const ABOUT_TEXT = 'about text'; private const SUCCESS_MESSAGE = 'Blog Configuration successfully updated!'; /** @var BlogInfoService|Phake_IMock */ private $blogInfoService; /** @var Environment|Phake_IMock */ private $twig; /** @var AdminAuthenticator|Phake_IMock */ private $authenticationService; /** @var BlogInfoController */ private $controller; /** @var ServerRequestInterface|Phake_IMock */ private $request; /** * {@inheritdoc} */ public function setUp(): void { $this->twig = Phake::mock(Environment::class); $this->authenticationService = Phake::mock(AdminAuthenticator::class); $this->blogInfoService = Phake::mock(BlogInfoService::class); $this->request = Phake::mock(ServerRequestInterface::class); $this->controller = new BlogInfoController( $this->twig, $this->blogInfoService, $this->authenticationService, $this->request ); } public function testEdit(): void { Phake::when($this->authenticationService)->authenticateAsAdmin()->thenReturn(true); Phake::when($this->blogInfoService)->getBlogTitle()->thenReturn(self::BLOG_TITLE); Phake::when($this->blogInfoService)->getBlogDescription()->thenReturn(self::BLOG_DESCRIPTION); Phake::when($this->blogInfoService)->getAboutText()->thenReturn(self::ABOUT_TEXT); $this->controller->edit(); Phake::verify($this->twig)->display( 'blog-info/edit.twig', ['title' => self::BLOG_TITLE, 'description' => self::BLOG_DESCRIPTION, 'about' => self::ABOUT_TEXT] ); } public function testEdit_ForbiddenAccess(): void { $this->expectException(HttpException::class); $this->expectExceptionCode(StatusCode::UNAUTHORIZED); $this->controller->edit(); } public function testUpdate_ForbiddenAccess(): void { $this->expectException(HttpException::class); $this->expectExceptionCode(StatusCode::UNAUTHORIZED); $this->controller->update(); } public function testUpdate_InvalidParams(): void { $this->expectException(HttpException::class); $this->expectExceptionCode(StatusCode::BAD_REQUEST); Phake::when($this->authenticationService)->authenticateAsAdmin()->thenReturn(true); $this->controller->update(); } public function testUpdate(): void { Phake::when($this->authenticationService)->authenticateAsAdmin()->thenReturn(true); Phake::when($this->request)->getParsedBody()->thenReturn( [ 'blog' => [ 'title' => self::BLOG_TITLE, 'description' => self::BLOG_DESCRIPTION, 'about' => self::ABOUT_TEXT ] ] ); $this->controller->update(); Phake::verify($this->twig)->display( 'blog-info/edit.twig', [ 'title' => self::BLOG_TITLE, 'description' => self::BLOG_DESCRIPTION, 'about' => self::ABOUT_TEXT, 'success' => self::SUCCESS_MESSAGE ] ); } }
import { getCurrentHub } from '@sentry/core'; import { flush } from '@sentry/node'; import { Integration, SessionStatus } from '@sentry/types'; import { app } from 'electron'; /** Tracks sessions as the main process lifetime. */ export class MainProcessSession implements Integration { /** @inheritDoc */ public static id: string = 'MainProcessSession'; /** @inheritDoc */ public name: string = MainProcessSession.id; /** @inheritDoc */ public setupOnce(): void { const hub = getCurrentHub(); hub.startSession(); // We track sessions via the 'will-quit' event which is the last event emitted before close. // // We need to be the last 'will-quit' listener so as not to interfere with any user defined listeners which may // call `event.preventDefault()`. this._ensureExitHandlerLast(); // 'before-quit' is always called before 'will-quit' so we listen there and ensure our 'will-quit' handler is still // the last listener app.on('before-quit', () => { this._ensureExitHandlerLast(); }); } /** * Hooks 'will-quit' and ensures the handler is always last */ private _ensureExitHandlerLast(): void { app.removeListener('will-quit', this._exitHandler); app.on('will-quit', this._exitHandler); } /** Handles the exit */ private _exitHandler: (event: Electron.Event) => Promise<void> = async (event: Electron.Event) => { // Stop the exit so we have time to send the session event.preventDefault(); const hub = getCurrentHub(); const session = hub.getScope()?.getSession(); const terminalStates = [SessionStatus.Exited, SessionStatus.Crashed]; if (session && !terminalStates.includes(session.status)) { hub.endSession(); } await flush(); // After flush we can safely exit app.exit(); }; } /** Sets the current session as crashed */ export function sessionCrashed(): void { const hub = getCurrentHub(); const session = hub.getScope()?.getSession(); session?.update({ status: SessionStatus.Crashed, errors: (session.errors += 1) }); }
# encoding: utf-8 require 'digest/sha1' class Invite < ActiveRecord::Base belongs_to :user validates_presence_of :email, :user_id attr_accessor :used DEFAULT_EXPIRATION = 14.days validate :validate_email_registered before_create :set_token before_create :set_expires_at after_create :revoke_invite before_destroy :grant_invite class << self # Makes a unique random token. def unique_token token = nil token = Digest::SHA1.hexdigest(rand(65535).to_s + Time.now.to_s) until token && !self.exists?(:token => token) token end def find_by_token(token) self.where(:token => token).first end # Gets the default expiration time. def expiration_time DEFAULT_EXPIRATION end # Finds valid invites def find_active self.find(:all, :conditions => ['expires_at >= ?', Time.now], :order => 'created_at DESC', :include => [:user]) end # Finds expired invites def find_expired self.find(:all, :conditions => ['expires_at < ?', Time.now], :order => 'created_at DESC') end # Deletes expired invites def destroy_expired! self.find_expired.each do |invite| invite.destroy end end end # Has this invite expired? def expired? (Time.now <= self.expires_at) ? false : true end # Expire this invite def expire! self.used = true self.destroy end private def revoke_invite self.user.revoke_invite! end def grant_invite self.user.grant_invite! unless self.used end def set_token self.token ||= Invite.unique_token end def set_expires_at self.expires_at ||= Time.now + Invite.expiration_time end def validate_email_registered if User.exists?(:email => self.email) self.errors.add(:email, 'is already registered!') end if Invite.find_active.select{|i| i != self && i.email == self.email }.length > 0 self.errors.add(:email, 'has already been invited!') end end end
using System; using System.Collections.Generic; using System.Text; namespace SistemaSolar { enum Planets { Mercury, Venus, Earth, Mars, Jupiter, Saturn, Neptune, Uranus, Pluton } public struct Position { public float x; public float y; public float z; public Position(int x,int y, int z) { this.x = x; this.y = y; this.z = z; } } public class SolarSystem { Camara camara = new Camara(); Star estrella = new Star(); Sun sol = new Sun(); List<Planet> planetas = new List<Planet>(); public void CreateScene() { planetas.Add(new Planet(0.5f, Planets.Mercury, new Position(5, 0, 0), "mercurio.jpg",false)); planetas.Add(new Planet(0.7f, Planets.Venus, new Position(11, 0, 0), "venus.jpg", false)); planetas.Add(new Planet(1, Planets.Earth, new Position(15, 0, 0), "tierra.jpg", true)); planetas.Add(new Planet(1, Planets.Mars, new Position(22, 0, 0), "marte.jpg", false)); planetas.Add(new Planet(1.5f, Planets.Jupiter, new Position(28, 0, 0), "jupiter.jpg", false)); planetas.Add(new Planet(1.2f, Planets.Saturn, new Position(35, 0, 0), "saturno.bmp", false)); planetas.Add(new Planet(1.2f, Planets.Uranus, new Position(41, 0, 0), "urano.jpg", false)); planetas.Add(new Planet(1.2f, Planets.Neptune, new Position(51, 0, 0), "restantes.jpg", false)); planetas.Add(new Planet(1.2f, Planets.Pluton, new Position(60, 0, 0), "restantes.jpg", false)); estrella.CreateStars(500); sol.Create(); foreach (var item in planetas) { item.Create(); } } public Camara Camara { get { return camara; } } public void DrawScene() { estrella.Draw(); sol.Paint(); foreach (var item in planetas) { item.Paint(); } } } }
import { useControl } from '../hooks' import { Wrapper, RadioContainer, LabelContainer, RadioInput, StyledRadio } from './styles' import { GroupProps } from './Group' import React, { FC } from 'react' export type RadioProps = { checked?: boolean onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void style?: React.CSSProperties & object disabled?: boolean value?: string } type RadioFC<P> = FC<P> & { Group?: FC<GroupProps> Button?: FC<P> } const Radio: RadioFC<RadioProps> = React.forwardRef< HTMLInputElement, RadioProps >( ( { children, checked: checkedProps, onChange: onChangeProps, style, disabled, ...props }, ref ) => { const onChange = (e: React.ChangeEvent<HTMLInputElement>) => { if (onChangeProps) onChangeProps(e) return e.target.checked } const { value: checked, setValue: setChecked } = useControl({ value: checkedProps, defaultValue: false, onChange: onChange as (newValue: unknown) => unknown }) as { value: boolean setValue: (event: React.ChangeEvent<HTMLInputElement>) => void } const radioNode = ( <RadioContainer> <RadioInput type='radio' checked={checked} onChange={setChecked} disabled={disabled} {...props} ref={ref} /> <StyledRadio checked={checked} disabled={disabled} /> </RadioContainer> ) const labelNode = React.Children.count(children) ? ( <LabelContainer>{children}</LabelContainer> ) : null return ( <Wrapper style={style} disabled={disabled}> {radioNode} {labelNode} </Wrapper> ) } ) export { Radio }
# termanteus.com #### Special thanks A very big thanks to tiulpin and broccolini.
--- layout: custom_category author_profile: true title: Linux permalink: /categories/linux/ header: image: assets/images/banner.jpg ---
// Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved. package jodd.json; import jodd.datetime.JDateTime; import jodd.introspector.ClassDescriptor; import jodd.introspector.ClassIntrospector; import jodd.json.impl.ArraysJsonSerializer; import jodd.json.impl.BooleanArrayJsonSerializer; import jodd.json.impl.BooleanJsonSerializer; import jodd.json.impl.ByteArrayJsonSerializer; import jodd.json.impl.CalendarJsonSerializer; import jodd.json.impl.CharSequenceJsonSerializer; import jodd.json.impl.CharacterJsonSerializer; import jodd.json.impl.ClassJsonSerializer; import jodd.json.impl.DateJsonSerializer; import jodd.json.impl.DoubleArrayJsonSerializer; import jodd.json.impl.EnumJsonSerializer; import jodd.json.impl.FloatArrayJsonSerializer; import jodd.json.impl.IntArrayJsonSerializer; import jodd.json.impl.IterableJsonSerializer; import jodd.json.impl.JDateTimeSerializer; import jodd.json.impl.LongArrayJsonSerializer; import jodd.json.impl.MapJsonSerializer; import jodd.json.impl.NumberJsonSerializer; import jodd.json.impl.ObjectJsonSerializer; import jodd.util.collection.ClassMap; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Map; /** * Map of {@link jodd.json.TypeJsonSerializer json type serializers}. */ public class TypeJsonSerializerMap { /** * Creates new serializers map and optionally registers defaults. */ public TypeJsonSerializerMap(boolean registerDefaults) { if (registerDefaults) { registerDefaults(); } } protected final ClassMap<TypeJsonSerializer> map = new ClassMap<TypeJsonSerializer>(); protected final ClassMap<TypeJsonSerializer> cache = new ClassMap<TypeJsonSerializer>(); /** * Registers default set of {@link jodd.json.TypeJsonSerializer serializers}. */ public void registerDefaults() { // main map.put(Object.class, new ObjectJsonSerializer()); map.put(Map.class, new MapJsonSerializer()); map.put(Iterable.class, new IterableJsonSerializer()); // arrays map.put(int[].class, new IntArrayJsonSerializer()); map.put(long[].class, new LongArrayJsonSerializer()); map.put(double[].class, new DoubleArrayJsonSerializer()); map.put(float[].class, new FloatArrayJsonSerializer()); map.put(boolean[].class, new BooleanArrayJsonSerializer()); map.put(byte[].class, new ByteArrayJsonSerializer()); map.put(Integer[].class, new ArraysJsonSerializer<Integer>() { @Override protected int getLength(Integer[] array) { return array.length; } @Override protected Integer get(Integer[] array, int index) { return array[index]; } }); map.put(Long[].class, new ArraysJsonSerializer<Long>() { @Override protected int getLength(Long[] array) { return array.length; } @Override protected Long get(Long[] array, int index) { return array[index]; } }); map.put(Arrays.class, new ArraysJsonSerializer()); // strings TypeJsonSerializer jsonSerializer = new CharSequenceJsonSerializer(); map.put(String.class, jsonSerializer); map.put(StringBuilder.class, jsonSerializer); map.put(CharSequence.class, jsonSerializer); // number jsonSerializer = new NumberJsonSerializer(); map.put(Number.class, jsonSerializer); map.put(Integer.class, jsonSerializer); map.put(int.class, jsonSerializer); map.put(Long.class, jsonSerializer); map.put(long.class, jsonSerializer); map.put(Double.class, jsonSerializer); map.put(double.class, jsonSerializer); map.put(Float.class, jsonSerializer); map.put(float.class, jsonSerializer); map.put(BigInteger.class, jsonSerializer); map.put(BigDecimal.class, jsonSerializer); // other map.put(Boolean.class, new BooleanJsonSerializer()); map.put(Date.class, new DateJsonSerializer()); map.put(Calendar.class, new CalendarJsonSerializer()); map.put(JDateTime.class, new JDateTimeSerializer()); map.put(Enum.class, new EnumJsonSerializer()); jsonSerializer = new CharacterJsonSerializer(); map.put(Character.class, jsonSerializer); map.put(char.class, jsonSerializer); map.put(Class.class, new ClassJsonSerializer()); // clear cache cache.clear(); } /** * Registers new serializer. */ public void register(Class type, TypeJsonSerializer typeJsonSerializer) { map.put(type, typeJsonSerializer); cache.clear(); } /** * Lookups for the {@link jodd.json.TypeJsonSerializer serializer} for given type. * If serializer not found, then all interfaces and subclasses of the type are checked. * Finally, if no serializer is found, object's serializer is returned. */ public TypeJsonSerializer lookup(Class type) { TypeJsonSerializer tjs = cache.unsafeGet(type); if (tjs != null) { return tjs; } tjs = _lookup(type); cache.put(type, tjs); return tjs; } protected TypeJsonSerializer _lookup(Class type) { synchronized (map) { TypeJsonSerializer tjs = map.unsafeGet(type); if (tjs != null) { return tjs; } ClassDescriptor cd = ClassIntrospector.lookup(type); // check array if (cd.isArray()) { return map.unsafeGet(Arrays.class); } // now iterate interfaces Class[] interfaces = cd.getAllInterfaces(); for (Class interfaze : interfaces) { tjs = map.unsafeGet(interfaze); if (tjs != null) { return tjs; } } // now iterate all superclases Class[] superclasses = cd.getAllSuperclasses(); for (Class clazz : superclasses) { tjs = map.unsafeGet(clazz); if (tjs != null) { return tjs; } } // nothing found, go with the Object return map.unsafeGet(Object.class); } } }
/*! * @author electricessence / https://github.com/electricessence/ * Licensing: MIT https://github.com/electricessence/TypeScript.NET/blob/master/LICENSE.md */ import {Type} from "../Types"; import {OrderedStringKeyDictionary} from "../Collections/Dictionaries/OrderedStringKeyDictionary"; import {isEnumerableOrArrayLike} from "../Collections/Enumeration/Enumerator"; import {UriComponent} from "./UriComponent"; import {QueryParam} from "./QueryParam"; import {encode, parse} from "./QueryParams"; import __extendsImport from "../../extends"; // noinspection JSUnusedLocalSymbols const __extends = __extendsImport; /** * Provides a means for parsing and building a set of parameters. * * In other languages, dictionaries are not reliable for retaining the order of stored values. So for certainty and flexibility we use an ordered dictionary as a base class. */ export class QueryBuilder extends OrderedStringKeyDictionary<UriComponent.Value|UriComponent.Value[]> { constructor( query:QueryParam.Convertible, decodeValues:boolean = true) { super(); this.importQuery(query, decodeValues); } static init( query:QueryParam.Convertible, decodeValues:boolean = true):QueryBuilder { return new QueryBuilder(query, decodeValues); } importQuery( query:QueryParam.Convertible, decodeValues:boolean = true):QueryBuilder { if(Type.isString(query)) { this.importFromString(<string>query, decodeValues); } else if(isEnumerableOrArrayLike(query)) { this.importEntries(query); } else { this.importMap(<UriComponent.Map>query); } return this; } /** * Property parses the components of an URI into their values or array of values. * @param values * @param deserialize * @param decodeValues * @returns {QueryBuilder} */ importFromString( values:string, deserialize:boolean = true, decodeValues:boolean = true):QueryBuilder { const _ = this; parse(values, (key, value)=> { if(_.containsKey(key)) { const prev = _.getValue(key); if((prev)instanceof(Array)) prev.push(value); else _.setValue(key, [<UriComponent.Value>prev, value]); } else _.setValue(key, value); }, deserialize, decodeValues); return this; } /** * Returns the encoded URI string */ encode(prefixIfNotEmpty?:boolean):string { return encode(this, prefixIfNotEmpty); } toString():string { return this.encode(); } } export default QueryBuilder;
import I18n from '../src' const mockedTranslations = { en: { hello: 'hello %{name}', not_translated: 'translate me!', beers: { one: '%{count} beer', other: '%{count} beers' }, role: { admin: 'admin', basic: 'basic' }, current: { another: 'other', current: 'current' }, common: { loading: 'loading' } }, es: { hello: 'hola %{name}', beers: { one: '%{count} cerveza', other: '%{count} cervezas' }, role: { admin: 'administrador', basic: 'básico' }, current: { another: 'eres tu?', current: 'soy yo?' }, common: { loading: 'cargando' } }, fr: { beers: { one: '%{count} bière', other: '%{count} bières' } } } describe('i18n', () => { let i18n beforeEach(() => { i18n = new I18n() i18n.setTranslations(mockedTranslations) process.env.NODE_ENV = 'development' }) describe('t', () => { it('throws if the path is not found', () => { expect(() => { i18n.t('ola.k.ase') }).toThrowError() }) it('throws if the path is not a string', () => { expect(() => { i18n.t('common') }).toThrowError() }) describe('with spanish locale', () => { beforeEach(() => { i18n.setLocale('es') }) it('uses spanish', () => { expect(i18n.t('common.loading')).toBe('cargando') }) describe('when it has a interpolation', () => { it('does not thhrow if the variable is not found', () => { expect(i18n.t('hello')).toBe('hola ') }) it('interpolates and do not escapes', () => { expect(i18n.t('hello', { name: '<b>coca-cola</b>' })).toBe( 'hola <b>coca-cola</b>' ) }) }) }) }) describe('formatNumber', () => { it('formats percentages', () => { expect(i18n.formatNumber(0.2, 'percent')).toBe('20%') }) it('formats the correct currency without locale code', () => { expect(i18n.formatNumber(1500, 'currency', 'GBP')).toBe('£1,500.00') }) it('formats number with just a number', () => { expect(i18n.formatNumber(1500)).toBe('1,500') }) it('formats currency with setLocale of language and country', () => { i18n.setLocale('de-DE') const spacer = String.fromCharCode(160) expect(i18n.formatNumber(123456.789, 'currency', 'EUR')).toBe('123.456,79' + spacer + '€') }) it('formats currency with setLocale of just country', () => { i18n.setLocale('GB') expect(i18n.formatNumber(1500, 'currency', 'GBP')).toBe('£1,500.00') }) it('formats currency with setLocale of just language', () => { i18n.setLocale('en') expect(i18n.formatNumber(1500, 'currency', 'GBP')).toBe('£1,500.00') }) }) describe('tp', () => { beforeEach(() => { i18n.setLocale('fr') }) it('throws if `count` is not provided', () => { expect(() => { i18n.tp('beers') }).toThrowError() }) it('throws if `count` is not a number', () => { expect(() => { i18n.tp('beers', { count: null }) }).toThrowError() }) describe('fr', () => { beforeEach(() => { i18n.setLocale('fr') }) it('uses pluralizations correctly otherwise', () => { expect(i18n.tp('beers', { count: 0 })).toBe('0 bière') expect(i18n.tp('beers', { count: 1 })).toBe('1 bière') expect(i18n.tp('beers', { count: 2 })).toBe('2 bières') }) }) describe('es', () => { beforeEach(() => { i18n.setLocale('es') }) it('uses pluralizations correctly otherwise', () => { expect(i18n.tp('beers', { count: 0 })).toBe('0 cervezas') expect(i18n.tp('beers', { count: 1 })).toBe('1 cerveza') expect(i18n.tp('beers', { count: 2 })).toBe('2 cervezas') }) }) }) describe('tx', () => { beforeEach(() => { i18n.setLocale('es') }) it('uses a variable correctly', () => { expect(i18n.tx('role', 'admin')).toBe('administrador') expect(i18n.tx('role', 'basic')).toBe('básico') }) }) })
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mediator { public interface IChatRoom { void Join(IParticipant participant); void Send(ChatMessage message); } public interface IParticipant { string Name { get; } void Send(string message); void ReceiveMessage(ChatMessage message); void ChatRoomJoined(IChatRoom chatRoom); } public class ChatMessage { public ChatMessage(IParticipant from, string content) { Sender = from ?? throw new ArgumentNullException(nameof(from)); Content = content ?? throw new ArgumentNullException(nameof(content)); } public IParticipant Sender { get; } public string Content { get; } } public class User : IParticipant { private IChatRoom _chatRoom; private readonly IMessageWriter<ChatMessage> _messageWriter; public User(IMessageWriter<ChatMessage> messageWriter, string name) { _messageWriter = messageWriter ?? throw new ArgumentNullException(nameof(messageWriter)); Name = name ?? throw new ArgumentNullException(nameof(name)); } public string Name { get; } public void ChatRoomJoined(IChatRoom chatRoom) { _chatRoom = chatRoom; } public void ReceiveMessage(ChatMessage message) { _messageWriter.Write(message); } public void Send(string message) { _chatRoom.Send(new ChatMessage(this, message)); } } public class ChatRoom : IChatRoom { private readonly List<IParticipant> _participants = new List<IParticipant>(); public void Join(IParticipant participant) { _participants.Add(participant); participant.ChatRoomJoined(this); Send(new ChatMessage(participant, "Has joined the channel")); } public void Send(ChatMessage message) { _participants.ForEach(participant => participant.ReceiveMessage(message)); } } }
#!/usr/bin/env ruby # f(x) = x^2 + ax + b # f(0) = b; b needs to be prime and positive # f(1) = 1 + a + b; unless b = 2, |a| < b && a needs to be odd require 'prime' LIMIT = 1_000 def prime_length(a, b) prime = n = 0 begin n += 1 prime = n**2 + a*n + b end while prime.prime? n end product = max_prime_length = 0 Prime.each(LIMIT) do |b| next if b == 2 (-(b-2)..(b-2)).each do |a| current_prime_length = prime_length(a, b) if current_prime_length > max_prime_length max_prime_length = current_prime_length product = a * b end end end puts product
package com.packt.javapath.ch18demo; import java.util.List; public class Exercise { public static void main(String... args) { List<Integer> list = List.of(2, 3, 4); int r = list.stream().reduce(1, (x, y) -> x * y); System.out.println(r); //prints: 24 } }
Site pour immobilier, by nabz used Bootstrap Je me suis aider des lignes de https://github.com/BlackrockDigital
import istype from './istype'; class EventEmitter { private _listeners: Map<string, Function>; constructor() { this._listeners = new Map(); } on(eventKey, callback) { this._listeners.set(eventKey, callback); } remove(eventKey) { this._listeners.delete(eventKey); } trigger(eventKey, ...args) { let listener = this._listeners.get(eventKey); if (istype.function(listener)) { listener(...args); return true; } else { return false; } } } export default EventEmitter;
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Subject } from 'rxjs/Subject'; @Injectable() export class pagesToggleService { //Search Toggle private _searchToggle = new Subject(); searchToggle = this._searchToggle.asObservable(); //Quickview Toggle private _quickViewToggle = new Subject(); quickViewToggle = this._quickViewToggle.asObservable(); //Sidebar Toggle - Mobile private _sideBarToggle = <Subject<boolean>> new Subject(); sideBarToggle = this._sideBarToggle.asObservable(); //Secondary Sidebar Toggle - Mobile private _secondarySideBarToggle = <Subject<any>> new Subject(); secondarySideBarToggle = this._secondarySideBarToggle.asObservable(); //Horizontal Menu Toggle - Mobile private _mobileHorizontaMenu = <Subject<boolean>> new Subject(); mobileHorizontaMenu = this._mobileHorizontaMenu.asObservable(); //Menu Pin Toggle private _menuPinToggle = new Subject(); menuPinToggle = this._menuPinToggle.asObservable(); //Menu Pin Toggle private _menuDrawer = <Subject<string>> new Subject(); menuDrawer = this._menuDrawer.asObservable(); //Page Wrapper Class private _pageContainerClass = <Subject<string>> new Subject(); pageContainerClass = this._pageContainerClass.asObservable(); //Page Content Class private _contentClass = <Subject<string>> new Subject(); contentClass = this._contentClass.asObservable(); //Header Class private _headerClass = <Subject<string>> new Subject(); headerClass = this._headerClass.asObservable(); //Body Layout Class private _bodyLayoutClass = <Subject<string>> new Subject(); bodyLayoutClass = this._bodyLayoutClass.asObservable(); //App Layout private _layout = <Subject<string>> new Subject(); Applayout = this._layout.asObservable(); //Footer Visiblity private _footer = <Subject<boolean>> new Subject(); Footer = this._footer.asObservable(); //Page Container Hover Event - Used for sidebar private _pageContainerHover = <Subject<boolean>> new Subject(); pageContainerHover = this._pageContainerHover.asObservable(); setContent(className:string){ this._contentClass.next(className); } setPageContainer(className:string){ this._pageContainerClass.next(className); } setHeaderClass(className:string){ this._headerClass.next(className); } setBodyLayoutClass(className:string){ this._bodyLayoutClass.next(className); } removeBodyLayoutClass(className:string){ this._bodyLayoutClass.next(className); } changeLayout(className:string){ this._layout.next(className); } toggleSearch(toggle:boolean) { this._searchToggle.next({text:toggle}); } toggleMenuPin(toggle:boolean){ this._menuPinToggle.next({text:toggle}); } toggleMenuDrawer(){ this._menuDrawer.next(); } toggleQuickView() { this._quickViewToggle.next(); } toggleMobileSideBar(toggle:boolean){ this._sideBarToggle.next(toggle); } toggleSecondarySideBar(toggle){ this._secondarySideBarToggle.next(toggle); } toggleMobileHorizontalMenu(toggle){ this._mobileHorizontaMenu.next(toggle); } toggleFooter(toggle:boolean){ this._footer.next(toggle); } triggerPageContainerHover(toggle:boolean){ this._pageContainerHover.next(toggle); } }
<meta http-equiv="refresh" content="0; URL='https://twitter.com/_digitalrights'" /> You are being redirected, if that didn't work [click here](https://twitter.com/_digitalrights)
#nullable disable using System.Threading; using System.Threading.Tasks; namespace WWT.Providers { [RequestEndpoint("/wwtweb/weblogin.aspx")] public class WebloginProvider : RequestProvider { public override string ContentType => ContentTypes.Text; public override bool IsCacheable => false; public override async Task RunAsync(IWwtContext context, CancellationToken token) { context.Response.AddHeader("Expires", "0"); await context.Response.WriteAsync("Key:Authorized", token); } } }
# Building a container To build the container, you must first [download the games](../games). Next, copy the downloaded games to this directory: ``` cp -r ../games/downloaded_games . ``` Now you can run `docker build`: ``` docker build --tag muniverse:VERSION . ```
#ifndef __CAMERA_H__ #define __CAMERA_H__ #include <iostream> #include <GL/gl.h> #include <assimp/cimport.h> #include <assimp/scene.h> #include <assimp/postprocess.h> #include <vectors.h> /* Camera class */ class Camera { private: Vec3 eyePos; Vec3 centerPos; Vec3 upVector; public: /* Camera constructor */ Camera(); /* Update the camera to look at the correct position with correct orientation */ void updateCamera(); /* Compute the current up vector */ void calculateUp(); void setPos(Vec3 newPos); void setOrient(Vec3 newOrient); Vec3 getPos(); Vec3 getOrient(); }; #endif
##!/bin/bash # ############################################################################## ## ## Puropse: ## Help implement Open-Close mechanism for bash files - open for extension, ## closed for modification. Changes the PATH for the executing script and ## its child processes to include all directories from which to load ## all modules needed to compose the initial and secondary scripts. This ## permits changing the behavior of the application by simply changing ## the order of how overriding modules are found by searching the PATH. ## ############################################################################### path_Set(){ local -r scriptFilePath="$(readlink -f "$1")" local -r scriptDir="$( dirname "$scriptFilePath")" # include dependent utilities/libraries in path if [ -d "$scriptDir/module" ]; then local modDir for modDir in $( ls -d "$scriptDir/module"/* ); do PATH="$modDir:$PATH" done fi export PATH="$scriptDir:$PATH" } path_Set "${BASH_SOURCE[0]}"
import scalafx.scene.input.KeyCode class Controller { private var buttons = Array.fill(8)(false) private var index = 0 private var strobe = 0 def setButtons(b: Array[Boolean]): Unit = { buttons = b } def read: Int = { var value = 0 if (index < 8 && buttons(index)) { value = 1 } index += 1 if ((strobe & 0x1) == 1) { index = 0 } value } def write(value: Int): Unit = { strobe = value if ((strobe & 0x1) == 1) { index = 0 } } } class Controllers(val c1: Controller, val c2: Controller) { private val b1 = Array.fill(8)(false) private val b2 = Array.fill(8)(false) private val buttons1: Map[KeyCode, Int] = Map( KeyCode.K -> 0, // A KeyCode.J -> 1, // B KeyCode.Control -> 2, // Select KeyCode.Enter -> 3, // Start KeyCode.W -> 4, // Up KeyCode.S -> 5, // Down KeyCode.A -> 6, // Left KeyCode.D -> 7 // Right ) def changeState(ke: KeyCode, isPressed: Boolean): Unit = { // TODO: Implement player 2 if (buttons1.contains(ke)) { if(isPressed) { b1(buttons1(ke)) = true } else { b1(buttons1(ke)) = false } } } def updateController1(): Unit = c1.setButtons(b1) def updateController2(): Unit = c2.setButtons(b2) } object Controllers { def apply(c1: Controller, c2: Controller) = new Controllers(new Controller, new Controller) }
/** * 判断B树是不是A的子树 * 本质上树的中序遍历,判断函数是--判断两个树是否相等的变形 */ struct BinaryTreeNode{ double m_dbValue; BinaryTreeNode* m_pLeft; BinaryTreeNode* m_pRight; }; bool equalDouble(double a, double b){ if((a-b>-0.0000001)&&(a-b<0.0000001)) return true; else return false; } bool tree1HasTree2(BinaryTreeNode* tree1, BinaryTreeNode* tree2){ if(tree2 == nullptr) return true; if(tree1 == nullptr) return false; if(!equalDouble(tree1->m_dbValue,tree2->m_dbValue)) return false; return tree1HasTree2(tree1->m_pLeft,tree2->m_pLeft)&&tree1HasTree2(tree1->m_pRight,tree2->m_pRight); return false; } bool hasSubTree(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2) { bool result = false; if(pRoot1!= nullptr&&pRoot2!= nullptr){ if(equalDouble(pRoot1->m_dbValue,pRoot2->m_dbValue)) result=tree1HasTree2(pRoot1,pRoot2); if(!result) result = tree1HasTree2(pRoot1->m_pLeft,pRoot2); if(!result) result = tree1HasTree2(pRoot1->m_pRight, pRoot2); } return result; }
const SYMBOL_MATCH = 'SYMBOL_MATCH' export default class TokenStream { index = 0; nodes; functionName; lastValue; rewindIndex; constructor(nodes, parent = null) { this.index = 0 this.nodes = nodes this.functionName = parent != null ? parent.value : null this.lastValue = null this.rewindIndex = -1 } hasTokens() { return this.index <= this.nodes.length - 1 } [SYMBOL_MATCH](...tokenDescriptors) { if (!this.hasTokens()) return null const node = this.nodes[this.index] for (let i = 0; i < tokenDescriptors.length; i += 1) { const tokenDescriptor = tokenDescriptors[i] const value = tokenDescriptor(node) if (value !== null) { this.index += 1 this.lastValue = value return value } } return null } matches(...tokenDescriptors) { return this[SYMBOL_MATCH](...tokenDescriptors) !== null } expect(...tokenDescriptors) { const value = this[SYMBOL_MATCH](...tokenDescriptors) return value !== null ? value : this.throw() } matchesFunction() { const node = this.nodes[this.index] if (node.type !== 'function') return null const value = new TokenStream(node.nodes, node) this.index += 1 this.lastValue = null return value } expectFunction() { const value = this.matchesFunction() return value !== null ? value : this.throw() } expectEmpty() { if (this.hasTokens()) this.throw() } throw() { throw new Error(`Unexpected token type: ${this.nodes[this.index].type}`) } saveRewindPoint() { this.rewindIndex = this.index } rewind() { if (this.rewindIndex === -1) throw new Error('Internal error') this.index = this.rewindIndex this.lastValue = null } }
// $Id$ // Author: Sijtsche de Jong // (c) COPYRIGHT MIT, ERCIM and Keio, 2003. // Please first read the full copyright statement in file COPYRIGHT.html package org.w3c.css.css; import java.util.ArrayList; import java.util.List; import org.w3c.css.parser.AtRule; import org.w3c.css.util.Messages; public class CssRuleList implements ICssStyleRuleOrCssRuleList { AtRule atRule; ArrayList<ICssStyleRuleOrCssRuleList> rulelist; public String pseudopage; String indent; public CssRuleList() { atRule = null; rulelist = new ArrayList<>(); indent = new String(); } public void addStyleRule(CssStyleRule stylerule) { rulelist.add(stylerule); } public ArrayList<CssStyleRule> getStyleRules() { ArrayList<CssStyleRule> r = new ArrayList<>(this.rulelist.size()); for(ICssStyleRuleOrCssRuleList u: this.rulelist) { if (u instanceof CssStyleRule) { r.add((CssStyleRule) u); } } return r; } public List<ICssStyleRuleOrCssRuleList> getStyleRulesTree() { return rulelist; } public List<CssStyleRule> getStyleRulesAllInTree() { ArrayList<CssStyleRule> r = new ArrayList<>(); this.appendStyleRulesTree(r); return r; } protected void appendStyleRulesTree(List<CssStyleRule> r) { for(ICssStyleRuleOrCssRuleList u: this.rulelist) { if (u instanceof CssStyleRule) { r.add((CssStyleRule) u); }else if (u instanceof CssRuleList) { CssRuleList l = (CssRuleList) u; l.appendStyleRulesTree(r); } } } /** * This should be rather named setAtRule * @param atRule */ public void addAtRule(AtRule atRule) { this.atRule = atRule; } public String getAtRule() { return (atRule != null) ? atRule.toString() : ""; } public AtRule getAtRuleObject() { return atRule; } public String getAtRuleEscaped() { return Messages.escapeString(atRule.toString()); } public boolean isEmpty() { return atRule.isEmpty() /*&& rulelist.isEmpty() */; } public String toString() { String atRuleString = atRule.toString(); StringBuilder ret = new StringBuilder(); if (null != atRule && atRule.isEmpty()) { if (atRuleString.length() != 0) { ret.append(atRuleString); ret.append("\n\n"); } } else { if (atRuleString.length() != 0) { ret.append(atRuleString); ret.append(" {\n\n"); } for (ICssStyleRuleOrCssRuleList styleRule : rulelist) { ret.append(styleRule); } if (atRuleString.length() != 0) { ret.append("}\n"); } } return ret.toString(); } public void addSubRulelist(CssRuleList rulelist) { this.rulelist.add(rulelist); } }
# # (c) Jan Gehring <[email protected]> # # vim: set ts=3 sw=3 tw=0: # vim: set expandtab: package Rex::Cloud::Jiffybox; use strict; use warnings; use Rex::Logger; use LWP::UserAgent; use HTTP::Request::Common; use JSON::XS; use Data::Dumper; use Rex::Cloud::Base; use base qw(Rex::Cloud::Base); sub new { my $that = shift; my $proto = ref($that) || $that; my $self = { @_ }; bless($self, $proto); $self->{"__endpoint"} = "https://api.jiffybox.de/%s/v1.0/%s"; Rex::Logger::debug("Creating new Jiffybox Object, with endpoint: " . $self->{"__endpoint"}); return $self; } sub _auth_key { my ($self) = @_; return $self->{"__auth_key"}; } sub _do_request { my ($self, $type, $action, @params) = @_; my $url = sprintf($self->{"__endpoint"}, $self->_auth_key, $action); Rex::Logger::debug("Requesting $url"); my $ua = LWP::UserAgent->new; my ($res); if($type eq "GET") { $res = $ua->request(GET $url); } elsif($type eq "POST") { $res = $ua->request(POST $url, \@params); } elsif($type eq "PUT") { my $req = POST $url, \@params; $req->method("PUT"); $res = $ua->request($req); } elsif($type eq "DELETE") { my $req = GET $url; $req->method("DELETE"); $res = $ua->request($req); } if($res->code >= 500) { Rex::Logger::info($res->content); die("Error on request."); } my $json = JSON::XS->new; my $data = $json->decode($res->decoded_content); Rex::Logger::debug(Dumper($data)); unless($data->{"result"}) { die("Error talking to jiffybox: " . $data->{"messages"}->[0]->{"message"}); } return $data; } sub _result_to_array { my ($self, $data, $with_key) = @_; my @ret = (); for my $key (keys %{$data->{"result"}}) { if($with_key) { $data->{"result"}->{$key}->{$with_key} = $key; } push(@ret, $data->{"result"}->{$key}); } return @ret; } sub set_auth { my ($self, $key) = @_; $self->{"__auth_key"} = $key; } sub list_plans { my ($self) = @_; Rex::Logger::debug("Listing plans"); my $data = $self->_do_request("GET", "plans"); return $self->_result_to_array($data); } sub list_operating_systems { my ($self) = @_; Rex::Logger::debug("Listing operating systems"); my $data = $self->_do_request("GET", "distributions"); return $self->_result_to_array($data, "os_id"); } sub run_instance { my ($self, %data) = @_; my @jiffy_data; Rex::Logger::debug("Trying to start a new instance with data:"); Rex::Logger::debug(" $_ -> " . ($data{$_}?$data{$_}:"undef")) for keys %data; push(@jiffy_data, "name" => $data{"name"}, "planid" => $data{"plan_id"}, "distribution" => $data{"image_id"}); if(exists $data{"password"}) { push(@jiffy_data, "password" => $data{"password"}); } if(exists $data{"key"}) { push(@jiffy_data, "use_sshkey" => $data{"key"}); } if(exists $data{"metadata"}) { push(@jiffy_data, "metadata" => $data{"metadata"}); } my $data = $self->_do_request("POST", "jiffyBoxes", @jiffy_data); my $instance_id = $data->{"result"}->{"id"}; my $sleep_countdown = 10; sleep $sleep_countdown; # wait 10 seconds ($data) = grep { $_->{"id"} eq $instance_id } $self->list_instances(); while($data->{"state"} ne "STOPPED") { Rex::Logger::debug("Waiting for instance to be created..."); ($data) = grep { $_->{"id"} eq $instance_id } $self->list_instances(); sleep $sleep_countdown; --$sleep_countdown; if($sleep_countdown <= 3) { $sleep_countdown = 7; } } $self->start_instance(instance_id => $instance_id); return $data; } sub start_instance { my ($self, %data) = @_; my $instance_id = $data{"instance_id"}; Rex::Logger::debug("Starting instance $instance_id"); $self->_do_request("PUT", "jiffyBoxes/$instance_id", status => "START"); } sub terminate_instance { my ($self, %data) = @_; my $instance_id = $data{"instance_id"}; Rex::Logger::debug("Terminating instance $instance_id"); $self->_do_request("DELETE", "jiffyBoxes/$instance_id"); } sub stop_instance { my ($self, %data) = @_; my $instance_id = $data{"instance_id"}; Rex::Logger::debug("Stopping instance $instance_id"); $self->_do_request("PUT", "jiffyBoxes/$instance_id", status => "SHUTDOWN"); } sub list_instances { my ($self) = @_; my @ret; my $data = $self->_do_request("GET", "jiffyBoxes"); for my $instance_id (keys %{$data->{"result"}}) { my $state = $data->{"result"}->{$instance_id}->{"status"}; if($state eq "READY") { if($data->{"result"}->{$instance_id}->{"running"}) { $state = "RUNNING"; } else { $state = "STOPPED"; } } push(@ret, { ip => $data->{"result"}->{$instance_id}->{"ips"}->{"public"}->[0], id => $instance_id, architecture => undef, type => $data->{"result"}->{$instance_id}->{"plan"}->{"name"}, dns_name => "j$instance_id.servers.jiffybox.net", state => $state, __state => $data->{"result"}->{$instance_id}->{"status"}, launch_time => undef, name => $data->{"result"}->{$instance_id}->{"name"}, }); } return @ret; } sub list_running_instances { my ($self) = @_; return grep { $_->{"__state"} eq "READY" || $_->{"__state"} eq "UPDATING" } $self->list_instances(); } 1;
DROP TABLE IF EXISTS `stats`; DROP TABLE IF EXISTS `survey`; CREATE TABLE `survey` ( `cookie` char(80) character set latin1 default NULL, `ip` char(40) character set latin1 NOT NULL, `ip4` char(40) character set latin1 default NULL, `ip6` char(40) character set latin1 default NULL, `status_a` enum('ok','slow','bad','timeout','unknown','skipped') character set latin1 NOT NULL, `status_aaaa` enum('ok','slow','bad','timeout','unknown','skipped') character set latin1 NOT NULL, `status_ds4` enum('ok','slow','bad','timeout','unknown','skipped') character set latin1 NOT NULL, `status_ds6` enum('ok','slow','bad','timeout','unknown','skipped') character set latin1 NOT NULL, `status_ipv4` enum('ok','slow','bad','timeout','unknown','skipped') character set latin1 NOT NULL, `status_ipv6` enum('ok','slow','bad','timeout','unknown','skipped') character set latin1 NOT NULL, `status_dsmtu` enum('ok','slow','bad','timeout','unknown','skipped') NOT NULL, `time_a` mediumint(8) unsigned default NULL, `time_aaaa` mediumint(8) unsigned default NULL, `time_ds4` mediumint(8) unsigned default NULL, `time_ds6` mediumint(8) unsigned default NULL, `time_ipv4` mediumint(8) unsigned default NULL, `time_ipv6` mediumint(8) unsigned default NULL, `time_dsmtu` mediumint(8) unsigned default NULL, `tokens` char(200) character set latin1 default NULL, `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP, `ua_id` int(11) default NULL, `status_v6ns` enum('ok','slow','bad','timeout','unknown','skipped') character set latin1 NOT NULL, `time_v6ns` mediumint(8) unsigned default NULL, `ix` bigint(20) unsigned NOT NULL auto_increment, `status_v6mtu` enum('ok','slow','bad','timeout','unknown','skipped') character set latin1 default NULL, `time_v6mtu` mediumint(8) unsigned default NULL, PRIMARY KEY (`ix`), KEY `status_a` (`status_a`), KEY `status_aaaa` (`status_aaaa`), KEY `status_ds4` (`status_ds4`), KEY `status_ds6` (`status_ds6`), KEY `status_ipv4` (`status_ipv4`), KEY `status_ipv6` (`status_ipv6`), KEY `timestamp` (`timestamp`), KEY `status_v6mtu` (`status_v6mtu`) ) ENGINE=MyISAM AUTO_INCREMENT=220869 DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `user_agent`; DROP TABLE IF EXISTS `user_agents`; CREATE TABLE `user_agents` ( `id` int(11) NOT NULL auto_increment, `user_agent` varchar(255) character set latin1 NOT NULL, UNIQUE KEY `user_agent` (`user_agent`), UNIQUE KEY `id` (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=23798 DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `daily_summary`; CREATE TABLE `daily_summary` ( `datestamp` date NOT NULL, `total` int(10) unsigned default NULL, `tokens` char(200) character set latin1 default NULL, KEY `datestamp` (`datestamp`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `monthly_summary`; CREATE TABLE `monthly_summary` ( `datestamp` date NOT NULL, `total` int(10) unsigned default NULL, `tokens` char(200) character set latin1 default NULL, KEY `datestamp` (`datestamp`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
import {isTraversable} from "../../../helpers/is-traversable"; import {iteratorToMap} from "../../../helpers/iterator-to-map"; import {TwingErrorRuntime} from "../../../error/runtime"; import {isPlainObject} from "../../../helpers/is-plain-object"; /** * Return the values from a single column in the input array. * * <pre> * {% set items = [{ 'fruit' : 'apple'}, {'fruit' : 'orange' }] %} * * {% set fruits = items|column('fruit') %} * * {# fruits now contains ['apple', 'orange'] #} * </pre> * * @param {*} thing An iterable * @param {*} columnKey The column key * * @return {Promise<Array<any>>} The array of values */ export function column(thing: any, columnKey: any): Promise<Array<any>> { let map: Map<any, any>; if (!isTraversable(thing) || isPlainObject(thing)) { throw new TwingErrorRuntime(`The column filter only works with arrays or "Traversable", got "${typeof thing}" as first argument.`); } else { map = iteratorToMap(thing); } let result: any[] = []; for (let value of map.values()) { let valueAsMap: Map<any, any> = iteratorToMap(value); for (let [key, value] of valueAsMap) { if (key === columnKey) { result.push(value); } } } return Promise.resolve(result); }
<?php namespace App\Services; use App\Services\Interfaces\UserServiceInterface; use App\Services\Interfaces\ReportServiceInterface; use Illuminate\Support\Facades\Auth; use App\User; use App\Models\Role; use App\Models\TimeSheet; use App\Models\Task; use App\Models\Report; use Illuminate\Support\Facades\Hash; use Laravel\Socialite\Facades\Socialite; class UserService extends BaseService implements UserServiceInterface { protected $reportService; public function __construct(ReportServiceInterface $reportService){ $this->reportService = $reportService; } public function getAllUser(){ return User::all(); } public function getUserById($id){ return User::find($id); } public function updateUser(string $avatarName, array $data){ $user = Auth::user(); $params = [ 'username' => \Arr::get($data, 'username'), 'email' => \Arr::get($data, 'email'), 'address' => \Arr::get($data, 'address'), 'birthday' => \Arr::get($data, 'birthday'), 'avatar' => $avatarName, ]; return $user->update($params); } public function deleteUser($memberId){ $member = $this->getUserById($memberId); $member->timesheets()->delete(); $member->reports()->delete(); $member->update(['is_active' => 2]); $member->delete(); } public function createUser(string $avatarName, array $data){ $params = [ 'username' => \Arr::get($data, 'username'), 'email' => \Arr::get($data, 'email'), 'password' => bcrypt(\Arr::get($data, 'password')), 'address' => \Arr::get($data, 'address'), 'birthday' => convertFormatDate(\Arr::get($data, 'birthday')), 'avatar' => $avatarName ]; $user = User::create($params); if($user) $this->reportService->create($user); return true; } public function getRolesOfUser($user){ return $user->roles()->pluck('name')->toArray(); } public function getAndSortRolesOfUser($id){ $user = $this->getUserById($id); $roles = $this->getRolesOfUser($user); sort($roles); return $roles; } public function updateRole($queries, $memberId){ $user = $this->getUserById($memberId); $roles = $this->getRolesOfUser($user); $diffRole1 = array_diff($queries, $roles); $diffRole2 = array_diff($roles, $queries); if(count($diffRole1) != 0){ foreach($diffRole1 as $item){ $roleId = Role::where('name', $item)->get()->first()->id; $user->roles()->attach((int)$roleId); } } if(count($diffRole2) != 0){ foreach($diffRole2 as $item){ $roleId = Role::where('name', $item)->get()->first()->id; $user->roles()->detach((int)$roleId); } } return convertRolesArrayToString($this->getAndSortRolesOfUser($memberId)); } public function saveNewPass(array $data){ $user = Auth::user(); $hashedPass = $user->password; $curPass = \Arr::get($data, 'cur-password'); if(!Hash::check($curPass, $hashedPass)) return false; $user->update([ 'password' => bcrypt(\Arr::get($data, 'new-password')), ]); return true; } public function redirectToProvider($provider){ return Socialite::driver($provider)->redirect(); } public function handleProviderCallback($provider){ $user = Socialite::driver($provider)->user(); $authUser = $this->mainProviderLogin($user); return Auth::login($authUser); } public function mainProviderLogin($data){ $user = User::where('username', '=', $data->name)->first(); if($user) return $user; else{ $params = [ 'username' => $data->name, 'email' => $data->email !== null ? $data->email : '[email protected]', 'password' => bcrypt($data->id), ]; $newUser = User::create($params); $this->reportService->create($newUser); return $newUser; } } }
;; Maps: conj ;; When operating on a map, the conj function returns a new map with one or more key-value pairs "added". (def result {:a 1, :b 2, :c 3}) ;; Tests (println (= {:a 1, :b 2, :c 3} (conj {:a 1} result [:c 3])))
class CacheMaster ################### # CLASS METHODS ################### def self.expire_caches(work_ids) work_ids.each { |id| self.new(id).expire } end def self.record(work_id, owner_type, owner_id) self.new(work_id).record(owner_type, owner_id) end ################### # INSTANCE METHODS ################### attr_reader :work_id def initialize(work_id) @work_id = work_id end def key "works:#{work_id}:assocs" end def get_hash REDIS_GENERAL.hgetall(key) end def get_value(owner_type) REDIS_GENERAL.hget(key, owner_type) end def set_value(owner_type, value) REDIS_GENERAL.hset(key, owner_type, value) end def reset! REDIS_GENERAL.del(key) end def record(owner_type, owner_id) owner_type = owner_type.to_s data = get_value(owner_type) value = data.nil? ? owner_id.to_s : "#{data},#{owner_id}" set_value(owner_type, value) end def expire get_hash.each_pair do |key, id_string| klass = key.classify.constantize klass.expire_ids(id_string.split(',')) end reset! end end
echo "printing something on the screen" echo -e "this script also has newlines.\n\nIsn't is something?" sleep 2 echo "This something went to sleep for 2 seconds!"
# 大数据相关练习、代码、实例记录(Spark,Kafka,Hadoop,Zookeeper,HBase,Hive) ## Spark练习代码 ## SparkSQLPrac 练习代码 ## SparkStreamingKafka实时计算相关代码 # 良心友情链接 [腾讯QQ群快速检索](http://u.720life.cn/s/8cf73f7c) [软件免费开发论坛](http://u.720life.cn/s/bbb01dc0)
({ "insertResponse": function (cmp, a) { $A.createComponent("actionsTest:transactionsEntry", { "transactionId":$A.getCurrentTransactionId(), "actionId":a.getId(), "state":a.getState() }, function (newCmp) { if (cmp.isValid()) { var holder = cmp.find("responses"); var body = holder.get("v.body"); body.push(newCmp); holder.set("v.body", body); } }) }, "handleCb" : function(cmp, action, callback) { this.insertResponse(cmp, action); if (callback) { callback.call(this, action); } }, "sendAction" : function(cmp, abortable, transactionId, callback) { var serverAction = cmp.get("c.executeInForeground"); if (transactionId) { $A.setCurrentTransactionId(transactionId); } serverAction.setAbortable(abortable); serverAction.setCallback(this, function(action) { this.handleCb(cmp, action, callback); }, "SUCCESS"); serverAction.setCallback(this, function(action) { this.handleCb(cmp, action, callback); }, "ERROR"); serverAction.setCallback(this, function(action) { this.handleCb(cmp, action, callback); }, "INCOMPLETE"); serverAction.setCallback(this, function(action) { this.handleCb(cmp, action, callback); }, "ABORTED"); $A.enqueueAction(serverAction); } })
--- layout: page title: About me subtitle: Make it simple, but significant! --- My name is Doãn (English name: John). I have the following qualities: - I'm good at cooking my code - I'm extremely loyal to my family What else do you need? ### mail me @ [email protected]
// Package xmlx extends the features of the encoding/xml package with a // generic unmarshallable xml structure. // // It provides a new structure, Node, which can unmarshal any xml data. This node has two useful // methods: Map and Split. // // The Map method returns a map of name, data, attributes and subnodes to // their values. // // The Split method returns an array of nodes having the same property as the parent, // splitted after a subnode name. package xmlx
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use\App\Models\AdminModel; use\App\Models\MasyarakatModel; use\App\Models\BeritaModel; use\App\Models\PengaduanModel; class SuperAdmin_dashboardController extends Controller { public function index() { $admins = AdminModel::count(); $masyarakats = MasyarakatModel::count(); $beritas = BeritaModel::count(); $pengaduans = PengaduanModel::count(); return view('superadmin/dashboard',compact('admins','masyarakats','beritas','pengaduans'))->with('i'); } }
class IncreaseLengthOfTargetUrlInAlerts < ActiveRecord::Migration def change change_column :alerts, :target_url, :string, :null=>true, :limit => 1000 end end
import { XSampleWebComponent } from './packages/showcase-sample-web-components'; customElements.define('x-sample-web-component', XSampleWebComponent);
# slacker ## NOTE: this project is unmaintained. Rust wrapper over the slack API.
INSERT INTO raw_home_data (rec_territory, cases, deaths, recovered, severe, tested, active) VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT ON CONSTRAINT unique_home_entry DO NOTHING
import {ObjectMeta} from "@mittwald/kubernetes/types/meta/v1"; import {PoolSpec} from "./pool"; import {Placement} from "./placement"; export interface Gateway { type: "s3"; sslCertificateRef?: string; port?: number; securePort?: number; instances?: number; allNodes?: boolean; placement?: Placement; } export interface ObjectStoreSpec { metadataPool?: PoolSpec; dataPool?: PoolSpec; gateway?: Gateway; } export interface ObjectStore { metadata: ObjectMeta; spec: ObjectStoreSpec; }
using Revise, ScatteringTransform, Plots, LinearAlgebra pyplot() k = 2^9 t = (-1+1/k):1/k:1; size(t) # interval n = 20 # degree of polynomial testSignal = hcat([t.^i for i=0:n]...)* randn(n+1) plot(t, testSignal) layers = stParallel(2, length(testSignal)) # 11 is *way* too far out layers = stParallel(2, length(testSignal), CWTType = WT.Morlet(11), nScales=[8 for i=1:3]) layers.shears[1].averagingLength # let's look at the actual filters that are used n = ScatteringTransform.getNs(size(testSignal), layers) i=1 layers.shears[i] daughters,ξ = computeWavelets(n[i], layers.shears[i]) layers.shears[1].frameBound ω = [0:ceil(Int, n[1]); -floor(Int,n[1])+1:-1]*2π; plot(daughters[:, :], legend=false) plot(daughters[:, end], legend=false) plt = Array{Any,1}(undef,4) for (k,x) in enumerate([(:none,"Unnormalized (may be using this one)"), (:sqrtScaling, "2-norm Scaling"), (:absScaling, "1-norm scaling"), (:maxOne, "∞-norm scaling (they use)")]) tmpDaughters = zeros(33,n[1]+1) for i=0:32 tmpDaughters[i+1, :] = ScatteringTransform.Daughter(layers.shears[1], 2.0^(2+i/8), ω, x[1])[1:(n[1]+1)] end plt[k] = plot(tmpDaughters[:,:]', legend=false, title="$(x[2])") end plot(plt...,layout=(4,1)) savefig("possibleScalings.pdf") norm(ScatteringTransform.Daughter(layers.shears[i], 2.0^(3/8), ω)[1:(n[1]+1)]) layers.shears[i] stResult = st(testSignal, layers, absType())
## Sample 2: Popover Placement The `Popover` control has also the `Placement` property. Use this property to specify on which side the overlay appears. The `Placement` property can be set to `Top`, `Bottom`, `Left`, `Right` and `Auto`.
USE master IF DB_ID('cheshire') IS NOT NULL DROP DATABASE cheshire GO CREATE DATABASE cheshire GO USE cheshire CREATE TABLE tblDM ( idDM INT IDENTITY(1,1) PRIMARY KEY, tenDM NVARCHAR(100) ) GO CREATE TABLE tblTG ( idTG INT IDENTITY(1,1) PRIMARY KEY, tenTG NVARCHAR(100), imgTG NVARCHAR(100), tgVN BIT DEFAULT 1, -- tác giả việt nam = 1 tgDG NVARCHAR(100) DEFAULT N'', -- tác giả đạt giải motaTG NTEXT, tinhtrang BIT DEFAULT 1, ngaytao DATE ) GO CREATE TABLE tblSach ( idSach INT IDENTITY(1,1) PRIMARY KEY, tenSach NVARCHAR(100), imgSach NVARCHAR(100), giaSach INT DEFAULT 0, motaSach NTEXT, daban INT DEFAULT 0, daxem INT DEFAULT 0, idDM INT FOREIGN KEY REFERENCES dbo.tblDM(idDM), tinhtrang BIT DEFAULT (1), -- còn hàng = 1 ngaytao DATE ) GO CREATE TABLE tbl_TG_Sach ( idTG INT REFERENCES dbo.tblTG(idTG) NOT NULL, idSach INT REFERENCES dbo.tblSach(idSach) NOT NULL, PRIMARY KEY(idTG,idSach) ) GO CREATE TABLE tblTK ( idTK INT IDENTITY(1,1) PRIMARY KEY, nickname NVARCHAR(50), emailTK VARCHAR(50) UNIQUE, passwordTK VARCHAR(100) NOT NULL, quyen int DEFAULT(0) NOT NULL, ngaytao DATE, imgTK NVARCHAR(100) ) GO CREATE TABLE tblLH ( idLH INT IDENTITY(1,1) PRIMARY KEY, tenLH NVARCHAR(100), mota NTEXT, tinhtrang BIT DEFAULT(1), ngaytao DATE ) GO CREATE TABLE tblHoaDon ( idHD INT IDENTITY(1,1) PRIMARY KEY, ngaytao datetime, chuthich NVARCHAR(100), diachi NVARCHAR(100), sdt varchar(15), tongtien float, idTK int FOREIGN KEY REFERENCES dbo.tblTK, trangthai int DEFAULT(0),-- Chua xac nhan don hang thi la 0 xacnhan da nhan la 1 xac nhan da thanh toan la 2 ) GO create table tbl_CTHD( idHD int REFERENCES dbo.tblHoaDon , idSach int REFERENCES dbo.tblSach, giaSach INT, Soluong int, primary key (idHD,idSach), ) GO
require 'opal' def a b end def b 2 + 2 == 5 c end def c nomethoderror end a
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:crypto/crypto.dart'; final _usage = 'Usage: dart hash.dart <md5|sha1|sha256> <input_filename>'; Future main(List<String> args) async { if (args.length != 2) { print(_usage); exitCode = 64; // Command was used incorrectly. return; } Hash hasher; switch (args[0]) { case 'md5': hasher = md5; break; case 'sha1': hasher = sha1; break; case 'sha256': hasher = sha256; break; default: print(_usage); exitCode = 64; // Command was used incorrectly. return; } var filename = args[1]; var input = File(filename); if (!input.existsSync()) { print('File "$filename" does not exist.'); exitCode = 66; // An input file did not exist or was not readable. return; } var value = await hasher.bind(input.openRead()).first; print(value); }
using System; using System.Globalization; using System.Text; namespace Sylphe.Utils { /// <summary> /// Separate a text string into individual tokens (lexical scanning). /// Token types: Name, String, Number, Operator, End (of input). /// Operators always use ordinal, names the given string comparison. /// </summary> public class Tokenizer { private readonly string _text; private readonly StringBuilder _buffer; private int _index; private Token _currentToken; private const string DefaultExtraNameChars = "$_"; public Tokenizer(string text, int index = 0) { if (text == null) throw new ArgumentNullException(nameof(text)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); _text = text; _index = index; _buffer = new StringBuilder(); _currentToken = Token.None; AllowDecimals = true; AllowExponent = true; ExtraNameChars = DefaultExtraNameChars; AllowDoubleQuotedString = true; AllowSingleQuotedString = true; NameComparison = StringComparison.Ordinal; } public bool AllowDecimals; public bool AllowExponent; public string ExtraNameChars; public bool AllowDoubleQuotedString; public bool AllowSingleQuotedString; public StringComparison NameComparison; public bool Advance() { _currentToken = NextToken(_text, ref _index); return _currentToken.Type != TokenType.End; } public int Index => _index; public object CurrentValue => _currentToken.Value; public void ExpectName() { if (_currentToken.Type != TokenType.Name) { throw SyntaxError(_currentToken.Index, "Expected a name, got {0}", _currentToken); } } public void ExpectOperator(string op) { if (_currentToken.Type != TokenType.Operator || !string.Equals(_currentToken.Value as string, op, StringComparison.Ordinal)) { throw SyntaxError(_currentToken.Index, "Expected {0}, got {1}", op, _currentToken); } } public bool IsName() { return _currentToken.Type == TokenType.Name; } public bool IsName(string name) { if (_currentToken.Type != TokenType.Name) return false; var value = (string) _currentToken.Value; return string.Equals(value, name, NameComparison); } public bool IsString() { return _currentToken.Type == TokenType.String; } public bool IsNumber() { return _currentToken.Type == TokenType.Number; } public bool IsOperator(string op) { if (_currentToken.Type != TokenType.Operator) return false; var value = (string) _currentToken.Value; return string.Equals(value, op, StringComparison.Ordinal); } public bool IsOperator(string op1, string op2) { if (_currentToken.Type != TokenType.Operator) return false; var value = (string) _currentToken.Value; return string.Equals(value, op1, StringComparison.Ordinal) || string.Equals(value, op2, StringComparison.Ordinal); } public bool IsOperator(string op1, string op2, string op3) { if (_currentToken.Type != TokenType.Operator) return false; var value = (string) _currentToken.Value; return string.Equals(value, op1, StringComparison.Ordinal) || string.Equals(value, op2, StringComparison.Ordinal) || string.Equals(value, op3, StringComparison.Ordinal); } public bool IsEnd => _currentToken.Type == TokenType.End; private Token NextToken(string text, ref int index) { // Name: trim, Hello, null // Number: 123, 0.345, 1.567, 7.89e2 // String: "You said: \"Hi!\"" or 'Rock''n''Roll' // Operator: = && ? : { } != <= ( ) etc. while (index < text.Length && char.IsWhiteSpace(text, index)) { index += 1; // skip white space } if (index >= text.Length) { return Token.End(index); } char cc = text[index]; if (IsInitialNameChar(cc, ExtraNameChars)) { int length = ScanName(text, index); int anchor = index; index += length; return Token.Name(text.Substring(anchor, length), anchor); } if (cc == '"' && AllowDoubleQuotedString) { int anchor = index; index += ScanCString(text, index, _buffer.Clear()); return Token.String(_buffer.ToString(), anchor); } if (cc == '\'' && AllowSingleQuotedString) { int anchor = index; index += ScanSqlString(text, index, _buffer.Clear()); return Token.String(_buffer.ToString(), anchor); } if (char.IsDigit(cc)) { // Unary minus or plus is considered an operator, // not part of the number token. int length = ScanNumber(text, index, AllowDecimals, AllowExponent); int anchor = index; index += length; var s = text.Substring(anchor, length); double value = double.Parse(s, NumberStyles.Number, CultureInfo.InvariantCulture); return Token.Number(value, anchor); } // Multi-character operators: what's the best way to scan them? // Options that come to mind: (1) treat them all as special cases, // (2) if cc in a set of "prefix" chars then scan while cc in a // set of "suffix" chars, which usually accepts many more operators // than are desired, (3) Knuth's METAFONT has the concept where each // multi-character operator is composed of a characters from a few // disjoint character classes, (4) scan along the branches of a // trie of the operators, but that's a bit non-trivial. // Here: approach (1) for the following set of multi-character ops: // && ** ++ -- .. // << == >> ?? || -> => <= >= += -= *= /= %= &= |= ^= != <> // (this is _approximately_ the C# operators and may easily be changed) const string dups = "&*+-./<=>?|"; // && ** ++ -- .. // << == >> ?? || if (dups.IndexOf(cc) >= 0 && IsChar(text, index+1, cc)) { int anchor = index; index += 2; return Token.Operator(text.Substring(anchor, index - anchor), anchor); } const string assgns = "+-*/%&|^<>!"; // += -= *= /= %= &= |= ^= <= >= != if (assgns.IndexOf(cc) >= 0 && IsChar(text, index+1, '=')) { int anchor = index; index += 2; return Token.Operator(text.Substring(anchor, index - anchor), anchor); } if ((cc == '-' || cc == '=' || cc == '<') && IsChar(text, index+1, '>')) { int anchor = index; index += 2; return Token.Operator(text.Substring(anchor, index - anchor), anchor); } if (!char.IsControl(cc)) { int anchor = index; index += 1; return Token.Operator(text.Substring(anchor, 1), anchor); } throw SyntaxError(index, "Invalid input character: U+{0:X4}", (int) cc); } private static bool IsChar(string text, int index, char cc) { return index < text.Length && text[index] == cc; } #region Lexical scanning /// <summary> /// Scan a run of white space from <paramref name="text"/> starting /// at <paramref name="index"/> and return the number chars scanned. /// If no white space is found, zero will be returned. /// </summary> /// <remarks> /// This method is useful to skip over optional white space: /// <code> /// int index = ...; /// string text = "..."; /// index += ScanWhite(text, index);</code> /// </remarks> public static int ScanWhite(string text, int index) { if (text == null) throw new ArgumentNullException(nameof(text)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); int anchor = index; while (index < text.Length && char.IsWhiteSpace(text, index)) { index += 1; } return index - anchor; } /// <summary> /// Scan a name token from <paramref name="text"/> starting /// at <paramref name="index"/> and return the number of chars /// scanned. If no name token is found, zero will be returned. /// A name token is any sequence of letters, underscores, and /// digits, not starting with a digit. /// </summary> public static int ScanName(string text, int index, string extra = null) { if (text == null) throw new ArgumentNullException(nameof(text)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); extra = extra ?? DefaultExtraNameChars; int anchor = index; if (index >= text.Length || !IsInitialNameChar(text[index], extra)) { return 0; } index += 1; while (index < text.Length && IsSequentNameChar(text[index], extra)) { index += 1; } return index - anchor; } private static bool IsInitialNameChar(char c, string extra) { return char.IsLetter(c) || extra.IndexOf(c) >= 0; } private static bool IsSequentNameChar(char c, string extra) { return char.IsLetterOrDigit(c) || extra.IndexOf(c) >= 0; } /// <summary> /// Scan a number token from <paramref name="text"/> starting /// at <paramref name="index"/> and return the number of chars /// scanned. If no number token is found, zero will be returned. /// The text scanned is not converted to a numeric type. /// </summary> public static int ScanNumber(string text, int index, bool allowDecimal = false, bool allowExponent = false) { if (text == null) throw new ArgumentNullException(nameof(text)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); char cc; int anchor = index; while (index < text.Length && char.IsDigit(text, index)) { index += 1; } if (allowDecimal && index < text.Length && text[index] == '.') { index += 1; while (index < text.Length && char.IsDigit(text, index)) { index += 1; } } if (allowExponent && index < text.Length && ((cc = text[index]) == 'e' || cc == 'E')) { index += 1; if (index < text.Length && ((cc = text[index]) == '-' || cc == '+')) { index += 1; } while (index < text.Length && char.IsDigit(text, index)) { index += 1; } } return index - anchor; } /// <summary> /// Scan an integer from <paramref name="text"/> starting /// at <paramref name="index"/> and return the number of /// chars scanned. Convert the text scanned to Int32. /// </summary> public static int ScanNumber(string text, int index, out int value) { if (text == null) throw new ArgumentNullException(nameof(text)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); int anchor = index; value = 0; while (index < text.Length && char.IsDigit(text, index)) { char cc = text[index]; if ((uint) value > (0x7FFFFFFF / 10)) throw new OverflowException(); value *= 10; value += (cc - '0'); if (value < 0) throw new OverflowException(); index += 1; } return index - anchor; // #chars scanned } /// <summary> /// Scan a string token from <paramref name="text"/> starting /// at <paramref name="index"/>, append the value of the string /// (with all escapes expanded) <paramref name="buffer"/>, and /// return the number of characters scanned. /// If no string is found, zero will be returned. /// Single-quoted strings use SQL escape conventions. /// Double-quoted strings use C# escape conventions. /// If the string is malformed, an exception will be thrown. /// </summary> public static int ScanString(string text, int index, StringBuilder buffer) { if (text == null) throw new ArgumentNullException(nameof(text)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); if (index >= text.Length) return 0; if (buffer == null) buffer = new StringBuilder(); // else: don't clear buffer, append to it switch (text[index]) { case '\'': return ScanSqlString(text, index, buffer); case '"': return ScanCString(text, index, buffer); } return 0; // no string found } private static int ScanSqlString(string text, int index, StringBuilder buffer) { char quote = text[index]; int anchor = index++; // skip opening apostrophe while (index < text.Length) { char cc = text[index++]; if (cc == quote) { if (index < text.Length && text[index] == quote) { buffer.Append(quote); // un-escape index += 1; // skip 2nd apostrophe } else { return index - anchor; } } else { buffer.Append(cc); } } throw SyntaxError(anchor, "Unterminated string"); } private static int ScanCString(string text, int index, StringBuilder buffer) { char quote = text[index]; int anchor = index++; // skip opening quote while (index < text.Length) { char cc = text[index++]; if (cc < ' ') { throw SyntaxError(index - 1, "Control character in string"); } if (cc == quote) { return index - anchor; } if (cc == '\\') { if (index >= text.Length) { break; } switch (cc = text[index++]) { case '"': case '\'': case '\\': case '/': buffer.Append(cc); break; case 'a': buffer.Append('\a'); break; case 'b': buffer.Append('\b'); break; case 'f': buffer.Append('\f'); break; case 'n': buffer.Append('\n'); break; case 'r': buffer.Append('\r'); break; case 't': buffer.Append('\t'); break; case 'v': buffer.Append('\v'); break; case 'u': index += ScanHex4(text, index, buffer); break; default: throw SyntaxError(index, "Unknown escape '\\{0}' in string", cc); } } else { buffer.Append(cc); } } throw SyntaxError(anchor, "Unterminated string"); } private static int ScanHex4(string text, int index, StringBuilder buffer) { if (index + 4 >= text.Length) { throw SyntaxError(index, "Incomplete \\u escape in string"); } int u = 0; for (int i = 0; i < 4; i++) { u *= 16; switch (text[index + i]) { case '0': u += 0; break; case '1': u += 1; break; case '2': u += 2; break; case '3': u += 3; break; case '4': u += 4; break; case '5': u += 5; break; case '6': u += 6; break; case '7': u += 7; break; case '8': u += 8; break; case '9': u += 9; break; case 'a': case 'A': u += 10; break; case 'b': case 'B': u += 11; break; case 'c': case 'C': u += 12; break; case 'd': case 'D': u += 13; break; case 'e': case 'E': u += 14; break; case 'f': case 'F': u += 15; break; default: throw SyntaxError(index+i, "Incomplete \\u escape in string"); } } buffer.Append(char.ConvertFromUtf32(u)); return 4; } #endregion #region Formatting literals /// <summary> /// Append a string representation of <paramref name="value"/> /// to <paramref name="result"/>. Strings are formatted as /// C like strings, <c>null</c> as "null", boolean values /// as "true" or "false", and numbers using invariant culture. /// </summary> public static void FormatValue(object value, StringBuilder result) { if (value == null) { result.Append("null"); return; } if (value is bool b) { result.Append(b ? "true" : "false"); return; } if (value is string s) { FormatString(s, result); return; } result.AppendFormat(CultureInfo.InvariantCulture, "{0}", value); } private static void FormatString(string value, StringBuilder result) { int len = value.Length; result.Append('"'); for (int j = 0; j < len; j++) { char c = value[j]; const string escapes = "\"\"\\\\\bb\ff\nn\rr\tt"; int k = escapes.IndexOf(c); if (k >= 0 && k % 2 == 0) { result.Append('\\'); result.Append(escapes[k + 1]); } else if (char.IsControl(c)) { result.AppendFormat("\\u{0:x4}", (int)c); } else { result.Append(c); } } result.Append('"'); } #endregion public static Exception SyntaxError(int position, string format, params object[] args) { var sb = new StringBuilder(); sb.AppendFormat(format, args); sb.AppendFormat(" (at position {0})", position); return new FormatException(sb.ToString()); } #region Nested types: Token and TokenType private readonly struct Token { public readonly int Index; public readonly TokenType Type; public readonly object Value; private Token(int index, TokenType type, object value) { Index = index; Type = type; Value = value; } public static Token Name(string value, int index) { return new Token(index, TokenType.Name, value); } public static Token String(string value, int index) { return new Token(index, TokenType.String, value); } public static Token Number(double value, int index) { return new Token(index, TokenType.Number, value); } public static Token Operator(string value, int index) { return new Token(index, TokenType.Operator, value); } public static Token End(int index) { return new Token(index, TokenType.End, null); } public static Token None => new Token(0, TokenType.None, null); } private enum TokenType { None = 0, Name, String, Number, Operator, End } #endregion } }
#!/bin/bash echo "This is a simple password generator" echo "Please enter the length of the password: " read PASS_LENGTH for p in $(seq 1 10); do openssl rand -base64 48 | cut -c1-$PASS_LENGTH done echo "Successfully Generated!"
const {ApolloGenerator, loadRemoteSchema} = require("graphql-ts-client-codegen"); const path = require("path"); const generator = new ApolloGenerator({ schemaLoader: async() => { return loadRemoteSchema("http://localhost:8080/graphql"); }, targetDir: path.join(__dirname, "../src/__generated"), /* * Daprtment.avgSalary is an expensive calculation property, * declaring it in the default fetcher "department$$" is not an good idea. * * Department.avgSalary is neither association nor parameterized, * so declaring it in "department$$" is the default behavior, * but we can exclude it manually. */ defaultFetcherExcludeMap: { "Department": ["avgSalary"] }, }); generator.generate();
import showModal from "discourse/lib/show-modal"; export default Ember.Component.extend({ classNames: ["bulk-select-container"], actions: { showBulkActions() { const controller = showModal("topic-bulk-actions", { model: { topics: this.get("selected"), category: this.get("category") }, title: "topics.bulk.actions" }); controller.set("refreshClosure", () => this.sendAction()); } } });
package com.ge.verdict.attackdefensecollector.model; import java.util.Optional; /** Confidentiality, Integrity, or Availability (the CIA triad). */ public enum CIA { C("Confidentiality"), I("Integrity"), A("Availability"); private String fullName; private CIA(String fullName) { this.fullName = fullName; } /** @return the full name (e.g. "Integrity" instead of just "I"). */ public String getFullName() { return fullName; } /** * Constructs a CIA from a string. Ignores case and accepts short form (e.g. "I") and long form * (e.g. "Integrity"). * * @param str the string to parse * @return the parsed CIA, or empty */ public static Optional<CIA> fromStringOpt(String str) { switch (str.toLowerCase()) { case "c": case "confidentiality": return Optional.of(C); case "i": case "integrity": return Optional.of(I); case "a": case "availability": return Optional.of(A); default: return Optional.empty(); } } /** * Constructs a CIA from a string. Same as fromStringOpt(), except throws an exception instead * of returning an empty option. * * @param str the string to parse * @return the parsed CIA */ public static CIA fromString(String str) { Optional<CIA> opt = fromStringOpt(str); if (opt.isPresent()) { return opt.get(); } else { throw new RuntimeException("Invalid CIA string: " + str); } } /** * Constructs a CIA from the first valid CIA string in a sequence of strings. Throws an * exception if none of the strings is a valid CIA string. * * @param strs the possible strings to parse * @return the parsed CIA */ public static CIA fromStrings(String... strs) { // Check all for (String str : strs) { Optional<CIA> opt = fromStringOpt(str); if (opt.isPresent()) { // Return first one found return opt.get(); } } // None found StringBuilder msg = new StringBuilder(); msg.append("No valid CIA found in strings: "); for (String str : strs) { msg.append(str); msg.append(","); } throw new RuntimeException(msg.toString()); } }
import 'package:dashbook/dashbook.dart'; import 'package:flame/game.dart'; import '../../commons/commons.dart'; import 'follow_object.dart'; import 'zoom.dart'; void addCameraAndViewportStories(Dashbook dashbook) { dashbook.storiesOf('Camera & Viewport') ..add( 'Follow Object', (context) { return GameWidget( game: CameraAndViewportGame( viewportResolution: Vector2( context.numberProperty('viewport width', 500), context.numberProperty('viewport height', 500), ), ), ); }, codeLink: baseLink('camera_and_viewport/follow_object.dart'), /* Text for instructions: Move around with W, A, S, D and notice how the camera follows the white square The blue squares can also be clicked to show how the coordinate system respect The camera transformation */ ) ..add( 'Zoom', (context) { return GameWidget( game: ZoomGame( viewportResolution: Vector2( context.numberProperty('viewport width', 500), context.numberProperty('viewport height', 500), ), ), ); }, codeLink: baseLink('camera_and_viewport/zoom.dart'), /* Text for instructions: On web: use scroll to zoom in and out On mobile: use scale gesture to zoom in and out */ ); }
using System.Collections.Generic; using NuPattern.VisualStudio.Extensions; using NuPattern.VisualStudio.Solution.Templates; namespace NuPattern.Runtime { /// <summary> /// Represents an installed extension that provides a toolkit. /// </summary> public interface IInstalledToolkitInfo : IToolkitInfo { /// <summary> /// Gets the installed extension information. /// </summary> IInstalledExtension Extension { get; } /// <summary> /// Gets the icon of the pattern. /// </summary> string PatternIconPath { get; } /// <summary> /// Gets the icon of the toolkit. /// </summary> string ToolkitIconPath { get; } /// <summary> /// Gets the schema information. /// </summary> IPatternModelInfo Schema { get; } /// <summary> /// Gets the VS Templates deployed by the toolkit. /// </summary> IEnumerable<IVsTemplate> Templates { get; } /// <summary> /// Gets the classification of the toolkit. /// </summary> IToolkitClassification Classification { get; } } }
using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Opendentity.Database.Entities; using Opendentity.Domain.Models; using Opendentity.Domain.RequestPipeline; using Opendentity.OpenId.Extensions; using Opendentity.OpenId.Services; using Shamyr.Exceptions; namespace Opendentity.Domain.CQRS.CurrentUser; public record SetCurrentUserPasswordCommand(SetPasswordModel Model): IRequest, ITransactionRequest; public class SetCurrentUserPasswordCommandHandler: IRequestHandler<SetCurrentUserPasswordCommand> { private readonly IHttpContextAccessor httpContextAccessor; private readonly UserManager<ApplicationUser> userManager; private readonly ISubjectTokenRevokationService subjectTokenRevokationService; public SetCurrentUserPasswordCommandHandler( IHttpContextAccessor httpContextAccessor, UserManager<ApplicationUser> userManager, ISubjectTokenRevokationService subjectTokenRevokationService) { this.httpContextAccessor = httpContextAccessor; this.userManager = userManager; this.subjectTokenRevokationService = subjectTokenRevokationService; } public async Task<Unit> Handle(SetCurrentUserPasswordCommand request, CancellationToken cancellationToken) { var user = await userManager.GetUserAsync(httpContextAccessor.HttpContext!.User); if (await userManager.HasPasswordAsync(user)) throw new ConflictException($"Current user has password set."); var result = await userManager.AddPasswordAsync(user, request.Model.Password); if (!result.Succeeded) throw new IdentityException(result); await subjectTokenRevokationService.RevokeAllAsync(user.Id, cancellationToken); return Unit.Value; } }
import pandas as pd from tklearn.datasets.base import Dataset examples = [ 'That\'s one small step for man, one giant leap for mankind.', 'When life gives you lemons, make lemonade.' ] data = { 'id': [i for i in range(len(examples))], 'text': examples, 'target': [1, 0], 'tokens': [x.split() for x in examples], 'token_targets': [pd.Series(['O' for t in x.split()], name='tokens') for x in examples], } ds = Dataset(data) ds = ds.assign(cleaned_text=ds.text.applymap(str.lower)) print(ds) print(ds.cleaned_text.to_list()) print(ds.token_targets.to_list())
// Copyright 2021 The LUCI 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. import stableStringify from 'fast-json-stable-stringify'; export const CRITICAL_HEADERS = Object.freeze(['accept', 'content-type', 'authorization']); /** * Generates a cache key for prpc-request. * A unique prefix should be added so different key-gen functions won't * accidentally generates the same key. * * Caveats: * * You may want to clone the request before calling this function because this * function consumes the request body. */ export async function genCacheKeyForPrpcRequest( prefix: string, req: Request, additionalCriticalHeaderKeys: readonly string[] = [] ) { // We don't clone the req here so the caller can avoid cloning if they // don't need to reuse the request body. const reqBody = await req.json(); return ( prefix + stableStringify([ req.url, CRITICAL_HEADERS.map((k) => req.headers.get(k)), additionalCriticalHeaderKeys.map((k) => req.headers.get(k)), // Remove properties that won't have any effect when the request hit the // server. e.g. `{ "pageToken": "" }` is the same as `{}`. removeDefaultProps(reqBody), ]) ); } /** * Returns a new object where false-ish properties and empty arrays from the * original object are removed. */ export function removeDefaultProps(obj: unknown): unknown { // Do not use `instanceof Array` because it may not work with cross frame // objects. if (Array.isArray(obj)) { return obj.map((ele) => removeDefaultProps(ele)); } // Do not use `instanceof Object` because // 1. it may not work with cross frame objects, and // 2. functions might be classified as objects. // Also check `&& obj` because `typeof null === 'object'`. if (typeof obj === 'object' && obj) { return Object.fromEntries( Object.entries(obj).flatMap(([key, item]) => { if (!item || (Array.isArray(item) && item.length === 0)) { return [] as Array<[string, unknown]>; } else { return [[key, removeDefaultProps(item)]] as Array<[string, unknown]>; } }) ); } return obj; }
using System; using System.ComponentModel.DataAnnotations; namespace HotelListingAppVersion2.Models { public class CreateHotelDTO { [Required] [StringLength(maximumLength:150, ErrorMessage = "Country Name is Too Long")] public string Name { get; set; } [Required] [StringLength(maximumLength: 150, ErrorMessage = " Address Name is Too Long")] public string Address { get; set; } [Required] [Range(1,5)] public double Rating { get; set; } [Required] public int CountryId { get; set; } } public class HotelDTO : CreateHotelDTO { public int Id { get; set; } public CountryDTO Country { get; set; } } }
import { Field, ID, Int, ObjectType } from '@nestjs/graphql'; import { CollectionModel } from './collection.model'; import { PlaceModel } from '../../places/models/place.model'; import { Collection, CollectionPlace, Place } from '.prisma/client'; @ObjectType() export class CollectionPlaceModel implements CollectionPlace { @Field(() => ID) id: string; @Field(() => CollectionModel) collection: Collection; @Field(() => PlaceModel) place: Place; collectionId: string; placeId: string; }
using System.Collections.Generic; using System.Linq; using System.Web; using Newtonsoft.Json; public class Ipfs { [JsonProperty("ipfsHash")] public string ipfsHash { get; set; } }
import { GameObjectType } from '../common/gameobjecttype'; export interface IGameObject { id: number; x: number; y: number; width: number; height: number; objecttype: GameObjectType; updatePos(x: number, y: number): void; }
--- layout: tagpage title: "Tag: IntelliJ" tag: IntelliJ ---
package com.journaldev.files; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermission; import java.util.HashSet; import java.util.Set; public class FilePermissions { /** * File Permissions Java Example using File and PosixFilePermission * @param args * @throws IOException */ public static void main(String[] args) throws IOException { File file = new File("/Users/pankaj/temp.txt"); //set application user permissions to 455 file.setExecutable(false); file.setReadable(false); file.setWritable(true); //change permission to 777 for all the users //no option for group and others file.setExecutable(true, false); file.setReadable(true, false); file.setWritable(true, false); //using PosixFilePermission to set file permissions 777 Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); //add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); //add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); //add others permissions perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); Files.setPosixFilePermissions(Paths.get("/Users/pankaj/run.sh"), perms); } }
//! //! Precision of the Measurement being Stored/Loaded //! use crate::InfluxError; use std::fmt; /// The time resolution the bucket is to keep its measurements #[derive(Debug, Clone)] pub enum Precision { /// Self explanatory nanoseconds Nanoseconds, /// Self explanatory microseconds Microseconds, /// Self explanatory milliseconds Milliseconds, /// Self explanatory seconds Seconds, } impl std::str::FromStr for Precision { type Err = InfluxError; fn from_str(s: &str) -> Result<Self, Self::Err> { let p = match s { "ns" => Precision::Nanoseconds, "u" => Precision::Microseconds, "ms" => Precision::Milliseconds, "s" => Precision::Seconds, _ => { return Err(format!("Invalid precision: {}", s).into()) } }; Ok(p) } } impl fmt::Display for Precision { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Precision::Nanoseconds => "ns".fmt(f), Precision::Microseconds => "u".fmt(f), Precision::Milliseconds => "ms".fmt(f), Precision::Seconds => "s".fmt(f), } } } impl Default for Precision { fn default() -> Self { Self::Nanoseconds } }
import sha1 from 'crypto-js/sha1'; import * as sdk from '../../../dist'; const authDataObj: any = { // 测试环境鉴权参数 dev: { access_key: '6374106c5eb449a4ad6c2430f30796e6', access_secret: 'defb3f69277340d5a0b55dc4831b5edb', }, }; export default { /** * @param authMode 是否开启鉴权 * @description 初始化鉴权 和 ready * @returns Promise */ init(authMode: boolean): Promise<any> { return new Promise((resolve, reject) => { const authData: any = authDataObj.dev; let result: any = null; // 鉴权成功返回的数据 const nonce: string = this.getRandomStr(6); // 随机字符串 const timestamp = `${new Date().getTime()}`; // 时间戳 const params = { access_key: authData.access_key, nonce, timestamp, signature: this.getSignature(authData.access_secret, nonce, timestamp), debug: false, }; // 开启日志 sdk.init({ debug: true, auth: authMode, useHttp: false }); // 非鉴权模式自动返回成功 if (!authMode) { return resolve({ code: 0 }); } // 开始鉴权 sdk .config(params) .then((data: any) => { const { result: res } = data; result = res; if (res && res.code !== 0) { reject(new Error('Authentication failed')); } }) .catch((err: any) => { reject(err); }); // 监听sdk异常 sdk.error((error: any) => { console.log('SDK API 异常', error); }); /** * 如果调用时,授权并未完成,则会在授权完成时触发; * 如果调用时,授权已经完成,则会马上被触发; */ sdk.ready(() => { resolve(result || { code: 0, message: '鉴权成功' }); // 走了ready 必定已经鉴权成功 }); }); }, /** * @description 获取签名 * @param accessSecret * @param nonce * @param timestamp * @returns string */ getSignature(accessSecret: string, nonce: string, timestamp: string): string { const content: string = [accessSecret, nonce, timestamp] .sort() .reduce((str: string, item: string): string => { const all = str + item; return all; }, ''); // 最终还需要转成全小写 const signature = sha1(content) .toString() .toLowerCase(); return signature; }, /** * @description 获取0-9随机数字符串 * @param n 随机数位数 */ getRandomStr(n: number): string { return Math.random() .toFixed(n) .slice(-n); }, };
#!/bin/bash # # Copyright (c) 2019-2020 P3TERX <https://p3terx.com> # # This is free software, licensed under the MIT License. # See /LICENSE for more information. # # https://github.com/P3TERX/Actions-OpenWrt # File name: diy-part1.sh # Description: OpenWrt DIY script part 1 (Before Update feeds) # # Uncomment a feed source sed -i 's/^#\(.*helloworld\)/\1/' feeds.conf.default # Add a feed source #sed -i '$a src-git lienol https://github.com/Lienol/openwrt-package' feeds.conf.default WORKINGDIR="`pwd`/feeds/packages/net/smartdns" mkdir $WORKINGDIR -p rm $WORKINGDIR/* -fr wget https://github.com/pymumu/openwrt-smartdns/archive/master.zip -O $WORKINGDIR/master.zip unzip $WORKINGDIR/master.zip -d $WORKINGDIR mv $WORKINGDIR/openwrt-smartdns-master/* $WORKINGDIR/ rmdir $WORKINGDIR/openwrt-smartdns-master rm $WORKINGDIR/master.zip LUCIBRANCH="lede" #更换此变量 WORKINGDIR="`pwd`/feeds/luci/applications/luci-app-smartdns" mkdir $WORKINGDIR -p rm $WORKINGDIR/* -fr wget https://github.com/pymumu/luci-app-smartdns/archive/${LUCIBRANCH}.zip -O $WORKINGDIR/${LUCIBRANCH}.zip unzip $WORKINGDIR/${LUCIBRANCH}.zip -d $WORKINGDIR mv $WORKINGDIR/luci-app-smartdns-${LUCIBRANCH}/* $WORKINGDIR/ rmdir $WORKINGDIR/luci-app-smartdns-${LUCIBRANCH} rm $WORKINGDIR/${LUCIBRANCH}.zip
import { ScaleLinear } from "d3-scale"; import { Container } from "../../../renderer/display"; import { Text } from "../../../renderer/text"; import { AXIS_HEIGHT } from "../depth-chart"; import { FONT_SIZE } from "../depth-chart"; /** * Draws a horizontal axis at the bottom of the chart */ export class HorizontalAxis extends Container { /** * Cache ticks */ private nodeByKeyValue = new Map<string, Text>(); constructor() { super(); } public update( scale: ScaleLinear<number, number>, width: number, height: number, resolution: number = 1 ) { const numTicks = width / resolution / 200; const ticks = scale.ticks(numTicks); const tickFormat = scale.tickFormat(numTicks); const enter = ticks.filter( (tick) => !this.nodeByKeyValue.has(tickFormat(tick)) ); const update = ticks.filter((tick) => this.nodeByKeyValue.has(tickFormat(tick)) ); const exit = [...this.nodeByKeyValue.keys()].filter( (node) => !(ticks.map(tickFormat).indexOf(node) !== -1) ); for (const node of enter) { const text = new Text(tickFormat(node), { fill: 0xa1a1a1, fontFamily: "monospace", fontSize: FONT_SIZE, }); text.x = scale(node); text.y = height - (resolution * AXIS_HEIGHT) / 2; text.anchor.set(0.5, 0.5); text.updateText(); // TODO: Should not need to call this this.nodeByKeyValue.set(tickFormat(node), text); this.addChild(text); } for (const node of update) { const text = this.nodeByKeyValue.get(tickFormat(node))!; text.x = scale(node); text.y = height - (resolution * AXIS_HEIGHT) / 2; } for (const node of exit) { const text = this.nodeByKeyValue.get(node)!; this.nodeByKeyValue.delete(node); this.removeChild(text); } } }
import os import numpy as np from loguru import logger import time import math import torch from torch import nn, optim from torch.nn import functional as F from torch.distributions import Normal import utils from utils.checker import * from functools import partial from utils import ph_helper from utils.ph_helper import get_gt_sel_loc, load_prior_with_patch_bank from model.transform import CanvasPlotter from model.transform import zcls_BHWK_to_psel_BHW_phw, coords_ij_to_distmap, transform_ij from model.vary_loc_at_modules import build_model from model.modules import gumbel_softmax from model.base import Base import torch.distributions as D def logmeanexp(inputs, dim=1): if inputs.size(dim) == 1: return inputs else: input_max = inputs.max(dim, keepdim=True)[0] return (inputs - input_max).exp().mean(dim).log() + input_max def draw_sample(logits_y, estimator=None, temp=None): ''' # do categorical sampling Ban this function: since we require y_logits_2_flat sampled recurssively?? perform sampling, given logits_y, sampled the 1-of-k hot vector Args: logits_y: B,...,K estimator (str): if gs, return soft vec ''' # return sampled y: [B,K] CHECK2D(logits_y) B,K = logits_y.shape if estimator == 'gs': y_sample = gumbel_softmax(logits=logits_y, temperature=temp, hard=False) y_flat = y_sample.view(-1) elif estimator == 'stgs': y_sample = gumbel_softmax(logits=logits_y, temperature=temp, hard=True) y_flat = y_sample.view(-1) else: raise NotImplementedError return y_flat.view(B,K) def draw_ber(probs, temp=None): return torch.bernoulli(probs).float() class CatVaryLocAT(Base): model_name = 'cat_vloc_at' auto_regressive_posterior = False discrete_loc = True def __init__(self, cfg): super().__init__() self.loc_dist = 'cat' self.n_class_loc = None self.prior_valid_step = None self.prior_loc_var = None self.z_dim = 0 self.cfg = cfg self.add_stop = cfg.cat_vae.add_stop self.setup_temp() self.init_data_param() # parse size: self.img_np = (self.img_size**2) * self.imgd self.canv_d = self.canvasd self.nloci = cfg.vary_loc_vae.nloc self.nlocj = 1 self.latent_dim = self.nloci*self.nlocj self.categorical_dim = self.cfg.K self.N = self.latent_dim self.K = self.categorical_dim logger.info('categorical_dim={}, nloc={}', self.categorical_dim, self.nloci*self.nlocj) # build model: self.try_load_float_matrix() self.build_model() self.xid = None self.info_dict = {'categorical_dim': self.K, 'nloci': self.nloci, 'nlocj':self.nlocj, 'ph': self.cfg.wh, 'pw':self.cfg.ww, 'canvas_size':self.canvas_size, 'img_size':self.img_size, 'latent_dim': self.latent_dim, 'imgd':self.imgd, 'canvasd': self.canvasd} self.pred_locvar = cfg.vary_loc_vae.pred_locvar if self.pred_locvar: assert(not cfg.vary_loc_vae.latent_loc_sample), 'not support' assert(self.float_matrix is not None and self.n_class_loc is not None) def build_model(self): ''' will be called in Base.class, need to set encoder and self.decoder ''' self.encoder, self.decoder = build_model(self.cfg, self.n_class_loc) def try_load_float_matrix(self): float_matrix_in_pridir = os.path.join(os.path.dirname(self.cfg.prior_weight), 'float_matrix.npy') if os.path.exists(float_matrix_in_pridir): logger.info('[LOAD] float_matrix from {}', float_matrix_in_pridir) float_matrix = torch.from_numpy(np.load(float_matrix_in_pridir)).float() self.n_class_loc = float_matrix.shape[1] CHECK3D(float_matrix) else: raise ValueError('loc_dist=cat require %s'%float_matrix_in_pridir) self.float_matrix = float_matrix return self.float_matrix # --------------------------- # Forward Function | # --------------------------- def decode(self, z): ''' vary loc Args: z: latent dict {'sampled_loc', 'sampled_sel', 'sampled_stp', ...} N = nloc - z_cls: B,N,K: 1-of-K vector - z_loc: B,N,2: range: -inf,+nan, need normalized - last dim is z_stp: B,N,1 Returns: pred: canvas: latent (tensor): [B,nloc,2,canvas_size, canvas_size] ''' pred, canv_dist = self.decoder(z) canvas, latent = canv_dist['canvas'], canv_dist['latent'] return pred, canvas, latent # --------------------------- # compute train loss fun | # --------------------------- def loss_function(self, recon_x, x, latent_dict, canvas): '''Compute BCE and KLD for ELBO pi_normed shape: B,nloc*nloc == latent_dim, K KLD = q_y * log(q_y / (1 / prob_prior)) = q_y * (log(q_y) - log(prop_prior), ) Args: recon_x: x: latent_dict: dict of latent: key: 'sampled_loc/sel/stp/extra_z' and 'logits_loc/sel/stp/extra_z': which is the parameters of different latent variable canvas: for vis Returns: loss_dict: ''' loss, vis = {}, {} B = recon_x.shape[0] K, nloc = self.categorical_dim, self.nloci*self.nlocj BCE = self.compute_recont_loss(recon_x, x, B) # == KL == all_KL, kl_lossd, kl_visd = self.compute_KL(latent_dict, canvas) # , latent) loss.update(kl_lossd) vis.update(kl_visd) # == ELBO == ELBO = self.cfg.kld_weight * all_KL + self.cfg.bce_weight * BCE loss.update({'BCE':BCE, 'ELBO': ELBO }) if self.xid is not None: assert(self.xid is not None) # require xid xid = self.xid.to(x.device) reg_loss, reg_vis = self.compute_reg_loss(xid, latent_dict, B) loss.update(reg_loss) vis.update(reg_vis) return loss, vis def compute_KL(self, latent_dict, canvas): ''' Args: latent_dict (dict) : {logits_sel, sampled_sel, sampled_stp, sampled_loc} canvas (tensor) ''' loss, vis = {}, {} B = canvas.shape[0] K, nloc = self.categorical_dim, self.nloci*self.nlocj assert(self.prior_model.name in ['rnn_one_head', 'cnn_head']) logits_sel = latent_dict['logits_sel'].view(B,nloc,K) log_q_z1_x = torch.log_softmax(logits_sel, dim=2) all_KL = 0 tic = time.time() if self.cfg.use_prior_model and self.cfg.kld_weight > 0: # -- prepare input for prior model -- # B,nloc,ksel | B,nloc,kloc | B,nloc,1 sampled_sel, sampled_loc, sampled_stp = latent_dict['sampled_sel'], \ latent_dict['sampled_loc'], latent_dict['sampled_stp'] CHECKSIZE(sampled_sel, (B,nloc,K)) CHECKSIZE(sampled_loc, (B,nloc,self.n_class_loc)) CHECKSIZE(sampled_stp, (B,nloc,1)) prior_input = torch.cat([sampled_sel, sampled_loc, sampled_stp], dim=2) prior_output, prior_output_sampled = self.prior_model.evaluate( prior_input) CHECKSIZE(prior_output, (B,nloc,K+self.n_class_loc+1)) py_pid_BNK = prior_output[:,:,:K] log_p_z1 = torch.log_softmax(py_pid_BNK, dim=2) CHECKTYPE(log_q_z1_x, log_p_z1) KLD_sel = log_q_z1_x.exp() * (-log_p_z1 + log_q_z1_x) KLD_sel = KLD_sel.view(B,nloc,K).sum(-1) log_q_z2_x = torch.log_softmax(latent_dict['logits_loc'].view( B,nloc,self.n_class_loc), dim=2) py_loc_BNK = prior_output[:,:,K:K+self.n_class_loc] log_p_z2 = torch.log_softmax(py_loc_BNK, dim=2) # log(p_z_sel) CHECKTYPE(log_q_z2_x, log_p_z2) KLD_loc = log_q_z2_x.exp() * (-log_p_z2 + log_q_z2_x) KLD_loc = KLD_loc.view(B,nloc,-1).sum(-1) assert(self.add_stop) prob_stp = latent_dict['logits_stp'] prob_stp = prob_stp.view(B,nloc) prior_valid_step = prior_output[:,:,-1] CHECKTYPE(prob_stp, prior_valid_step) eps = 1e-6 KLD_stp = prob_stp*(prob_stp/(prior_valid_step+eps) + eps).log() \ + (1-prob_stp) * ((1-prob_stp)/(eps+1-prior_valid_step) + eps).log() KLD_stp = KLD_stp.sum(-1) all_KL += KLD_stp loss.update({'KLD_stp_print': KLD_stp}) if latent_dict.get('sampled_stp') is not None: sel_stp = latent_dict['sampled_stp'] KLD_sel = KLD_sel * sel_stp.view(B,nloc) KLD_loc = KLD_loc * sel_stp.view(B,nloc) KLD_sel = KLD_sel.sum(-1) KLD_loc = KLD_loc.sum(-1) else: KLD_loc = logits_sel.new_zeros(B) KLD_sel = logits_sel.new_zeros(B) all_KL += KLD_loc+KLD_sel loss.update( { 'KLD_sel_print':KLD_sel, 'KLD_loc_print':KLD_loc, 'KLD': all_KL}) return all_KL, loss, vis def compute_reg_loss(self, xid, latent_dict, B): ''' compute KL( p_h(z|x); q(z|x) ); called by loss_function Args: xid (tensor): locs_mu_2BN_01 (tensor): (2,B,nloc), range(0,1), predicted location; log_q_z1_x (tensor): (B,nloc,K), logsoftmax of K selection; predicted patch selection Return: loss_dict, vis_dict ''' loss, vis = {}, {} K,ph,nloc = self.categorical_dim, self.cfg.wh, self.latent_dim prior_gt = self.prior_gt.index_select(0, xid) # B,N,5 # 4D: [cls, loci, locj, mask]; # ph_zcls:(B,nloc); ph_zloc_bn2_tl:(B,nloc,2); ph_mask:(B,nloc,1) ph_zcls, ph_zloc_bn2_tl, ph_mask = prior_gt[:,:,0],prior_gt[:,:,1:3], prior_gt[:,:,3:4] ph_zloc_bn2_tl = ph_zloc_bn2_tl.float() ph_mask = ph_mask.float() # pid,loci,locj,has_gt_patch,has_gt_loc ph_mask_loc = ph_mask if prior_gt.shape[-1] == 4 else prior_gt[:,:,4:5] # B,N,1 ph_mask_loc = ph_mask_loc.float() ph_zcls = ph_zcls.float() if self.cfg.cat_vae.n_samples > 1 and xid.shape[0] != B: size_g = self.prior_gt.shape[-1] B_ori = xid.shape[0] prior_gt = prior_gt.view(1, B_ori, nloc, size_g).expand( self.cfg.cat_vae.n_samples,-1,-1,-1).contiguous().view(B,nloc,size_g) ph_zloc_bn2_ctr = ph*0.5+ph_zloc_bn2_tl # (B,Nloc,2) range [0,28] # from (B,Nloc,2) to (B,Nloc,1) ph_zloc_bn2_ctr_ind = self.loc_transform_f2i(ph_zloc_bn2_ctr.view( B*nloc,2)).view(B,nloc,-1).max(2)[1] logits_loc = latent_dict['logits_loc'] # B,Nloc,ncls_loc CHECKSIZE(logits_loc, (B,nloc,self.n_class_loc)) loss['loc_loss'] = (F.nll_loss( torch.log_softmax( logits_loc.view(B*nloc,self.n_class_loc), dim=1), ph_zloc_bn2_ctr_ind.view(B*nloc).long(), ignore_index=-1, reduction='none')*ph_mask.view(B*nloc)).view(B,nloc).sum(-1) # -- debug used -- prob_stp = latent_dict.get('logits_stp') if prob_stp is not None: valid_mask = (ph_zcls >= 0).float() # B,nloc; if gets 0: skip current step ## ph_mask_loc expected to be same as valid_mask ? stp_target = valid_mask.view(B,nloc) loss['stp_loss'] = F.binary_cross_entropy(prob_stp.view(B,nloc), stp_target, reduction='none').view(B,-1).sum(-1) logits_sel = latent_dict['logits_sel'].view(B,nloc,K) log_q_z1_x = torch.log_softmax(logits_sel, dim=2) CHECKTYPE(loss['loc_loss'], ph_mask_loc, log_q_z1_x, ph_zcls) loss['sel_loss'] = (F.nll_loss( log_q_z1_x.view(B*nloc,K), ph_zcls.view(B*nloc).long(), ignore_index=-1, reduction='none')*ph_mask.view(B*nloc)).view(B,nloc).sum(-1) return loss, vis # ----------------------------------------------- # Eval Function: compute test elbo & vis | # ----------------------------------------------- @torch.no_grad() def test_loss(self, x, num_sample): ''' Args: x: input tensor, (B,C,H,W) num_sample: number of samples used to do iwae estimation of NLL Returns: output: (dict), {'pred': #pred img, shape(num_sample,B,C,H,W) out_d: (dict), {'NLL50', 'NLL1', 'NLL', 'BCE', 'KLD'} ''' output = {} B,K,N = x.shape[0], self.categorical_dim, self.N B_new = num_sample * B x = x.view(1,B,-1).expand(num_sample, -1, -1).contiguous().view(B_new,-1) # q(z|x), logits_loc: B,nloc,2 or B,nloc,3 estimator = 'stgs' if self.cfg.cat_vae.estimator == 'gs' else self.cfg.cat_vae.estimator latent_dict = self.encode(x, estimator) # use stgs if ## -- deal with cases where GT of some latent is given -- te_sel_gt = self.cfg.vary_loc_vae.te_sel_gt if te_sel_gt: self.xid = self.xid.view(1,B).expand(num_sample,-1).contiguous().view(-1) self.xid = None # set it as None to avoid computing loss # x ~ p(z|x); decoder also sample and turn z_loc into z_stp # TODO: add z_stp sampling ?? pred, canvas, latent = self.decode(latent_dict) # [test_loss] need to deal with prob_stp, to compute KL loss, vis = self.loss_function(pred, x, latent_dict, canvas) #, latent) output['pred'] = self.out2sampled(pred) BCE, KLD = loss['BCE'], loss['KLD'] BCE = BCE.view(num_sample,B,-1).sum(-1).view(num_sample, B).double() KLD = KLD.view(num_sample,B,-1).sum(-1).view(num_sample, B).double() log_weight = (- BCE) - KLD loss = - logmeanexp(log_weight, 0).mean() #loss = - helper.logmeanexp(log_weight, 0).mean() NLL = loss out_d = {'BCE':BCE.mean(), 'KLD':KLD.mean(), 'NLL': NLL} out_d[f'NLL{num_sample}'] = NLL out_d[f'NLL1'] = - log_weight.mean() return output, out_d def encode(self, x, estimator): ''' x -> q(z|x), gives the sample function to the encoder, s.t. the encoder can do sampling in the loop if needed ''' # sample z ~ q(z|x) latent_dict = self.encoder(x, sampler_sel=partial(draw_sample, estimator=estimator, temp=self.temp.detach()), sampler_stp=partial(draw_ber, temp=self.temp.detach()), sampler_loc=partial(draw_sample, estimator='stgs', temp=self.temp.detach()) ) return latent_dict def fillq_gt_ifnid(self, latent_dict): """ fill latent_dict with hand-crafted gt if needed Parameters ---------- latent_dict : dict with the sampled latent z Returns ------- latent_dict : dict updated latent_dict with the gt filled if needed """ te_sel_gt = self.cfg.vary_loc_vae.te_sel_gt if te_sel_gt: ## y_flat_gt: [B,Nloc,Ncls]; logits_loc_gt: [B,Nloc,Ncls] if te_sel_gt == 4: # need to do annealing, flip a coin to decide whether to use gt y_flat_gt, logits_loc_gt = self.get_gt_sel_loc(self.xid) nsample, nloc, _ = logits_loc_gt.shape # within test_loss, not using gt coin = torch.zeros_like(self.xid) + self.temp_gt_q coin = torch.bernoulli(coin).float().view(-1,1,1) # 1: use gt, 0: not use gt sampled_loc_gt = self.loc_transform_f2i( logits_loc_gt.view(nsample*nloc,2)*self.canvas_size).view(nsample, nloc, -1) latent_dict['sampled_loc'] = latent_dict['sampled_loc'] * (1-coin) + sampled_loc_gt * coin latent_dict['sampled_sel'] = latent_dict['sampled_sel'] * (1-coin) + y_flat_gt * coin return latent_dict @torch.no_grad() def vis(self, x): ''' x -> encode q(z|x) -> sampling z -> decode p(x|z) Args: x (tensor) Returns: stack of vis (tensor) ''' img_size = self.img_size Hc,Wc = self.canvas_size,self.canvas_size B,N,K = x.shape[0],self.N, self.K estimator = 'stgs' if self.cfg.cat_vae.estimator == 'gs' else self.cfg.cat_vae.estimator latent_dict = self.encode(x, estimator) ## -- deal with cases where GT of some latent is given -- self.xid = self.xid.view(B) latent_dict = self.fillq_gt_ifnid(latent_dict) pred, canvas, latent = self.decode(latent_dict) pred_out = self.out2sampled(pred).view(B,self.imgd,self.img_size,self.img_size) # B,1,H*ph,W*pw latent = latent.view(B,-1,2,self.canvasd,Hc,Wc) nloc = latent.shape[1] # -- before debuggging -- latent_vis = latent.view(-1,2*self.canvasd,Hc,Wc) latent_vis = F.interpolate(latent_vis, img_size, mode='bilinear', align_corners=True).view(B,-1,2,self.canvasd,img_size,img_size) # upsample canvas_vis = canvas.view(-1,self.canvasd,Hc,Wc) canvas_vis = F.interpolate(canvas_vis, img_size, mode='bilinear', align_corners=True).view(B,self.canvasd,img_size,img_size) # upsample vis_sp = [B,self.imgd, img_size,img_size] vis_canv = [B,self.canvasd,img_size,img_size] output = torch.cat([ latent_vis[:,:,1].max(1)[0].view(*vis_canv).expand(*vis_sp), canvas_vis.view(*vis_canv).expand(*vis_sp), pred_out.view(*vis_sp) ]) return output.view(-1,B,self.imgd,img_size,img_size) def compute_elbo(self, x): ''' x -> encoder q(z|x) -> sampling z -> compute elbo Args: x (tensor) Returns: elbo (value) ''' ### need to tile logits_loc b,n,k = x.shape[0],self.N, self.K latent_dict = self.encode(x, self.cfg.cat_vae.estimator) ## -- deal with cases where GT of some latent is given -- self.xid = self.xid.view(b) latent_dict = self.fillq_gt_ifnid(latent_dict) # For evaluation, we compute analytical KL, otherwise we cannot compare # get x ~ p(x|z_cls, z_loc, z_stp) B,N,K = x.shape[0],self.N, self.K pred, canvas, latent = self.decode(latent_dict) # B,1,H*ph,W*pw loss, vis = self.loss_function(pred, x, latent_dict, canvas) ## , latent) return loss, vis # ---------------------- # sample function | # ---------------------- @torch.no_grad() def sample_from_prior(self, B): ''' Returns: z (tensor): (B,canv_d,csize,csize) ''' img_size = self.img_size csize = self.canvas_size upscale = lambda x: F.interpolate(x.view(B,1,csize,csize), img_size) # sample: B,Nloc,canvas_size,canvas_size if self.prior_model.name == 'rnn_one_head' or self.prior_model.name == 'cnn_head': sample = self.prior_model.generate( shape=self.nloci*self.nlocj, batch_size=B) #64 z = {'sampled_sel': sample[:,:,:self.categorical_dim], 'sampled_loc': sample[:,:,self.categorical_dim:-1], 'sampled_stp': sample[:,:,-1].unsqueeze(2)} canvas = None else: sample, loc_map = self.prior_model.generate( shape=self.nloci*self.nlocj, batch_size=B) #64 sample = sample.view(B,self.nloci*self.nlocj,csize,csize)[:,-1:,:,:] # B,1,canvas_size,canvas_size if self.canv_d == 2: loc_m = loc_map.view(B,self.nloci*self.nlocj,csize,csize).max(1)[0].unsqueeze(1) #[:,-1:,:,:] z = torch.cat([sample, loc_m], dim=1) canvas = [sample, loc_m] if csize < img_size: canvas = [upscale(c) for c in canvas] if self.canv_d == 1: z = sample canvas = sample if csize == img_size else upscale(sample) return z, canvas @torch.no_grad() def sample(self, nsample=64): ''' draw samples: x ~ p(x|z), z ~ p(z) ''' B = nsample K = self.categorical_dim nsample_z = B # -- different way to draw sample, depends on the prior model -- if self.prior_model.name in ['rnn_one_head', 'cnn_head'] : latent_dict, _ = self.sample_from_prior(nsample_z) pred, canvas, _ = self.decode(latent_dict) else: sample, canvas = self.sample_from_prior(nsample_z) CHECKSIZE(sample, (B,1,self.canvas_size,self.canvas_size)) sshape = sample.shape[1:] # canv_d,csize,csize if nsample_z < B: sample = sample.view(1,nsample_z,-1).expand(B//nsample_z,-1,-1 ).contiguous().view(B,*sshape) # View as B,cd,cs,cs S = B pred, canvas = self.decoder.forward_with_canvas( sample, return_canvas=True) canvas = canvas['canvas'] pred = self.out2sampled(pred).view(B,self.imgd,self.img_size,self.img_size) return pred, canvas def get_optim(self, lr): logger.info('*'*30) logger.info('[build_optimizer] diff_lr: %d | '%( self.cfg.optim.diff_lr)) logger.info('*'*30) other_param, enc_param = [],[] head_loc = [] for name, param in self.named_parameters(): if param.requires_grad: if 'prior_model' in name: logger.info('found prior_model weight: {}', name) continue if 'encoder' in name: enc_param.append(param) else: other_param.append(param) diff_lr = self.cfg.optim.diff_lr if diff_lr == 0: lr_other = lr else: lr_other = 0.1 / diff_lr * lr logger.info('LR for enc: {}, LR for other: {}', lr, lr_other) # lr_other = 0.1*lr if self.cfg.optim.diff_lr else lr return optim.Adam([ {'params': enc_param, 'lr': lr}, {'params': other_param, 'lr': lr_other}], lr=lr) def set_bank(self, device): info_dict = self.info_dict self.patch_bank, self.prior_model, self.prior_gt = load_prior_with_patch_bank( info_dict=info_dict, cfg=self.cfg, device=device, metric=self.metric, n_class_loc=self.n_class_loc) float_matrix = self.float_matrix patch_bank = self.patch_bank self.grid_H = torch.arange(1., 1.+self.canvas_size).to(device).detach() self.zcls_BHWK_to_psel_BHW_phw = partial(zcls_BHWK_to_psel_BHW_phw, info_dict=info_dict, patch_bank=patch_bank) self.coords_ij_to_distmap = partial(coords_ij_to_distmap, info_dict=info_dict, grid_H=self.grid_H) self.transform_ij = partial(transform_ij, info_dict=info_dict, grid_H=self.grid_H) self.get_gt_sel_loc = partial(get_gt_sel_loc, info_dict, self.prior_gt) self.vis_prior_output = 0 float_matrix = float_matrix if float_matrix is not None else \ ph_helper.prepare_loc_float_matrix(self.canvas_size, self.cfg.vary_loc_vae.loc_stride) self.loc_transform_i2f = partial(ph_helper.loc_transform_i2f, float_matrix) self.loc_transform_f2i = partial(ph_helper.loc_transform_f2i, float_matrix) logger.info('[INIT] float_matrix: {}', float_matrix.shape) # -- set funct for decoder -- self.set_dec_func( self.zcls_BHWK_to_psel_BHW_phw, self.coords_ij_to_distmap, self.transform_ij, self.loc_transform_i2f, self.loc_transform_f2i) cfg = self.cfg self.canvas_plotter = CanvasPlotter(n_class_loc=self.n_class_loc, n_class_sel=cfg.K, nloc=cfg.vary_loc_vae.nloc, dataset=cfg.dataset, loc_dist='cat', device=device, patch_bank=self.patch_bank, patch_size=cfg.ww, ##patch_size, loc_stride=cfg.vary_loc_vae.loc_stride, add_stop=cfg.cat_vae.add_stop, loc_transform_i2f=self.loc_transform_i2f, loc_transform_f2i=self.loc_transform_f2i) if self.prior_model.name == 'cnn_head': logger.info('set plotter') self.prior_model.canvas_plotter = self.canvas_plotter def set_dec_func(self, *args): self.decoder.set_func(*args)
# Custom Iterator look at creating a custom iterator over pages which are represented as lines. # TODO - [ ] use Enumerable as per [Design patterns in ruby - Iterator example](https://github.com/davidgf/design-patterns-in-ruby/blob/master/iterator.md) - [ ] more on pattern http://www.informit.com/articles/article.aspx?p=1398604 - [ ] focus on simplifying the `pages` method - [ ] waht about using currying? https://stackoverflow.com/questions/4272114/simple-currying-in-ruby http://genua.github.io/ruby/2015/03/17/ruby-function-composition-and-more/ http://andrewberls.com/blog/post/partial-function-application-for-humans https://neiro.io/2016/03/08/partial-function-application-and-currying-in-ruby.html https://www.sitepoint.com/functional-programming-techniques-with-ruby-part-ii/ ```ruby doc = [ "Heading on page 1", "content of page 1", "footer page 1 of 3", "Heading on page 2", "content of page 2", "footer page 2 of 3", "Heading on page 3", "content of page 3", "footer page 3 of 3" ] ``` have an iterator that allows me to: * get all pages ```ruby doc.pages [ { 1: [ "Heading on page 1", "content of page 1", "footer page 1 of 3 ] }, { 2: [ "Heading on page 2", "content of page 2", "footer page 2 of 3", ] }, { 3: [ "Heading on page 3", "content of page 3", "footer page 3 of 3" ] } ] ``` * iterate through pages ```ruby doc.each_by_page do |page| page # ["Heading on page 1", "content of page 1", "footer page 1 of 3"] end ``` * get a particular page ```ruby doc.page(3) # ["Heading on page 3", "content of page 3", "footer page 3 of 3"] ```
## TODO - d.ts 文件合并 - ts-config 详细设置
package test.collections import stdhack.test.* import std.io.* import std.util.* import java.io.* import java.util.* class IoTest() : TestSupport() { fun testLineIteratorWithManualClose() { val reader = sample().buffered() try { val list = reader.lineIterator().toArrayList() assertEquals(arrayList("Hello", "World"), list) } finally { reader.close() } } fun sample() : Reader { return StringReader("Hello\nWorld"); } fun testLineIterator() { // TODO we should maybe zap the useLines approach as it encourages // use of iterators which don't close the underlying stream val list1 = sample().useLines{it.toArrayList()} val list2 = sample().useLines<ArrayList<String>>{it.toArrayList()} assertEquals(arrayList("Hello", "World"), list1) assertEquals(arrayList("Hello", "World"), list2) } fun testForEach() { val list = ArrayList<String>() val reader = sample().buffered() reader.foreach{ while (true) { val line = it.readLine() if (line != null) list.add(line) else break } } assertEquals(arrayList("Hello", "World"), list) } fun testForEachLine() { val list = ArrayList<String>() val reader = sample() /* TODO would be nicer maybe to write this as reader.lines.foreach { ... } as we could one day maybe one day write that as for (line in reader.lines) if the for(elem in thing) {...} statement could act as syntax sugar for thing.foreach{ elem -> ... } if thing is not an Iterable/array/Iterator but has a suitable foreach method */ reader.foreachLine{ list.add(it) } assertEquals(arrayList("Hello", "World"), list) } }
#! /bin/bash docker exec -it mongo mongodump --db swipe --collection names --out /tmp/mongo-backup docker cp mongo:/tmp/mongo-backup/ .
/* libpe - the PE library Copyright (C) 2010 - 2017 libpe authors This file is part of libpe. libpe 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, either version 3 of the License, or (at your option) any later version. libpe is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with libpe. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBPE_DIR_RESOURCES_H #define LIBPE_DIR_RESOURCES_H #include <stdint.h> #include <wchar.h> #ifdef __cplusplus extern "C" { #endif #define IMAGE_RESOURCE_NAME_IS_STRING 0x80000000 #define IMAGE_RESOURCE_DATA_IS_DIRECTORY 0x80000000 // REFERENCE: https://docs.microsoft.com/en-us/windows/win32/menurc/resource-types typedef enum { RT_CURSOR = 1, // cursor image RT_BITMAP = 2, // bitmap (.bmp) RT_ICON = 3, // icon RT_MENU = 4, // menu RT_DIALOG = 5, // dialog window RT_STRING = 6, // unicode string RT_FONTDIR = 7, // font directory RT_FONT = 8, // font RT_ACCELERATOR = 9, // hot keys RT_RCDATA = 10, // data RT_MESSAGETABLE = 11, // string table RT_GROUP_CURSOR = 12, // cursor group RT_GROUP_ICON = 14, // icon group RT_VERSION = 16, // version information RT_DLGINCLUDE = 17, // names of header files for dialogs (*.h) used by compiler RT_PLUGPLAY = 19, // data determined by application RT_VXD = 20, // vxd info RT_ANICURSOR = 21, // animated cursor RT_ANIICON = 22, // animated icon RT_HTML = 23, // html page RT_MANIFEST = 24, // manifest of Windows XP build RT_DLGINIT = 240, // strings used for initiating some controls in dialogs RT_TOOLBAR = 241 // configuration of toolbars } ResourceType; #pragma pack(push, 1) typedef struct { uint32_t Characteristics; uint32_t TimeDateStamp; uint16_t MajorVersion; uint16_t MinorVersion; uint16_t NumberOfNamedEntries; uint16_t NumberOfIdEntries; } IMAGE_RESOURCE_DIRECTORY; typedef struct { union { struct { uint32_t NameOffset:31; uint32_t NameIsString:1; } data; uint32_t Name; uint16_t Id; } u0; union { uint32_t OffsetToData; struct { uint32_t OffsetToDirectory:31; uint32_t DataIsDirectory:1; } data; } u1; } IMAGE_RESOURCE_DIRECTORY_ENTRY; typedef struct { uint16_t Length; char String[1]; } IMAGE_RESOURCE_DATA_STRING; typedef struct { uint16_t Length; // Number of Unicode characters wchar_t String[1]; } IMAGE_RESOURCE_DATA_STRING_U; typedef struct { uint32_t OffsetToData; uint32_t Size; uint32_t CodePage; uint32_t Reserved; } IMAGE_RESOURCE_DATA_ENTRY; typedef struct { uint32_t dwSignature; uint32_t dwStrucVersion; uint32_t dwFileVersionMS; uint32_t dwFileVersionLS; uint32_t dwProductVersionMS; uint32_t dwProductVersionLS; uint32_t dwFileFlagsMask; uint32_t dwFileFlags; uint32_t dwFileOS; uint32_t dwFileType; uint32_t dwFileSubtype; uint32_t dwFileDateMS; uint32_t dwFileDateLS; } VS_FIXEDFILEINFO; #pragma pack(pop) #ifdef __cplusplus } // extern "C" #endif #endif
package gulajava.speedcepat.hitungkecepatan import android.app.Application import android.arch.lifecycle.AndroidViewModel import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import android.content.Context import android.location.Address import android.location.Location import gulajava.jdwl.locations.CekGPSNet import gulajava.speedcepat.Konstans import gulajava.speedcepat.database.models.DbSetelan import gulajava.speedcepat.database.repositorys.RepoHitungKecepatan import gulajava.speedcepat.internets.models.GeocodingLocationModel import gulajava.speedcepat.locationutils.GeocoderLocationParsers import gulajava.speedcepat.models.KecepatanItems import gulajava.speedcepat.models.MsgHasilGeocoder import gulajava.speedcepat.states.StateData import gulajava.speedcepat.states.StateKecepatanBatas import gulajava.speedcepat.states.StateKonstans import gulajava.speedcepat.dataparsers.DataParsers import gulajava.speedcepat.dataparsers.KecepatanParsers import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.PublishSubject import org.joda.time.DateTime /** * Created by Gulajava Ministudio on 6/23/18. */ class HitungKecepatanViewModel : AndroidViewModel, HitungKecepatanContract.Presenter { private val mApplication: Application private val mKecepatanParsers: KecepatanParsers private val mDataParsers: DataParsers private val mGeocodersLokasi: GeocoderLocationParsers private val mRepoHitungKecepatan: RepoHitungKecepatan = RepoHitungKecepatan(this@HitungKecepatanViewModel) private var mDbSetelan: DbSetelan = DbSetelan() //ambil lokasi pengguna private var mDoubleLatitude = 0.0 private var mDoubleLongitude = 0.0 private var mLocationPengguna: Location = Location("") private var mLocationAwal: Location = Location("") private var mLocationAkhir: Location = Location("") private var mLongWaktuAwal: Long = 0 private var mLongWaktuAkhir: Long = 0 private var isInternet: Boolean = false private var isNetworkNyala: Boolean = false private var isNetworkGPS: Boolean = false private var mCekGPSNet: CekGPSNet? = null private var isInitPengukurOK: Boolean = false private var mKecepatanItemsPengguna: KecepatanItems = KecepatanItems() private lateinit var mCompositeDisposable: CompositeDisposable private var mPublishSubjectHitungGeocoder: PublishSubject<Boolean> = PublishSubject.create() private var mPublishSubjectHitungKecepatan: PublishSubject<Boolean> = PublishSubject.create() private var mPublishSubjectCekBatasKecepatan: PublishSubject<Boolean> = PublishSubject.create() // live data private val mGeocoderPenggunaLiveData: MutableLiveData<MsgHasilGeocoder> = MutableLiveData() private val mStatesViewLiveData: MutableLiveData<StateData> = MutableLiveData() private val mKecepatanItemLiveData: MutableLiveData<KecepatanItems> = MutableLiveData() private val mBatasKecepatanStatusLiveData: MutableLiveData<StateKecepatanBatas> = MutableLiveData() private val mDbSetelanLiveData: MutableLiveData<DbSetelan> = MutableLiveData() constructor(application: Application) : super(application) { mApplication = application mKecepatanParsers = KecepatanParsers(mApplication.applicationContext) mDataParsers = DataParsers(mApplication.applicationContext) mGeocodersLokasi = GeocoderLocationParsers() } override fun getLiveDataAlamatLokasiPengguna(): LiveData<MsgHasilGeocoder> { return mGeocoderPenggunaLiveData } override fun getLiveDataNilaiKecepatan(): LiveData<KecepatanItems> { return mKecepatanItemLiveData } override fun getLiveDataDbSetelan(): LiveData<DbSetelan> { return mDbSetelanLiveData } override fun getLiveDataStateBatasKecepatan(): LiveData<StateKecepatanBatas> { return mBatasKecepatanStatusLiveData } override fun getLiveDataStateView(): LiveData<StateData> { return mStatesViewLiveData } override fun initSubscriber() { if (!this::mCompositeDisposable.isInitialized) { mCompositeDisposable = CompositeDisposable() } else { if (mCompositeDisposable.isDisposed) { mCompositeDisposable = CompositeDisposable() } } initPublishSubjectSubscriber() mRepoHitungKecepatan.initSubscriptions() } override fun stopSubscriber() { mCompositeDisposable.dispose() mRepoHitungKecepatan.stopSubscriptions() } override fun restartSubscribers() { mCompositeDisposable.dispose() if (!this::mCompositeDisposable.isInitialized) { mCompositeDisposable = CompositeDisposable() } else { if (mCompositeDisposable.isDisposed) { mCompositeDisposable = CompositeDisposable() } } initPublishSubjectSubscriber() } override fun initPublishSubjectSubscriber() { mCompositeDisposable.add( mPublishSubjectHitungGeocoder .observeOn(Schedulers.io()) .map { return@map mGeocodersLokasi.getFromUrlsLocation( mDoubleLatitude, mDoubleLongitude ) } .flatMap { stringurl: String -> return@flatMap mGeocodersLokasi.getObservableRequestGeocoders(stringurl) } .map { geocodingmodel: GeocodingLocationModel -> return@map mGeocodersLokasi.parseJsonDataLokasiGeocoder(geocodingmodel) } .map { arraylistalamat: ArrayList<Address> -> return@map mGeocodersLokasi.getDataGeocoderAddress(arraylistalamat) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { msghasilgeocoder: MsgHasilGeocoder? -> val stringAlamatGabungan: String = msghasilgeocoder?.mStringAlamatGabungan ?: "" if (stringAlamatGabungan.isNotEmpty() && msghasilgeocoder != null) { // setel posisi gps pengguna setelTeksLokasiPengguna(msghasilgeocoder) } }, { error: Throwable? -> error?.printStackTrace() restartSubscribers() } ) ) mCompositeDisposable.add( mPublishSubjectHitungKecepatan .observeOn(Schedulers.single()) .map { val kecepatanItems: KecepatanItems = mKecepatanParsers.hitungKecepatanKendaraan( mLocationAwal, mLocationAkhir, mLongWaktuAwal, mLongWaktuAkhir ) val stringBatasKecepatan: String = mDbSetelan.stringKecepatanMaks kecepatanItems.mStringBatasKecepatan = stringBatasKecepatan val stringTipeBatasKecepatan: String = mDbSetelan.stringTipeKecepatan kecepatanItems.mStringTipeKecepatanBatas = stringTipeBatasKecepatan // testing error val nilaiKecepatan = (kecepatanItems.mIntKecepatanKmh + 1).toString() return@map kecepatanItems } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { kecepatanitems: KecepatanItems? -> // setel teks kecepatan pengguna if (kecepatanitems != null) { mKecepatanItemsPengguna = kecepatanitems mKecepatanItemLiveData.postValue(mKecepatanItemsPengguna) // task ambil geocoder pengguna startTaskAmbilGeocoderPengguna() // cek batas kecepatan cekBatasKecepatanKendaraan() } }, { error: Throwable? -> error?.printStackTrace() } ) ) mCompositeDisposable.add( mPublishSubjectCekBatasKecepatan .observeOn(Schedulers.single()) .map { _: Boolean -> val isKecepatanLewatBatas: Boolean val stringTipeKecepatan: String = mDbSetelan.stringTipeKecepatan val stringBatasKecepatan: String = mDbSetelan.stringKecepatanMaks val doubleBatasKecepatan: Double = stringBatasKecepatan.toDoubleOrNull() ?: 70.toDouble() val mDoubleKecepatanKmh: Double = mKecepatanItemsPengguna.mIntKecepatanKmh.toDouble() val mDoubleKecepatanMph: Double = mKecepatanItemsPengguna.mIntKecepatanMph.toDouble() val mDoubleKecepatanKnot: Double = mKecepatanItemsPengguna.mIntKecepatanKnot.toDouble() when (stringTipeKecepatan) { Konstans.STR_KMH -> { isKecepatanLewatBatas = mDoubleKecepatanKmh >= doubleBatasKecepatan } Konstans.STR_MPH -> { isKecepatanLewatBatas = mDoubleKecepatanMph >= doubleBatasKecepatan } Konstans.STR_KNT -> { isKecepatanLewatBatas = mDoubleKecepatanKnot >= doubleBatasKecepatan } else -> { isKecepatanLewatBatas = mDoubleKecepatanKmh >= doubleBatasKecepatan } } return@map isKecepatanLewatBatas } .subscribeOn(Schedulers.single()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { isKecepatanLewatBatas: Boolean? -> if (isKecepatanLewatBatas == true || isKecepatanLewatBatas == false) { sendNotifikasiBatasKecepatan(isKecepatanLewatBatas) } }, { error: Throwable? -> error?.printStackTrace() } ) ) } override fun cekStatusKoneksiGPSInternet() { val context: Context? = mApplication.applicationContext mCekGPSNet = context?.let { CekGPSNet(it) } isInternet = mCekGPSNet?.cekStatusInternet() ?: false isNetworkNyala = mCekGPSNet?.cekStatusNetworkGSM() ?: false isNetworkGPS = mCekGPSNet?.cekStatusNetwork() ?: false } override fun cekLokasiPengguna(location: Location) { mLocationPengguna = location mDoubleLatitude = mLocationPengguna.latitude mDoubleLongitude = mLocationPengguna.longitude val lokasiPenggunaString = mDoubleLatitude.toString() + ", " + mDoubleLongitude.toString() val msgHasilGeocoder = MsgHasilGeocoder() msgHasilGeocoder.mStringAlamatGabungan = lokasiPenggunaString setelTeksLokasiPengguna(msgHasilGeocoder) startTaskAmbilGeocoderPengguna() // ambil untuk menghitung kecepatan mLocationAwal = location mLocationAkhir = location val dateTimed = DateTime() mLongWaktuAwal = dateTimed.millis mLongWaktuAkhir = dateTimed.millis mDoubleLatitude = mLocationAwal.latitude mDoubleLongitude = mLocationAwal.longitude isInitPengukurOK = true // hitung lokasi kecepatan task if (isInitPengukurOK) { hitungKecepatanKendaraan() } } override fun cekLokasiPenggunaUpdate(location: Location) { mLocationPengguna = location mDoubleLatitude = mLocationPengguna.latitude mDoubleLongitude = mLocationPengguna.longitude val lokasiPenggunaString = mDoubleLatitude.toString() + ", " + mDoubleLongitude.toString() val msgHasilGeocoder = MsgHasilGeocoder() msgHasilGeocoder.mStringAlamatGabungan = lokasiPenggunaString setelTeksLokasiPengguna(msgHasilGeocoder) // mulai ambil geocoder startTaskAmbilGeocoderPengguna() // cek apakah status pengukur sudah di inisialisasi atau belum if (!isInitPengukurOK) { // ambil untuk menghitung kecepatan mLocationAwal = location mLocationAkhir = location val dateTimed = DateTime() mLongWaktuAwal = dateTimed.millis mLongWaktuAkhir = dateTimed.millis mDoubleLatitude = mLocationAwal.latitude mDoubleLongitude = mLocationAwal.longitude // setel status pengukur sudah ok isInitPengukurOK = true } else { // jika pengukur sudah diinisialisasi //perbarui data waktu, waktu akhir jadi waktu awal, // dan waktu baru jadi waktu akhir mLongWaktuAwal = mLongWaktuAkhir val dateTime = DateTime() mLongWaktuAkhir = dateTime.millis // perbarui data lokasi, lokasi akhir jadi lokasi awal, // lokasi baru jadi lokasi akhir mLocationAwal = mLocationAkhir mLocationAkhir = location mDoubleLatitude = mLocationAkhir.latitude mDoubleLongitude = mLocationAkhir.longitude } //hitung lokasi kecepatan task //jika pengukur lagi aktif if (isInitPengukurOK) { hitungKecepatanKendaraan() } } override fun setelTeksLokasiPengguna(msgHasilGeocoder: MsgHasilGeocoder) { mGeocoderPenggunaLiveData.postValue(msgHasilGeocoder) } override fun startTaskAmbilGeocoderPengguna() { if (mPublishSubjectHitungGeocoder.hasObservers()) { mPublishSubjectHitungGeocoder.onNext(true) } } override fun hitungKecepatanKendaraan() { if (mPublishSubjectHitungKecepatan.hasObservers()) { mPublishSubjectHitungKecepatan.onNext(true) } } override fun getDataBatasKecepatanDb() { mRepoHitungKecepatan.cekDatabaseSetelan() } override fun setDataBatasKecepatanDb(dbSetelan: DbSetelan) { mDbSetelan = dbSetelan mDbSetelanLiveData.postValue(mDbSetelan) } override fun cekBatasKecepatanKendaraan() { if (mPublishSubjectCekBatasKecepatan.hasObservers()) { mPublishSubjectCekBatasKecepatan.onNext(true) } } override fun sendNotifikasiBatasKecepatan(isKecepatanLewatBatas: Boolean) { val stateKecepatanBatas = StateKecepatanBatas() stateKecepatanBatas.intKodeState = StateKonstans.STATE_STATUS_BATAS_KECEPATAN stateKecepatanBatas.isBatasMelebihi = isKecepatanLewatBatas mBatasKecepatanStatusLiveData.postValue(stateKecepatanBatas) } override fun stopHitungKecepatan() { isInitPengukurOK = false restartSubscribers() } override fun tampilPesanPeringatan(resID: Int) { val stateData = StateData() stateData.intKodeState = StateKonstans.STATE_SHOW_TOAST stateData.intPayloadData = resID mStatesViewLiveData.value = stateData } }
// <copyright file="SequenceStep.cs" company="natsnudasoft"> // Copyright (c) Adrian John Dunstan. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> namespace Natsnudasoft.RgbLedSequencerLibrary { using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using Natsnudasoft.NatsnudaLibrary; /// <summary> /// Describes an individual step, and the delay time of the step, within an RGB LED Sequencer /// sequence. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public sealed class SequenceStep : IEquatable<SequenceStep> { /// <summary> /// Initializes a new instance of the <see cref="SequenceStep"/> class. /// </summary> /// <param name="sequencerConfig">The <see cref="IRgbLedSequencerConfiguration"/> that /// describes the configuration of the RGB LED Sequencer.</param> /// <param name="grayscaleData">The <see cref="RgbLedSequencerLibrary.GrayscaleData"/> that /// this step has. /// </param> /// <param name="stepDelay">The step delay (time to wait at the end of this step) value for /// this step. This value must be positive, and can not be larger than the maximum step /// delay defined in the specified configuration.</param> /// <exception cref="ArgumentNullException"><paramref name="sequencerConfig"/>, or /// <paramref name="grayscaleData"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="stepDelay"/> is less than /// zero or larger than the maximum step delay defined in the specified configuration. /// </exception> public SequenceStep( IRgbLedSequencerConfiguration sequencerConfig, GrayscaleData grayscaleData, int stepDelay) { ParameterValidation.IsNotNull(sequencerConfig, nameof(sequencerConfig)); ParameterValidation.IsNotNull(grayscaleData, nameof(grayscaleData)); ParameterValidation.IsBetweenInclusive( stepDelay, 0, sequencerConfig.MaxStepDelay, nameof(stepDelay)); this.GrayscaleData = grayscaleData; this.StepDelay = stepDelay; } /// <summary> /// Initializes a new instance of the <see cref="SequenceStep"/> class, using the /// specified factory to create a <see cref="GrayscaleData"/> instance. /// </summary> /// <param name="sequencerConfig">The <see cref="IRgbLedSequencerConfiguration"/> that /// describes the configuration of the RGB LED Sequencer.</param> /// <param name="grayscaleDataFactory">The factory to use to create instances of /// <see cref="RgbLedSequencerLibrary.GrayscaleData"/>.</param> /// <param name="stepDelay">The step delay (time to wait at the end of this step) value for /// this step. This value must be positive, and can not be larger than the maximum step /// delay defined in the specified configuration.</param> /// <exception cref="ArgumentNullException"><paramref name="sequencerConfig"/>, or /// <paramref name="grayscaleDataFactory"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="stepDelay"/> is less than /// zero or larger than the maximum step delay defined in the specified configuration. /// </exception> public SequenceStep( IRgbLedSequencerConfiguration sequencerConfig, Func<GrayscaleData> grayscaleDataFactory, int stepDelay) { ParameterValidation.IsNotNull(sequencerConfig, nameof(sequencerConfig)); ParameterValidation.IsNotNull(grayscaleDataFactory, nameof(grayscaleDataFactory)); ParameterValidation.IsBetweenInclusive( stepDelay, 0, sequencerConfig.MaxStepDelay, nameof(stepDelay)); #pragma warning disable CC0031 // Check for null before calling a delegate this.GrayscaleData = grayscaleDataFactory(); #pragma warning restore CC0031 // Check for null before calling a delegate this.StepDelay = stepDelay; } /// <summary> /// Gets the grayscale data for the RGB LED Sequencer at this step. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public GrayscaleData GrayscaleData { get; } /// <summary> /// Gets the step delay (time to wait at the end of this step) value for this step. /// </summary> public int StepDelay { get; } /// <summary> /// Gets the debugger display string. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] [EditorBrowsable(EditorBrowsableState.Never)] public string DebuggerDisplay => string.Format( CultureInfo.CurrentCulture, "{{{0}: {1}, {2}: {3}}}", nameof(this.GrayscaleData), this.GrayscaleData.DebuggerDisplay, nameof(this.StepDelay), this.StepDelay); /// <inheritdoc/> public bool Equals(SequenceStep other) { bool result; if (ReferenceEquals(other, null)) { result = false; } else if (ReferenceEquals(other, this)) { result = true; } else { var grayscaleDataEqual = ReferenceEquals(other.GrayscaleData, this.GrayscaleData) || (other.GrayscaleData?.Equals(this.GrayscaleData)).GetValueOrDefault(); result = grayscaleDataEqual && other.StepDelay == this.StepDelay; } return result; } /// <inheritdoc/> public override bool Equals(object obj) { return this.Equals(obj as SequenceStep); } /// <inheritdoc/> public override int GetHashCode() { const int InitPrime = 17; const int MultPrime = 23; var hash = InitPrime; unchecked { hash = (hash * MultPrime) + (this.GrayscaleData != null ? this.GrayscaleData.GetHashCode() : 0); hash = (hash * MultPrime) + this.StepDelay.GetHashCode(); } return hash; } } }
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'My::Blogs', type: :request do describe 'GET /my/blogs' do context 'When user does not logged in' do it 'is returned 302' do get my_blogs_path expect(response).to have_http_status(302) end end context 'When user logged in' do let(:user) { create(:user, :with_identity) } before do sign_in(user) end it 'is returned 200 OK' do get my_blogs_path expect(response).to have_http_status(200) end end end describe 'GET /my/blogs/new' do context 'When user does not logged in' do it 'is returned 302' do get new_my_blog_path expect(response).to have_http_status(302) end end context 'When user logged in' do let(:user) { create(:user, :with_identity) } before do sign_in(user) end it 'is returned 200 OK' do get new_my_blog_path expect(response).to have_http_status(200) end end end describe 'POST /my/blogs' do context 'When user does not logged in' do it 'is returned 302' do post my_blogs_path expect(response).to have_http_status(302) end end context 'When user logged in' do let(:user) { create(:user, :with_identity) } before do sign_in(user) end context 'When blog is written by user' do context 'With valid params' do let(:params) { { form_blog_contribution: { title: 'new title', body: 'new body' } } } it 'is returned 200 OK' do post my_blogs_path, params: params expect(response).to have_http_status(200) body = response.body expect(body).to include 'new title' expect(body).to include 'new body' end end context 'With invalid params' do let(:params) { { form_blog_contribution: { title: '', body: 'new body' } } } it 'is returned 200 OK' do post my_blogs_path, params: params expect(response).to have_http_status(200) expect(response).to render_template(:new) end end end end end describe 'GET /my/blogs/:id' do let(:other_user_blog) { create(:blog, author) } context 'When user does not logged in' do let(:blog) { create(:blog, :with_author) } it 'is returned 302' do get my_blog_path(blog.id) expect(response).to have_http_status(302) end end context 'When user logged in' do let(:user) { create(:user, :with_identity) } before do sign_in(user) end context 'When blog is written by user' do let(:blog) { create(:blog, author: user) } it 'is returned 200 OK' do get my_blog_path(blog.id) expect(response).to have_http_status(200) end end context 'When blog is written by other user' do let(:blog) { create(:blog, :with_author) } it 'is expected to raise record not found' do expect { get edit_my_blog_path(blog.id) }.to raise_error(ActiveRecord::RecordNotFound) end end end end describe 'GET /my/blogs/:id/edit' do let(:other_user_blog) { create(:blog, author) } context 'When user does not logged in' do let(:blog) { create(:blog, :with_author) } it 'is returned 302' do get edit_my_blog_path(blog.id) expect(response).to have_http_status(302) end end context 'When user logged in' do let(:user) { create(:user, :with_identity) } before do sign_in(user) end context 'When blog is written by user' do let(:blog) { create(:blog, author: user) } it 'is returned 200 OK' do get edit_my_blog_path(blog.id) expect(response).to have_http_status(200) end end context 'When blog is written by other user' do let(:blog) { create(:blog, :with_author) } it 'is expected to raise record not found' do expect { get edit_my_blog_path(blog.id) }.to raise_error(ActiveRecord::RecordNotFound) end end end end describe 'PATCH /my/blogs/:id' do let(:other_user_blog) { create(:blog, author) } context 'When user does not logged in' do let(:blog) { create(:blog, :with_author) } it 'is returned 302' do patch my_blog_path(blog.id) expect(response).to have_http_status(302) end end context 'When user logged in' do let(:user) { create(:user, :with_identity) } before do sign_in(user) end context 'When blog is written by user' do let(:blog) { create(:blog, author: user) } context 'With valid params' do let(:params) { { form_blog_contribution: { title: 'updated title', body: 'updated body' } } } it 'is returned 200 OK' do patch my_blog_path(blog.id), params: params expect(response).to have_http_status(200) body = response.body expect(body).to include 'updated title' expect(body).to include 'updated body' end end context 'With invalid params' do let(:params) { { form_blog_contribution: { title: '', body: 'updated body' } } } it 'is returned 200 OK' do patch my_blog_path(blog.id), params: params expect(response).to have_http_status(200) expect(response).to render_template(:edit) end end end context 'When blog is written by other user' do let(:blog) { create(:blog, :with_author) } it 'is expected to raise record not found' do expect { patch my_blog_path(blog.id) }.to raise_error(ActiveRecord::RecordNotFound) end end end end describe 'DELETE /my/blogs/:id' do let(:other_user_blog) { create(:blog, author) } context 'When user does not logged in' do let(:blog) { create(:blog, :with_author) } it 'is returned 302' do delete my_blog_path(blog.id) expect(response).to have_http_status(302) end end context 'When user logged in' do let(:user) { create(:user, :with_identity) } before do sign_in(user) end context 'When blog is written by user' do let(:blog) { create(:blog, author: user) } context 'With valid params' do it 'is returned 200 OK' do delete my_blog_path(blog.id) expect(response).to have_http_status(302) expect { Blog.find(blog.id) }.to raise_error(ActiveRecord::RecordNotFound) end end end context 'When blog is written by other user' do let(:blog) { create(:blog, :with_author) } it 'is expected to raise record not found' do expect { delete my_blog_path(blog.id) }.to raise_error(ActiveRecord::RecordNotFound) end end end end end
# Класс DocumentFactory Класс `Mekras\OData\Client\DocumentFactory` позволяет создавать новые документы OData. Вместо самостоятельного создания экземпляров этого класса используйте метод [Service::getDocumentFactory](service.ru.md#getDocumentFactory). ## createEntityDocument Создаёт новый документ OData, содержащий незаполненную сущность. ```php public function createEntityDocument(string $type = null): Mekras\OData\Client\Document\EntryDocument ``` ### Аргументы - **$type** — Класс сущности. Если аргумент не указан или `null`, то вам надо будет самостоятельно задать класс, используя метод `Mekras\OData\Client\Element\Entry::setEntityClass`. ### Возвращаемые значения Возвращает экземпляр `Mekras\OData\Client\Document\EntryDocument`, содержащий новую (пустую) сущность. ### Ошибки / исключения Метод вбрасывает следующие исключения. - `\Mekras\OData\Client\Exception\LogicException` если функция более низкого уровня, используемая для создания документов, возвращает документ не того типа. ### Примеры - [examples/create_entry.php](examples/create_entry.php) ### См. также - [Создание объектов](create.ru.md)
package com.twllio.video.quickstart.kotlin.utils import android.media.AudioManager class AudioUtils(val audioManager: AudioManager) { }
package com.dante.kfa.ui.activity import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.dante.kfa.presenter.base.BasePersenter /** * create date: 2018/12/20 */ abstract class BaseActivity<P : BasePersenter<*>> : AppCompatActivity() { //kotlin 懒加载,在第一次使用Presenter时初始化,这种设计是针对一个View只针对一个Presenter。 //多个Presenter的情况此处不应该使用泛型 protected val mPresenter: P? by lazy { initPresenter() } abstract val layoutId: Int abstract fun initView() abstract fun initData() abstract fun initPresenter(): P? override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(layoutId) initView() initData() } protected fun open(act: Activity, intent: Intent) { act.startActivity(intent) } }