text
stringlengths
27
775k
extern crate adventofcode; use adventofcode::{input_reader, Part}; use std::env; use std::io::BufRead; fn main() { let part = env::args() .nth(1) .expect("missing part") .parse::<Part>() .expect("invalid part"); let input_file = env::args().nth(2).unwrap_or("input/2017/day-5.txt".into()); let mut array = input_reader(input_file) .expect("failed to open file") .lines() .map(|line| { line.expect("could not read line").parse().expect( "failed to parse input", ) }) .collect::<Vec<i32>>(); let mut pos = 0; let mut counter = 0; loop { counter += 1; let cur = array[pos]; array[pos] += match (&part, cur >= 3) { (&Part::Two, true) => -1, _ => 1, }; let next = pos as i32 + cur; //println!("{:?} pos({}) cur({}) next({})", array, pos, cur, next); if next < 0 || next >= array.len() as i32 { break; } pos = next as usize; } println!("{}", counter); }
//! Definitions for all of the different types. pub use self::func::FunctionType; pub use self::integer::IntegerType; pub use self::composite::*; pub mod func; pub mod integer; pub mod composite; use SafeWrapper; use ir::Context; use sys; use std::marker; /// An LLVM type. pub struct Type<'ctx> { inner: sys::TypeRef, phantom: marker::PhantomData<&'ctx ()>, } impl<'ctx> Type<'ctx> { /// Gets the `void` type. pub fn void(context: &Context) -> Self { unsafe { Type::from_inner(sys::LLVMRustTypeGetVoidTy(context.inner())) } } /// Dump the type to standard error. pub fn dump(&self) { unsafe { sys::LLVMRustTypeDump(self.inner); } } } impl<'ctx> SafeWrapper for Type<'ctx> { type Inner = sys::TypeRef; unsafe fn from_inner(inner: sys::TypeRef) -> Self { Type { inner: inner, phantom: marker::PhantomData } } fn inner(&self) -> sys::TypeRef { self.inner } }
import 'dart:math'; import 'package:flutter/material.dart'; Color genRandomColor() { int baseColor = 0xff000000; int tempRandomNum = 0xffffff - 0x000000; int randomNum = baseColor + Random().nextInt(tempRandomNum); return Color(randomNum); } double genRandomOneOrNegative() { if (Random().nextBool()) { return -Random().nextDouble(); } return Random().nextDouble(); }
<?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return redirect('/member-customer'); }); Route::get('/tambah-member','c_member@tambah'); Route::get('/member-customer','c_member@show'); Route::get('/lihatin/{id}','c_member@detail'); Route::get('/edit/{id}','c_member@edit'); Route::post('/ubah/{id}','c_member@ubah'); Route::post('/pendaftaran','c_member@add');
import java.util.*; public class Ejercicio3 { public static void main(String[] args) { //int temperatura; System.out.println("introducir mes en numero: "); Scanner teclado=new Scanner(System.in); int numero=teclado.nextInt(); teclado.close(); switch(numero){ case 1: System.out.println("Mes: Enero "); break; case 2: System.out.println("Mes:Febrero "); break; case 3: System.out.println("Mes:Marzo "); break; case 4: System.out.println("Mes:Abril "); break; case 5: System.out.println("Mes:Mayo "); break; case 6: System.out.println("Mes: Junio "); break; case 7: System.out.println("Mes: Julio "); break; case 8: System.out.println("Mes:Agosto "); break; case 9: System.out.println("Mes: Septiembre "); break; case 10: System.out.println("Mes:Octubre "); break; case 11: System.out.println("Mes: Noviembre "); break; case 12: System.out.println("Mes: Diciembre "); break; default: System.out.println("Eso no es un mes"); break; } } }
uses OpenCLABC; begin Writeln(CombineSyncQueue(a->a.JoinToString, nil as object, nil as object)); Writeln(CombineAsyncQueue(a->a.JoinToString, nil as object, nil as object)); end.
package io.github.kavahub.learnjava.concurrent; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.annotation.Nullable; import com.google.common.base.Function; import com.google.common.util.concurrent.AsyncCallable; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.junit.jupiter.api.Test; /** * * {@link ListeningExecutorService} 继承 <code>ExecutorService</code> * * <p> * {@link MoreExecutors} 是对jdk自带的Executors工具类的扩展, 创建 <code>ListeningExecutorService</code> 实例 * * @author PinWei Wan * @since 1.0.0 */ public class ListenableFutureComplexTest { @Test public void givenAllSucceedingTasks_whenAllAsList_thenAllSuccess() { final ListeningExecutorService listeningExecService = MoreExecutors.newDirectExecutorService(); final ListenableFutureService service = new ListenableFutureService(listeningExecService); ListenableFuture<String> task1 = service.fetchConfig("config.0"); ListenableFuture<String> task2 = service.fetchConfig("config.1"); ListenableFuture<String> task3 = service.fetchConfig("config.2"); ListenableFuture<List<String>> configsTask = Futures.allAsList(task1, task2, task3); Futures.addCallback(configsTask, new FutureCallback<List<String>>() { @Override public void onSuccess(@Nullable List<String> configResults) { assertNotNull(configResults); assertEquals(3, configResults.size()); for (int i = 0; i < 3; i++) { assertTrue(configResults.get(i) .contains("config." + i)); } } @Override public void onFailure(Throwable t) { fail("Unexpected failure detected", t); } }, listeningExecService); } @Test public void givenOneFailingTask_whenAllAsList_thenFailure() { final ListeningExecutorService listeningExecService = MoreExecutors.newDirectExecutorService(); final ListenableFutureService service = new ListenableFutureService(listeningExecService); ListenableFuture<String> task1 = service.fetchConfig("config.0"); ListenableFuture<String> task2 = service.failingTask(); ListenableFuture<String> task3 = service.fetchConfig("config.2"); ListenableFuture<List<String>> configsTask = Futures.allAsList(task1, task2, task3); Futures.addCallback(configsTask, new FutureCallback<List<String>>() { @Override public void onSuccess(@Nullable List<String> configResults) { fail("Expected a failed future"); } @Override public void onFailure(Throwable t) { assertTrue(t instanceof ListenableFutureException); } }, listeningExecService); } @Test public void givenOneFailingTask_whenSuccessfulAsList_thenSomeSuccess() { final ListeningExecutorService listeningExecService = MoreExecutors.newDirectExecutorService(); final ListenableFutureService service = new ListenableFutureService(listeningExecService); ListenableFuture<String> task1 = service.fetchConfig("config.0"); ListenableFuture<String> task2 = service.failingTask(); ListenableFuture<String> task3 = service.fetchConfig("config.2"); ListenableFuture<List<String>> configsTask = Futures.successfulAsList(task1, task2, task3); Futures.addCallback(configsTask, new FutureCallback<List<String>>() { @Override public void onSuccess(@Nullable List<String> configResults) { assertNotNull(configResults); assertTrue(configResults.get(0).contains("config.0")); assertNull(configResults.get(1)); assertTrue(configResults.get(2).contains("config.2")); } @Override public void onFailure(Throwable t) { fail("Unexpected failure detected", t); } }, listeningExecService); } @Test public void givenAllSucceedingTasks_whenAllSucceed_thenSuccess() { ListeningExecutorService listeningExecService = MoreExecutors.newDirectExecutorService(); ListenableFutureService service = new ListenableFutureService(listeningExecService); ListenableFuture<Integer> cartIdTask = service.getCartId(); ListenableFuture<String> customerNameTask = service.getCustomerName(); ListenableFuture<List<String>> cartItemsTask = service.getCartItems(); ListenableFuture<CartInfo> cartInfoTask = Futures // 所有的任务运行完成 .whenAllSucceed(cartIdTask, customerNameTask, cartItemsTask) // 然后执行 .call(() -> { // 获取任务返回值 int cartId = Futures.getDone(cartIdTask); String customerName = Futures.getDone(customerNameTask); List<String> cartItems = Futures.getDone(cartItemsTask); return new CartInfo(cartId, customerName, cartItems); }, listeningExecService); // 任务完成后回调 Futures.addCallback(cartInfoTask, new FutureCallback<CartInfo>() { @Override public void onSuccess(@Nullable CartInfo result) { assertNotNull(result); assertTrue(result.cartId >= 0); assertFalse(result.customerName.isEmpty()); assertFalse(result.cartItems.isEmpty()); } @Override public void onFailure(Throwable t) { fail("Unexpected failure detected", t); } }, listeningExecService); } @Test public void givenAllSucceedingTasks_whenAllComplete_thenSomeSuccess() { ListeningExecutorService listeningExecService = MoreExecutors.newDirectExecutorService(); ListenableFutureService service = new ListenableFutureService(listeningExecService); ListenableFuture<Integer> cartIdTask = service.getCartId(); ListenableFuture<String> customerNameTask = service.failingTask(); ListenableFuture<List<String>> cartItemsTask = service.getCartItems(); ListenableFuture<CartInfo> cartInfoTask = Futures.whenAllComplete(cartIdTask, customerNameTask, cartItemsTask) .call(() -> { Integer cartId = getOrNull(cartIdTask); String customerName = getOrNull(customerNameTask); List<String> cartItems = getOrNull(cartItemsTask); return new CartInfo(cartId, customerName, cartItems); }, listeningExecService); Futures.addCallback(cartInfoTask, new FutureCallback<CartInfo>() { @Override public void onSuccess(@Nullable CartInfo result) { assertNotNull(result); assertTrue(result.cartId >= 0); assertNull(result.customerName); assertFalse(result.cartItems.isEmpty()); } @Override public void onFailure(Throwable t) { fail("Unexpected failure detected", t); } }, listeningExecService); } @Test public void whenTransform_thenTransformSuccess() { ListeningExecutorService listenExecService = MoreExecutors.newDirectExecutorService(); ListenableFutureService service = new ListenableFutureService(listenExecService); ListenableFuture<List<String>> cartItemsTask = service.getCartItems(); Function<List<String>, Integer> itemCountFunc = cartItems -> { assertNotNull(cartItems); return cartItems.size(); }; ListenableFuture<Integer> itemCountTask = Futures.transform(cartItemsTask, itemCountFunc, listenExecService); Futures.addCallback(itemCountTask, new FutureCallback<Integer>() { @Override public void onSuccess(@Nullable Integer cartItemCount) { assertNotNull(cartItemCount); assertTrue(cartItemCount > 0); } @Override public void onFailure(Throwable t) { fail("Unexpected failure detected", t); } }, listenExecService); } @Test public void whenSubmitAsync_thenSuccess() { ListeningExecutorService executor = MoreExecutors.newDirectExecutorService(); ListenableFutureService service = new ListenableFutureService(executor); AsyncCallable<String> asyncConfigTask = () -> { ListenableFuture<String> configTask = service.fetchConfig("config.a"); TimeUnit.MILLISECONDS.sleep(500); //some long running task return configTask; }; ListenableFuture<String> configTask = Futures.submitAsync(asyncConfigTask, executor); Futures.addCallback(configTask, new FutureCallback<String>() { @Override public void onSuccess(@Nullable String result) { assertNotNull(result); assertTrue(result.contains("config.a")); } @Override public void onFailure(Throwable t) { fail("Unexpected failure detected", t); } }, executor); } @Test public void whenAsyncTransform_thenSuccess() { ListeningExecutorService executor = MoreExecutors.newDirectExecutorService(); ListenableFutureService service = new ListenableFutureService(executor); ListenableFuture<String> usernameTask = service.generateUsername("john"); AsyncFunction<String, String> passwordFunc = username -> { ListenableFuture<String> generatePasswordTask = service.generatePassword(username); TimeUnit.MILLISECONDS.sleep(500); // some long running task return generatePasswordTask; }; ListenableFuture<String> passwordTask = Futures.transformAsync(usernameTask, passwordFunc, executor); Futures.addCallback(passwordTask, new FutureCallback<String>() { @Override public void onSuccess(@Nullable String password) { assertNotNull(password); assertTrue(password.contains("john")); assertTrue(password.contains("@")); } @Override public void onFailure(Throwable t) { fail("Unexpected failure detected", t); } }, executor); } private static <T> T getOrNull(ListenableFuture<T> future) { try { return Futures.getDone(future); } catch (ExecutionException e) { return null; } } static class CartInfo { Integer cartId; String customerName; List<String> cartItems; public CartInfo(Integer cartId, String customerName, List<String> cartItems) { this.cartId = cartId; this.customerName = customerName; this.cartItems = cartItems; } } public class ListenableFutureService { private final ListeningExecutorService lExecService; public <T> ListenableFuture<T> failingTask() { return Futures.immediateFailedFuture(new ListenableFutureException()); } public ListenableFutureService(ListeningExecutorService lExecService) { this.lExecService = lExecService; } public ListenableFuture<String> fetchConfig(String configKey) { return lExecService.submit(() -> { TimeUnit.MILLISECONDS.sleep(500); return String.format("%s.%d", configKey, new Random().nextInt(Integer.MAX_VALUE)); }); } public ListenableFuture<Integer> getCartId() { return lExecService.submit(() -> { TimeUnit.MILLISECONDS.sleep(500); return new Random().nextInt(Integer.MAX_VALUE); }); } public ListenableFuture<String> getCustomerName() { String[] names = new String[] { "Mark", "Jane", "June" }; return lExecService.submit(() -> { TimeUnit.MILLISECONDS.sleep(500); return names[new Random().nextInt(names.length)]; }); } public ListenableFuture<List<String>> getCartItems() { String[] items = new String[] { "Apple", "Orange", "Mango", "Pineapple" }; return lExecService.submit(() -> { TimeUnit.MILLISECONDS.sleep(500); int noOfItems = new Random().nextInt(items.length); if (noOfItems == 0) ++noOfItems; return Arrays.stream(items, 0, noOfItems).collect(Collectors.toList()); }); } public ListenableFuture<String> generateUsername(String firstName) { return lExecService.submit(() -> { TimeUnit.MILLISECONDS.sleep(500); return firstName.replaceAll("[^a-zA-Z]+","") .concat("@service.com"); }); } public ListenableFuture<String> generatePassword(String username) { return lExecService.submit(() -> { TimeUnit.MILLISECONDS.sleep(500); if (username.contains("@")) { String[] parts = username.split("@"); return parts[0] + "123@" + parts[1]; } else { return username + "123"; } }); } } public class ListenableFutureException extends Exception { } }
<?php namespace App\Controllers\sales; use App\Controllers\BaseController; use App\Models\CustomModel; class Sales extends BaseController{ public function index(){ $data = [ 'meta-title' => '', 'title' => 'Sales', ]; $data['name'] = $this->request->getGet('name'); $data['id'] = $this->request->getGet('id'); $data['now'] = $this->request->getGet('monthSelected'); $db = db_connect(); $model = new CustomModel($db); $data['sales'] = $model->showSearchDate($data); return view('sales/viewAll', $data); } public function jsonSales(){ $data['now'] = date("yy-m-d"); $db = db_connect(); $model = new CustomModel($db); $data['sales'] = $model->showAllSales($data); return $data['sales']; } public function searchSales(){ $data = [ 'meta-title' => '', 'title' => 'Sales', ]; $db = db_connect(); $model = new CustomModel($db); return view('sales/sales', $data); } public function showMembers(){ $data = [ 'meta-title' => '', 'title' => 'Members', ]; $db = db_connect(); $model = new CustomModel($db); $data['members'] = $model->showMembers(); return view('sales/members', $data); } public function memberPurchases(){ $data = [ 'meta-title' => '', 'title' => 'Member Details', ]; $db = db_connect(); $model = new CustomModel($db); $userId = $this->request->getGet('id'); $data['userId'] = $userId; $data['name'] = $this->request->getGet('name'); $data['members'] = $model->showMemberDetails($userId); return view('sales/memberDetails', $data); } public function searchByMemberDate(){ $data = [ 'meta-title' => '', 'title' => 'Member Details', ]; $dates = [ 'now' => $this->request->getGet('selectedMonth'), 'id' => $this->request->getGet('id') ]; $data['name'] = $this->request->getGet('name'); $data['userId'] = $this->request->getGet('id'); $db = db_connect(); $model = new CustomModel($db); $data['members'] = $model->showMemberDate($dates); return view('sales/memberDetails', $data); } public function searchByMonth(){ } }
<?php namespace app\controllers; use GraphQL\Examples\Blog\Types; use GraphQL\Type\Definition\ResolveInfo; use Yii; use yii\web\Controller; class BaseController extends Controller { // public function __construct() // { // $config = [ // 'name' => 'BaseController', // 'description' => 'Our blog authors', // 'fields' => function() { // return [ // 'id' => Types::id(), // ]; // }, // 'interfaces' => [ // Types::node() // ], // 'resolveField' => function($user, $args, $context, ResolveInfo $info) { // $method = 'resolve' . ucfirst($info->fieldName); // if (method_exists($this, $method)) { // return $this->{$method}($user, $args, $context, $info); // } else { // return $user->{$info->fieldName}; // } // } // ]; // parent::__construct($config); // } public function beforeAction($action) { date_default_timezone_set("Asia/Jakarta"); if(Yii::$app->user->isGuest){ return $this->redirect(["site/login"]); } return parent::beforeAction($action); } }
#include "listnd.h" #include "util.h" int main() { std::shared_ptr<item> items(new item[10],std::default_delete<item>()); items.get()[0]=item(1,10); items.get()[1]=item(2,9); items.get()[2]=item(3,8); items.get()[3]=item(4,7); items.get()[4]=item(5,6); items.get()[5]=item(6,11); items.get()[6]=item(7,4); items.get()[7]=item(8,3); items.get()[8]=item(9,25); items.get()[9]=item(10,1); items=sort<item>(items.get(),items.get()+10); for(int i=0;i<10;i++) { std::cout<<items.get()[i]<<" "; } std::cout<<std::endl; }
package hotel import ( "fmt" "github.com/gin-gonic/gin" ) type Controllers struct { Services Services } /* .d8888b. 8888888b. 8888888888 d8888 88888888888 8888888888 d88P Y88b 888 Y88b 888 d88888 888 888 888 888 888 888 888 d88P888 888 888 888 888 d88P 8888888 d88P 888 888 8888888 888 8888888P" 888 d88P 888 888 888 888 888 888 T88b 888 d88P 888 888 888 Y88b d88P 888 T88b 888 d8888888888 888 888 "Y8888P" 888 T88b 8888888888 d88P 888 888 8888888888 */ func (controllers Controllers) AddHotel(c *gin.Context) { fmt.Println("Controller: AddHotel") query := c.Request.URL.Query() location := Location{ Address: query["address"][0], Street: query["street"][0], Ward: query["ward"][0], District: query["district"][0], CityOrProvince: query["cityOrProvince"][0], Country: query["country"][0], } code, message := controllers.Services.AddHotel(query["hotelName"][0], location) c.JSON(code, gin.H{ "status": "succeed", "message": message, }) } /* 8888888b. 8888888888 d8888 8888888b. 888 Y88b 888 d88888 888 "Y88b 888 888 888 d88P888 888 888 888 d88P 8888888 d88P 888 888 888 8888888P" 888 d88P 888 888 888 888 T88b 888 d88P 888 888 888 888 T88b 888 d8888888888 888 .d88P 888 T88b 8888888888 d88P 888 8888888P" */ // func (controllers Controllers) Login(c *gin.Context) { // fmt.Println("Controller: Login") // username := c.PostForm("username") // password := c.PostForm("password") // isUserLoginSucceed := controllers.Services.ValidateUser(username, password) // fmt.Println(isUserLoginSucceed) // if isUserLoginSucceed { // c.JSON(200, gin.H{ // "status": "succeed", // "message": "Login succeed!", // "access_token": "jwt-token", // }) // return // } // c.JSON(404, gin.H{ // "status": "failed", // "message": "Login failed!", // }) // } /* 888 888 8888888b. 8888888b. d8888 88888888888 8888888888 888 888 888 Y88b 888 "Y88b d88888 888 888 888 888 888 888 888 888 d88P888 888 888 888 888 888 d88P 888 888 d88P 888 888 8888888 888 888 8888888P" 888 888 d88P 888 888 888 888 888 888 888 888 d88P 888 888 888 Y88b. .d88P 888 888 .d88P d8888888888 888 888 "Y88888P" 888 8888888P" d88P 888 888 8888888888 */ /* 8888888b. 8888888888 888 8888888888 88888888888 8888888888 888 "Y88b 888 888 888 888 888 888 888 888 888 888 888 888 888 888 8888888 888 8888888 888 8888888 888 888 888 888 888 888 888 888 888 888 888 888 888 888 888 .d88P 888 888 888 888 888 8888888P" 8888888888 88888888 8888888888 888 8888888888 */
package io.laminext.fetch package upickle import _root_.upickle.default._ import com.raquo.laminar.api.L._ import org.scalajs.dom.experimental.Response import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scala.scalajs.js.Thenable.Implicits._ import scala.util.Failure import scala.util.Success import scala.util.Try class FetchEventStreamBuilderUpickleOps(underlying: FetchEventStreamBuilder) { private def decodeResponse[A](response: Response)(implicit decoder: Reader[A]): Future[A] = response.text().flatMap { text => Try(read[A](text)) match { case Success(a) => Future.successful(a) case Failure(error) => Future.failed(new ResponseDecodeFailed(error, response)) } } private def acceptJson(b: FetchEventStreamBuilder): FetchEventStreamBuilder = b.updateHeaders(_.updated("accept", "application/json")) def decode[A](implicit decoder: Reader[A]): EventStream[FetchResponse[A]] = acceptJson(underlying).build(decodeResponse[A](_)) def decodeEither[NonOkay, Okay](implicit decodeNonOkay: Reader[NonOkay], decodeOkay: Reader[Okay] ): EventStream[FetchResponse[Either[NonOkay, Okay]]] = acceptJson(underlying).build { response => if (response.ok) { decodeResponse[Okay](response).map(Right(_)) } else { decodeResponse[NonOkay](response).map(Left(_)) } } def decodeOkay[Okay](implicit decodeOkay: Reader[Okay]): EventStream[FetchResponse[Okay]] = acceptJson(underlying).build { response => if (response.ok) { decodeResponse(response)(decodeOkay) } else { Future.failed(new NonOkayResponse(response)) } } }
#!/bin/bash # Use the requirejs optimizer r.js to optimise js files # By default it will create a sibling build directory called 'csl' # or it uses a command line argument if present if [ "$1" == "" ] then BUILD_DIR="../bethecamera.com" else BUILD_DIR="$1" fi echo "deploying to build dir $BUILD_DIR" GIT_COMMIT=$(git rev-parse HEAD) echo "git commit is $GIT_COMMIT" rm -rf "$BUILD_DIR" mkdir "$BUILD_DIR" node external/r.js -o build.js dir=$BUILD_DIR # TODO: Replace $GIT_COMMIT with the git commit hash in all php files cd $BUILD_DIR sed s/\$GIT_COMMIT/$GIT_COMMIT/g <index.html >tempFile mv tempFile index.html
var path = require('path'); var fsx = require('fs-extra'); var Filesystem = require('../'); describe('machinepack-fs :: rmrf-sync', function() { before(function() { fsx.copySync(path.resolve(__dirname, 'fixtures' ,'files'), path.resolve(__dirname, 'fixtures', 'sandbox')); }); after(function() { fsx.removeSync(path.resolve(__dirname, 'fixtures', 'sandbox')); }); it('when called with a valid directory, should remove it and all its contents', function() { Filesystem.rmrfSync({ path: path.resolve(__dirname, 'fixtures', 'sandbox') }).execSync(); // Verify that the directory was removed try { fsx.statSync(path.resolve(__dirname, 'fixtures', 'sandbox')); throw new Error('Directory should have been removed but it still exists!'); } catch (e) { if (e.code !== 'ENOENT') { throw e; } // Otherwise, this is an ENOENT error, which is what we're looking for. } }); it('when called with a non-existent directory, should fail silently', function() { Filesystem.rmrfSync({ path: path.resolve(__dirname, 'fixtures', 'sandbox') }).execSync(); }); });
# functions Pure functions deployed to AWS A content-first approach for the very challenging process of conversation (not chat) ## Getting Started ## LICENSE MIT //https://medium.com/@tjholowaychuk/dos-and-don-ts-of-aws-lambda-7dfcab7ad115 // coupon apex up //medium-16B55817D719
'use strict'; goog.require('Blockly.Arduino'); Blockly.Arduino.oxocard_audio_wait_for_tone = function(block) { return 'oxocard.audio->setToneBlocking(true);\n'; }; Blockly.Arduino.oxocard_audio_wait_not_for_tone = function(block) { return 'oxocard.audio->setToneBlocking(false);\n'; }; Blockly.Arduino.oxocard_audio_set_volume = function() { var volume = Blockly.Arduino.valueToCode(this, 'VOL', Blockly.Arduino.ORDER_ATOMIC) || 0; return 'oxocard.audio->setVolume(' + volume + ');\n'; }; Blockly.Arduino.oxocard_audio_get_volume = function() { var code = 'oxocard.audio->getVolume()'; return [code, Blockly.Arduino.ORDER_ATOMIC]; }; Blockly.Arduino.oxocard_audio_volume_up = function(block) { return 'oxocard.audio->volumeUp();\n'; }; Blockly.Arduino.oxocard_audio_volume_down = function(block) { return 'oxocard.audio->volumeDown();\n'; }; Blockly.Arduino.oxocard_audio_set_octave = function() { var octave = this.getFieldValue('OCTAVE'); return 'oxocard.audio->setGlobalOctave(Octave::' + octave +');\n'; }; Blockly.Arduino.oxocard_audio_set_waveform = function() { var waveform = this.getFieldValue('WAVEFORM'); return 'oxocard.audio->setGlobalWaveForm(WaveFormGenerator::' + waveform +');\n'; }; Blockly.Arduino.oxocard_audio_set_bpm = function() { var bpm = Blockly.Arduino.valueToCode(this, 'BPM', Blockly.Arduino.ORDER_ATOMIC) || 0; return 'oxocard.audio->setGlobalBPM(' + bpm + ');\n'; }; Blockly.Arduino.oxocard_audio_wait = function() { var duration = this.getFieldValue('DUR'); return 'delay(oxocard.audio->noteToMs(' + duration + '));\n'; }; Blockly.Arduino.oxocard_audio_record_for = function() { var duration = this.getFieldValue('DUR'); return 'oxocard.audio->recordFor(' + duration + ');\n'; }; Blockly.Arduino.oxocard_audio_play_recorded = function() { var forever = this.getFieldValue('FOREVER').toLowerCase(); return 'oxocard.audio->playRecorded(' + forever + ');\n'; }; Blockly.Arduino.oxocard_audio_wait_for_loud_noise = function() { return 'oxocard.audio->waitForLoudNoise();\n'; }; Blockly.Arduino.oxocard_audio_stop_tone = function(block) { return 'oxocard.audio->noTone();\n'; }; Blockly.Arduino.oxocard_audio_play_tone = function() { var note = this.getFieldValue('NOTE'); return 'oxocard.audio->tone(Note::' + note +');\n'; }; Blockly.Arduino.oxocard_audio_play_tone_dur_ms = function() { var note = this.getFieldValue('NOTE'); var duration = Blockly.Arduino.valueToCode(this, 'DUR', Blockly.Arduino.ORDER_ATOMIC) || 0; return 'oxocard.audio->tone(Note::' + note +', ' + duration +');\n'; }; Blockly.Arduino.oxocard_audio_play_tone_dur = function() { var note = this.getFieldValue('NOTE'); var duration = this.getFieldValue('DUR'); return 'oxocard.audio->tone(Note::' + note +', oxocard.audio->noteToMs(' + duration +'));\n'; }; Blockly.Arduino.oxocard_audio_play_tone_hz = function() { var note = Blockly.Arduino.valueToCode(this, 'FRQ', Blockly.Arduino.ORDER_ATOMIC) || 0; return 'oxocard.audio->tone(' + note +');\n'; }; Blockly.Arduino.oxocard_audio_play_tone_hz_dur_ms = function() { var note = Blockly.Arduino.valueToCode(this, 'FRQ', Blockly.Arduino.ORDER_ATOMIC) || 0; var duration = Blockly.Arduino.valueToCode(this, 'DUR', Blockly.Arduino.ORDER_ATOMIC) || 0; return 'oxocard.audio->tone(' + note +', ' + duration +');\n'; }; Blockly.Arduino.oxocard_audio_play_tone_hz_dur = function() { var note = Blockly.Arduino.valueToCode(this, 'FRQ', Blockly.Arduino.ORDER_ATOMIC) || 0; var duration = this.getFieldValue('DUR'); return 'oxocard.audio->tone(' + note +', oxocard.audio->noteToMs(' + duration +'));\n'; }; Blockly.Arduino.oxocard_audio_play_sound_effect = function() { var sound = this.getFieldValue('SOUND'); var forever = this.getFieldValue('FOREVER').toLowerCase(); return 'oxocard.audio->playWavFile((uint8_t*)' + sound + '_wav, ' + sound + '_wav_size, ' + forever + ');\n'; };
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using JSON; namespace CommonClass { public abstract class MatterBasic:IJsonAble { public int user_id=0; public string matter_desc=""; public Json matter_addion_info=new Json(); public DateTime matter_end_time= DateTime.Now; public MatterType matter_type=MatterType.oneOffEvent; public int matter_id=0; public string matter_name=""; public DateTime matter_start_time = DateTime.Now; public DateTime matter_next_effect_time = DateTime.Now; public int folder_id=0; public bool is_new = false;//创建时标记一下 public int is_noticed = 0; public string Test { get { return "1"; } set { } } public int Matter_id { get => matter_id; set => matter_id = value; } public int User_id { get => user_id; set => user_id = value; } public string Matter_name { get => matter_name; set => matter_name = value; } public string Matter_desc { get => matter_desc; set => matter_desc = value; } public Json Matter_addion_info { get => matter_addion_info; set => matter_addion_info = value; } public DateTime Matter_start_time { get => matter_start_time; set => matter_start_time = value; } public string Matter_next_effect_time_style { get { if (matter_next_effect_time < DateTime.Now) { return "Red"; } else return "DeepSkyBlue"; } } public string Matter_next_effect_time { get { if (matter_next_effect_time.Date == DateTime.Now.Date) return "今天 " + matter_next_effect_time.ToString("HH:mm"); else return matter_next_effect_time.ToString("yyyy-MM-dd"); } } public DateTime Matter_end_time { get => matter_end_time; set => matter_end_time = value; } public MatterType Matter_type { get => matter_type; set => matter_type = value; } public int GetID() { return Matter_id; } public MatterType GetMatterType() { return Matter_type; } public string GetName() { return Matter_name; } public string GetDesc() { return Matter_desc; } public DateTime GetStartTime() { return Matter_start_time; } public abstract DateTime GetNextEffectTime(); public DateTime GetEndTime() { return Matter_end_time; } public int GetUserID() { return User_id; } public abstract Object fromJson(Json json); public virtual Json toJson() { return Json.ConvertFrom(this, (string c, string m) => { switch (m) { case "is_new": return false; } return true; }); } public static MatterBasic ParseFromDB(IDictionary<string, string> info) { var type = (MatterType)Enum.Parse(typeof(MatterType), info["matter_type"]); switch (type) { case MatterType.oneOffEvent: return Json.Import<string, string>(info).ConvertTo<MatterOneOff>(); case MatterType.periodicEvent: return Json.Import<string, string>(info).ConvertTo<MatterPeriodicity>(); case MatterType.email: return Json.Import<string, string>(info).ConvertTo<MatterEmail>(); } return null; } public static MatterBasic ParseFromJson(Json info) { var type = (MatterType)Enum.Parse(typeof(MatterType), info["matter_type"]); switch (type) { case MatterType.oneOffEvent: return info.ConvertTo<MatterOneOff>(); case MatterType.periodicEvent: return info.ConvertTo<MatterPeriodicity>(); case MatterType.email: return info.ConvertTo<MatterEmail>(); } return null; } protected static void CopyTo(MatterBasic source,MatterBasic target) { target.user_id = source.user_id; target.matter_desc = source.matter_desc; target.matter_addion_info = source.matter_addion_info; target.matter_end_time = source.matter_end_time; target.matter_type = source.matter_type; target.matter_id = source.matter_id; target.matter_name = source.matter_name; target.matter_start_time = source.matter_start_time; target.matter_next_effect_time = source.matter_next_effect_time; target.folder_id = source.folder_id; target.is_new = source.is_new; } /// <summary> /// 用于服务器上定时执行任务 /// </summary> public void Tick() { } /// <summary> /// 返回事件是否结束 /// </summary> public virtual bool OnUserFinish() { return false; } } }
import { AxiosInstance } from "axios"; export abstract class BaseApi { protected axiosInstance: AxiosInstance; constructor(axiosInstance: AxiosInstance) { this.axiosInstance = axiosInstance; } }
package com.guet.flexbox.handshake.lan import java.net.Inet4Address import java.net.InetAddress import java.net.NetworkInterface import java.util.* class MacOsLANAddressProvider : LANAddressProvider { private val interfaceName = "Netif" override fun get(): InetAddress? { var net: Process? = null try { net = Runtime.getRuntime() .exec("netstat -rn") val output = net .inputStream .bufferedReader() var line: String? var interfaceIndex = -1 do { line = output.readLine() if (line.contains(interfaceName)) { val strArray = line.split(" ") for (item in strArray) { if (item.trim().isNotEmpty()) { interfaceIndex++ } if (item.trim() == interfaceName) { break } } } if (line.trim().startsWith("default") && interfaceIndex >= 0) { val tokenizer = StringTokenizer(line) repeat(interfaceIndex){ tokenizer.nextToken() } val name = tokenizer.nextToken() return Iterable { Iterable { NetworkInterface.getNetworkInterfaces().iterator() }.first { it.name == name }.inetAddresses.iterator() }.first { it is Inet4Address } } } while (line != null) } catch (e: Throwable) { e.printStackTrace() } finally { net?.destroy() } return null } }
<?php namespace App\Http\Services\Video; use App\Http\Controllers\Controller; use App\Http\Resources\Screencast\VideoResource; use App\Http\Services\Service; use App\Models\Screencast\Playlist; use App\Models\Screencast\Video; use Exception; class VideoQueries extends Service { static $rules = [ 'title' => 'required|max:50|min:3', 'description' => 'required|max:200|min:10', 'video_path_url' => 'required|url', 'runtime' => 'required', 'is_intro' => 'nullable' ]; static $mesaages = [ 'required' => ':attribute tidak boleh kosong', 'min' => ':attribute minimal :min karakter', 'max' => ':attribute maximal :max karakter', 'numeric' => ':attribute yang dimasukan harus angka', 'url' => ':attribute yang dimasukan harus berupa alamat url', 'unique' => ':attribute sudah ada' ]; static $attributes = [ 'title' => 'Judul', 'description' => 'Deskripsi', 'video_path_url' => 'URL', 'episode' => 'Episode', 'runtime' => 'Runtime' ]; public static function getAllVideo() { try { return Video::with(['playlist'])->get(); } catch (Exception $th) { if (in_array($th->getCode(), self::$error_codes)) { throw new Exception($th->getMessage(), $th->getCode()); } throw new Exception($th->getMessage(), 500); } } public static function getListVideoByPlaylist(int $key, array $orderBy = ['id', 'ASC'], int $paginated = 5) { try { return Video::where('playlist_id', $key) ->with(['playlist']) ->orderBy($orderBy[0], $orderBy[1]) ->paginate($paginated); } catch (Exception $th) { if (in_array($th->getCode(), self::$error_codes)) { throw new Exception($th->getMessage(), $th->getCode()); } throw new Exception($th->getMessage(), 500); } } public static function getOneVideo($video) { try { return $video; } catch (Exception $th) { if (in_array($th->getCode(), self::$error_codes)) { throw new Exception($th->getMessage(), $th->getCode()); } throw new Exception($th->getMessage(), 500); } } public static function getVideoByPlaylist($playlist_slug) { try { $playlist = Playlist::with(['videos'])->where('slug', $playlist_slug)->first(); if (empty($playlist)) { return self::ctr()->respondWithData(false, 'Data tidak di temukan.', 404, []); } return self::ctr()->respondWithData( true, 'Berhasil mendapatkan data', 200, VideoResource::collection($playlist->videos()->orderBy('episode')->get()) ); } catch (Exception $th) { if (in_array($th->getCode(), self::$error_codes)) { throw new Exception($th->getMessage(), $th->getCode()); } throw new Exception($th->getMessage(), 500); } } public static function getOneVideoByEps($playlist_slug, int $episode) { try { if ($episode == 0 || $episode == false) { return self::ctr()->respondWithData(false, 'Episode tidak boleh kosong.', 404, []); } $playlist = Playlist::with(['videos'])->where('slug', $playlist_slug)->first(); if (empty($playlist)) { return self::ctr()->respondWithData(false, 'Data tidak di temukan.', 404, []); } $video = $playlist->videos()->where('episode', $episode)->first(); if (!$video) { return self::ctr()->respondWithData(false, 'Episode pada playlist ini tidak ditemukan.', 404, []); } else { if (auth()->user()->hasBought($playlist) || $video->is_intro == 1) { return self::ctr()->respondWithData( true, 'Berhasil mendapatkan data', 200, new VideoResource($video) ); } return self::ctr()->respondWithData(false, 'You have to buy before you watch.', 200, []); } } catch (Exception $th) { if (in_array($th->getCode(), self::$error_codes)) { throw new Exception($th->getMessage(), $th->getCode()); } throw new Exception($th->getMessage(), 500); } } }
<?php namespace app\modules\admin\modules\brand\controllers; use yii\web\Controller; use app\modules\admin\modules\brand\models\BrandForm; use yii\filters\AccessControl; use Yii; class DefaultController extends Controller { //правила доступа (действия 'update', 'index' доступны только после входа в учётную запись) public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'only' => ['update', 'index'], 'rules' => [ [ 'allow' => true, 'actions' => ['update', 'index',], 'roles' => ['@'], ], ], ], ]; } //открывает стартовую страницу public function actionIndex() { return $this->render('index'); } //открывает страницу для редактирования конкретной записи из модели /** * открывает представление редактирования бренда * * проверяет $id, * если не передан - устанавливает new по умолчанию * если передан - находит соответствующий бренд в БД по ИД * проверяет данные ПОСТ запроса * если запрос не пустой - сохраняет данные в модель * * @param string|int $id идентификатор товара из БД, либо слово new для создания нового * @return string представление редактирования товара */ public function actionUpdate($id) { $modelBrandForm = BrandForm::find()->where('brand_id = :id', [':id' => $id])->one(); $request = Yii::$app->request; if ($modelBrandForm->load($request->post())) { $modelBrandForm->save(); $this->redirect(['index']); } return $this->render( 'update', [ 'modelBrandForm' => $modelBrandForm, ] ); } //удаление записи с указанным ИД public function actionDelete($id) { $modelBrandForm = BrandForm::find()->where('brand_id = :id', [':id' => $id])->one(); $modelBrandForm->delete(); if (!Yii::$app->request->isAjax) { return $this->redirect(['index']); } } public function actionCreate() { $modelBrandForm= new BrandForm; $request = Yii::$app->request; if ($modelBrandForm->load($request->post())) { $modelBrandForm->save(); $this->redirect(['index']); } return $this->render( 'create', [ 'modelBrandForm' => $modelBrandForm, ] ); } }
import { GitProgressParser } from './git' const steps = [{ title: 'Checking out files', weight: 1 }] /** * A class that parses output from `git checkout --progress` and provides * structured progress events. */ export class CheckoutProgressParser extends GitProgressParser { public constructor() { super(steps) } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Constants { public static string MCS_COMPUTERVISIONKEY = "---------Computer-Vision-Key---------"; }
#!/bin/sh -eux file="OpenJDK8U-jdk_x64_linux_hotspot_8u212b04.tar.gz" download /opt/java/openjdk/jdk8u212-b04 \ "https://github.com/AdoptOpenJDK/openjdk8-binaries/releases/download/jdk8u212-b04/$file" \ "09f6ccbfd8a86e52665b56751403fd4e2513ad071e2b3f36bab73f86273d1ead" file="OpenJDK11U-jdk_x64_linux_hotspot_11.0.4_11.tar.gz" download /opt/java/openjdk/jdk-11.0.4_11 \ "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.4%2B11/$file" \ "90c33cf3f2ed0bd773f648815de7347e69cfbb3416ef3bf41616ab1c4aa0f5a8" echo 'export JAVA_HOME=/opt/java/openjdk/jdk-11.0.4_11' > /etc/profile.d/java.sh echo 'export PATH="/opt/java/openjdk/jdk-11.0.4_11/bin:$PATH"' >> /etc/profile.d/java.sh
<?php namespace App\Http\Controllers; // use Illuminate\Support\Facades\Storage; use App\Http\Requests\StoreRoomPost; use App\Models\Room; use App\Models\Service; use App\Models\Gender; use App\Models\Characteristics; use App\Models\Option; use App\Models\RoomType; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; class RoomController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $room = Room::all(); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $genders = Gender::all(); $services = Service::all(); $characteristics = Characteristics::all(); $types = RoomType::all(); $options = Option::all(); return view('Dashboard/Publication-create', compact( 'genders', 'services', 'characteristics', 'types', 'options' )); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(StoreRoomPost $request) { $room = Room::create($request->all()); $room->services()->attach($request->services); $room->characteristics()->attach($request->characteristics); $room->options()->attach($request->options); if ($request->hasfile('file')) { $file = $request->file('file'); $name = time() . $file->getClientOriginalName(); $file->move(public_path().'/images/', $name); //\Storage::disk('local')->put($name, \File::get($file)); $room->imagen = $name; $room->save(); } return redirect('user/publication')->with('status', 'Publicación creada correctamente'); } /** * Display the specified resource. * * @param \App\room $room * @return \Illuminate\Http\Response */ public function show($id) { } /** * Show the form for editing the specified resource. * * @param \App\room $room * @return \Illuminate\Http\Response */ public function edit(room $room) { } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\room $room * @return \Illuminate\Http\Response */ public function update(Request $request, room $room) { // } /** * Remove the specified resource from storage. * * @param \App\room $room * @return \Illuminate\Http\Response */ public function destroy(room $room) { // } }
using System.Collections; using UnityEngine; public class RewindBullet : MonoBehaviour { public float speed = 20f; public Rigidbody2D rb; public CircleCollider2D cC; public SpriteMask rewindPortal; private bool madeportal = false; // Start is called before the first frame update void Start() { rb.velocity = transform.right * speed; StartCoroutine(SelfDestruct()); } void OnTriggerEnter2D(Collider2D collider) { if (collider.tag == "Ground" && !madeportal) { madeportal = true; Instantiate(rewindPortal, transform.position, Quaternion.identity); Destroy(gameObject); } else if (collider.tag == "Player" || collider.tag == "Enemy") { Physics2D.IgnoreCollision(collider, cC); } } IEnumerator SelfDestruct() { yield return new WaitForSeconds(20f); Destroy(gameObject); GameObject.FindObjectOfType<PlayerMovement>().bulletsShot--; } }
class EstimatesController < ApplicationController def index @custom_matchup = Estimate.custom_matchup(["Sanders", "Clinton", "Biden"]) #these need to be made dynamically @sanders_array = Estimate.make_chart_array("Sanders", @custom_matchup) @clinton_array = Estimate.make_chart_array("Clinton", @custom_matchup) @biden_array = Estimate.make_chart_array("Biden", @custom_matchup) # binding.pry @linechart_dates = @custom_matchup.collect { |date,info| date.to_s} #put dates in ascending order @linechart_dates.reverse! @array_of_polls = nil #get count of number of candidates # arrays_needed = @custom_matchup.values[0].length @dem_estimate = Estimate.latest_dem_chart @gop_estimate = Estimate.latest_gop_chart @dem_candidates = @dem_estimate.collect {|can_hash| can_hash[:choice]} @dem_poll_numbers = @dem_estimate.collect {|can_hash| can_hash[:value]} @gop_candidates = @gop_estimate.collect {|can_hash| can_hash[:choice]} @gop_poll_numbers = @gop_estimate.collect {|can_hash| can_hash[:value]} respond_to do |format| format.html format.js end end end
#!/bin/bash echo "flake8 test started" flake8 app --exclude="settings.py, migrations" if [ $? -ne 0 ]; then echo "flake8 tests failed" exit 1 fi echo "flake8 test successfully passed"
package io.dac.mara.lang.variables import io.dac.mara.core._ import io.dac.mara.phases.{Factory, FactoryOp, Node} trait FactoryVariable extends FactoryOp with VariableAlg[Factory] { case class ValDeclare(name: String, typex: Option[String]) extends Node { override def exec[E: Empty](alg: ExprAlg[E]): E = alg match { case alg: VariableAlg[E] => alg.valdeclare(name, typex) } } case class ValAssign(name: String, typex: Option[String], value: Factory) extends Node { override def exec[E: Empty](alg: ExprAlg[E]): E = alg match { case alg: VariableAlg[E] => alg.valassign(name, typex, value.build.exec(alg)) } } case class ValSubstitution(name: String) extends Node { override def exec[E: Empty](alg: ExprAlg[E]): E = alg match { case alg: VariableAlg[E] => alg.valsubstitution(name) } } case class TypeSubstitution(name: String) extends Node { override def exec[E: Empty](alg: ExprAlg[E]): E = alg match { case alg: VariableAlg[E] => alg.typesubstitution(name) } } override def valdeclare(name: String, typex: Option[String]): Factory = op { ValDeclare(name, typex) } override def valassign(name: String, typex: Option[String], value: Factory): Factory = op { ValAssign(name, typex, value) } override def valsubstitution(name: String): Factory = op { ValSubstitution(name) } override def typesubstitution(name: String): Factory = op { TypeSubstitution(name) } }
using PBApplication.Events.Publishing.Abstractions; using PBApplication.Services.Abstractions; using PBCommon.Serialization; namespace PBApplication.Events.ServiceObservers { internal sealed class CUDServiceObserver : ServiceObserver<IEventfulCUDService> { public CUDServiceObserver(IEventPublisher publisher) : base(publisher) { } public override void Observe(IEventfulCUDService service) { service.CUDEvaluated += async (args) => await Send(nameof(IEventfulCUDService.CUDEvaluated), args); } } }
package org.higherstate.jameson.parsers import reflect.{ClassTag, classTag} import org.higherstate.jameson.Path import org.higherstate.jameson.tokenizers._ import org.higherstate.jameson.failures._ case class AnyRefParser[T]()(implicit typeTag:ClassTag[T]) extends Parser[T] { def parse(tokenizer:Tokenizer, path: Path) = tokenizer.head match { case AnyRefToken(value) if classTag[T].runtimeClass.isAssignableFrom(value.getClass) => Success(value.asInstanceOf[T]) case token => Failure(InvalidTokenFailure(this, "Expected any ref token", token, path)) } def schema = Map.empty }
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ //! Utilities for parsing information from headers use std::borrow::Cow; use std::convert::TryFrom; use std::error::Error; use std::fmt; use std::fmt::{Display, Formatter}; use std::str::FromStr; use http::header::{HeaderName, ValueIter}; use http::HeaderValue; use aws_smithy_types::date_time::Format; use aws_smithy_types::primitive::Parse; use aws_smithy_types::DateTime; #[derive(Debug, Eq, PartialEq)] #[non_exhaustive] pub struct ParseError { message: Option<Cow<'static, str>>, } impl ParseError { #[allow(clippy::new_without_default)] pub fn new() -> Self { Self { message: None } } pub fn new_with_message(message: impl Into<Cow<'static, str>>) -> Self { Self { message: Some(message.into()), } } } impl Display for ParseError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "Output failed to parse in headers")?; if let Some(message) = &self.message { write!(f, ". {}", message)?; } Ok(()) } } impl Error for ParseError {} /// Read all the dates from the header map at `key` according the `format` /// /// This is separate from `read_many` below because we need to invoke `DateTime::read` to take advantage /// of comma-aware parsing pub fn many_dates( values: ValueIter<HeaderValue>, format: Format, ) -> Result<Vec<DateTime>, ParseError> { let mut out = vec![]; for header in values { let mut header = header .to_str() .map_err(|_| ParseError::new_with_message("header was not valid utf-8 string"))?; while !header.is_empty() { let (v, next) = DateTime::read(header, format, ',').map_err(|err| { ParseError::new_with_message(format!("header could not be parsed as date: {}", err)) })?; out.push(v); header = next; } } Ok(out) } pub fn headers_for_prefix<'a>( headers: &'a http::HeaderMap, key: &'a str, ) -> impl Iterator<Item = (&'a str, &'a HeaderName)> { let lower_key = key.to_ascii_lowercase(); headers .keys() .filter(move |k| k.as_str().starts_with(&lower_key)) .map(move |h| (&h.as_str()[key.len()..], h)) } pub fn read_many_from_str<T: FromStr>( values: ValueIter<HeaderValue>, ) -> Result<Vec<T>, ParseError> { read_many(values, |v: &str| { v.parse() .map_err(|_err| ParseError::new_with_message("failed during FromString conversion")) }) } pub fn read_many_primitive<T: Parse>(values: ValueIter<HeaderValue>) -> Result<Vec<T>, ParseError> { read_many(values, |v: &str| { T::parse_smithy_primitive(v).map_err(|primitive| { ParseError::new_with_message(format!( "failed reading a list of primitives: {}", primitive )) }) }) } /// Read many comma / header delimited values from HTTP headers for `FromStr` types fn read_many<T>( values: ValueIter<HeaderValue>, f: impl Fn(&str) -> Result<T, ParseError>, ) -> Result<Vec<T>, ParseError> { let mut out = vec![]; for header in values { let mut header = header.as_bytes(); while !header.is_empty() { let (v, next) = read_one(header, &f)?; out.push(v); header = next; } } Ok(out) } /// Read exactly one or none from a headers iterator /// /// This function does not perform comma splitting like `read_many` pub fn one_or_none<T: FromStr>( mut values: ValueIter<HeaderValue>, ) -> Result<Option<T>, ParseError> { let first = match values.next() { Some(v) => v, None => return Ok(None), }; let value = std::str::from_utf8(first.as_bytes()) .map_err(|_| ParseError::new_with_message("invalid utf-8"))?; match values.next() { None => T::from_str(value.trim()) .map_err(|_| ParseError::new()) .map(Some), Some(_) => Err(ParseError::new_with_message( "expected a single value but found multiple", )), } } pub fn set_request_header_if_absent<V>( request: http::request::Builder, key: HeaderName, value: V, ) -> http::request::Builder where HeaderValue: TryFrom<V>, <HeaderValue as TryFrom<V>>::Error: Into<http::Error>, { if !request .headers_ref() .map(|map| map.contains_key(&key)) .unwrap_or(false) { request.header(key, value) } else { request } } pub fn set_response_header_if_absent<V>( response: http::response::Builder, key: HeaderName, value: V, ) -> http::response::Builder where HeaderValue: TryFrom<V>, <HeaderValue as TryFrom<V>>::Error: Into<http::Error>, { if !response .headers_ref() .map(|map| map.contains_key(&key)) .unwrap_or(false) { response.header(key, value) } else { response } } /// Functions for parsing multiple comma-delimited header values out of a /// single header. This parsing adheres to /// [RFC-7230's specification of header values](https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.6). mod parse_multi_header { use super::ParseError; use std::borrow::Cow; fn trim(s: Cow<'_, str>) -> Cow<'_, str> { match s { Cow::Owned(s) => Cow::Owned(s.trim().into()), Cow::Borrowed(s) => Cow::Borrowed(s.trim()), } } fn replace<'a>(value: Cow<'a, str>, pattern: &str, replacement: &str) -> Cow<'a, str> { if value.contains(pattern) { Cow::Owned(value.replace(pattern, replacement)) } else { value } } /// Reads a single value out of the given input, and returns a tuple containing /// the parsed value and the remainder of the slice that can be used to parse /// more values. pub(crate) fn read_value(input: &[u8]) -> Result<(Cow<'_, str>, &[u8]), ParseError> { for (index, &byte) in input.iter().enumerate() { let current_slice = &input[index..]; match byte { b' ' | b'\t' => { /* skip whitespace */ } b'"' => return read_quoted_value(&current_slice[1..]), _ => { let (value, rest) = read_unquoted_value(current_slice)?; return Ok((trim(value), rest)); } } } // We only end up here if the entire header value was whitespace or empty Ok((Cow::Borrowed(""), &[])) } fn read_unquoted_value(input: &[u8]) -> Result<(Cow<'_, str>, &[u8]), ParseError> { let next_delim = input.iter().position(|&b| b == b',').unwrap_or(input.len()); let (first, next) = input.split_at(next_delim); let first = std::str::from_utf8(first) .map_err(|_| ParseError::new_with_message("header was not valid utf8"))?; Ok((Cow::Borrowed(first), then_comma(next).unwrap())) } /// Reads a header value that is surrounded by quotation marks and may have escaped /// quotes inside of it. fn read_quoted_value(input: &[u8]) -> Result<(Cow<'_, str>, &[u8]), ParseError> { for index in 0..input.len() { match input[index] { b'"' if index == 0 || input[index - 1] != b'\\' => { let mut inner = Cow::Borrowed(std::str::from_utf8(&input[0..index]).map_err(|_| { ParseError::new_with_message("header was not valid utf8") })?); inner = replace(inner, "\\\"", "\""); inner = replace(inner, "\\\\", "\\"); let rest = then_comma(&input[(index + 1)..])?; return Ok((inner, rest)); } _ => {} } } Err(ParseError::new_with_message( "header value had quoted value without end quote", )) } fn then_comma(s: &[u8]) -> Result<&[u8], ParseError> { if s.is_empty() { Ok(s) } else if s.starts_with(b",") { Ok(&s[1..]) } else { Err(ParseError::new_with_message("expected delimiter `,`")) } } } /// Read one comma delimited value for `FromStr` types fn read_one<'a, T>( s: &'a [u8], f: &impl Fn(&str) -> Result<T, ParseError>, ) -> Result<(T, &'a [u8]), ParseError> { let (value, rest) = parse_multi_header::read_value(s)?; Ok((f(&value)?, rest)) } /// Conditionally quotes and escapes a header value if the header value contains a comma or quote. pub fn quote_header_value<'a>(value: impl Into<Cow<'a, str>>) -> Cow<'a, str> { let value = value.into(); if value.trim().len() != value.len() || value.contains('"') || value.contains(',') || value.contains('(') || value.contains(')') { Cow::Owned(format!( "\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\"") )) } else { value } } #[cfg(test)] mod test { use std::collections::HashMap; use aws_smithy_types::{date_time::Format, DateTime}; use http::header::HeaderName; use crate::header::{ headers_for_prefix, many_dates, read_many_from_str, read_many_primitive, set_request_header_if_absent, set_response_header_if_absent, ParseError, }; use super::quote_header_value; #[test] fn put_on_request_if_absent() { let builder = http::Request::builder().header("foo", "bar"); let builder = set_request_header_if_absent(builder, HeaderName::from_static("foo"), "baz"); let builder = set_request_header_if_absent(builder, HeaderName::from_static("other"), "value"); let req = builder.body(()).expect("valid request"); assert_eq!( req.headers().get_all("foo").iter().collect::<Vec<_>>(), vec!["bar"] ); assert_eq!( req.headers().get_all("other").iter().collect::<Vec<_>>(), vec!["value"] ); } #[test] fn put_on_response_if_absent() { let builder = http::Response::builder().header("foo", "bar"); let builder = set_response_header_if_absent(builder, HeaderName::from_static("foo"), "baz"); let builder = set_response_header_if_absent(builder, HeaderName::from_static("other"), "value"); let response = builder.body(()).expect("valid response"); assert_eq!( response.headers().get_all("foo").iter().collect::<Vec<_>>(), vec!["bar"] ); assert_eq!( response .headers() .get_all("other") .iter() .collect::<Vec<_>>(), vec!["value"] ); } #[test] fn parse_floats() { let test_request = http::Request::builder() .header("X-Float-Multi", "0.0,Infinity,-Infinity,5555.5") .header("X-Float-Error", "notafloat") .body(()) .unwrap(); assert_eq!( read_many_primitive::<f32>(test_request.headers().get_all("X-Float-Multi").iter()) .expect("valid"), vec![0.0, f32::INFINITY, f32::NEG_INFINITY, 5555.5] ); assert_eq!( read_many_primitive::<f32>(test_request.headers().get_all("X-Float-Error").iter()) .expect_err("invalid"), ParseError::new_with_message( "failed reading a list of primitives: failed to parse input as f32" ) ) } #[test] fn test_many_dates() { let test_request = http::Request::builder() .header("Empty", "") .header("SingleHttpDate", "Wed, 21 Oct 2015 07:28:00 GMT") .header( "MultipleHttpDates", "Wed, 21 Oct 2015 07:28:00 GMT,Thu, 22 Oct 2015 07:28:00 GMT", ) .header("SingleEpochSeconds", "1234.5678") .header("MultipleEpochSeconds", "1234.5678,9012.3456") .body(()) .unwrap(); let read = |name: &str, format: Format| { many_dates(test_request.headers().get_all(name).iter(), format) }; let read_valid = |name: &str, format: Format| read(name, format).expect("valid"); assert_eq!( read_valid("Empty", Format::DateTime), Vec::<DateTime>::new() ); assert_eq!( read_valid("SingleHttpDate", Format::HttpDate), vec![DateTime::from_secs_and_nanos(1445412480, 0)] ); assert_eq!( read_valid("MultipleHttpDates", Format::HttpDate), vec![ DateTime::from_secs_and_nanos(1445412480, 0), DateTime::from_secs_and_nanos(1445498880, 0) ] ); assert_eq!( read_valid("SingleEpochSeconds", Format::EpochSeconds), vec![DateTime::from_secs_and_nanos(1234, 567_800_000)] ); assert_eq!( read_valid("MultipleEpochSeconds", Format::EpochSeconds), vec![ DateTime::from_secs_and_nanos(1234, 567_800_000), DateTime::from_secs_and_nanos(9012, 345_600_000) ] ); } #[test] fn read_many_strings() { let test_request = http::Request::builder() .header("Empty", "") .header("Foo", " foo") .header("FooTrailing", "foo ") .header("FooInQuotes", "\" foo \"") .header("CommaInQuotes", "\"foo,bar\",baz") .header("CommaInQuotesTrailing", "\"foo,bar\",baz ") .header("QuoteInQuotes", "\"foo\\\",bar\",\"\\\"asdf\\\"\",baz") .header( "QuoteInQuotesWithSpaces", "\"foo\\\",bar\", \"\\\"asdf\\\"\", baz", ) .header("JunkFollowingQuotes", "\"\\\"asdf\\\"\"baz") .header("EmptyQuotes", "\"\",baz") .header("EscapedSlashesInQuotes", "foo, \"(foo\\\\bar)\"") .body(()) .unwrap(); let read = |name: &str| read_many_from_str::<String>(test_request.headers().get_all(name).iter()); let read_valid = |name: &str| read(name).expect("valid"); assert_eq!(read_valid("Empty"), Vec::<String>::new()); assert_eq!(read_valid("Foo"), vec!["foo"]); assert_eq!(read_valid("FooTrailing"), vec!["foo"]); assert_eq!(read_valid("FooInQuotes"), vec![" foo "]); assert_eq!(read_valid("CommaInQuotes"), vec!["foo,bar", "baz"]); assert_eq!(read_valid("CommaInQuotesTrailing"), vec!["foo,bar", "baz"]); assert_eq!( read_valid("QuoteInQuotes"), vec!["foo\",bar", "\"asdf\"", "baz"] ); assert_eq!( read_valid("QuoteInQuotesWithSpaces"), vec!["foo\",bar", "\"asdf\"", "baz"] ); assert!(read("JunkFollowingQuotes").is_err()); assert_eq!(read_valid("EmptyQuotes"), vec!["", "baz"]); assert_eq!( read_valid("EscapedSlashesInQuotes"), vec!["foo", "(foo\\bar)"] ); } #[test] fn read_many_bools() { let test_request = http::Request::builder() .header("X-Bool-Multi", "true,false") .header("X-Bool-Multi", "true") .header("X-Bool", "true") .header("X-Bool-Invalid", "truth,falsy") .header("X-Bool-Single", "true,false,true,true") .header("X-Bool-Quoted", "true,\"false\",true,true") .body(()) .unwrap(); assert_eq!( read_many_primitive::<bool>(test_request.headers().get_all("X-Bool-Multi").iter()) .expect("valid"), vec![true, false, true] ); assert_eq!( read_many_primitive::<bool>(test_request.headers().get_all("X-Bool").iter()).unwrap(), vec![true] ); assert_eq!( read_many_primitive::<bool>(test_request.headers().get_all("X-Bool-Single").iter()) .unwrap(), vec![true, false, true, true] ); assert_eq!( read_many_primitive::<bool>(test_request.headers().get_all("X-Bool-Quoted").iter()) .unwrap(), vec![true, false, true, true] ); read_many_primitive::<bool>(test_request.headers().get_all("X-Bool-Invalid").iter()) .expect_err("invalid"); } #[test] fn check_read_many_i16() { let test_request = http::Request::builder() .header("X-Multi", "123,456") .header("X-Multi", "789") .header("X-Num", "777") .header("X-Num-Invalid", "12ef3") .header("X-Num-Single", "1,2,3,-4,5") .header("X-Num-Quoted", "1, \"2\",3,\"-4\",5") .body(()) .unwrap(); assert_eq!( read_many_primitive::<i16>(test_request.headers().get_all("X-Multi").iter()) .expect("valid"), vec![123, 456, 789] ); assert_eq!( read_many_primitive::<i16>(test_request.headers().get_all("X-Num").iter()).unwrap(), vec![777] ); assert_eq!( read_many_primitive::<i16>(test_request.headers().get_all("X-Num-Single").iter()) .unwrap(), vec![1, 2, 3, -4, 5] ); assert_eq!( read_many_primitive::<i16>(test_request.headers().get_all("X-Num-Quoted").iter()) .unwrap(), vec![1, 2, 3, -4, 5] ); read_many_primitive::<i16>(test_request.headers().get_all("X-Num-Invalid").iter()) .expect_err("invalid"); } #[test] fn test_prefix_headers() { let test_request = http::Request::builder() .header("X-Prefix-A", "123,456") .header("X-Prefix-B", "789") .header("X-Prefix-C", "777") .header("X-Prefix-C", "777") .body(()) .unwrap(); let resp: Result<HashMap<String, Vec<i16>>, ParseError> = headers_for_prefix(test_request.headers(), "X-Prefix-") .map(|(key, header_name)| { let values = test_request.headers().get_all(header_name); read_many_primitive(values.iter()).map(|v| (key.to_string(), v)) }) .collect(); let resp = resp.expect("valid"); assert_eq!(resp.get("a"), Some(&vec![123_i16, 456_i16])); } #[test] fn test_quote_header_value() { assert_eq!("", &quote_header_value("")); assert_eq!("foo", &quote_header_value("foo")); assert_eq!("\" foo\"", &quote_header_value(" foo")); assert_eq!("foo bar", &quote_header_value("foo bar")); assert_eq!("\"foo,bar\"", &quote_header_value("foo,bar")); assert_eq!("\",\"", &quote_header_value(",")); assert_eq!("\"\\\"foo\\\"\"", &quote_header_value("\"foo\"")); assert_eq!("\"\\\"f\\\\oo\\\"\"", &quote_header_value("\"f\\oo\"")); assert_eq!("\"(\"", &quote_header_value("(")); assert_eq!("\")\"", &quote_header_value(")")); } }
const expect = require('chai').expect const knex = require('../../../knex').stagingSchema const cleanTables = require('../../../app/wmt-etl/clean-tables') const config = require('../../../etl-config') const Promise = require('bluebird').Promise describe('wmt-etl/test-clean-tables', function () { it('should delete all data from all staging schema tables extract file(s) into the staging schema', function () { return cleanTables() .then(function () { return Promise.each(config.VALID_SHEET_NAMES, function (sheetName) { return knex(sheetName).columns(config.VALID_COLUMNS[sheetName]) .then(function (results) { expect(results.length, sheetName + ' table should contain 0 entries').to.equal(0) expect(results, sheetName + ' table results should be equal []').to.deep.equal([]) }) }) }) }) })
(in-package :extensions) (require :java) (export '(*gui-backend* init-gui make-dialog-prompt-stream)) (defvar *gui-backend* :swing) (defun init-gui () "Dummy function used to autoload this file" t) (defun make-dialog-prompt-stream () (%make-dialog-prompt-stream *gui-backend*)) (defgeneric %make-dialog-prompt-stream (gui-backend)) (defmethod %make-dialog-prompt-stream ((gui-backend (eql :swing))) (java:jnew (java:jconstructor "org.armedbear.lisp.java.swing.SwingDialogPromptStream"))) (defmethod %make-dialog-prompt-stream ((gui-backend (eql :awt))) (java:jnew (java:jconstructor "org.armedbear.lisp.java.awt.AwtDialogPromptStream")))
#!/usr/bin/env perl use lib qw{ ./t/lib }; use Messenger; Messenger->runtests;
//@ Auto-Generated indexing files for avg.engine export * from './avg-native-fs'; export * from './avg-native-path'; export * from './avg-native-util';
<?php /** * Copyright 2012 do ICMBio * Este arquivo é parte do programa SISICMBio * O SISICMBio é um software livre; você pode redistribuí-lo e/ou modificá-lo dentro * dos termos da Licença Pública Geral GNU como publicada pela Fundação do Software Livre * (FSF); na versão 2 da Licença. * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA GARANTIA; * sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. * Veja a Licença Pública Geral GNU/GPL em português para maiores detalhes. * Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título "LICENCA.txt", * junto com este programa, se não, acesse o Portal do Software Público Brasileiro no * endereço www.softwarepublico.gov.br ou escreva para a Fundação do Software Livre(FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ namespace Artefato\Service; /** * Classe para Service de Fecho * * @package Minuta * @category Service * @name Vocativo * @version 1.0.0 */ class EnderecoSgdoce extends \Core_ServiceLayer_Service_CrudDto { /** * @var string */ protected $_entityName = 'app:EnderecoSgdoce'; public function saveEnderecoDestinatario($dto, $params = null) { $filter = new \Zend_Filter(); $entityEnderecoArtefato = $this->_newEntity('app:EnderecoSgdoce'); $pessoaSgdoce = $this->getEntityManager()->getPartialReference( 'app:PessoaSgdoce', $dto->getSqPessoaSgdoce()->getSqPessoaSgdoce()); $entityEnderecoArtefato->setSqPessoaSgdoce($pessoaSgdoce); $tipoEndereco = $this->getEntityManager() ->getPartialReference( 'app:VwTipoEndereco', \Core_Configuration::getSgdoceTipoEnderecoResidencial() ); if($dto->getSqTipoEndereco()){ $tipoEndereco = $this->getEntityManager()->getPartialReference( 'app:VwTipoEndereco', $dto->getSqTipoEndereco()->getSqTipoEndereco()); } $entityEnderecoArtefato->setDtCadastro(date('Y-m-d')); if($dto->getSqMunicipio()->getSqMunicipio()){ $municipio = $this->getEntityManager()->getPartialReference( 'app:VwMunicipio', $dto->getSqMunicipio()->getSqMunicipio()); $entityEnderecoArtefato->setSqMunicipio($municipio); } if($dto->getCoCep()){ $entityEnderecoArtefato->setCoCep($filter->filterStatic($dto->getCoCep(),'Digits')); } if($dto && $dto->getNoContato()) { $entityEnderecoArtefato->setNoContato($dto->getNoContato()); } $entityEnderecoArtefato->setNoBairro($dto->getNoBairro()); $entityEnderecoArtefato->setTxComplemento($dto->getTxComplemento()); $entityEnderecoArtefato->setNuEndereco($dto->getNuEndereco()); $entityEnderecoArtefato->setSqTipoEndereco($tipoEndereco); $entityEnderecoArtefato->setTxEndereco($dto->getTxEndereco()); $this->getEntityManager()->persist($entityEnderecoArtefato); $this->getEntityManager()->flush($entityEnderecoArtefato); if (!empty($params['sqAnexoComprovanteAntigo'])) { $anexoAntigo = $this->getEntityManager()->getReference( 'app:anexoComprovante', $params['sqAnexoComprovanteAntigo'] ); $entityAnexoComprovante = $this->_newEntity('app:AnexoComprovante'); $entityAnexoComprovante->setDeCaminhoArquivo($anexoAntigo->getDeCaminhoArquivo()); $entityAnexoComprovante->setSqEnderecoSgdoce($entityEnderecoArtefato); $this->getEntityManager()->persist($entityAnexoComprovante); $this->getEntityManager()->flush($entityAnexoComprovante); } return $entityEnderecoArtefato; } public function getEnderecoFromCorporativo($entity, $sqPessoaSgdoce) { return $this->_getRepository('app:EnderecoSgdoce')->getEnderecoFromCorporativo($entity, $sqPessoaSgdoce); } public function saveEnderecoPessoaRodape($dto,$entityAux) { $filter = new \Zend_Filter(); $criteria = array('sqPessoaSgdoce' => $entityAux->getSqPessoaSgdoce()); $entityEnderecoArtefato = $this->_getRepository('app:EnderecoSgdoce')->findOneBy($criteria); if (!$entityEnderecoArtefato) { $entityEnderecoArtefato = $this->_newEntity('app:EnderecoSgdoce'); $entityEnderecoArtefato->setSqPessoaSgdoce($entityAux); } $tipoEndereco = $this->getEntityManager() ->getPartialReference( 'app:VwTipoEndereco', \Core_Configuration::getSgdoceTipoEnderecoResidencial() ); $entityEnderecoArtefato->setSqTipoEndereco($tipoEndereco); $entityEnderecoArtefato->setTxEndereco($dto->getTxEnderecoRodape()); $entityEnderecoArtefato->setCoCep($filter->filterStatic($dto->getCoCepRodape(),'Digits')); $this->getEntityManager()->persist($entityEnderecoArtefato); $this->getEntityManager()->flush($entityEnderecoArtefato); return $entityEnderecoArtefato; } public function dtoEntityEndereco($params) { $dtoEnderecoSgdoce = \Core_Dto::factoryFromData($params, 'entity', array('entity'=> 'Sgdoce\Model\Entity\EnderecoSgdoce', 'mapping' => array( 'sqPessoaSgdoce' => 'Sgdoce\Model\Entity\PessoaSgdoce', 'sqMunicipio' => 'Sgdoce\Model\Entity\VwMunicipio', 'sqTipoEndereco' => 'Sgdoce\Model\Entity\VwTipoEndereco'))); $res = $this->saveEnderecoDestinatario($dtoEnderecoSgdoce); return $entityEndereco = $this->getEntityManager()->getPartialReference( 'app:VwEndereco',$res->getSqEnderecoSgdoce()); } public function findEndereco($dto) { return $this->_getRepository()->findOneBy( array('sqPessoaSgdoce' => $dto->getSqPessoaSgdoce())); } public function saveEnderecoSgdoce($entity,$entityAux1) { $endereco = $this->getServiceLocator()->getService('VwEndereco')->findEndereco($entity->getSqPessoa()); $entityEnderecoArtefato = NULL; $filter = new \Zend_Filter(); if($endereco->getSqEndereco()){ $entityEnderecoArtefato = $this->_newEntity('app:EnderecoSgdoce'); $entityEnderecoArtefato->setDtCadastro(date('Y-m-d')); if($endereco->getSqMunicipio()){ $municipio = $this->getEntityManager()->getPartialReference( 'app:VwMunicipio', $endereco->getSqMunicipio()->getSqMunicipio()); $entityEnderecoArtefato->setSqMunicipio($municipio); } if($endereco->getSqCep()){ $entityEnderecoArtefato->setCoCep($filter->filterStatic($endereco->getSqCep(),'Digits')); } $entityEnderecoArtefato->setSqPessoaSgdoce($entityAux1); $entityEnderecoArtefato->setSqTipoEndereco($endereco->getSqTipoEndereco()); $entityEnderecoArtefato->setTxEndereco($endereco->getTxEndereco()); $this->getEntityManager()->persist($entityEnderecoArtefato); $this->getEntityManager()->flush($entityEnderecoArtefato); } return $entityEnderecoArtefato; } public function saveExtraDadosPessoa($params,$dtoSearch){ $entityPessoa = $this->getServiceLocator()->getService('Pessoa')->findPessoa($dtoSearch); //endereco if($params['sqEndereco'] == ''){ $endereco = $this->_getRepository('app:VwEndereco')->findEndereco( $entityPessoa->getSqPessoaCorporativo()->getSqPessoa()); if($endereco){ $params['sqTipoEndereco'] = $endereco->getSqtipoEndereco()->getSqtipoEndereco(); } }else{ $endereco = $this->getServiceLocator()->getService('VwEndereco')->findId($dtoSearch->getSqEndereco()); } $dtoEnderecoSgdoce = \Core_Dto::factoryFromData($params, 'entity', array('entity'=> 'Sgdoce\Model\Entity\EnderecoSgdoce', 'mapping' => array( 'sqPessoaSgdoce' => 'Sgdoce\Model\Entity\PessoaSgdoce', 'sqMunicipio' => 'Sgdoce\Model\Entity\VwMunicipio', 'sqTipoEndereco' => 'Sgdoce\Model\Entity\VwTipoEndereco'))); // buscar pelo pessoa artefato $dadosEnderecoSgdoce = $this->findEndereco($dtoEnderecoSgdoce->getSqPessoaSgdoce()); // persistindo informacoes de endereco $params = $this->trataPersistEndereco($dadosEnderecoSgdoce, $dtoEnderecoSgdoce, $params, $endereco); $dtoTelefoneSgdoce = \Core_Dto::factoryFromData($params, 'entity', array('entity'=> 'Sgdoce\Model\Entity\TelefoneSgdoce', 'mapping' => array( 'sqPessoaSgdoce' => 'Sgdoce\Model\Entity\PessoaSgdoce'))); $dadosTelefoneSgdoce = $this->getServiceLocator()->getService('TelefoneSgdoce')->findTelefone( $dtoEnderecoSgdoce->getSqPessoaSgdoce()); $params = $this->salvaDadosTelefone($dadosTelefoneSgdoce, $entityPessoa, $dtoTelefoneSgdoce, $params); $dtoEmailSgdoce = \Core_Dto::factoryFromData($params, 'entity', array('entity'=> 'Sgdoce\Model\Entity\EmailSgdoce', 'mapping' => array( 'sqPessoaSgdoce' => 'Sgdoce\Model\Entity\PessoaSgdoce'))); $dadosEmailSgdoce = $this->getServiceLocator()->getService('EmailSgdoce') ->findEmail($dtoEnderecoSgdoce->getSqPessoaSgdoce()); $params = $this->salvaDadosEmail($dadosEmailSgdoce, $entityPessoa, $dtoEmailSgdoce, $params); return $params; } public function salvaDadosEmail($dadosEmailSgdoce, $entityPessoa, $dtoEmailSgdoce, $params) { if($dadosEmailSgdoce == NULL){ $email = $this->getServiceLocator()->getService('VwEmail')->findEmail( $entityPessoa->getSqPessoaCorporativo()->getSqPessoa()); if($email){ $dadosEmailSgdoce = $this->getServiceLocator()->getService('EmailSgdoce') ->saveEmailPessoaRodape($dtoEmailSgdoce,$entityPessoa); } } if($dadosEmailSgdoce){ $params['sqEmailSgdoce'] = $dadosEmailSgdoce->getSqEmailSgdoce(); } return $params; } public function salvaDadosTelefone($dadosTelefoneSgdoce, $entityPessoa, $dtoTelefoneSgdoce, $params) { if($dadosTelefoneSgdoce == NULL){ $telefone = $this->getServiceLocator()->getService('VwTelefone')->findTelefone( $entityPessoa->getSqPessoaCorporativo()->getSqPessoa()); if($telefone){ $dadosTelefoneSgdoce = $this->getServiceLocator()->getService('TelefoneSgdoce') ->saveTelefonePessoaRodape($dtoTelefoneSgdoce,$entityPessoa); } } if($dadosTelefoneSgdoce){ $params['sqTelefoneSgdoce'] = $dadosTelefoneSgdoce->getSqTelefoneSgdoce(); } return $params; } public function trataPersistEndereco($dadosEnderecoSgdoce, $dtoEnderecoSgdoce, $params, $endereco = NULL) { if($dadosEnderecoSgdoce == NULL || $params['checkCorporativo'] == '1'){ if($endereco){ $dadosEnderecoSgdoce = $this->saveEnderecoDestinatario($dtoEnderecoSgdoce); } }else{ if(!$dadosEnderecoSgdoce->getNoBairro()){ $dadosEnderecoSgdoce->setNoBairro($dtoEnderecoSgdoce->getNoBairro()); } if(!$dadosEnderecoSgdoce->getTxComplemento()){ $dadosEnderecoSgdoce->setTxComplemento($dtoEnderecoSgdoce->getTxComplemento()); } if(!$dadosEnderecoSgdoce->getNuEndereco()){ $dadosEnderecoSgdoce->setNuEndereco($dtoEnderecoSgdoce->getNuEndereco()); } $this->getEntityManager()->persist($dadosEnderecoSgdoce); $this->getEntityManager()->flush($dadosEnderecoSgdoce); } if($dadosEnderecoSgdoce){ $params['sqEnderecoSgdoce'] = $dadosEnderecoSgdoce->getSqEnderecoSgdoce(); } return $params; } public function findByArray($pessoaSgdoce) { return $this->_getRepository()->findByArray($pessoaSgdoce); } public function addEnderecoPessoaSgdoce(\Sgdoce\Model\Entity\PessoaSgdoce $entPessoaSgdoce, $arrEntityVwEndereco) { foreach ($arrEntityVwEndereco as $entVwEndereco) { $entEnderecoSgdoce = $this->_newEntity(); $entEnderecoSgdoce->setSqPessoaSgdoce($entPessoaSgdoce) ->setDtCadastro(\Zend_Date::now()) ->setSqTipoEndereco($entVwEndereco->getSqTipoEndereco()) ->setSqMunicipio($entVwEndereco->getSqMunicipio()) // ->setCoCep() não tem essa informação em vwEndereco ->setNoBairro($entVwEndereco->getNoBairro()) ->setTxEndereco($entVwEndereco->getTxEndereco()) ->setNuEndereco($entVwEndereco->getNuEndereco()) ->setTxComplemento($entVwEndereco->getTxComplemento()); $this->getEntityManager()->persist($entEnderecoSgdoce); $this->getEntityManager()->flush($entEnderecoSgdoce); } return $this; } }
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // @dart = 2.6 import 'package:ui/ui.dart'; import 'package:test/test.dart'; void main() { test('rect accessors', () { const Rect r = Rect.fromLTRB(1.0, 3.0, 5.0, 7.0); expect(r.left, equals(1.0)); expect(r.top, equals(3.0)); expect(r.right, equals(5.0)); expect(r.bottom, equals(7.0)); }); test('rect created by width and height', () { const Rect r = Rect.fromLTWH(1.0, 3.0, 5.0, 7.0); expect(r.left, equals(1.0)); expect(r.top, equals(3.0)); expect(r.right, equals(6.0)); expect(r.bottom, equals(10.0)); expect(r.shortestSide, equals(5.0)); expect(r.longestSide, equals(7.0)); }); test('rect intersection', () { const Rect r1 = Rect.fromLTRB(0.0, 0.0, 100.0, 100.0); const Rect r2 = Rect.fromLTRB(50.0, 50.0, 200.0, 200.0); final Rect r3 = r1.intersect(r2); expect(r3.left, equals(50.0)); expect(r3.top, equals(50.0)); expect(r3.right, equals(100.0)); expect(r3.bottom, equals(100.0)); final Rect r4 = r2.intersect(r1); expect(r4, equals(r3)); }); test('rect expandToInclude overlapping rects', () { const Rect r1 = Rect.fromLTRB(0.0, 0.0, 100.0, 100.0); const Rect r2 = Rect.fromLTRB(50.0, 50.0, 200.0, 200.0); final Rect r3 = r1.expandToInclude(r2); expect(r3.left, equals(0.0)); expect(r3.top, equals(0.0)); expect(r3.right, equals(200.0)); expect(r3.bottom, equals(200.0)); final Rect r4 = r2.expandToInclude(r1); expect(r4, equals(r3)); }); test('rect expandToInclude crossing rects', () { const Rect r1 = Rect.fromLTRB(50.0, 0.0, 50.0, 200.0); const Rect r2 = Rect.fromLTRB(0.0, 50.0, 200.0, 50.0); final Rect r3 = r1.expandToInclude(r2); expect(r3.left, equals(0.0)); expect(r3.top, equals(0.0)); expect(r3.right, equals(200.0)); expect(r3.bottom, equals(200.0)); final Rect r4 = r2.expandToInclude(r1); expect(r4, equals(r3)); }); test('size created from doubles', () { const Size size = Size(5.0, 7.0); expect(size.width, equals(5.0)); expect(size.height, equals(7.0)); expect(size.shortestSide, equals(5.0)); expect(size.longestSide, equals(7.0)); }); test('rounded rect created from rect and radii', () { const Rect baseRect = Rect.fromLTWH(1.0, 3.0, 5.0, 7.0); final RRect r = RRect.fromRectXY(baseRect, 1.0, 1.0); expect(r.left, equals(1.0)); expect(r.top, equals(3.0)); expect(r.right, equals(6.0)); expect(r.bottom, equals(10.0)); expect(r.shortestSide, equals(5.0)); expect(r.longestSide, equals(7.0)); }); }
--- title: COLOUR TRIAD --- `COLOUR TRIAD` undefined` undefined
use crate::SpawnError; /// A value that spawns futures of a specific type. /// /// The trait is generic over `T`: the type of future that can be spawened. This /// is useful for implementing an executor that is only able to spawn a specific /// type of future. /// /// The [`spawn`] function is used to submit the future to the executor. Once /// submitted, the executor takes ownership of the future and becomes /// responsible for driving the future to completion. /// /// This trait is useful as a bound for applications and libraries in order to /// be generic over futures that are `Send` vs. `!Send`. /// /// # Examples /// /// Consider a function that provides an API for draining a `Stream` in the /// background. To do this, a task must be spawned to perform the draining. As /// such, the function takes a stream and an executor on which the background /// task is spawned. /// /// [`spawn`]: TypedExecutor::spawn /// ``` /// use tokio::executor::TypedExecutor; /// use tokio::sync::oneshot; /// /// use futures_core::{ready, Stream}; /// use std::future::Future; /// use std::pin::Pin; /// use std::task::{Context, Poll}; /// /// async fn drain<T, E>(stream: T, executor: &mut E) /// where /// T: Stream + Unpin, /// E: TypedExecutor<Drain<T>> /// { /// let (tx, rx) = oneshot::channel(); /// /// executor.spawn(Drain { /// stream, /// tx: Some(tx), /// }).unwrap(); /// /// rx.await.unwrap() /// } /// /// // The background task /// pub struct Drain<T> { /// stream: T, /// tx: Option<oneshot::Sender<()>>, /// } /// /// impl<T: Stream + Unpin> Future for Drain<T> { /// type Output = (); /// /// fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { /// loop { /// let item = ready!( /// Pin::new(&mut self.stream).poll_next(cx) /// ); /// /// if item.is_none() { break; } /// } /// /// self.tx.take().unwrap().send(()).map_err(|_| ()); /// Poll::Ready(()) /// } /// } /// ``` /// /// By doing this, the `drain` fn can accept a stream that is `!Send` as long as /// the supplied executor is able to spawn `!Send` types. pub trait TypedExecutor<T> { /// Spawns a future to run on this executor. /// /// `future` is passed to the executor, which will begin running it. The /// executor takes ownership of the future and becomes responsible for /// driving the future to completion. /// /// # Panics /// /// Implementations are encouraged to avoid panics. However, panics are /// permitted and the caller should check the implementation specific /// documentation for more details on possible panics. /// /// # Examples /// /// ```rust /// use tokio_executor::TypedExecutor; /// /// use std::future::Future; /// use std::pin::Pin; /// use std::task::{Context, Poll}; /// /// fn example<T>(my_executor: &mut T) /// where /// T: TypedExecutor<MyFuture>, /// { /// my_executor.spawn(MyFuture).unwrap(); /// } /// /// struct MyFuture; /// /// impl Future for MyFuture { /// type Output = (); /// /// fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> { /// println!("running on the executor"); /// Poll::Ready(()) /// } /// } /// ``` fn spawn(&mut self, future: T) -> Result<(), SpawnError>; /// Provides a best effort **hint** to whether or not `spawn` will succeed. /// /// This function may return both false positives **and** false negatives. /// If `status` returns `Ok`, then a call to `spawn` will *probably* /// succeed, but may fail. If `status` returns `Err`, a call to `spawn` will /// *probably* fail, but may succeed. /// /// This allows a caller to avoid creating the task if the call to `spawn` /// has a high likelihood of failing. /// /// # Panics /// /// This function must not panic. Implementers must ensure that panics do /// not happen. /// /// # Examples /// /// ```rust /// use tokio_executor::TypedExecutor; /// /// use std::future::Future; /// use std::pin::Pin; /// use std::task::{Context, Poll}; /// /// fn example<T>(my_executor: &mut T) /// where /// T: TypedExecutor<MyFuture>, /// { /// if my_executor.status().is_ok() { /// my_executor.spawn(MyFuture).unwrap(); /// } else { /// println!("the executor is not in a good state"); /// } /// } /// /// struct MyFuture; /// /// impl Future for MyFuture { /// type Output = (); /// /// fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> { /// println!("running on the executor"); /// Poll::Ready(()) /// } /// } /// ``` fn status(&self) -> Result<(), SpawnError> { Ok(()) } } impl<E, T> TypedExecutor<T> for Box<E> where E: TypedExecutor<T>, { fn spawn(&mut self, future: T) -> Result<(), SpawnError> { (**self).spawn(future) } fn status(&self) -> Result<(), SpawnError> { (**self).status() } }
const Rx = require("rxjs/Rx"); let stream$ = Rx.Observable.create(observer => { observer.next(1); observer.error("err"); }) .retry(3); // emits 1 1 1 1 err stream$ .subscribe(data => console.log(data));
require "headline_sources/scraper" require "headline_sources/fetchers/gawker_fetcher" module HeadlineSources class DefamerFetcher < RSSFetcher def feed_url "http://defamer.gawker.com/rss" end end end
package chapter4_4 import "fmt" // 结构体比较 type address struct { hostname string port int } func StructCompare() { p := Point{1, 2} q := Point{2, 1} fmt.Println(p.X == q.X && p.Y == q.Y) // "false" fmt.Println(p == q) // "false" // 可比较的结构体类型和其他可比较的类型一样,可以用于map的key类型。 hits := make(map[address]int) hits[address{"golang.org", 443}]++ }
require 'ncaa_scrape' RSpec.describe NCAABasketball do before do @scrape = NCAABasketball.new end describe 'attributes' do it 'is initialized with data from NCAA.com' do expect(NCAABasketball.new.instance_variable_get('@division_one_data')).to be_a Hash expect(NCAABasketball.new.instance_variable_get('@division_one_data')).not_to be_empty end end describe '#team_names' do it 'returns an array of team names' do all_team_names = @scrape.team_names expect(all_team_names).to be_a Array expect(all_team_names).not_to be_empty expect(all_team_names.last).to be_a String end end describe '#team_wins' do it "returns an integer with a team's wins" do team = @scrape.team_wins('Texas') expect(team).to be_a Integer end end describe '#pick_five_total' do it 'returns an integer when given the names of five teams' do pick_five = @scrape.pick_five_total('Texas', 'North Carolina', 'Georgetown', 'Indiana', 'Michigan St.') expect(pick_five).to be_a Integer end end end
namespace Main.Logger { public class NullProcessLogger : IProcessLogger { public void ShowProcessMessage(string message, params object[] args) { //nothing to do } public void ShowProcessMessage(string message) { //nothing to do } public static NullProcessLogger Instance = new NullProcessLogger(); } }
var Key = { pressed: [], LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, ENTER: 13, SPACE: 32, PAGE_UP: 33, PAGE_DOWN: 34, W: 87, A: 65, S: 83, D: 68, isDown: function(keyCode) { return this.pressed[keyCode]; }, reset: function(keyCode) { this.pressed[keyCode] = false; }, onKeydown: function(event) { this.pressed[event.keyCode] = true; }, onKeyup: function(event) { delete this.pressed[event.keyCode]; } }; window.addEventListener('keyup', function(event) { Key.onKeyup(event); }, false); window.addEventListener('keydown', function(event) { Key.onKeydown(event); }, false);
#!/bin/sh set -e test ! -z "$DEBUG" && set -x dc_ip_address() { _domain="$1" dig A +short $(dig -t SRV _ldap._tcp.dc._msdcs."$_domain" +short | cut -d' ' -f4) | \ head -n 1 } main() { _username="$1" [ -z "$_username" ] && echo "Username is required" && exit 100 _domain="$2" [ -z "$_domain" ] && echo "Domain is required" && exit 100 _ip_address=$(dc_ip_address "$_domain") /usr/bin/smbpasswd -U "$_username" -r "$_ip_address" } main "$@"
# twitch-recognition youtube-dl + SpeechRecognition get twitch audio stream -> split into segments -> log speech recognition result ## Usage python main.py -c <username> [options] ### options -l, --language SpeechRecognition language code -e, --engine SpeechRecognition engine -st, --segment-time ffmpeg segment_time in seconds -h, --help options help ## Install ### requirements ffmpeg #### Python 3 youtube-dl>=2020.11.1.1 SpeechRecognition>=3.8.1 ### config.json config default values can be overwritten with options `channel` (str): twitch.tv username `language` (str): language code `segment_time` (int): ffmpeg segment_time in seconds `engine` (str): SpeechRecognition engine (Google or Sphinx) `targets` (object of str): key: string to search for, value: response string
at(100033914,302303673). at(100033914,302304841). at(100845915,301204643). at(100845915,301204965). at(101092370,300485135). at(101092370,300486321). at(101218209,300198526). at(101218209,300199039). at(104628098,300953896). at(104628367,300954437). at(104629320,301353869). at(104630470,301137376). at(104630470,301138269). at(104630969,302575716). at(104630969,302576745). at(104633637,300856955). at(104633637,300860047). at(104633637,301259404). at(104633637,301260684). at(104633637,302541266). at(104633637,302541827). at(104634062,300798380). at(104634062,300799050). at(104638046,300363547). at(104638046,300365559). at(104639057,302286688). at(104639057,302289059). at(104639514,300808265). at(104642461,300032087). at(104642461,300033687). at(104642461,300038863). at(104643754,300039705). at(104645280,301767351). at(104645280,301767957). at(104653905,302125659). at(104653905,302127738). at(104656618,302129139). at(104656618,302130695). at(104659992,302256093). at(104659992,302257185). at(104660287,302264897). at(104660287,302266356). at(104661226,302260390). at(104661226,302260821). at(104661694,301078338). at(104661694,301080481). at(104667893,302427668). at(104667893,302429304). at(104668338,301353522). at(104668338,301353724). at(104668746,301340439). at(104668746,301341768). at(104670851,300309819). at(104670851,300312461). at(104671120,301984219). at(104671120,301985067). at(104671770,300163651). at(104671770,300164255). at(104676604,302003477). at(104676604,302005010). at(104691171,300219320). at(104691171,300222548). at(104693352,300167408). at(104693352,300170426). at(104708808,300433163). at(104710772,300434829). at(104712672,300804397). at(104713435,300581435). at(104713435,300583752). at(104713638,301289803). at(104713638,301291153). at(104713638,301622205). at(104713638,301624233). at(104715389,300752852). at(104716529,300748528). at(104723223,300135772). at(104723223,300136789). at(104723223,300139437). at(104723223,300139890). at(104723486,301003236). at(104723486,301004300). at(104725839,300607261). at(104725839,300607505). at(104726275,300019169). at(104726275,300019912). at(104726275,300184353). at(104726275,300187221). at(104731092,301126910). at(104731092,301129296). at(104731092,301823004). at(104731092,301823738). at(104734196,301261689). at(104734196,301263095). at(104735326,302349336). at(104735326,302353767). at(104740880,300345024). at(104740880,300348093). at(104743997,300919820). at(104743997,300920321). at(104745881,300585590). at(104745881,300586470). at(104749775,302070074). at(104750006,302076759). at(104750845,302078824). at(104750845,302080517). at(104752054,301413463). at(104752054,301413762). at(104755139,300893124). at(104755139,300895672). at(104756076,302072149). at(104758560,302516600). at(104758560,302518026). at(104760710,300336319). at(104760710,300337066). at(104761695,300552502). at(104761695,300552997). at(104763890,301414308). at(104763890,301415272). at(104767104,300013179). at(104768026,300629641). at(104768026,300630251). at(104768026,300632838). at(104768026,300633643). at(104768467,300628097). at(104768467,300628492). at(104769389,300011776). at(104770548,300495505). at(104771667,301105084). at(104771667,301106714). at(104771996,300494722). at(104773530,302182456). at(104773530,302183738). at(104774586,301966104). at(104774586,301967466). at(104775044,300678969). at(104775044,300679725). at(104776695,300912628). at(104776695,300914441). at(104785869,301805299). at(104785869,301806732). at(104786760,301590750). at(104788030,301591485). at(104788240,301628814). at(104788240,301631640). at(104788240,301632363). at(104788240,301632738). at(104790142,300647861). at(104790142,300648515). at(104791892,301432984). at(104791892,301433720). at(104793136,301574358). at(104793136,301574863). at(104794991,300073656). at(104794991,300074954). at(104799588,300051265). at(104799588,300051936). at(104800247,301766383). at(104800247,301767094). at(104802000,301677162). at(104802000,301679784). at(104802794,300487699). at(104802794,300489640). at(104803335,300491099). at(104803335,300492026). at(104803540,300968795). at(104803540,300969666). at(104804731,301038139). at(104806593,301038139). at(104807608,301691099). at(104807608,301692724). at(104808562,301694333). at(104808562,301695526). at(104808781,300607893). at(104808781,300608979). at(104809447,300634232). at(104809447,300635278). at(104810156,300021803). at(104810156,300023420). at(104813883,302595419). at(104813883,302598414). at(104815891,301821123). at(104815891,301822300). at(104816489,301403566). at(104816489,301404858). at(104817036,301398622). at(104817036,301399052). at(104827489,300429900). at(104827489,300431687). at(104829263,300943706). at(104829263,300944754). at(104834002,301786023). at(104834002,301787064). at(104836156,301264939). at(104836156,301265721). at(104838958,301114727). at(104838958,301116284). at(104843499,300104850). at(104843499,300105822). at(104845162,301354915). at(104845162,301355743). at(104846385,300959321). at(104846385,300960366). at(104847242,301374976). at(104847242,301376655). at(104847768,300225394). at(104848212,300228210). at(104850019,300228595). at(104853764,300225758). at(104854001,301552360). at(104854001,301553334). at(104854001,301911024). at(104854001,301911556). at(104854364,302042235). at(104854364,302042744). at(104856472,301133477). at(104856990,300361730). at(104856990,300362589). at(104859319,301134543). at(104861179,300623350). at(104861179,300625237). at(104862369,302061222). at(104862369,302062183). at(104864314,300263658). at(104866016,300250587). at(104867296,300265642). at(104867990,300252675). at(104874361,302186899). at(104874361,302188427). at(104875961,301229113). at(104875961,301230010). at(104877535,301592579). at(104877535,301593624). at(104878569,302326142). at(104878569,302326807). at(104880153,301739133). at(104880500,301738685). at(104884180,300962069). at(104884180,300962920). at(104884725,300964581). at(104884725,300965823). at(104891137,300009065). at(104893296,300009997). at(104893841,301895355). at(104896722,301899020). at(104905614,301884565). at(104905614,301886613). at(104908124,301541980). at(104908124,301543026). at(104912365,302460186). at(104912365,302461024). at(104913019,302396713). at(104913450,301616581). at(104913450,301618017). at(104915003,302397788). at(104918597,301045598). at(104918597,301047939). at(104918597,301048915). at(104918597,301049410). at(104919909,300642864). at(104919909,300643305). at(104920159,300644180). at(104920159,300644662). at(104921310,300645401). at(104921310,300645747). at(104925387,300764460). at(104925387,300765898). at(104925944,300773875). at(104925944,300774315). at(104929964,301909796). at(104929964,301910335). at(104931280,301491608). at(104931280,301493085). at(104931280,301642580). at(104931280,301645077). at(104931280,301648062). at(104931280,301651383). at(104933905,301071383). at(104935185,301072500). at(104941723,302424186). at(104941723,302426097). at(104943580,302424186). at(104943580,302426097). at(104945025,301154418). at(104945025,301156249). at(104946501,300711461). at(104946501,300713189). at(104948141,300006354). at(104948141,300007832). at(104953255,300029456). at(104953255,300031646). at(104954054,302238735). at(104954054,302239996). at(104958550,300270855). at(104958550,300273948). at(104963771,300395623). at(104963771,300402711). at(104982389,300367771). at(104982389,300387453). at(104984219,300244463). at(104984219,300245359). at(104986674,300393873). at(104986674,300394166). at(104986674,300409737). at(104986674,300410517). at(104987257,301058772). at(104987257,301061474). at(104990651,301508304). at(104990651,301508997). at(104992447,301215869). at(104992447,301218092). at(104997456,301455372). at(104997456,301457415). at(104999341,302403682). at(104999341,302408123). at(105002696,300134488). at(105002696,300134922). at(105009517,302393670). at(105009517,302395180). at(105012631,300118877). at(105012631,300119049). at(105012993,300095301). at(105012993,300096133). at(105013204,300118196). at(105013204,300118565). at(105014082,301479992). at(105014082,301481113). at(105014082,301481933). at(105014082,302142650). at(105014082,302143325). at(105018974,301250274). at(105018974,301254201). at(105018974,302539669). at(105018974,302540350). at(105025269,300279417). at(105025269,300284569). at(105026100,300175025). at(105026100,300175640). at(105026827,302110761). at(105026827,302112655). at(105034009,301188475). at(105034009,301189951). at(105034301,300989218). at(105034301,300991420). at(105036872,300709335). at(105036872,300710810). at(105036872,302328781). at(105036872,302332106). at(105041380,301829730). at(105041380,301830237). at(105041628,301550389). at(105041628,301550516). at(105042144,301550760). at(105042144,301550993). at(105042144,301551174). at(105042144,301551998). at(105042144,301552128). at(105050613,300741517). at(105050613,300741912). at(105053160,300126583). at(105053160,300128168). at(105053160,300816521). at(105053160,300819510). at(105053160,300820050). at(105053160,301732158). at(105053160,301735600). at(105053160,301736519). at(105057530,300669281). at(105057530,300671807). at(105057819,301539804). at(105058400,301440837). at(105058400,301445077). at(105060366,301758923). at(105060366,301760139). at(105061281,300597095). at(105065291,300979699). at(105065291,300983718). at(105070898,300660221). at(105071206,302318575). at(105071206,302319224). at(105081543,301033637). at(105081543,301034481). at(105081943,300131850). at(105081943,300132498). at(105081943,300951310). at(105081943,300951878). at(105081943,300952756). at(105081943,300953480). at(105081943,300955585). at(105081943,300956057). at(105087073,301238732). at(105087073,301240770). at(105089997,300164857). at(105089997,300166125). at(105091408,300444378). at(105091408,300446553). at(105091408,300447582). at(105091408,300448955). at(105097645,301502253). at(105101152,301213526). at(105101152,301215141). at(105101152,301512398). at(105101152,301513206). at(105106204,301385012). at(105106204,301394303). at(105110372,302419189). at(105110372,302420960). at(105116040,300013906). at(105116040,300016794). at(105116040,302343832). at(105116040,302344427). at(105119909,300106545). at(105119909,300107268). at(105124960,301535494). at(105124960,301537239). at(105129173,301555990). at(105129173,301557242). at(105129822,301473917). at(105130115,301474283). at(105136466,301436368). at(105136466,301438878). at(105141812,300693335). at(105141812,300694973). at(105141812,300696211). at(105141812,300696805). at(105143415,302571278). at(105143415,302572618). at(105144430,301207229). at(105144430,301209146). at(105155946,302505612). at(105155946,302506940). at(105156572,301094001). at(105156572,301094686). at(105158335,301840022). at(105158335,301842067). at(105167957,301950023). at(105167957,301951277). at(105168623,300177411). at(105168623,300178121). at(105168623,300178468). at(105168623,300179263). at(105175788,301278672). at(105175788,301283088). at(105177340,302168847). at(105177340,302171958). at(105178572,300903909). at(105178572,300905804). at(105180480,300906671). at(105180480,300906890). at(105198072,301831389). at(105198072,301833253). at(105199719,301346766). at(105199719,301347811). at(105200606,300403480). at(105200606,300405279). at(105206554,300837737). at(105206554,300839148). at(105207137,300842395). at(105207137,300842950). at(105207437,300001740). at(105207437,300002098). at(105209302,300191068). at(105209302,300191511). at(105209765,300307112). at(105209765,300308272). at(105213007,300810082). at(105216381,301042490). at(105216381,301043525). at(105624029,300001740). at(105625389,301337350). at(105625389,301339540). at(105626632,301335338). at(105626632,301336670). at(105630964,300307112). at(105630964,300308272). at(105632483,300646272). at(105632483,300647394). at(105646331,301424552). at(105647276,300835614). at(105647276,300835739). at(105683749,300191603). at(105683749,300193091). at(105705100,300337729). at(105705100,300338302). at(105705328,300337729). at(105705328,300338302). at(105710673,301197257). at(105710673,301198026). at(105742504,300172851). at(105742504,300173713). at(105757616,302401445). at(105757616,302401968). at(106008718,302091950). at(106008718,302092278). at(106222574,300576723). at(106222574,300577581). at(106568472,300179875). at(106568472,300180786). at(106790003,302086159). at(106790003,302087627). at(107104300,300548866). at(107104300,300551001). at(107262270,302108860). at(107262270,302109601). at(107527704,302113270). at(107527704,302114041). at(107534492,300078253). at(107534492,300082141). at(107535012,300194616). at(107535012,300198152). at(107541744,300339715). at(107541744,300340839). at(107541996,301151786). at(107541996,301152997). at(108578618,301604915). at(108578618,301608808). at(108579120,301609663). at(108580157,300829153). at(108580717,300830498). at(108639173,302039393). at(108639173,302040360). at(108700313,300828657). at(108700557,300829509). at(109072700,301606912). at(109072700,301611230). at(109073186,301611230). at(109074770,301610335). at(109075108,301610335). at(111447028,300171417). at(111464912,300706218). at(111464912,300706407). at(111499458,300171217). at(113813601,300568364). at(113813601,300569857). at(113849639,301297423). at(113849639,301298564). at(113850288,301235508). at(113850288,301236220). at(113850288,301237040). at(113866887,300126583). at(113866887,300128168). at(113866887,300131223). at(113866887,300131353). at(113956593,300653599). at(113956593,300654719). at(113965156,301582720). at(113968971,300260434). at(113968971,300261296). at(113968971,300262111). at(113968971,300794782). at(113968971,300796546). at(113972794,302107054). at(113972794,302107989). at(113977471,300930258). at(113977471,300930819). at(113978104,300043985). at(113978747,301939402). at(113978747,301941146). at(113979774,302469730). at(113979774,302470951). at(113980887,301852337). at(113980887,301853600). at(113984978,300095301). at(113984978,300096133). at(113991028,300361730). at(114010908,301151786). at(114010908,301152997). at(114015308,301065188). at(114015308,301067975). at(114017633,300729216). at(114017633,300731008). at(114027802,301566164). at(114027802,301568466). at(114030430,300040548). at(114035282,300040908). at(114035644,300041273). at(114054590,301936911). at(114054590,301938650). at(114057069,300654957). at(114057069,300655555). at(114060493,300924255). at(114060493,300925835). at(114074976,301005108). at(114074976,301005778). at(114435385,300027360). at(114435385,300028785). at(114437698,302116958). at(114448184,301491608). at(114448184,301493085). at(114461591,301989711). at(114461591,301990862). at(114468845,300478809). at(114468845,300480005). at(114471374,301173787). at(114471374,301176433). at(114474157,301584458). at(114474157,301585523). at(114475377,301086845). at(114475377,301090234). at(114475908,302271436). at(114475908,302271738). at(114482870,301753804). at(114482870,301756665). at(114484149,300289948). at(114484149,300290231). at(114484149,300516809). at(114484149,300518464). at(114484558,300522139). at(114484558,300526155). at(114485103,300527630). at(114498478,302339254). at(114498478,302341445). at(114503199,302267791). at(114503199,302269142). at(114503199,302270298). at(114505513,301826770). at(114505513,301828578). at(114506204,300044573). at(114510351,301911832). at(114510351,301914420). at(114511901,302029118). at(114511901,302030204). at(114519777,300418932). at(114519777,300420808). at(114524492,301598231). at(114524492,301600178). at(114525129,302477858). at(114525129,302479427). at(114553663,302369003). at(114553663,302371926). at(114555374,302115478). at(114555374,302115639). at(114558298,302558087). at(114558298,302562150). at(114570638,302095101). at(114570638,302095231). at(114570780,302095343). at(114570780,302095459). at(115154879,300131484). at(115154879,300131668). at(300001740,105207437). at(300001740,105624029). at(300002098,105207437). at(300006354,104948141). at(300007832,104948141). at(300009065,104891137). at(300009997,104893296). at(300011776,104769389). at(300013179,104767104). at(300013906,105116040). at(300016794,105116040). at(300019169,104726275). at(300019912,104726275). at(300021803,104810156). at(300023420,104810156). at(300027360,114435385). at(300028785,114435385). at(300029456,104953255). at(300031646,104953255). at(300032087,104642461). at(300033687,104642461). at(300038863,104642461). at(300039705,104643754). at(300040548,114030430). at(300040908,114035282). at(300041273,114035644). at(300043985,113978104). at(300044573,114506204). at(300051265,104799588). at(300051936,104799588). at(300073656,104794991). at(300074954,104794991). at(300078253,107534492). at(300082141,107534492). at(300095301,105012993). at(300095301,113984978). at(300096133,105012993). at(300096133,113984978). at(300104850,104843499). at(300105822,104843499). at(300106545,105119909). at(300107268,105119909). at(300118196,105013204). at(300118565,105013204). at(300118877,105012631). at(300119049,105012631). at(300126583,105053160). at(300126583,113866887). at(300128168,105053160). at(300128168,113866887). at(300131223,113866887). at(300131353,113866887). at(300131484,115154879). at(300131668,115154879). at(300131850,105081943). at(300132498,105081943). at(300134488,105002696). at(300134922,105002696). at(300135772,104723223). at(300136789,104723223). at(300139437,104723223). at(300139890,104723223). at(300163651,104671770). at(300164255,104671770). at(300164857,105089997). at(300166125,105089997). at(300167408,104693352). at(300170426,104693352). at(300171217,111499458). at(300171417,111447028). at(300172851,105742504). at(300173713,105742504). at(300175025,105026100). at(300175640,105026100). at(300177411,105168623). at(300178121,105168623). at(300178468,105168623). at(300179263,105168623). at(300179875,106568472). at(300180786,106568472). at(300184353,104726275). at(300187221,104726275). at(300191068,105209302). at(300191511,105209302). at(300191603,105683749). at(300193091,105683749). at(300194616,107535012). at(300198152,107535012). at(300198526,101218209). at(300199039,101218209). at(300219320,104691171). at(300222548,104691171). at(300225394,104847768). at(300225758,104853764). at(300228210,104848212). at(300228595,104850019). at(300244463,104984219). at(300245359,104984219). at(300250587,104866016). at(300252675,104867990). at(300260434,113968971). at(300261296,113968971). at(300262111,113968971). at(300263658,104864314). at(300265642,104867296). at(300270855,104958550). at(300273948,104958550). at(300279417,105025269). at(300284569,105025269). at(300289948,114484149). at(300290231,114484149). at(300307112,105209765). at(300307112,105630964). at(300308272,105209765). at(300308272,105630964). at(300309819,104670851). at(300312461,104670851). at(300336319,104760710). at(300337066,104760710). at(300337729,105705100). at(300337729,105705328). at(300338302,105705100). at(300338302,105705328). at(300339715,107541744). at(300340839,107541744). at(300345024,104740880). at(300348093,104740880). at(300361730,104856990). at(300361730,113991028). at(300362589,104856990). at(300363547,104638046). at(300365559,104638046). at(300367771,104982389). at(300387453,104982389). at(300393873,104986674). at(300394166,104986674). at(300395623,104963771). at(300402711,104963771). at(300403480,105200606). at(300405279,105200606). at(300409737,104986674). at(300410517,104986674). at(300418932,114519777). at(300420808,114519777). at(300429900,104827489). at(300431687,104827489). at(300433163,104708808). at(300434829,104710772). at(300444378,105091408). at(300446553,105091408). at(300447582,105091408). at(300448955,105091408). at(300478809,114468845). at(300480005,114468845). at(300485135,101092370). at(300486321,101092370). at(300487699,104802794). at(300489640,104802794). at(300491099,104803335). at(300492026,104803335). at(300494722,104771996). at(300495505,104770548). at(300516809,114484149). at(300518464,114484149). at(300522139,114484558). at(300526155,114484558). at(300527630,114485103). at(300548866,107104300). at(300551001,107104300). at(300552502,104761695). at(300552997,104761695). at(300568364,113813601). at(300569857,113813601). at(300576723,106222574). at(300577581,106222574). at(300581435,104713435). at(300583752,104713435). at(300585590,104745881). at(300586470,104745881). at(300597095,105061281). at(300607261,104725839). at(300607505,104725839). at(300607893,104808781). at(300608979,104808781). at(300623350,104861179). at(300625237,104861179). at(300628097,104768467). at(300628492,104768467). at(300629641,104768026). at(300630251,104768026). at(300632838,104768026). at(300633643,104768026). at(300634232,104809447). at(300635278,104809447). at(300642864,104919909). at(300643305,104919909). at(300644180,104920159). at(300644662,104920159). at(300645401,104921310). at(300645747,104921310). at(300646272,105632483). at(300647394,105632483). at(300647861,104790142). at(300648515,104790142). at(300653599,113956593). at(300654719,113956593). at(300654957,114057069). at(300655555,114057069). at(300660221,105070898). at(300669281,105057530). at(300671807,105057530). at(300678969,104775044). at(300679725,104775044). at(300693335,105141812). at(300694973,105141812). at(300696211,105141812). at(300696805,105141812). at(300706218,111464912). at(300706407,111464912). at(300709335,105036872). at(300710810,105036872). at(300711461,104946501). at(300713189,104946501). at(300729216,114017633). at(300731008,114017633). at(300741517,105050613). at(300741912,105050613). at(300748528,104716529). at(300752852,104715389). at(300764460,104925387). at(300765898,104925387). at(300773875,104925944). at(300774315,104925944). at(300794782,113968971). at(300796546,113968971). at(300798380,104634062). at(300799050,104634062). at(300804397,104712672). at(300808265,104639514). at(300810082,105213007). at(300816521,105053160). at(300819510,105053160). at(300820050,105053160). at(300828657,108700313). at(300829153,108580157). at(300829509,108700557). at(300830498,108580717). at(300835614,105647276). at(300835739,105647276). at(300837737,105206554). at(300839148,105206554). at(300842395,105207137). at(300842950,105207137). at(300856955,104633637). at(300860047,104633637). at(300893124,104755139). at(300895672,104755139). at(300903909,105178572). at(300905804,105178572). at(300906671,105180480). at(300906890,105180480). at(300912628,104776695). at(300914441,104776695). at(300919820,104743997). at(300920321,104743997). at(300924255,114060493). at(300925835,114060493). at(300930258,113977471). at(300930819,113977471). at(300943706,104829263). at(300944754,104829263). at(300951310,105081943). at(300951878,105081943). at(300952756,105081943). at(300953480,105081943). at(300953896,104628098). at(300954437,104628367). at(300955585,105081943). at(300956057,105081943). at(300959321,104846385). at(300960366,104846385). at(300962069,104884180). at(300962920,104884180). at(300964581,104884725). at(300965823,104884725). at(300968795,104803540). at(300969666,104803540). at(300979699,105065291). at(300983718,105065291). at(300989218,105034301). at(300991420,105034301). at(301003236,104723486). at(301004300,104723486). at(301005108,114074976). at(301005778,114074976). at(301033637,105081543). at(301034481,105081543). at(301038139,104804731). at(301038139,104806593). at(301042490,105216381). at(301043525,105216381). at(301045598,104918597). at(301047939,104918597). at(301048915,104918597). at(301049410,104918597). at(301058772,104987257). at(301061474,104987257). at(301065188,114015308). at(301067975,114015308). at(301071383,104933905). at(301072500,104935185). at(301078338,104661694). at(301080481,104661694). at(301086845,114475377). at(301090234,114475377). at(301094001,105156572). at(301094686,105156572). at(301105084,104771667). at(301106714,104771667). at(301114727,104838958). at(301116284,104838958). at(301126910,104731092). at(301129296,104731092). at(301133477,104856472). at(301134543,104859319). at(301137376,104630470). at(301138269,104630470). at(301151786,107541996). at(301151786,114010908). at(301152997,107541996). at(301152997,114010908). at(301154418,104945025). at(301156249,104945025). at(301173787,114471374). at(301176433,114471374). at(301188475,105034009). at(301189951,105034009). at(301197257,105710673). at(301198026,105710673). at(301204643,100845915). at(301204965,100845915). at(301207229,105144430). at(301209146,105144430). at(301213526,105101152). at(301215141,105101152). at(301215869,104992447). at(301218092,104992447). at(301229113,104875961). at(301230010,104875961). at(301235508,113850288). at(301236220,113850288). at(301237040,113850288). at(301238732,105087073). at(301240770,105087073). at(301250274,105018974). at(301254201,105018974). at(301259404,104633637). at(301260684,104633637). at(301261689,104734196). at(301263095,104734196). at(301264939,104836156). at(301265721,104836156). at(301278672,105175788). at(301283088,105175788). at(301289803,104713638). at(301291153,104713638). at(301297423,113849639). at(301298564,113849639). at(301335338,105626632). at(301336670,105626632). at(301337350,105625389). at(301339540,105625389). at(301340439,104668746). at(301341768,104668746). at(301346766,105199719). at(301347811,105199719). at(301353522,104668338). at(301353724,104668338). at(301353869,104629320). at(301354915,104845162). at(301355743,104845162). at(301374976,104847242). at(301376655,104847242). at(301385012,105106204). at(301394303,105106204). at(301398622,104817036). at(301399052,104817036). at(301403566,104816489). at(301404858,104816489). at(301413463,104752054). at(301413762,104752054). at(301414308,104763890). at(301415272,104763890). at(301424552,105646331). at(301432984,104791892). at(301433720,104791892). at(301436368,105136466). at(301438878,105136466). at(301440837,105058400). at(301445077,105058400). at(301455372,104997456). at(301457415,104997456). at(301473917,105129822). at(301474283,105130115). at(301479992,105014082). at(301481113,105014082). at(301481933,105014082). at(301491608,104931280). at(301491608,114448184). at(301493085,104931280). at(301493085,114448184). at(301502253,105097645). at(301508304,104990651). at(301508997,104990651). at(301512398,105101152). at(301513206,105101152). at(301535494,105124960). at(301537239,105124960). at(301539804,105057819). at(301541980,104908124). at(301543026,104908124). at(301550389,105041628). at(301550516,105041628). at(301550760,105042144). at(301550993,105042144). at(301551174,105042144). at(301551998,105042144). at(301552128,105042144). at(301552360,104854001). at(301553334,104854001). at(301555990,105129173). at(301557242,105129173). at(301566164,114027802). at(301568466,114027802). at(301574358,104793136). at(301574863,104793136). at(301582720,113965156). at(301584458,114474157). at(301585523,114474157). at(301590750,104786760). at(301591485,104788030). at(301592579,104877535). at(301593624,104877535). at(301598231,114524492). at(301600178,114524492). at(301604915,108578618). at(301606912,109072700). at(301608808,108578618). at(301609663,108579120). at(301610335,109074770). at(301610335,109075108). at(301611230,109072700). at(301611230,109073186). at(301616581,104913450). at(301618017,104913450). at(301622205,104713638). at(301624233,104713638). at(301628814,104788240). at(301631640,104788240). at(301632363,104788240). at(301632738,104788240). at(301642580,104931280). at(301645077,104931280). at(301648062,104931280). at(301651383,104931280). at(301677162,104802000). at(301679784,104802000). at(301691099,104807608). at(301692724,104807608). at(301694333,104808562). at(301695526,104808562). at(301732158,105053160). at(301735600,105053160). at(301736519,105053160). at(301738685,104880500). at(301739133,104880153). at(301753804,114482870). at(301756665,114482870). at(301758923,105060366). at(301760139,105060366). at(301766383,104800247). at(301767094,104800247). at(301767351,104645280). at(301767957,104645280). at(301786023,104834002). at(301787064,104834002). at(301805299,104785869). at(301806732,104785869). at(301821123,104815891). at(301822300,104815891). at(301823004,104731092). at(301823738,104731092). at(301826770,114505513). at(301828578,114505513). at(301829730,105041380). at(301830237,105041380). at(301831389,105198072). at(301833253,105198072). at(301840022,105158335). at(301842067,105158335). at(301852337,113980887). at(301853600,113980887). at(301884565,104905614). at(301886613,104905614). at(301895355,104893841). at(301899020,104896722). at(301909796,104929964). at(301910335,104929964). at(301911024,104854001). at(301911556,104854001). at(301911832,114510351). at(301914420,114510351). at(301936911,114054590). at(301938650,114054590). at(301939402,113978747). at(301941146,113978747). at(301950023,105167957). at(301951277,105167957). at(301966104,104774586). at(301967466,104774586). at(301984219,104671120). at(301985067,104671120). at(301989711,114461591). at(301990862,114461591). at(302003477,104676604). at(302005010,104676604). at(302029118,114511901). at(302030204,114511901). at(302039393,108639173). at(302040360,108639173). at(302042235,104854364). at(302042744,104854364). at(302061222,104862369). at(302062183,104862369). at(302070074,104749775). at(302072149,104756076). at(302076759,104750006). at(302078824,104750845). at(302080517,104750845). at(302086159,106790003). at(302087627,106790003). at(302091950,106008718). at(302092278,106008718). at(302095101,114570638). at(302095231,114570638). at(302095343,114570780). at(302095459,114570780). at(302107054,113972794). at(302107989,113972794). at(302108860,107262270). at(302109601,107262270). at(302110761,105026827). at(302112655,105026827). at(302113270,107527704). at(302114041,107527704). at(302115478,114555374). at(302115639,114555374). at(302116958,114437698). at(302125659,104653905). at(302127738,104653905). at(302129139,104656618). at(302130695,104656618). at(302142650,105014082). at(302143325,105014082). at(302168847,105177340). at(302171958,105177340). at(302182456,104773530). at(302183738,104773530). at(302186899,104874361). at(302188427,104874361). at(302238735,104954054). at(302239996,104954054). at(302256093,104659992). at(302257185,104659992). at(302260390,104661226). at(302260821,104661226). at(302264897,104660287). at(302266356,104660287). at(302267791,114503199). at(302269142,114503199). at(302270298,114503199). at(302271436,114475908). at(302271738,114475908). at(302286688,104639057). at(302289059,104639057). at(302303673,100033914). at(302304841,100033914). at(302318575,105071206). at(302319224,105071206). at(302326142,104878569). at(302326807,104878569). at(302328781,105036872). at(302332106,105036872). at(302339254,114498478). at(302341445,114498478). at(302343832,105116040). at(302344427,105116040). at(302349336,104735326). at(302353767,104735326). at(302369003,114553663). at(302371926,114553663). at(302393670,105009517). at(302395180,105009517). at(302396713,104913019). at(302397788,104915003). at(302401445,105757616). at(302401968,105757616). at(302403682,104999341). at(302408123,104999341). at(302419189,105110372). at(302420960,105110372). at(302424186,104941723). at(302424186,104943580). at(302426097,104941723). at(302426097,104943580). at(302427668,104667893). at(302429304,104667893). at(302460186,104912365). at(302461024,104912365). at(302469730,113979774). at(302470951,113979774). at(302477858,114525129). at(302479427,114525129). at(302505612,105155946). at(302506940,105155946). at(302516600,104758560). at(302518026,104758560). at(302539669,105018974). at(302540350,105018974). at(302541266,104633637). at(302541827,104633637). at(302558087,114558298). at(302562150,114558298). at(302571278,105143415). at(302572618,105143415). at(302575716,104630969). at(302576745,104630969). at(302595419,104813883). at(302598414,104813883).
package hydro.common trait I18n { def apply(key: String, args: Any*): String }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> ERROR - 2019-05-22 12:04:39 --> 404 Page Not Found: Robotstxt/index ERROR - 2019-05-22 18:37:25 --> 404 Page Not Found: Apple-touch-icon-120x120-precomposedpng/index ERROR - 2019-05-22 18:37:25 --> 404 Page Not Found: Apple-touch-icon-120x120png/index ERROR - 2019-05-22 18:37:25 --> 404 Page Not Found: Apple-touch-icon-precomposedpng/index ERROR - 2019-05-22 18:37:25 --> 404 Page Not Found: Apple-touch-iconpng/index ERROR - 2019-05-22 18:37:39 --> 404 Page Not Found: admin/Skin-confightml/index ERROR - 2019-05-22 18:37:41 --> 404 Page Not Found: admin/Common/skin-config.html ERROR - 2019-05-22 18:37:53 --> 404 Page Not Found: admin/Common/skin-config.html ERROR - 2019-05-22 18:38:06 --> 404 Page Not Found: admin/Common/skin-config.html ERROR - 2019-05-22 18:38:22 --> 404 Page Not Found: admin/Common/skin-config.html ERROR - 2019-05-22 18:38:28 --> 404 Page Not Found: admin/Common/skin-config.html
require "test_helper" class LogTicketTest < ActiveSupport::TestCase setup do @log_ticket = LogTicket.create!(directory: "test", key: "foo", status: "pending") end should "not allow duplicate directory and key" do assert_raise ActiveRecord::RecordNotUnique do LogTicket.create!(directory: "test", key: "foo") end end should "allow different keys for the same directory" do LogTicket.create!(directory: "test", key: "bar") LogTicket.create!(directory: "test", key: "baz") end context "#pop" do setup do LogTicket.create!(directory: "test/2", key: "bar", status: "pending") end context "without any key" do should "pop the first inputed" do ticket = LogTicket.pop assert_equal "foo", ticket.key end end context "with a key" do should "pop the key" do ticket = LogTicket.pop(key: "bar") assert_equal "bar", ticket.key end end context "with a directory" do should "pop the first entry" do LogTicket.create!(directory: "test/2", key: "boo", status: "pending") ticket = LogTicket.pop(directory: "test/2") assert_equal "bar", ticket.key end end should "change the status" do ticket = LogTicket.pop assert_equal "processing", ticket.status end should "return nil after no more items are in the queue" do 2.times { LogTicket.pop } assert_nil LogTicket.pop end end context "fs" do context "local" do setup do @log_ticket.update!(backend: "local", key: "sample_logs/fastly-fake.log") @sample_log = Rails.root.join("test", "sample_logs", "fastly-fake.log").read end should "return a local fs" do assert_kind_of RubygemFs::Local, @log_ticket.fs end should "set the right base directory" do assert_equal "test", @log_ticket.fs.base_dir end should "body return the file body" do assert_equal @sample_log, @log_ticket.body end end context "s3" do setup do @log_ticket.update!(backend: "s3", key: "sample_logs/fastly-fake.log") @sample_log = Rails.root.join("test", "sample_logs", "fastly-fake.log").read Aws.config[:s3] = { stub_responses: { get_object: { body: @sample_log } } } end should "return a s3 fs" do assert_kind_of RubygemFs::S3, @log_ticket.fs end should "set the right bucket" do assert_equal "test", @log_ticket.fs.bucket end should "body return the file body" do assert_equal @sample_log, @log_ticket.body end end end end
import 'package:flutter/material.dart'; import 'package:mymgs/data/clubs.dart'; import 'package:mymgs/data/setup.dart'; import 'package:mymgs/data_classes/club.dart'; import 'package:mymgs/screens/main_navigation.dart'; import 'package:mymgs/widgets/clubs/club_card.dart'; import 'package:mymgs/widgets/dashboard_cards/dashboard_card.dart'; import '../spinner.dart'; class ClubsCard extends StatelessWidget { final Future<List<Club>> clubsFuture; ClubsCard({ Key? key, }) : clubsFuture = getYearGroup().then((y) => getClubs( yearGroup: y, todayOnly: true, limit: 3, )); @override Widget build(BuildContext context) { return FutureBuilder<List<Club>>( future: clubsFuture, builder: (context, snapshot) { bool loading = false; bool failed = false; final data = snapshot.data; if (snapshot.connectionState == ConnectionState.waiting) { loading = true; } else if (snapshot.hasError || data?.length == 0) { failed = true; } return DashboardCard( title: "Clubs", onPressed: () { DrawerSwitcher.of(context)?.switchTo("clubs"); }, children: [ if (loading) Spinner(), if (failed) Text( 'No clubs today.', style: Theme.of(context).textTheme.bodyText1, ), if (!failed && !loading && data != null) for (final club in data) ClubCard(club: club) ] ); } ); } }
#include "BEKeybinds.hpp" #include "../AutoSave/autoSave.hpp" #include "../../hooks/EditorUI.hpp" #include "../GroupIDFilter/AdvancedFilterLayer.hpp" #include "../GridSize/gridButton.hpp" #include "../../hooks/EditorPauseLayer.hpp" #include "../RotateSaws/rotateSaws.hpp" #include "../VisibilityTab/loadVisibilityTab.hpp" #include "../EditorLayerInput/editorLayerInput.hpp" #include "../EditTab/moveForCommand.hpp" #include "../RepeatPaste/repeatPaste.hpp" #include "../History/UndoHistoryPopup.hpp" #include "../ContextMenu/ContextMenu.hpp" #include "../Screenshot/screenshot.hpp" #include "../GroupSummary/GroupSummaryPopup.hpp" #include "../Debug/IntegratedConsole.hpp" #include "../../utils/moveGameLayer.hpp" #include "../Notifications/NotificationManager.hpp" enum Direction { kDirLeft, kDirRight, kDirUp, kDirDown, }; CCArray* g_pSelectedObjects = nullptr; Direction g_eLastDirection; bool isSelectable(GameObject* obj) { if (obj->m_bIsSelected) return false; auto l = LevelEditorLayer::get()->m_nCurrentLayer; if (l == -1) return true; if (obj->m_nEditorLayer == l) return true; if (obj->m_nEditorLayer2 == l) return true; return false; } void selectObjectDirection(EditorUI* ui, Direction dir) { CCPoint startPos = CCPointZero; auto winSize = CCDirector::sharedDirector()->getWinSize(); if (ui->m_pSelectedObject) startPos = ui->m_pSelectedObject->getPosition(); else if (ui->m_pSelectedObjects) startPos = ui->getGroupCenter(ui->m_pSelectedObjects, false); else startPos = ui->m_pEditorLayer->getObjectLayer()->convertToNodeSpace( winSize / 2 ); static constexpr const float range = 200.0f; static constexpr const float too_far = 500.0f; static constexpr const float too_near = 15.0f; GameObject* nearest = nullptr; CCARRAY_FOREACH_B_TYPE(ui->m_pEditorLayer->getAllObjects(), obj, GameObject) { switch (dir) { case kDirLeft: case kDirRight: if ( obj->getPositionY() > startPos.y - range && obj->getPositionY() < startPos.y + range ) { if (!isSelectable(obj)) continue; if (dir == kDirLeft) { if (obj->getPositionX() > startPos.x - too_near) continue; if (obj->getPositionX() < startPos.x - too_far) continue; if (!nearest) { nearest = obj; continue; } if (nearest->getPositionX() < obj->getPositionX()) nearest = obj; } else { if (obj->getPositionX() < startPos.x + too_near) continue; if (obj->getPositionX() > startPos.x + too_far) continue; if (!nearest) { nearest = obj; continue; } if (nearest->getPositionX() > obj->getPositionX()) nearest = obj; } } break; case kDirUp: case kDirDown: if ( obj->getPositionX() > startPos.x - range && obj->getPositionX() < startPos.x + range ) { if (!isSelectable(obj)) continue; if (dir == kDirUp) { if (obj->getPositionY() < startPos.y + too_near) continue; if (obj->getPositionY() > startPos.y + too_far) continue; if (!nearest) { nearest = obj; continue; } if (nearest->getPositionY() > obj->getPositionY()) nearest = obj; } else { if (obj->getPositionY() > startPos.y - too_near) continue; if (obj->getPositionY() < startPos.y - too_far) continue; if (!nearest) { nearest = obj; continue; } if (nearest->getPositionY() < obj->getPositionY()) nearest = obj; } } break; } } if (nearest) { if (g_eLastDirection != dir) { g_pSelectedObjects->removeAllObjects(); } if (g_pSelectedObjects->indexOfObject(nearest) != UINT_MAX) return; g_pSelectedObjects->addObject(nearest); g_eLastDirection = dir; ui->selectObject(nearest, true); ui->updateButtons(); auto gpos = ui->m_pEditorLayer->getObjectLayer()->convertToWorldSpace( nearest->getPosition() ); if ( gpos.x < w_edge || gpos.x > winSize.width - w_edge || gpos.y < w_edge || gpos.y > winSize.height - w_edge ) moveGameLayerSmooth(ui, { -gpos.x + winSize.width / 2, -gpos.y + winSize.height / 2 }); } } void loadBEKeybinds() { g_pSelectedObjects = CCArray::create(); g_pSelectedObjects->retain(); auto kbm = KeybindManager::get(); kbm->addEditorKeybind({ "Object Left Half", "betteredit.move_obj_half_left", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandHalfLeft); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Object Right Half", "betteredit.move_obj_half_right", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandHalfRight); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Object Up Half", "betteredit.move_obj_half_up", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandHalfUp); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Object Down Half", "betteredit.move_obj_half_down", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandHalfDown); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Object Left Quarter", "betteredit.move_obj_quarter_left", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandQuarterLeft); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Object Right Quarter", "betteredit.move_obj_quarter_right", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandQuarterRight); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Object Up Quarter", "betteredit.move_obj_quarter_up", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandQuarterUp); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Object Down Quarter", "betteredit.move_obj_quarter_down", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandQuarterDown); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Object Left Eigth", "betteredit.move_obj_eigth_left", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandEigthLeft); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Object Right Eigth", "betteredit.move_obj_eigth_right", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandEigthRight); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Object Up Eigth", "betteredit.move_obj_eigth_up", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandEigthUp); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Object Down Eigth", "betteredit.move_obj_eigth_down", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandEigthDown); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Object Left Half Tiny", "betteredit.move_obj_unit_left", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandQUnitLeft); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Object Right Half Tiny", "betteredit.move_obj_unit_right", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandQUnitRight); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Object Up Half Tiny", "betteredit.move_obj_unit_up", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandQUnitUp); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Object Down Half Tiny", "betteredit.move_obj_unit_down", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->moveObjectCall(kEditCommandQUnitDown); return false; }, "editor.move" }, {}); kbm->addEditorKeybind({ "Rotate 45 CCW", "betteredit.rotate_45_ccw", [](EditorUI* ui) -> bool { ui->transformObjectCall(kEditCommandRotateCCW45); return false; }, "editor.modify" }, {}); kbm->addEditorKeybind({ "Rotate 45 CW", "betteredit.rotate_45_cw", [](EditorUI* ui) -> bool { ui->transformObjectCall(kEditCommandRotateCW45); return false; }, "editor.modify" }, {}); kbm->addEditorKeybind({ "Rotate Snap", "betteredit.rotate_snap", [](EditorUI* ui) -> bool { ui->transformObjectCall(kEditCommandRotateSnap); return false; }, "editor.modify", false }, {}); kbm->addEditorKeybind({ "Show Scale Control", "betteredit.show_scale_control", [](EditorUI* ui) -> bool { ui->activateScaleControl(nullptr); return false; }, "editor.ui", false }, {}); kbm->addEditorKeybind({ "Cancel Autosave", "betteredit.cancel_autosave", [](EditorUI* ui) -> bool { if (getAutoSaveTimer(ui)->cancellable()) { getAutoSaveTimer(ui)->cancel(); return true; } return false; }, "editor.global", false }, {{ KEY_Escape, 0 }}); kbm->addEditorKeybind({ "Scroll Zoom Modifier", "betteredit.zoom_modifier", true, "editor.global" }, {{ KEY_None, Keybind::kmControl }}); kbm->addEditorKeybind({ "Scroll Horizontal Modifier", "betteredit.horizontal_modifier", true, "editor.global" }, {{ KEY_None, Keybind::kmShift }}); kbm->addEditorKeybind({ "Save Level", "betteredit.save_level", [](EditorUI* ui) -> bool { auto saveLabel = CCLabelBMFont::create("Saving...", "bigFont.fnt"); saveLabel->setPosition(CCDirector::sharedDirector()->getWinSize() / 2); saveLabel->setScale(.6f); ui->addChild(saveLabel, 999); ui->visit(); ui->draw(); // > Don't call it manually CCDirector::sharedDirector()->drawScene(); auto pause = EditorPauseLayer::create(ui->m_pEditorLayer); pause->saveLevel(); pause->release(); saveLabel->removeFromParent(); saveLabel->release(); return false; }, "editor.global", false }, {}); kbm->addEditorKeybind({ "Select All", "betteredit.select_all", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->selectAll(); return false; }, "editor.select", false }, {}); kbm->addEditorKeybind({ "Select All Left", "betteredit.select_all_left", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->selectAllWithDirection(true); return false; }, "editor.select", false }, {}); kbm->addEditorKeybind({ "Select All Right", "betteredit.select_all_right", [](EditorUI* ui) -> bool { if (ui->m_pEditorLayer->m_ePlaybackMode != kPlaybackModePlaying) ui->selectAllWithDirection(false); return false; }, "editor.select", false }, {}); kbm->addEditorKeybind({ "Select Object Left", "betteredit.select_obj_left", [](EditorUI* ui) -> bool { selectObjectDirection(ui, kDirLeft); return false; }, "editor.select" }, {}); kbm->addEditorKeybind({ "Select Object Right", "betteredit.select_obj_right", [](EditorUI* ui) -> bool { selectObjectDirection(ui, kDirRight); return false; }, "editor.select" }, {}); kbm->addEditorKeybind({ "Select Object Up", "betteredit.select_obj_up", [](EditorUI* ui) -> bool { selectObjectDirection(ui, kDirUp); return false; }, "editor.select" }, {}); kbm->addEditorKeybind({ "Select Object Down", "betteredit.select_obj_down", [](EditorUI* ui) -> bool { selectObjectDirection(ui, kDirDown); return false; }, "editor.select" }, {}); kbm->addEditorKeybind({ "Toggle UI", "betteredit.toggle_ui", [](EditorUI* ui) -> bool { toggleShowUI(ui); return false; }, "editor.ui", false }, {}); kbm->addEditorKeybind({ "Show UI", "betteredit.show_ui", [](EditorUI* ui) -> bool { ui->showUI(true); return false; }, "editor.ui", false }, {}); kbm->addEditorKeybind({ "Hide UI", "betteredit.hide_ui", [](EditorUI* ui) -> bool { ui->showUI(false); return false; }, "editor.ui", false }, {}); kbm->addEditorKeybind({ "Preview Mode", "betteredit.preview_mode", [](EditorUI* ui) -> bool { auto b = GameManager::sharedState()->getGameVariable("0036"); GameManager::sharedState()->setGameVariable("0036", !b); ui->m_pEditorLayer->updateEditorMode(); updateVisibilityTab(ui); return false; }, "editor.visibility", false }, {}); kbm->addEditorKeybind({ "Edit Object", "betteredit.edit_object", [](EditorUI* ui) -> bool { ui->editObject(nullptr); return false; }, "editor.modify", false }, {}); kbm->addEditorKeybind({ "Edit Group", "betteredit.edit_group", [](EditorUI* ui) -> bool { ui->editGroup(nullptr); return false; }, "editor.modify", false }, {}); kbm->addEditorKeybind({ "Edit Special", "betteredit.edit_special", [](EditorUI* ui) -> bool { ui->editObject2(nullptr); return false; }, "editor.modify", false }, {}); // kbm->addEditorKeybind({ "Repeat Copy + Paste", "betteredit.repeat_paste", // [](EditorUI* ui) -> bool { // repeatPaste(ui); // return false; // }, "editor.modify", false // }, {}); kbm->addEditorKeybind({ "Open Level Settings", "betteredit.open_level_settings", [](EditorUI* ui) -> bool { ui->onSettings(nullptr); return false; }, "editor.global", false }, {}); kbm->addEditorKeybind({ "Build Helper", "betteredit.build_helper", [](EditorUI* ui) -> bool { ui->dynamicGroupUpdate(false); return false; }, "editor.special", false }, {}); kbm->addEditorKeybind({ "Create Base", "betteredit.create_base", [](EditorUI* ui) -> bool { ui->createRockBase(); return false; }, "editor.special", false }, {}); kbm->addEditorKeybind({ "Create Edges", "betteredit.create_edges", [](EditorUI* ui) -> bool { ui->createRockEdges(); return false; }, "editor.special", false }, {}); kbm->addEditorKeybind({ "Create Outline", "betteredit.create_outline", [](EditorUI* ui) -> bool { ui->createRockOutline(); return false; }, "editor.special", false }, {}); kbm->addEditorKeybind({ "Uncheck All", "betteredit.uncheck_all_portals", [](EditorUI* ui) -> bool { auto p = EditorPauseLayer::create(ui->m_pEditorLayer); p->uncheckAllPortals(nullptr); p->release(); return false; }, "editor.global", false }, {}); kbm->addEditorKeybind({ "Copy Values", "betteredit.copy_values", [](EditorUI* ui) -> bool { ui->onCopyState(nullptr); return false; }, "editor.modify", false }, {}); kbm->addEditorKeybind({ "Paste State", "betteredit.paste_state", [](EditorUI* ui) -> bool { ui->onPasteState(nullptr); return false; }, "editor.modify", false }, {}); kbm->addEditorKeybind({ "Paste Color", "betteredit.paste_color", [](EditorUI* ui) -> bool { ui->onPasteColor(nullptr); return false; }, "editor.modify", false }, {}); kbm->addEditorKeybind({ "Toggle HSV Picker", "betteredit.toggle_hsv_picker", [](EditorUI* ui) -> bool { ui->editColor(nullptr); return false; }, "editor.ui", false }, {}); kbm->addEditorKeybind({ "Link Objects", "betteredit.link_objects", [](EditorUI* ui) -> bool { ui->onGroupSticky(nullptr); return false; }, "editor.modify", false }, {}); kbm->addEditorKeybind({ "Unlink Objects", "betteredit.unlink_objects", [](EditorUI* ui) -> bool { ui->onUngroupSticky(nullptr); return false; }, "editor.modify", false }, {}); kbm->addEditorKeybind({ "Go To Layer", "betteredit.go_to_layer", [](EditorUI* ui) -> bool { ui->onGoToLayer(nullptr); return false; }, "editor.ui", false }, {}); kbm->addEditorKeybind({ "Go To Next Free Layer", "betteredit.go_to_next_free_layer", [](EditorUI* ui) -> bool { as<EditorUI_CB*>(ui)->onNextFreeEditorLayer(nullptr); return false; }, "editor.ui", false }, {}); kbm->addEditorKeybind({ "Go To Base Layer", "betteredit.go_to_base_layer", [](EditorUI* ui) -> bool { ui->onGoToBaseLayer(nullptr); return false; }, "editor.ui", false }, {}); kbm->addEditorKeybind({ "Open Advanced Filter", "betteredit.open_advanced_filter", [](EditorUI* ui) -> bool { AdvancedFilterLayer::create()->show(); return false; }, "editor.modify", false }, {}); kbm->addEditorKeybind({ "Increase Grid Size", "betteredit.increase_grid_size", [](EditorUI* ui) -> bool { zoomEditorGrid(ui, true); return false; }, "editor.global", false }, {}); kbm->addEditorKeybind({ "Decrease Grid Size", "betteredit.decrease_grid_size", [](EditorUI* ui) -> bool { zoomEditorGrid(ui, false); return false; }, "editor.global", false }, {}); kbm->addEditorKeybind({ "Toggle Grid", "betteredit.toggle_grid", [](EditorUI* ui) -> bool { GameManager::sharedState()->toggleGameVariable("0038"); ui->m_pEditorLayer->updateOptions(); updateVisibilityTab(ui); return false; }, "editor.visibility", false }, {}); kbm->addEditorKeybind({ "Rotate Saws", "betteredit.rotate_saws", [](EditorUI* ui) -> bool { enableRotations(!shouldRotateSaw()); if (shouldRotateSaw()) beginRotations(LevelEditorLayer::get()); else stopRotations(LevelEditorLayer::get()); updateVisibilityTab(ui); return false; }, "editor.visibility", false }, {}); kbm->addEditorKeybind({ "Toggle LDM", "betteredit.toggle_ldm", [](EditorUI* ui) -> bool { setHideLDMObjects(); updateVisibilityTab(ui); return false; }, "editor.visibility", false }, {}); kbm->addEditorKeybind({ "Lock Layer", "betteredit.lock_layer", [](EditorUI* ui) -> bool { as<EditorUI_CB*>(ui)->onLockLayer(nullptr); return false; }, "editor.ui", false }, {}); kbm->addEditorKeybind({ "View Layers", "betteredit.view_layer_list", [](EditorUI* ui) -> bool { as<EditorUI_CB*>(ui)->onShowLayerPopup(nullptr); return false; }, "editor.ui", false }, {}); kbm->addEditorKeybind({ "Align X", "betteredit.align_x", [](EditorUI* ui) -> bool { ui->alignObjects(ui->getSelectedObjects(), false); return false; }, "editor.modify", false }, {}); kbm->addEditorKeybind({ "Align Y", "betteredit.align_y", [](EditorUI* ui) -> bool { ui->alignObjects(ui->getSelectedObjects(), true); return false; }, "editor.modify", false }, {}); kbm->addEditorKeybind({ "View Undo History", "betteredit.view_undo_history", [](EditorUI* ui) -> bool { UndoHistoryPopup::popup(ui->m_pEditorLayer); return false; }, "editor.modify", false }, {{ KEY_U, Keybind::kmControl }}); kbm->addEditorKeybind({ "Test Notification", "betteredit.test_notification", [](EditorUI* ui) -> bool { NotificationManager::get()->schedule( Notification::create(kNotificationTypeInfo, "Test Notification :)") ); return false; }, "editor.global", false }, {{ KEY_U, 0 }}); kbm->addEditorKeybind({ "View Group Summary", "betteredit.view_group_summary", [](EditorUI* ui) -> bool { GroupSummaryPopup::create(ui->m_pEditorLayer)->show(); return false; }, "editor.modify", false }, {{ KEY_G, Keybind::kmControl }}); kbm->addEditorKeybind({ "View Console", "betteredit.view_console", [](EditorUI* ui) -> bool { IntegratedConsole::create()->show(); return false; }, "editor.modify", false }, {}); kbm->addEditorKeybind({ "Context Menu", "betteredit.show_context_menu", [](EditorUI* ui) -> bool { ContextMenu::get()->show(); return true; }, "editor.global", false }, {{ kMouseButtonRight, 0 }}); kbm->addEditorKeybind({ "Take Screenshot", "betteredit.screenshot", [](EditorUI* ui) -> bool { takeScreenshot(ui); return true; }, "editor.global", false }, {{ KEY_L, 0 }}); }
#!/bin/bash mpirun -n 4 --tag-output python examples/cosmo.py |& tee $1
# # Copyright 2021 Ocean Protocol Foundation # SPDX-License-Identifier: Apache-2.0 # import pytest from ocean_lib.assets.utils import ( add_publisher_trusted_algorithm, create_publisher_trusted_algorithms, generate_trusted_algo_dict, remove_publisher_trusted_algorithm, ) from tests.resources.ddo_helpers import ( get_registered_algorithm_ddo, get_registered_ddo_with_compute_service, wait_for_ddo, ) from tests.resources.helper_functions import get_publisher_wallet def test_utilitary_functions_for_trusted_algorithms(publisher_ocean_instance): """Tests adding/removing trusted algorithms in the DDO metadata.""" publisher = get_publisher_wallet() algorithm_ddo = get_registered_algorithm_ddo(publisher_ocean_instance, publisher) wait_for_ddo(publisher_ocean_instance, algorithm_ddo.did) assert algorithm_ddo is not None, "Algorithm DDO is not found in cache." algorithm_ddo_v2 = get_registered_algorithm_ddo(publisher_ocean_instance, publisher) wait_for_ddo(publisher_ocean_instance, algorithm_ddo_v2.did) assert algorithm_ddo_v2 is not None, "Algorithm DDO is not found in cache." algorithm_ddo_v3 = get_registered_algorithm_ddo(publisher_ocean_instance, publisher) wait_for_ddo(publisher_ocean_instance, algorithm_ddo_v3.did) assert algorithm_ddo_v3 is not None, "Algorithm DDO is not found in cache." ddo = get_registered_ddo_with_compute_service( publisher_ocean_instance, publisher, trusted_algorithms=[algorithm_ddo.did] ) wait_for_ddo(publisher_ocean_instance, ddo.did) assert ddo is not None, "DDO is not found in cache." publisher_trusted_algorithms = create_publisher_trusted_algorithms( [algorithm_ddo.did], publisher_ocean_instance.config.metadata_cache_uri ) # add a new trusted algorithm to the publisher_trusted_algorithms list new_publisher_trusted_algorithms = add_publisher_trusted_algorithm( ddo.did, algorithm_ddo_v2.did, publisher_ocean_instance.config.metadata_cache_uri, ) assert ( new_publisher_trusted_algorithms is not None ), "Added a new trusted algorithm failed. The list is empty." assert len(new_publisher_trusted_algorithms) > len( publisher_trusted_algorithms ), "New trusted algorithm list should be longer than the old one." # add an existing algorithm to publisher_trusted_algorithms list new_publisher_trusted_algorithms = add_publisher_trusted_algorithm( ddo.did, algorithm_ddo.did, publisher_ocean_instance.config.metadata_cache_uri ) assert new_publisher_trusted_algorithms is not None for trusted_algorithm in publisher_trusted_algorithms: assert ( trusted_algorithm["did"] == algorithm_ddo.did ), "Added a different algorithm besides the existing ones." assert len(new_publisher_trusted_algorithms) == len(publisher_trusted_algorithms) # remove an existing algorithm to publisher_trusted_algorithms list new_publisher_trusted_algorithms = remove_publisher_trusted_algorithm( ddo.did, algorithm_ddo.did, publisher_ocean_instance.config.metadata_cache_uri ) assert ( new_publisher_trusted_algorithms is not None ), "Remove process of a trusted algorithm failed." assert len(new_publisher_trusted_algorithms) < len( publisher_trusted_algorithms ), "New trusted algorithm list should be shorter than the old one." # remove a trusted algorithm that does not belong to publisher_trusted_algorithms list new_publisher_trusted_algorithms = remove_publisher_trusted_algorithm( ddo.did, algorithm_ddo_v3.did, publisher_ocean_instance.config.metadata_cache_uri, ) assert new_publisher_trusted_algorithms is not None for trusted_algorithm in publisher_trusted_algorithms: assert ( trusted_algorithm["did"] != algorithm_ddo_v3.did ), "The trusted algorithm belongs to the list." assert len(new_publisher_trusted_algorithms) == len(publisher_trusted_algorithms) def test_add_trusted_algorithm_no_compute_service(publisher_ocean_instance, metadata): """Tests if the DDO has or not a compute service.""" publisher = get_publisher_wallet() metadata_copy = metadata.copy() algorithm_ddo = get_registered_algorithm_ddo(publisher_ocean_instance, publisher) wait_for_ddo(publisher_ocean_instance, algorithm_ddo.did) assert algorithm_ddo is not None, "Algorithm DDO is not found in cache." ddo = publisher_ocean_instance.assets.create(metadata_copy, publisher) wait_for_ddo(publisher_ocean_instance, ddo.did) assert ddo is not None, "DDO is not found in cache." create_publisher_trusted_algorithms( [algorithm_ddo.did], publisher_ocean_instance.config.metadata_cache_uri ) with pytest.raises(AssertionError): add_publisher_trusted_algorithm( ddo.did, algorithm_ddo.did, publisher_ocean_instance.config.metadata_cache_uri, ) def test_fail_generate_trusted_algo_dict(): """Tests if generate_trusted_algo_dict throws an AssertionError when all parameters are None.""" try: generate_trusted_algo_dict(None, None, None) except AssertionError as err: proposed_err = AssertionError( "Either DDO, or both did and metadata_cache_uri are None." ) assert isinstance(err, type(proposed_err)) assert err.args == proposed_err.args
import gzip import shutil import sys #with gzip.open(sys.argv[1], 'rt') as f_gz: iline = 0 for line in gzip.open(sys.argv[1], 'rt'): iline += 1 if iline > 10: break print("-->" + line)
# 1단계 - 화면 응답 개선하기 1. 성능 개선 결과를 공유해주세요. - [X] Smoke, Load, Stress 테스트 결과 요청시간 50ms 이하로 개선 - [X] 개선전 Smoke 테스트 결과 [바로가기](../k6/before/smoke_test_result.md) - [X] 개선전 Load 테스트 결과 [바로가기](../k6/before/load_test_result.md) - [X] 개선전 Stress 테스트 결과 [바로가기](../k6/before/stress_test_result.md) --- - [X] 개선후 Smoke 테스트 결과 [바로가기](../k6/after/smoke_test_result.md) - [X] 개선후 Load 테스트 결과 [바로가기](../k6/after/load_test_result.md) - [X] 개선후 Stress 테스트 결과 [바로가기](../k6/after/stress_test_result.md) 1. 어떤 부분을 개선해보셨나요? 과정을 설명해주세요. 1. 웹서버 개선하기 - 개선전 크롬 개발자 도구를 통해 Fast 3G, No cache 환경에서 테스트 - 메인페이지 17.26s 로딩걸림 - 힌트를 참고하여 nginx 최적화 - CPU Core에 맞는 적절한 Worker 프로세스를 할당 - 워커 커넥션 10240 설정 - gzip 압축 설정 후 WebPageTest에서 A 받음 - add_header Strict-Transport-Security "max-age=31536000" always 설정 - access_log off - http2 적용 - 개선 후 크롬 개발자 도구 같은 환경에서 6.67초로 대략 3배 감소 2. WAS 개선하기 - redis 추가 - Line 생성, 업데이트, 삭제, 조회 캐싱 - Member 생성, 업데이트, 삭제, 조회 캐싱 - Station 경로 조회 캐싱 - 캐시된 것 삭제 기간 10일 설정
import { BrokeragePolicy } from './BrokeragePolicy'; import { BrokerageRule } from './BrokerageRule'; export class PurchaseBrokeragePolicy implements BrokeragePolicy { rule: BrokerageRule[] = []; getRules: BrokerageRule[] = []; constructor() { this.rule.push( new BrokerageRule(50000000, 0.6, 250000), new BrokerageRule(200000000, 0.5, 800000), new BrokerageRule(600000000, 0.4, null), new BrokerageRule(900000000, 0.5, null), new BrokerageRule(Math.max(), 0.9, null), ); } async calculate(price: number): Promise<number> { const brokerageRule: BrokerageRule = this.getRules.find(rule => price < rule.getLessThan()); return brokerageRule.calculate(price); } }
DROP table score_array; RENAME TABLE score_array_part TO score_array; DELIMITER / DROP TRIGGER IF EXISTS partitionScoreArray / CREATE TRIGGER partitionScoreArray BEFORE INSERT ON score_array FOR EACH ROW BEGIN DECLARE v_cv INT DEFAULT 0; DECLARE v_type INT DEFAULT null; IF (NEW.experiment_id IS NOT NULL) THEN SELECT e.type_id INTO v_type FROM experiment e WHERE e.id = NEW.experiment_id; ELSEIF (NEW.phase_id IS NOT NULL) THEN SELECT e.type_id INTO v_type FROM phase p JOIN experiment e on (p.experiment_id = e.id) WHERE p.id = NEW.phase_id; ELSE SELECT e.type_id INTO v_type FROM session s JOIN experiment e on (s.experiment_id = e.id) WHERE s.id = NEW.session_id; END IF; IF v_type IS NULL THEN SELECT NEW.type_id INTO v_type; END IF; SELECT cv_id INTO v_cv FROM cv_term WHERE id = v_type; SET NEW.cv_id = v_cv; END; / DELIMITER ;
<?php use App\Http\Controllers\CommentsController; use App\Http\Controllers\PostController; use App\Http\Controllers\RegisterController; use App\Http\Controllers\LoginController; use App\Http\Controllers\UserController; use Illuminate\Support\Facades\Route; use App\Models\Post; use App\Models\Comment; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('home'); }); Route::get('/index', function () { return view('home'); }); Route::get('/posts', [PostController::class, 'index']); Route::get('/register', [RegisterController::class, 'create'])->middleware('guest'); Route::post('/register', [RegisterController::class, 'store'])->middleware('guest'); Route::get('/adPost', [PostController::class, 'showadPost'])->middleware('auth'); Route::post('/adPost', [PostController::class, 'storePost'])->middleware('auth'); Route::get('/post/{id}', [PostController::class, 'showPost'])->name('post'); Route::get('/login', [LoginController::class, 'create'])->middleware('guest'); Route::post('/login', [LoginController::class, 'login'])->middleware('guest'); Route::post('/logout', [LoginController::class, 'destroy'])->middleware('auth'); Route::get('/user', [UserController::class, 'showDashboard'])->middleware('auth'); //Route::get('/user', [UserController::class, 'showDashboard'])->middleware('auth'); Route::post('/edit/{id}', [PostController::class, 'editPost']); Route::post('/comment/{id}', [CommentsController::class, 'storeComment']); Route::post('/delete/{id}', [PostController::class, 'deletePost']); /* * *Router::get('/blog', function () { include("init.php"); $post = $container->create('postController'); $post->showPosts(); }); Router::get('/post/([0-9]*)', function (Request $req) { include("init.php"); $id = $req->params[0]; $post = $container->create('postController'); $post->showPost($id); }); Router::post('/post/([0-9]*)', function (Request $req) { include("init.php"); $id = $req->params[0]; $post = $container->create('postController'); $post->showPost($id); }); Router::get('/adPost', function () { include("init.php"); $post = $container->create('blogController'); $post->showAdPost(); }); Router::post('/adPost', function () { include("init.php"); $post = $container->create('blogController'); $post->savePost(); }); Router::get('/login', function () { include("init.php"); $user = $container->create('loginController'); $user->loginshow(); }); Router::post('/login', function () { include("init.php"); $user = $container->create('loginController'); $user->login(); }); Router::get('/register', function () { include("init.php"); $user = $container->create('loginController'); $user->registerShow(); }); Router::post('/register', function () { include("init.php"); $user = $container->create('loginController'); $user->register(); }); Router::get('/logout', function () { include("init.php"); $user = $container->create('loginController'); $user->logout(); }); Router::get('/admin', function () { include("init.php"); $user = $container->create('adminController'); $user->showAdmin(); }); Router::get('/user', function () { include("init.php"); $user = $container->create('adminController'); $user->showUser(); }); Router::post('/delete/([0-9]*)', function (Request $req) { include("init.php"); $id = $req->params[0]; $post = $container->create('postController'); $post->delete($id); }); Router::post('/edit/([0-9]*)', function (Request $req) { include("init.php"); $id = $req->params[0]; $post = $container->create('postController'); $post->edit($id); }); * */
def new @<%= singular_name %> = <%= class_name %>.new end
n, k = gets.split.collect{|i| i.to_i} if n/2 > k puts -1 elsif n == 1 if k > 0 puts -1 else puts 1 end else ans = Array.new(n) ans[0] = k-n/2+1 ans[1] = 2*ans[0] for i in 2...n ans[i] = ans[i-1]+1 end puts ans.join(' ') end
#!/bin/bash cello_dir=$1 # reading configure file curr_dir=`dirname $0` source ${curr_dir}/read_conf.sh read_conf "$2" read_conf "$3" curr_dir=`dirname $0` #${R_PATH}/Rscript -e "source('${curr_dir}/src/launch_viscello.R'); cello_local('$cello_dir')" ${R_PATH}/Rscript -e "library(VisCello.atac); cello('$cello_dir')"
<?php namespace View\Pages; /** * Publishing Tool */ class PubTool { /** * Label for the tool (e.g. PAGES, COMPONENTS, GLOSSARY) * @var string */ public $label; /** * Link to dashboard data for this tool * @var string */ public $link; }
package kr.owens.upa.service import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.PendingIntent.FLAG_UPDATE_CURRENT import android.content.Context import android.content.Intent import androidx.core.app.NotificationCompat import kr.owens.upa.R import kr.owens.upa.main.MainActivity object UpbitPriceNotification { private const val CHANNEL_ID = "업비트 가격 알리미" fun createNotification(context: Context, title: String, text: String): Notification { val notificationIntent = Intent(context, MainActivity::class.java) notificationIntent.action = Actions.MAIN notificationIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK val pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, FLAG_UPDATE_CURRENT) val notification = NotificationCompat.Builder(context, CHANNEL_ID) .setContentTitle(title) .setContentText(text) .setSmallIcon(R.drawable.ic_launcher_foreground) .setOngoing(true) .setSound(null) .setVibrate(longArrayOf(0)) .setContentIntent(pendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .build() val serviceChannel = NotificationChannel(CHANNEL_ID, CHANNEL_ID, NotificationManager.IMPORTANCE_NONE) val manager = context.getSystemService(NotificationManager::class.java) as NotificationManager manager.createNotificationChannel(serviceChannel) return notification } fun updateNotification(context: Context, title: String, text: String) { val notificationIntent = Intent(context, MainActivity::class.java) notificationIntent.action = Actions.MAIN notificationIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK val pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, FLAG_UPDATE_CURRENT) val notification = NotificationCompat.Builder(context, CHANNEL_ID) .setContentTitle(title) .setContentText(text) .setSmallIcon(R.drawable.ic_launcher_foreground) .setOngoing(true) .setSound(null) .setVibrate(longArrayOf(0)) .setContentIntent(pendingIntent) .build() val manager = context.getSystemService(NotificationManager::class.java) as NotificationManager manager.notify(5424, notification) } }
unit DelphiAMQP.Frames.BasicFrame; interface uses System.Rtti, DelphiAMQP.FrameIntf, System.Classes, System.SysUtils, DelphiAMQP.Frames.Header, DelphiAMQP.AMQPValue; type TAMQPBasicFrame = class(TPersistent) private procedure FillFrameInfo(); procedure BuildParams(); procedure FreeParams(); protected FContext: TRttiContext; FFrameHeader: TAMQPFrameHeader; FContentStream: TBytesStream; FParameters: TArray<TAMQPValueType>; FMethodId: Word; FClassId: Word; public constructor Create(); virtual; destructor Destroy; override; procedure Read(const AStream: TBytesStream); procedure Write(const AStream: TBytesStream); property FrameHeader: TAMQPFrameHeader read FFrameHeader; property Content: TBytesStream read FContentStream; published property ClassId: Word read FClassId write FClassId; property MethodId: Word read FMethodId write FMethodId; end; TAMQPFrameClass = class of TAMQPBasicFrame; implementation uses DelphiAMQP.Util.Helpers, System.TypInfo, DelphiAMQP.Util.Attributes, System.Generics.Collections; { TAMQPBasicFrame } procedure TAMQPBasicFrame.BuildParams; var prop: TRttiProperty; attr: TCustomAttribute; paramAttr: AMQPParamAttribute; value: TAMQPValueType; data: TDictionary<Integer,TAMQPValueType>; I: Integer; begin data := TDictionary<Integer, TAMQPValueType>.Create; try for prop in FContext.GetType(Self.ClassType).GetProperties do begin for attr in prop.GetAttributes do begin if not (attr is AMQPParamAttribute) then Continue; paramAttr := attr as AMQPParamAttribute; value := prop.GetValue(Self).AsObject as TAMQPValueType; if value = nil then begin value := TAMQPValueType.Create(paramAttr.DataType); try value.BitOffset := paramAttr.BitOffset; prop.SetValue(Self, TValue.From<TAMQPValueType>(value)); except FreeAndNil(value); raise; end; end else value.ValueType := paramAttr.DataType; Data.Add(paramAttr.Order, value); end; end; SetLength(FParameters, Data.Count); for I := 0 to Pred(Data.Count) do begin if not Data.ContainsKey(I) then raise EAMQPParserException.CreateFmt('Missing parameter %d for frame %s', [I, Self.ClassName]); FParameters[I] := Data.Items[I]; end; finally FreeAndNil(data); end; end; constructor TAMQPBasicFrame.Create; begin inherited; FFrameHeader := TAMQPFrameHeader.Create(nil); FContext := TRttiContext.Create; FillFrameInfo(); BuildParams(); FrameHeader.FrameType := 1; end; destructor TAMQPBasicFrame.Destroy; begin FContext.Free; FreeAndNil(FFrameHeader); FreeParams(); inherited; end; procedure TAMQPBasicFrame.FillFrameInfo; var attr: TCustomAttribute; begin for attr in FContext.GetType(Self.ClassType).GetAttributes do begin if not (attr is AMQPFrameAttribute) then Continue; ClassId := (attr as AMQPFrameAttribute).ClassId; MethodId := (attr as AMQPFrameAttribute).MethodId; end; end; procedure TAMQPBasicFrame.FreeParams; var prop: TRttiProperty; attr: TCustomAttribute; param: TObject; begin for prop in FContext.GetType(Self.ClassType).GetProperties do begin for attr in prop.GetAttributes do begin if not (attr is AMQPParamAttribute) then Continue; param := prop.GetValue(Self).AsObject; if param = nil then Continue; param.Free; prop.SetValue(Self, TValue.From<TAMQPValueType>(nil)) end; end; end; procedure TAMQPBasicFrame.Read(const AStream: TBytesStream); var param: TAMQPValueType; begin for param in FParameters do param.Parse(AStream); end; procedure TAMQPBasicFrame.Write(const AStream: TBytesStream); var param: TAMQPValueType; TempStream: TBytesStream; methodInfo: TBytes; begin TempStream := TBytesStream.Create(); try SetLength(methodInfo, 4); AMQPMoveEx(FClassId, methodInfo, 0, 2); AMQPMoveEx(MethodId, methodInfo, 2, 2); TempStream.Write(methodInfo, 4); for param in FParameters do param.Write(TempStream); FrameHeader.Size := TempStream.Size; FrameHeader.Write(AStream); TempStream.Position := 0; AStream.Write(TempStream.Bytes, TempStream.Size); finally FreeAndNil(TempStream); end; end; end.
package ore.models.project import scala.language.higherKinds import ore.data.Color import ore.data.Color._ import ore.db.access.QueryView import ore.db.impl.DefaultModelCompanion import ore.db.impl.OrePostgresDriver.api._ import ore.db.impl.common.Named import ore.db.impl.schema.{ChannelTable, VersionTable} import ore.db.{DbRef, Model, ModelQuery} import ore.syntax._ import slick.lifted.TableQuery /** * Represents a release channel for Project Versions. Each project gets it's * own set of channels. * * @param isNonReviewed Whether this channel should be excluded from the staff * approval queue * @param name Name of channel * @param color Color used to represent this Channel * @param projectId ID of project this channel belongs to */ case class Channel( projectId: DbRef[Project], name: String, color: Color, isNonReviewed: Boolean = false ) extends Named { def isReviewed: Boolean = !isNonReviewed } object Channel extends DefaultModelCompanion[Channel, ChannelTable](TableQuery[ChannelTable]) { implicit val channelsAreOrdered: Ordering[Channel] = (x: Channel, y: Channel) => x.name.compare(y.name) implicit val query: ModelQuery[Channel] = ModelQuery.from(this) implicit val isProjectOwned: ProjectOwned[Channel] = (a: Channel) => a.projectId /** * The colors a Channel is allowed to have. */ val Colors: Seq[Color] = Seq(Purple, Violet, Magenta, Blue, Aqua, Cyan, Green, DarkGreen, Chartreuse, Amber, Orange, Red) implicit class ChannelModelOps(private val self: Model[Channel]) extends AnyVal { /** * Returns all Versions in this channel. * * @return All versions */ def versions[V[_, _]: QueryView](view: V[VersionTable, Model[Version]]): V[VersionTable, Model[Version]] = view.filterView(_.channelId === self.id.value) } }
require 'rails_helper' require './spec/common/model_helpers' RSpec.describe 'Articles Index - Main Page', type: :feature do include ModelHelpers let!(:user) { User.create user_data } let!(:category) { Category.create category_data } let!(:article1) { user.articles.create article_data.merge(category_ids: category.id) } let!(:article2) { user.articles.create article_data.merge(category_ids: category.id) } scenario 'Displays the most voted article in full width correctly' do user.voted_articles << article2 visit root_path expect(page).to have_content(article2.title) end scenario 'Displays categories with the title of the most recent article' do visit root_path expect(page).to have_content(category.name) expect(page).to have_content(article2.title) end end
package com.middleware.middleware.model.edi.po; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlElement; @XmlRootElement(name = "PO") @XmlAccessorType(XmlAccessType.FIELD) public class PO { @XmlElement(name="assignedIdentifier") String assignedIdentifier; @XmlElement(name="quantityOrdered") String quantityOrdered; @XmlElement(name="unitOfMeasure") String unitOfMeasure; @XmlElement(name="itemUnitPrice") String itemUnitPrice; PID pid; List<ProductService> productServiceList; public String getAssignedIdentifier() { return assignedIdentifier; } public void setAssignedIdentifier(String assignedIdentifier) { this.assignedIdentifier = assignedIdentifier; } public String getQuantityOrdered() { return quantityOrdered; } public void setQuantityOrdered(String quantityOrdered) { this.quantityOrdered = quantityOrdered; } public String getUnitOfMeasure() { return unitOfMeasure; } public void setUnitOfMeasure(String unitOfMeasure) { this.unitOfMeasure = unitOfMeasure; } public String getItemUnitPrice() { return itemUnitPrice; } public void setItemUnitPrice(String itemUnitPrice) { this.itemUnitPrice = itemUnitPrice; } public List<ProductService> getProductServiceList() { return productServiceList; } public void setProductServiceList(List<ProductService> productServiceList) { this.productServiceList = productServiceList; } public PID getPid() { return pid; } public void setPid(PID pid) { this.pid = pid; } }
set -e if [ "$BRANCH" = "master" ] then yarn build:production else yarn build:dev fi
require 'spec_helper' describe 'license categories' do families.each do |family| context "the #{family} family" do family_licenses = licenses.select { |l| l['family'] == family } primary = family_licenses.select { |l| l['variant'] == false } variants = family_licenses.select { |l| l['variant'] == true } it 'should only have one primary license' do expect(primary.count).to eql(1) end it 'all other licenses should be variants' do expected = family_licenses.count - 1 expect(variants.count).to eql(expected) end end end end
class Bts class Item attr_reader :element def initialize element @element = element rank; link; title; magnet_link; added; size; files; popularity end def rank @rank ||= element.find('strong').text.to_i end def link @link ||= element.all('a')[0].native.attributes['href'] end def title @title ||= element.all('a')[0]['innerHTML'] end def magnet_link @magnet_link ||= element.all('.option a')[0].native.attributes['href'] end def added @added ||= element.all('.option span b')[0].text end def size @size ||= element.all('.option span b')[1].text end def files @files ||= element.all('.option span b')[2].text end def popularity @popularity ||= element.all('.option span b')[4].text end end end
#include "triangle_mesh.h" #include <cstring> namespace helios { Triangle::Triangle(const ponos::Transform *o2w, const ponos::Transform *w2o, bool ro, const TriangleMesh *m, uint32 n) : Shape(o2w, w2o, ro) { mesh.reset(m); v = &mesh->indices[3 * n]; } ponos::BBox Triangle::objectBound() const { const ponos::Point3& p1 = mesh->vertices[v[0]]; const ponos::Point3& p2 = mesh->vertices[v[1]]; const ponos::Point3& p3 = mesh->vertices[v[2]]; return ponos::make_union(ponos::BBox((*worldToObject)(p1), (*worldToObject)(p2)), (*worldToObject)(p3)); } ponos::BBox Triangle::worldBound() const { const ponos::Point3& p1 = mesh->vertices[v[0]]; const ponos::Point3& p2 = mesh->vertices[v[1]]; const ponos::Point3& p3 = mesh->vertices[v[2]]; return ponos::make_union(ponos::BBox(p1, p2), p3); } bool Triangle::intersect(const HRay &ray, float *tHit, float *rayEpsilon, DifferentialGeometry *dg) const { const ponos::Point3& p1 = mesh->vertices[v[0]]; const ponos::Point3& p2 = mesh->vertices[v[1]]; const ponos::Point3& p3 = mesh->vertices[v[2]]; float t, b1, b2; if(!ponos::triangle_ray_intersection(p1, p2, p3, static_cast<ponos::Ray3>(ray), &t, &b1, &b2)) return false; if(t < ray.min_t || t > ray.max_t) return false; // Compute triangle partial derivatives ponos::vec3 dpdu, dpdv; ponos::vec3 dp1 = p1 - p3; ponos::vec3 dp2 = p2 - p3; ponos::Point2 uvs[3]; getUVs(uvs); // Compute deltas for triangle partial derivatives ponos::mat2 m(uvs[0].x - uvs[2].x, uvs[0].y - uvs[2].y, uvs[1].x - uvs[2].x, uvs[1].y - uvs[2].y); if(m.determinant() == 0.f) { // Handle zero determinant for triangle partial derivative matrix ponos::makeCoordinateSystem(ponos::normalize(ponos::cross(p2 - p1, p3 - p1)), &dpdu, &dpdv); } else { ponos::mat2 inv = ponos::inverse(m); dpdu = inv.m[0][0] * dp1 + inv.m[0][1] * dp2; dpdv = inv.m[1][0] * dp1 + inv.m[1][1] * dp2; } // Interpolate (u, v) triangle parametric coordinates float b0 = 1 - b1 - b2; float tu = b0 * uvs[0][0] + b1 * uvs[1][0] + b2 * uvs[2][0]; float tv = b0 * uvs[0][1] + b1 * uvs[1][1] + b2 * uvs[2][1]; // Test intersection against alpha texture if(mesh->alphaTexture) { DifferentialGeometry dgLocal(ray(t), dpdu, dpdv, ponos::Normal(0, 0, 0), ponos::Normal(0, 0, 0), tu, tv, this); // TODO //if(mesh->alphaTexture->evaluate(dgLocal) == 0.f) //return false; } // Fill in DifferentialGeometry from triangle hit *dg = DifferentialGeometry(ray(t), dpdu, dpdv, ponos::Normal(0, 0, 0), ponos::Normal(0, 0, 0), tu, tv, this); *tHit = t; *rayEpsilon = 1e-3f * *tHit; return true; } float Triangle::surfaceArea() const { const ponos::Point3& p1 = mesh->vertices[v[0]]; const ponos::Point3& p2 = mesh->vertices[v[1]]; const ponos::Point3& p3 = mesh->vertices[v[2]]; return .5f * ponos::cross(p2 - p1, p3 - p1).length(); } void Triangle::getShadingGeometry(const ponos::Transform &o2w, const DifferentialGeometry &dg, DifferentialGeometry *dgShading) const { if(!mesh->normals.size() && !mesh->tangents.size()) { *dgShading = dg; return; } // Initialize Triangle shading geometry with normals and tangents // TODO pg 146 // compute barycentric coordinates for point // Use normals and tangents to compute shading tangents for triangle, ss and ts //ponos::Normal dndu, dndv; // Compute dn/du and dn/dv for triangle shading geometry //*dgShading = DifferentialGeometry(dg.p, ss, ts, //(*objectToWorld)(dndu), (*objectToWorld)(dndv), //dg.u, dg.v, dg.shape); } void Triangle::getUVs(ponos::Point2 uvs[3]) const { if(mesh->uvs.size()) { uvs[0] = mesh->uvs[v[0]]; uvs[1] = mesh->uvs[v[1]]; uvs[2] = mesh->uvs[v[2]]; } else { uvs[0] = ponos::Point2(0, 0); uvs[1] = ponos::Point2(1, 0); uvs[2] = ponos::Point2(1, 1); } } TriangleMesh::TriangleMesh(const ponos::Transform *o2w, const ponos::Transform *w2o, bool ro, const std::vector<ponos::Point3>& v, const std::vector<uint32>& i, const std::vector<ponos::Normal>& n, const std::vector<ponos::vec3>& s, const std::vector<ponos::Point2>& uv, const std::shared_ptr<Texture<float> >& atex) : Shape(o2w, w2o, ro), alphaTexture(atex) { // copy triangles indices.resize(i.size()); memcpy(&indices[0], &i[0], sizeof(uint32) * i.size()); ntrigs = indices.size() / 3; // copy vertices vertices.resize(v.size()); memcpy(&vertices[0], &v[0], sizeof(ponos::Point3) * v.size()); nverts = vertices.size(); // copy uv if(uv.size()) { uvs.resize(uv.size()); memcpy(&uvs[0], &uv[0], sizeof(ponos::Point2) * uv.size()); } // copy normals if(n.size()) { normals.resize(n.size()); memcpy(&normals[0], &n[0], sizeof(ponos::Normal) * n.size()); } // copy tangents if(s.size()) { tangents.resize(s.size()); memcpy(&tangents[0], &s[0], sizeof(ponos::Vector3) * s.size()); } // Transform mesh vertices to world space for(ponos::Point3& vertex : vertices) vertex = (*objectToWorld)(vertex); } ponos::BBox TriangleMesh::objectBound() const { ponos::BBox objectBounds; for(const ponos::Point3& v : vertices) objectBounds = ponos::make_union(objectBounds, (*worldToObject)(v)); return objectBounds; } ponos::BBox TriangleMesh::worldBound() const { ponos::BBox worldBounds; for(const ponos::Point3& v : vertices) worldBounds = ponos::make_union(worldBounds, v); return worldBounds; } void TriangleMesh::refine(std::vector<std::shared_ptr<Shape> >& refined) const { for(int i = 0; i < ntrigs; i++) refined.emplace_back(new Triangle(objectToWorld, worldToObject, reverseOrientation, this, i)); } } // helios namespace
using JetBrains.ProjectModel; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Modules; using JetBrains.ReSharper.Plugins.Yaml.ProjectModel; using JetBrains.ReSharper.Psi; namespace JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Caches { public interface IProjectSettingsAssetHandler { bool IsApplicable(IPsiSourceFile sourceFile); void Build(IPsiSourceFile sourceFile, ProjectSettingsCacheItem cacheItem); } }
import React from 'react'; import { BrowserRouter, Routes, Route } from 'react-router-dom'; import Blog from './views/Blog' import BlogsPage from './views/BlogsPage'; import NavBar from './components/NavBar'; const App = () => { return ( <BrowserRouter> <NavBar></NavBar> <Routes> <Route path="/blogs/" element={<BlogsPage />}> </Route> <Route path="blogs/blog/:id" element={<Blog />}></Route> </Routes> </BrowserRouter> ) } export default App
#![cfg(test)] use agpu::{u8n, VertexLayout, VertexLayoutInstance}; #[derive(VertexLayout)] struct MixedTypes { _position: [f32; 3], _color: [u8n; 4], _normal: [f32; 4], _some_raw_data: [u16; 4], } #[test] fn vertex_layout_mixed_types() { // Start at shader location 3 let layout = MixedTypes::vertex_buffer_layout::<3>(); assert_eq!( layout, wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<MixedTypes>() as u64, step_mode: wgpu::VertexStepMode::Vertex, attributes: &[ wgpu::VertexAttribute { offset: 0, shader_location: 3, format: wgpu::VertexFormat::Float32x3, }, wgpu::VertexAttribute { offset: 12, shader_location: 4, format: wgpu::VertexFormat::Unorm8x4, }, wgpu::VertexAttribute { offset: 16, shader_location: 5, format: wgpu::VertexFormat::Float32x4, }, wgpu::VertexAttribute { offset: 32, shader_location: 6, format: wgpu::VertexFormat::Uint16x4, }, ], } ); } #[derive(VertexLayoutInstance)] struct PerInstanceData { _rotation: [f32; 4], _position: [f32; 3], } #[test] fn vertex_layout_per_instance() { // Start at shader location 3 let layout = PerInstanceData::vertex_buffer_layout::<7>(); assert_eq!( layout, wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<PerInstanceData>() as u64, step_mode: wgpu::VertexStepMode::Instance, attributes: &[ wgpu::VertexAttribute { offset: 0, shader_location: 7, format: wgpu::VertexFormat::Float32x4, }, wgpu::VertexAttribute { offset: 16, shader_location: 8, format: wgpu::VertexFormat::Float32x3, }, ], } ); }
{$mode delphi} {$modeswitch objectivec1} {$modeswitch cvar} unit DefinedClassesWatchKit; interface type WKAccessibilityImageRegion = objcclass external; WKInterfaceButton = objcclass external; WKInterfaceController = objcclass external; WKInterfaceDate = objcclass external; WKInterfaceDevice = objcclass external; WKInterfaceGroup = objcclass external; WKInterfaceImage = objcclass external; WKInterfaceLabel = objcclass external; WKInterfaceMap = objcclass external; WKInterfaceObject = objcclass external; WKInterfaceSeparator = objcclass external; WKInterfaceSlider = objcclass external; WKInterfaceSwitch = objcclass external; WKInterfaceTable = objcclass external; WKInterfaceTimer = objcclass external; WKUserNotificationInterfaceController = objcclass external; type UIColor = objcclass external; UIImage = objcclass external; UILocalNotification = objcclass external; implementation end.
# frozen_string_literal: true class Authenticator def initialize(login, password, hostname) @login = login @password = password @hostname = hostname @server = Server.find_by(hostname: hostname) @user = find_user end def valid_credentials? user_active? && valid_password? && not_connected_yet? && vpn_enabled? && server_belongs_to_users_plan? end private def find_user User.find_by(vpn_login: @login) || User.find_by(email: @login) end def user_active? @user.active? end def vpn_enabled? @user.service_enabled? || test_period_active? end def test_period_active? @user.test_period.enabled? && (Date.current <= @user.test_period.test_period_until) end def valid_password? vpn_credentials_valid? || billing_credentials_valid? end def billing_credentials_valid? @user.valid_password?(@password) end def vpn_credentials_valid? @user.vpn_password == @password end def not_connected_yet? !@user.connected? end def server_belongs_to_users_plan? @user.plan.servers.map(&:hostname).include?(@hostname) end end
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "ColorTable", menuName = "ScriptableObjects/ColorTable", order = 4)] public class ColorTable : ScriptableObject { public ColorInfo FindColorWithName(string name) { for (int i = 0; i < colorInfoList.Count; i++) { if (name == colorInfoList[i].name) return colorInfoList[i]; } return null; } public ColorInfo GetColorInfo(int idx) { return colorInfoList[idx]; } public int Count { get { return colorInfoList.Count; } } [SerializeField] private List<ColorInfo> colorInfoList; }
# Who using saika - [kms-docs/starter](https://kms-docs.now.sh) 🍄 KMS guide's documentation. - [evillt/vercel-toast](https://toast.evila.me) 💬 A lightweight toast. - Add yours? PRs welcome!
package org.voovan.docker.message.node; import org.voovan.tools.json.JSON; import org.voovan.tools.log.Logger; import java.util.HashMap; import java.util.Map; /** * * @author helyho * <p> * DockerFly Framework. * WebSite: https://git.oschina.net/helyho/JDocker * Licence: Apache v2 License */ public class NodeUpdate { private String availability; private String name; private String role; private Map<String, String> labels; public NodeUpdate() { labels = new HashMap<String, String>(); availability = "active"; role = "manager"; } public String getAvailability() { return availability; } public void setAvailability(String availability) { this.availability = availability; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public Map<String, String> getLabels() { return labels; } public void setLabels(Map<String, String> labels) { this.labels = labels; } public static void main(String[] args) { NodeUpdate nodeUpdate = new NodeUpdate(); nodeUpdate.setName("ModyNode"); Logger.simple(JSON.formatJson(JSON.toJSON(nodeUpdate))); } }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title of the document</title> </head> <link rel="stylesheet" href="{{asset('assets/css/bootstrap.min.css')}}"> <body> <div class="navbar"> <div class="navbar-inner"> <a class="brand" href="#">Title</a> <ul class="nav"> <li class="active"><a href="#">Home</a></li> <li><a href="{{url('accueil')}}">Accueil</a> </li> <li><a href="{{url('service')}}">Service</a> </li> <li><a href="{{url('contact')}}">Contact</a> </li> </ul> <form class="navbar-form pull-left"> <input type="text" class="span2"> <button type="submit" class="btn">Submit</button> </form> </div> </div> @yield('content') <script src="{{asset(('assets/js/jquery.min.js'))}}"></script> <script src="{{asset(('assets/js/bootstrap.min.js'))}}"></script> </body> </html>
package org.d3ifcool.finpro.core.interfaces.lists; import org.d3ifcool.finpro.core.models.Bimbingan; import java.util.List; /** * Created by Faisal Amir * FrogoBox Inc License * ========================================= * Finpro * Copyright (C) 23/06/2019. * All rights reserved * ----------------------------------------- * Name : Muhammad Faisal Amir * E-mail : faisalamircs@gmail.com * Github : github.com/amirisback * LinkedIn : linkedin.com/in/faisalamircs * ----------------------------------------- * FrogoBox Software Industries * org.d3ifcool.base.interfaces.objects */ public interface BimbinganSearchListView { void showProgress(); void hideProgress(); void onGetListBimbinganSearch(List<Bimbingan> bimbinganList); void isEmptyListBimbingan(); void onFailed(String message); }
using System.Xml.Serialization; using VersionOne.ServiceHost.ConfigurationTool.Validation; namespace VersionOne.ServiceHost.ConfigurationTool.Entities { public class QCPriorityMapping { private Mapping qualityCenterPriority; public const string VersionOnePriorityIdProperty = "VersionOnePriorityId"; public const string QCPriorityNameProperty = "QCPriorityName"; public QCPriorityMapping() { QualityCenterPriority = new Mapping(); VersionOnePriority = new Mapping(); } public Mapping QualityCenterPriority { get { return qualityCenterPriority; } set { qualityCenterPriority = value; } } public Mapping VersionOnePriority { get; set; } [XmlIgnore] [NonEmptyStringValidator] public string VersionOnePriorityId { get { return VersionOnePriority.Id; } set { VersionOnePriority.Id = value; } } [XmlIgnore] [NonEmptyStringValidator] public string QCPriorityName { get { return qualityCenterPriority.Name; } set { qualityCenterPriority.Name = value; } } } }
<!-- ajax --> <script> function ajax_binder(data){ if(data.type == "user_ajax"){ // タグに情報を付加 $('#id').text(data['id']); $('#username').text(data['name']); $('#created_at').text(data['created_at']); $('#updated_at').text(data['updated_at']); } } </script>
package committee import "time" const ( // how often timer events are triggered in commiitee // each second timer tick is sent to consensus, another to state manager, so timer events // in objects are triggered each 200 milliseconds TimerTickPeriod = 100 * time.Millisecond // if leader actions does not reset deadline, leader is rotated according to current permutation // after this period of time. // if this parameters is too small, conflicts are possible. If it is too large, the committee is too slow // to change the leader when it is needed to come out of meta stable state. // usual rotation period when leader is too slow in sending startProcessingMessage LeaderRotationPeriod = 3 * time.Second // timeout for confirmation after the leader notifies the committee it has posted result transaction to the tangle ConfirmationWaitingPeriod = 6 * time.Second // when idle, consensus object periodically refreshes balances of its own address RequestBalancesPeriod = 10 * time.Second // if node is behind the current state (not synced) it send GetBatch messages to pseudo-randomly // selected peer to get the batch it needs. Node expects answer, if not the message is repeated to another // peer after some time PeriodBetweenSyncMessages = 1 * time.Second // State Manager is requesting transaction to confirm a pending batch from the goshimmer node. // Request is repeated if necessary. StateTransactionRequestTimeout = 10 * time.Second // each committee have input channel. If channel is congested, sending to it timeouts and message is lost ReceiveMsgChannelTimeout = 500 * time.Millisecond )
require 'spec_helper' require 'ddtrace' RSpec.describe Datadog::Contrib::Configuration::Resolver do subject(:resolver) { described_class.new } describe '#resolve' do subject(:resolve) { resolver.resolve(name) } let(:name) { double('name') } it { is_expected.to be name } end end
import { reflectY } from './reflect-y.js'; describe('Reflect point y coordinate', () => { it('returns proper point cordinates', () => { const p = reflectY( { x: -3, y: 5.5 } ); expect(p.x).to.equal(-3); expect(p.y).to.equal(-5.5); }); it('reflects over (10,10)', () => { const { x, y } = reflectY({ x: 10, y: 10 }, { x: 10, y: 10 }); expect(x).to.equal(10); expect(y).to.equal(10); }); it('reflects over (5,5))', () => { const { x, y } = reflectY({ x: 10, y: 10 }, { x: 5, y: 5 }); expect(x).to.equal(10); expect(y).to.equal(0); }); it('reflects over (20,20))', () => { const { x, y } = reflectY({ x: 10, y: 10 }, { x: 20, y: 20 }); expect(x).to.equal(10); expect(y).to.equal(30); }); it('reflects over (-5,-5)', () => { const { x, y } = reflectY({ x: 10, y: 10 }, { x: -5, y: -5 }); expect(x).to.equal(10); expect(y).to.equal(-20); }); it('reflects over (-20,-20)', () => { const { x, y } = reflectY({ x: 10, y: 10 }, { x: -20, y: -20 }); expect(x).to.equal(10); expect(y).to.equal(-50); }); it('throws if "point" has invalid type', () => { const fail = () => { reflectY(null); }; expect(fail).to.throw(TypeError); }); it('throws if "origin" has invalid type', () => { const fail = () => { reflectY({ x: 10, y: 10 }, null); }; expect(fail).to.throw(TypeError); }); });
# Project This repository contains the specifications and the reference implementation for EMP, the Extensible Messaging Protocol. # Specifications Protocol specifications are available [in the `specifications` directory](https://github.com/exograd/erl-emp/blob/master/specifications/emp.md). # Documentation A handbook is available [in the `doc` directory](https://github.com/exograd/erl-emp/blob/master/doc/handbook.md). # Contact If you find a bug or have any question, feel free to open a GitHub issue or to contact me [by email](mailto:khaelin@gmail.com). Please note that I do not currently review or accept any contribution.
// // Copyright 2021 Ardalan Amini // // 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. // #include <utility> #include "silicon/parser/AST/If.h" #include "macros.h" using namespace std; using namespace silicon::parser::AST; If::If(const string &location, Node *condition, Node *then_statements, Node *else_statements) : Node{ location}, condition(MOVE(condition)), then_statements(MOVE(then_statements)), else_statements( MOVE(else_statements)) {} If::If(If *node) : If{node->location, node->condition, node->then_statements, node->else_statements} {} node_t If::node_type() { return node_t::IF; } void If::set_else(Node *statements) { else_statements = MOVE(statements); } void If::make_inline(bool should_inline) { is_inline = should_inline; }
/* * This code is open-source, MIT license. See the LICENSE file */ part of view; typedef void Reset(); /** * A bunch of buttons to press to step/unstep the simulation */ class ControlBar { int speed; Duration msPerStep = new Duration(milliseconds:80); final SimulationPresentation presentation; final DivElement container; AnchorElement playButton; AnchorElement resetButton; bool playing = false; List<StreamSubscription> listeners = []; ControlBar(this.container, this.presentation, String simulationId,Reset reset, {this.speed:80,GlobalCosts costs:null,bool tariffControl: false}) { msPerStep = new Duration(milliseconds:speed); //this is how buttons look like in pure.css // <a class="pure-button" href="#">A Pure Button</a> //add play button playButton = new AnchorElement() ..className = "pure-button pure-button-primary" // ..href = "#" ..text = "Play"; listeners.add( playButton.onClick.listen((e) { playing = !playing; if(playing) { step(); playButton.className="pure-button pure-button-active pure-button-primary"; playButton.text = "Pause"; } else { playButton.className="pure-button pure-button-primary"; playButton.text = "Play"; } }) ); //add reset button resetButton = new AnchorElement() ..className = "pure-button" // ..href = "#" ..text = "Reset"; listeners.add( resetButton.onClick.listen((e)=>reset()) ); //add speed slider LabelElement label = new LabelElement() ..text = "Speed " ..htmlFor = "${simulationId}_speed"; InputElement slider = new InputElement() ..type = "range" ..id = "${simulationId}_speed" ..min= "10" ..value= "${speed}" ..max = "300" ..step="10"; slider.style.width = "60%"; label.append(slider); SpanElement speedometer = new SpanElement(); speedometer.text=" $speed ms"; //listen to it listeners.add( slider.onInput.listen((e){ speed=int.parse(slider.value); msPerStep = new Duration(milliseconds:speed); speedometer.text=" $speed ms"; }) ); SpanElement dayCounter = new SpanElement(); dayCounter.text = ""; listeners.add( presentation.stream.listen((e)=>dayCounter.text=" Day: ${e.day}") ); //add it all to the container container.append(playButton); container.append(resetButton); container.append(dayCounter); container.append(new BRElement()); container.append(label); container.append(speedometer); //if you are given global costs, add oil slider if(costs != null) { container.append(new BRElement()); container.append(addOilSlider(costs,simulationId)); if(tariffControl) { List<DivElement> sliders = addTariffSliders(costs,simulationId); for(DivElement e in sliders) { container.append(new BRElement()); container.append(e); } } } } step() { if(playing) { presentation.step(); Timer timer = new Timer(msPerStep,()=>step()); } } kill() { playing = false; for(StreamSubscription listener in listeners) listener.cancel(); } DivElement addOilSlider(GlobalCosts costs, String simulationId) { DivElement container = new DivElement(); //add speed slider LabelElement label = new LabelElement() ..text = "Oil Price" ..htmlFor = "${simulationId}_oil"; InputElement slider = new InputElement() ..type = "range" ..id = "${simulationId}_oil" ..min= "0" ..value= "${costs.oilPricePerKm}" ..max = "5" ..step="0.1"; slider.style.width = "60%"; label.append(slider); SpanElement meter = new SpanElement(); meter.text=" ${costs.oilPricePerKm}\$/km"; //listen to it listeners.add( slider.onInput.listen((e){ double cost=double.parse(slider.value); costs.oilPricePerKm = cost; meter.text=" ${costs.oilPricePerKm}\$/km"; }) ); SpanElement dayCounter = new SpanElement(); dayCounter.text = ""; container.append(label); container.append(meter); return container; } List<DivElement> addTariffSliders(GlobalCosts costs, String simulationId) { List<DivElement> toReturn = []; costs.tariffs.forEach((fishery,tariff) { DivElement container = new DivElement(); //add speed slider LabelElement label = new LabelElement() ..text = "${fishery.name} tariff " ..htmlFor = "${simulationId}_${fishery.name}"; InputElement slider = new InputElement() ..type = "range" ..id = "${simulationId}_${fishery.name}" ..min= "0" ..value= "${tariff}" ..max = "10" ..step="0.5"; slider.style.width = "60%"; label.append(slider); SpanElement meter = new SpanElement(); meter.text=" ${tariff}\$/day"; //listen to it listeners.add( slider.onInput.listen((e){ double newTariff=double.parse(slider.value); costs.tariffs[fishery] = newTariff; meter.text=" ${newTariff}\$/day"; }) ); SpanElement dayCounter = new SpanElement(); dayCounter.text = ""; container.append(label); container.append(meter); toReturn.add(container); }); return toReturn; } }
library(glue) library(rvest) library(dplyr) library(readr) library(rtweet) library(stringr) library(here) df <- read_csv("nuforc/march_april_2022.csv") # read archive of cases to prevent double-posting cases <- read_csv(here::here("nuforc", "data_raw", "archive.csv")) # filter out cases that were already tweeted df <- df %>% dplyr::group_by_all() %>% unique() %>% dplyr::ungroup() %>% dplyr::filter(!ID %in% cases$id) reports <- df %>% dplyr::sample_n(1) # append recent tweet case_numbers <- cases %>% dplyr::add_row(id = reports$ID) city_hashtag <- gsub("[[:punct:]]+", "", reports$City) city_hashtag <- paste0("#", gsub(" ", "", city_hashtag, fixed = TRUE)) tweet <- reports %>% glue::glue_data( "Summary: {`Summary`}", " Location: {City}, {State}, {Country}", " Date of Event: {`Date/Time`}", " #ufotwitter #uaptwitter {city_hashtag}" ) # update case number so it doesn't repeat write.csv(case_numbers, here::here("nuforc", "data_raw", "archive.csv"), row.names = F) # create token token <- rtweet::create_token( app = "mufonbot", consumer_key = Sys.getenv("TWITTER_CONSUMER_API_KEY"), consumer_secret = Sys.getenv("TWITTER_CONSUMER_API_SECRET"), access_token = Sys.getenv("TWITTER_ACCESS_TOKEN"), access_secret = Sys.getenv("TWITTER_ACCESS_TOKEN_SECRET"), set_renv = FALSE ) if (!is.na(reports$Image)) { temp_file <- tempfile() imgsrc <- rvest::read_html(reports$URL) %>% rvest::html_node(xpath = '//*/img') %>% rvest::html_attr('src') download.file(imgsrc, temp_file) rtweet::post_tweet( status = tweet, media = temp_file, token = token ) } else { rtweet::post_tweet( status = tweet, token = token ) }
require 'rails' # Register as a Rails engine # in order to hook into asset pipeline module SecureEscrow class Engine < ::Rails::Engine initializer :setup_escrow do |app| # Mix view helpers in through ActionController ActionController::Base.helper SecureEscrow::Railtie::ActionViewHelper # Mix routing helpers in through the Mapper class ActionDispatch::Routing::Mapper.send :include, SecureEscrow::Railtie::Routing end end end
import {seq_num_primitive} from '../src/js/seq_num_primitive.js'; import {seq_num} from '../src/js/seq_num.js'; import {seq} from '../src/js/seq.js'; import {seq_date} from '../src/js/seq_date.js'; import {standardize_date_units} from '../src/js/standardize_date_units.js'; import {calculate_date_by} from '../src/js/calculate_date_by.js'; import {DateMethods} from '../src/js/DateMethods.js'; import {seq_date_primitive} from '../src/js/seq_date_primitive.js'; QUnit.test( "seq date", function( assert ) { let result=seq_date({from:new Date(2010,1,1),by:"3 months",length_out:3}); let expected=[ new Date(2010,1,1), new Date(2010,4,1), new Date(2010,7,1) ]; assert.deepEqual(result,expected); }); QUnit.test( "seq date along_with", function( assert ) { let result=seq({from:new Date(2010,1,1),by:"3 months",along_with:[1,2,3]}); let expected=[ new Date(2010,1,1), new Date(2010,4,1), new Date(2010,7,1) ]; assert.deepEqual(result,expected); }); QUnit.test( "seq", function( assert ) { let result=seq({from:1,by:3,length_out:3}); let expected=[1,4,7]; assert.deepEqual(result,expected); }); QUnit.test( "seq along_with", function( assert ) { let result=seq({from:1,by:3,along_with:[1,2,3]}); let expected=[1,4,7]; assert.deepEqual(result,expected); }); QUnit.test( "seq single integer", function( assert ) { let result=seq(3); let expected=[1,2,3]; assert.deepEqual(result,expected); }); QUnit.test( "seq_date, missing to", function( assert ) { let result=seq_date({from:new Date(2010,1,1),by:"3 months",length_out:3}); let expected=[ new Date(2010,1,1), new Date(2010,4,1), new Date(2010,7,1) ]; assert.deepEqual(result,expected); }); QUnit.test( "seq_date, missing from", function( assert ) { let result=seq_date({to:new Date(2010,7,1),by:"3 months",length_out:3}); let expected=[ new Date(2010,1,1), new Date(2010,4,1), new Date(2010,7,1) ]; assert.deepEqual(result,expected); }); QUnit.test( "seq_date, missing length_out", function( assert ) { let result=seq_date({from:new Date(2010,1,1),to:new Date(2010,7,1),by:"3 months"}); let expected=[ new Date(2010,1,1), new Date(2010,4,1), new Date(2010,7,1) ]; assert.deepEqual(result,expected); }); //subtraction QUnit.test( "seq_date, missing to,negative by", function( assert ) { let result=seq_date({from:new Date(2010,1,1),by:"-3 months",length_out:3}); let expected=[ new Date(2010,1,1), new Date(2009,10,1), new Date(2009,7,1) ]; assert.deepEqual(result,expected); }); QUnit.test( "seq_date, missing from,negative by", function( assert ) { let result=seq_date({to:new Date(2010,7,1),by:"-3 months",length_out:3}); let expected=[ new Date(2011,1,1), new Date(2010,10,1), new Date(2010,7,1) ]; assert.deepEqual(result,expected); }); QUnit.test( "seq_date, wrong sign in By", function( assert ) { try{ let result=seq_date({from:new Date(2010,1,1),to:new Date(2010,7,1),by:"-3 months"}); }catch(e){ assert.equal(e,"wrong sign in by argument"); } }); QUnit.test( "seq_date, missing length_out reverse,negative by", function( assert ) { let result=seq_date({to:new Date(2010,1,1),from:new Date(2010,7,1),by:"-3 months"}); let expected=[ new Date(2010,7,1), new Date(2010,4,1), new Date(2010,1,1) ]; assert.deepEqual(result,expected); }); //end subtraction QUnit.test( "DateMethods", function( assert ) { let dt=new Date(); let options=['years','months','days','hours','mins','secs']; options.forEach(option=>{ let methods=DateMethods[option]; assert.ok(typeof dt[methods.get]==='function'); assert.ok(typeof dt[methods.set]==='function'); }); }); QUnit.test( "standardize_date_units", function( assert ) { let result=standardize_date_units("week"); assert.equal(result,"weeks"); }); QUnit.test( "calculate_date_by", function( assert ) { let by="3 week"; let result=calculate_date_by(by); let { by_unit, by_multiplier }=result; assert.equal(by_unit,'days'); assert.equal(by_multiplier,21); }); QUnit.test( "calculate_date_by not numeric", function( assert ) { let result=calculate_date_by("week"); assert.deepEqual(result,{ by_unit:'days', by_multiplier:7 }); }); QUnit.test( "seq_date missing by", function( assert ) { let result=seq_date({from:new Date(2010,1,1),to:new Date(2010,1,1,1),length_out:7}); assert.deepEqual(result,[ new Date(2010,1,1), new Date(2010,1,1,0,10), new Date(2010,1,1,0,20), new Date(2010,1,1,0,30), new Date(2010,1,1,0,40), new Date(2010,1,1,0,50), new Date(2010,1,1,1), ]); }); QUnit.test( "seq_num missing to", function( assert ) { let result=seq_num({from:-3.5,by:3,length_out:4}); assert.deepEqual(result,[-3.5,-0.5,2.5,5.5]); }); QUnit.test( "seq_num missing from", function( assert ) { let result=seq_num({to:5.5,by:3,length_out:4}); assert.deepEqual(result,[-3.5,-0.5,2.5,5.5]); }); QUnit.test( "seq_num missing by", function( assert ) { let result=seq_num({from:-3.5,to:5.5,length_out:4}); assert.deepEqual(result,[-3.5,-0.5,2.5,5.5]); }); QUnit.test( "seq_num missing length_out", function( assert ) { let result=seq_num({from:-3.5,to:5.5,by:3}); assert.deepEqual(result,[-3.5,-0.5,2.5,5.5]); }); QUnit.test( "seq_num missing length_out wrong sign in by", function( assert ) { try{ let result=seq_num({from:-3.5,to:5.5,by:-3}); }catch(e){ assert.deepEqual(e,"wrong sign in by argument"); } }); QUnit.test( "numeric seq missing to", function( assert ) { let result=seq({from:-3.5,by:3,length_out:4}); assert.deepEqual(result,[-3.5,-0.5,2.5,5.5]); }); QUnit.test( "numeric seq missing from", function( assert ) { let result=seq({to:5.5,by:3,length_out:4}); assert.deepEqual(result,[-3.5,-0.5,2.5,5.5]); }); QUnit.test( "numeric seq missing by", function( assert ) { let result=seq({from:-3.5,to:5.5,length_out:4}); assert.deepEqual(result,[-3.5,-0.5,2.5,5.5]); }); QUnit.test( "numeric seq missing length_out", function( assert ) { let result=seq({from:-3.5,to:5.5,by:3}); assert.deepEqual(result,[-3.5,-0.5,2.5,5.5]); }); QUnit.test( "numeric seq, along_with instead of length_out", function( assert ) { let result=seq({from:-3.5,by:3,along_with:[1,2,3,4]}); assert.deepEqual(result,[-3.5,-0.5,2.5,5.5]); }); QUnit.test( "seq_num_primitive", function( assert ) { let result=seq_num_primitive(-3.5,3,4); assert.deepEqual(result,[-3.5,-0.5,2.5,5.5]); }); QUnit.test( "backwards seq_num_primitive", function( assert ) { let result=seq_num_primitive(3,-3,4); assert.deepEqual(result,[3,0,-3,-6]); }); QUnit.test( "seq_date_primitive years", function( assert ) { let result=seq_date_primitive(new Date(2010,1,1),"years",1,5); assert.deepEqual(result,[ new Date(2010,1,1), new Date(2011,1,1), new Date(2012,1,1), new Date(2013,1,1), new Date(2014,1,1) ]); }); QUnit.test( "seq_date_primitive months", function( assert ) { let result=seq_date_primitive(new Date(2010,1,1),"months",2,5); assert.deepEqual(result,[ new Date(2010,1,1), new Date(2010,3,1), new Date(2010,5,1), new Date(2010,7,1), new Date(2010,9,1) ]); }); QUnit.test( "seq_date_primitive days", function( assert ) { let result=seq_date_primitive(new Date(2010,1,1),"days",1,5); assert.deepEqual(result,[ new Date(2010,1,1), new Date(2010,1,2), new Date(2010,1,3), new Date(2010,1,4), new Date(2010,1,5) ]); }); QUnit.test( "seq_date_primitive hours", function( assert ) { let result=seq_date_primitive(new Date(2010,1,1),"hours",3,5); assert.deepEqual(result,[ new Date(2010,1,1,0), new Date(2010,1,1,3), new Date(2010,1,1,6), new Date(2010,1,1,9), new Date(2010,1,1,12) ]); }); QUnit.test( "seq_date_primitive minutes", function( assert ) { let result=seq_date_primitive(new Date(2010,1,1),"mins",3,5); assert.deepEqual(result,[ new Date(2010,1,1,0,0), new Date(2010,1,1,0,3), new Date(2010,1,1,0,6), new Date(2010,1,1,0,9), new Date(2010,1,1,0,12) ]); }); QUnit.test( "seq_date_primitive seconds", function( assert ) { let result=seq_date_primitive(new Date(2010,1,1),"secs",3,5); assert.deepEqual(result,[ new Date(2010,1,1,0,0,0), new Date(2010,1,1,0,0,3), new Date(2010,1,1,0,0,6), new Date(2010,1,1,0,0,9), new Date(2010,1,1,0,0,12) ]); }); QUnit.test( "backwards seq_date_primitive years", function( assert ) { let result=seq_date_primitive(new Date(2010,1,1),"years",-1,5); assert.deepEqual(result,[ new Date(2010,1,1), new Date(2009,1,1), new Date(2008,1,1), new Date(2007,1,1), new Date(2006,1,1) ]); }); QUnit.test( "backwards seq_date_primitive months", function( assert ) { let result=seq_date_primitive(new Date(2010,1,1),"months",-2,5); assert.deepEqual(result,[ new Date(2010,1,1), new Date(2009,11,1), new Date(2009,9,1), new Date(2009,7,1), new Date(2009,5,1) ]); }); QUnit.test( "backwards seq_date_primitive days", function( assert ) { let result=seq_date_primitive(new Date(2010,1,1),"days",-1,5); assert.deepEqual(result,[ new Date(2010,1,1), new Date(2009,12,31), new Date(2009,12,30), new Date(2009,12,29), new Date(2009,12,28) ]); }); QUnit.test( "backwards seq_date_primitive hours", function( assert ) { let result=seq_date_primitive(new Date(2010,1,1),"hours",-3,5); assert.deepEqual(result,[ new Date(2010,1,1,0), new Date(2009,12,31,21), new Date(2009,12,31,18), new Date(2009,12,31,15), new Date(2009,12,31,12) ]); }); QUnit.test( "backwards seq_date_primitive minutes", function( assert ) { let result=seq_date_primitive(new Date(2010,1,1),"mins",-3,5); assert.deepEqual(result,[ new Date(2010,1,1,0,0), new Date(2009,12,31,23,57), new Date(2009,12,31,23,54), new Date(2009,12,31,23,51), new Date(2009,12,31,23,48) ]); }); QUnit.test( "backwards seq_date_primitive seconds", function( assert ) { let result=seq_date_primitive(new Date(2010,1,1),"secs",-3,5); assert.deepEqual(result,[ new Date(2010,1,1,0,0,0), new Date(2009,12,31,23,59,57), new Date(2009,12,31,23,59,54), new Date(2009,12,31,23,59,51), new Date(2009,12,31,23,59,48) ]); });
require 'rails_helper' RSpec.describe Review, type: :model do describe 'associations' do it { should belong_to(:customer).class_name('Customer') } it { should belong_to(:business).class_name('Business') } end describe 'validations' do it { should validate_presence_of(:customer_id) } it { should validate_presence_of(:business_id) } it { should validate_presence_of(:review) } it { should validate_presence_of(:rating) } end end
#include "referencing.hpp" #include "../util.hxx" using namespace svgdom; std::string referencing::get_local_id_from_iri() const { return iri_to_local_id(this->iri); }
#!/bin/sh -ex setup-xorg-base \ xorg-server xf86-video-vesa xf86-input-evdev xf86-input-mouse \ xf86-input-keyboard udev xinit if [ -z "$DWM" ]; then DWM=dwm; fi if [ -z "$ST" ]; then ST=st; fi if [ -z "$DMENU" ]; then DMENU=dmenu; fi if [ -z $"XRANDR" ]; then XRANDR=xrandr; fi if [ -z $"XRDP" ]; then XRDP=xrdp; fi apk add $DWM $ST $DMENU $XRANDR $XRDP cat << EOF > /home/$VAGRANT_USERNAME/.xinitrc #!/bin/sh st & exec dwm EOF chmod +x /home/$VAGRANT_USERNAME/.xinitrc chown $VAGRANT_USERNAME /home/$VAGRANT_USERNAME/.xinitrc
const electron=require('electron'); const ipcRenderer=electron.ipcRenderer; //catching cpustuff ipcRenderer.on('CPU_INFO',(event,cpu_data) =>{ console.log(cpu_data); document.getElementById('infoValueCPUMN').innerHTML=cpu_data[0]; document.getElementById('infoValueCPUMO').innerHTML=cpu_data[1]; document.getElementById('infoValueCores').innerHTML=cpu_data[2]; }); //catching systemdata ipcRenderer.on('OS_INFO',function(event,os_data){ //console.log(data); document.getElementById('infoValueOS').innerHTML=os_data[0]; document.getElementById('infoValueOSB').innerHTML=os_data[1]; document.getElementById('infoValueHN').innerHTML=os_data[2]; }); //catching Motherboardinfo ipcRenderer.on('MB_INFO',function(event,mb_data){ //console.log(data); document.getElementById('infoValueMAN').innerHTML=mb_data[0]; document.getElementById('infoValueMOD').innerHTML=mb_data[1]; document.getElementById('infoValueVER').innerHTML=mb_data[2]; }); //catching GpuInfo ipcRenderer.on('GFX_INFO',function(event,gfx_data){ //console.log(data); document.getElementById('infoValueGVN').innerHTML=gfx_data[0]; document.getElementById('infoValueGMD').innerHTML=gfx_data[1]; document.getElementById('infoValueGRM').innerHTML=gfx_data[2]; }); ipcRenderer.on('CPT_INFO',function(event,c_data){ //console.log(data); document.getElementById('infoValueCPT').innerHTML=c_data[0].toFixed(2); document.getElementById('infoValueCPM').innerHTML=c_data[1].toFixed(1); document.getElementById('infoValueCPN').innerHTML=c_data[2].toFixed(2); });
from forked.cli import main def test_main(): """Worst test ever.""" main([])