text
stringlengths
27
775k
-- phpMyAdmin SQL Dump -- version 2.10.1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: May 23, 2011 at 06:47 AM -- Server version: 5.0.41 -- PHP Version: 5.2.2 -- -- Database: `cecherthala` -- -- -------------------------------------------------------- -- -- Table structure for table `1styearcs` -- CREATE TABLE `1styearcs` ( `msgid` int(11) NOT NULL auto_increment, `username` varchar(25) NOT NULL, `message` varchar(255) NOT NULL, `datetime` int(11) NOT NULL, `comment` tinyint(1) NOT NULL, PRIMARY KEY (`msgid`) ) TYPE=MyISAM AUTO_INCREMENT=1 ; -- -- Dumping data for table `1styearcs` -- -- -------------------------------------------------------- -- -- Table structure for table `1styearec` -- CREATE TABLE `1styearec` ( `msgid` int(11) NOT NULL auto_increment, `username` varchar(25) NOT NULL, `message` varchar(255) NOT NULL, `datetime` int(11) NOT NULL, `comment` tinyint(1) NOT NULL, PRIMARY KEY (`msgid`) ) TYPE=MyISAM AUTO_INCREMENT=1 ; -- -- Dumping data for table `1styearec` -- -- -------------------------------------------------------- -- -- Table structure for table `2ndyearcs` -- CREATE TABLE `2ndyearcs` ( `msgid` int(11) NOT NULL auto_increment, `username` varchar(25) NOT NULL, `message` varchar(255) NOT NULL, `datetime` int(11) NOT NULL, `comment` tinyint(1) NOT NULL, PRIMARY KEY (`msgid`) ) TYPE=MyISAM AUTO_INCREMENT=1 ; -- -- Dumping data for table `2ndyearcs` -- -- -------------------------------------------------------- -- -- Table structure for table `2ndyearec` -- CREATE TABLE `2ndyearec` ( `msgid` int(11) NOT NULL auto_increment, `username` varchar(25) NOT NULL, `message` varchar(255) NOT NULL, `datetime` int(11) NOT NULL, `comment` tinyint(1) NOT NULL, PRIMARY KEY (`msgid`) ) TYPE=MyISAM AUTO_INCREMENT=1 ; -- -- Dumping data for table `2ndyearec` -- -- -------------------------------------------------------- -- -- Table structure for table `3rdyearcs` -- CREATE TABLE `3rdyearcs` ( `msgid` int(11) NOT NULL auto_increment, `username` varchar(25) NOT NULL, `message` varchar(255) NOT NULL, `datetime` int(11) NOT NULL, `comment` tinyint(1) NOT NULL, PRIMARY KEY (`msgid`) ) TYPE=MyISAM AUTO_INCREMENT=1 ; -- -- Dumping data for table `3rdyearcs` -- -- -------------------------------------------------------- -- -- Table structure for table `3rdyearec` -- CREATE TABLE `3rdyearec` ( `msgid` int(11) NOT NULL auto_increment, `username` varchar(25) NOT NULL, `message` varchar(255) NOT NULL, `datetime` int(11) NOT NULL, `comment` tinyint(1) NOT NULL, PRIMARY KEY (`msgid`) ) TYPE=MyISAM AUTO_INCREMENT=1 ; -- -- Dumping data for table `3rdyearec` -- -- -------------------------------------------------------- -- -- Table structure for table `4thyearcs` -- CREATE TABLE `4thyearcs` ( `msgid` int(11) NOT NULL auto_increment, `username` varchar(25) NOT NULL, `message` varchar(255) NOT NULL, `datetime` int(11) NOT NULL, `comment` tinyint(1) NOT NULL, PRIMARY KEY (`msgid`) ) TYPE=MyISAM AUTO_INCREMENT=1 ; -- -- Dumping data for table `4thyearcs` -- -- -------------------------------------------------------- -- -- Table structure for table `4thyearec` -- CREATE TABLE `4thyearec` ( `msgid` int(11) NOT NULL auto_increment, `username` varchar(25) NOT NULL, `message` varchar(255) NOT NULL, `datetime` int(11) NOT NULL, `comment` tinyint(1) NOT NULL, PRIMARY KEY (`msgid`) ) TYPE=MyISAM AUTO_INCREMENT=1 ; -- -- Dumping data for table `4thyearec` -- -- -------------------------------------------------------- -- -- Table structure for table `actions` -- CREATE TABLE `actions` ( `source` varchar(25) NOT NULL, `action` varchar(30) NOT NULL, `target` varchar(25) NOT NULL, `id` int(11) NOT NULL auto_increment, PRIMARY KEY (`id`) ) TYPE=MyISAM AUTO_INCREMENT=1 ; -- -- Dumping data for table `actions` -- -- -------------------------------------------------------- -- -- Table structure for table `allspeak` -- CREATE TABLE `allspeak` ( `msgid` int(11) NOT NULL auto_increment, `username` varchar(25) NOT NULL, `message` varchar(255) NOT NULL, `datetime` int(11) NOT NULL, `comment` tinyint(1) NOT NULL, PRIMARY KEY (`msgid`) ) TYPE=MyISAM AUTO_INCREMENT=1 ; -- -- Dumping data for table `allspeak` -- -- -------------------------------------------------------- -- -- Table structure for table `alumni` -- CREATE TABLE `alumni` ( `msgid` int(11) NOT NULL auto_increment, `username` varchar(25) NOT NULL, `message` varchar(255) NOT NULL, `datetime` int(11) NOT NULL, `comment` tinyint(1) NOT NULL, PRIMARY KEY (`msgid`) ) TYPE=MyISAM AUTO_INCREMENT=1 ; -- -- Dumping data for table `alumni` -- -- -------------------------------------------------------- -- -- Table structure for table `notify` -- CREATE TABLE `notify` ( `time` int(11) NOT NULL, `sl` int(11) NOT NULL ) TYPE=MyISAM; -- -- Dumping data for table `notify` -- INSERT INTO `notify` VALUES (1306128583, 0); INSERT INTO `notify` VALUES (1305446232, 1); INSERT INTO `notify` VALUES (1305478202, 2); INSERT INTO `notify` VALUES (1305908070, 3); INSERT INTO `notify` VALUES (123123, 4); INSERT INTO `notify` VALUES (5, 5); INSERT INTO `notify` VALUES (6, 6); INSERT INTO `notify` VALUES (1306085576, 7); INSERT INTO `notify` VALUES (1305998638, 8); INSERT INTO `notify` VALUES (1306127975, 9); -- -------------------------------------------------------- -- -- Table structure for table `online` -- CREATE TABLE `online` ( `sl` int(11) NOT NULL auto_increment, `username` varchar(25) NOT NULL, `ip` varchar(20) NOT NULL, `status` tinyint(1) NOT NULL, `bb` varchar(9) NOT NULL, PRIMARY KEY (`sl`) ) TYPE=MyISAM AUTO_INCREMENT=1 ; -- -- Dumping data for table `online` -- -- -------------------------------------------------------- -- -- Table structure for table `userdata` -- CREATE TABLE `userdata` ( `id` int(11) NOT NULL auto_increment, `username` varchar(25) NOT NULL, `passwd` varchar(100) NOT NULL, `fullname` varchar(25) NOT NULL, `batch` varchar(15) NOT NULL, `branch` tinytext NOT NULL, `dob` varchar(15) NOT NULL, `collegeid` int(11) default NULL, `alumni` tinyint(4) NOT NULL, `fordob` varchar(14) NOT NULL, `gender` varchar(8) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`) ) TYPE=MyISAM AUTO_INCREMENT=1 ; -- -- Dumping data for table `userdata` --
package com.refinedmods.refinedstorage.api.network.node import net.minecraft.nbt.CompoundTag import net.minecraft.util.math.BlockPos import net.minecraft.world.World /** * Creates a network node. * * @param tag the tag on disk * @param world the world * @param pos the pos * @return the network node */ typealias INetworkNodeFactory = (CompoundTag, World, BlockPos) -> INetworkNode
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // 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. use env_proxy; use serde_json; use url::Url; use reqwest::header::{qitem, Accept, Authorization, Basic, ContentType, Headers, UserAgent}; use reqwest::mime; use reqwest::Client; use reqwest::{Proxy, Response}; use crate::config::SegmentCfg; use crate::error::{SegmentError, SegmentResult}; const USER_AGENT: &str = "Habitat-Builder"; #[derive(Clone, Debug)] pub struct SegmentClient { inner: Client, pub url: String, pub write_key: String, } impl SegmentClient { pub fn new(config: SegmentCfg) -> Self { let mut headers = Headers::new(); headers.set(UserAgent::new(USER_AGENT)); headers.set(Accept(vec![qitem(mime::APPLICATION_JSON)])); headers.set(ContentType(mime::APPLICATION_JSON)); let mut client = Client::builder(); client.default_headers(headers); let url = Url::parse(&config.url).expect("valid segment url must be configured"); trace!("Checking proxy for url: {:?}", url); if let Some(proxy_url) = env_proxy::for_url(&url).to_string() { if url.scheme() == "http" { trace!("Setting http_proxy to {}", proxy_url); match Proxy::http(&proxy_url) { Ok(p) => { client.proxy(p); } Err(e) => warn!("Invalid proxy, err: {:?}", e), } } if url.scheme() == "https" { trace!("Setting https proxy to {}", proxy_url); match Proxy::https(&proxy_url) { Ok(p) => { client.proxy(p); } Err(e) => warn!("Invalid proxy, err: {:?}", e), } } } else { trace!("No proxy configured for url: {:?}", url); } SegmentClient { inner: client.build().unwrap(), url: config.url, write_key: config.write_key, } } pub fn identify(&self, user_id: &str) -> SegmentResult<Response> { let json = json!({ "userId": user_id }); self.http_post( "identify", &self.write_key, serde_json::to_string(&json).unwrap(), ) } pub fn track(&self, user_id: &str, event: &str) -> SegmentResult<Response> { let json = json!({ "userId": user_id, "event": event }); self.http_post( "track", &self.write_key, serde_json::to_string(&json).unwrap(), ) } fn http_post(&self, path: &str, token: &str, body: String) -> SegmentResult<Response> { let url_path = format!("{}/v1/{}", &self.url, path); let mut headers = Headers::new(); headers.set(Authorization(Basic { username: "".to_owned(), password: Some(token.to_owned()), })); self.inner .post(&url_path) .headers(headers) .body(body) .send() .map_err(SegmentError::HttpClient) } }
<?php namespace core\libs; class Controller { function __construct () { $this->view = new View(); } /** * loadModel - Loads the model associated with the Controller * @param string $name Name of the Model * @param string $path Location of the models */ public function loadModel ($name, $modelPath = 'model/') { $path = 'core/modules/'.$name.'/'.$modelPath . $name . '_model.php'; if (file_exists($path)) { require $path; $modelName = $name . '_Model'; $this->model = new $modelName(); } } }
#photo_batch_resizing Warning: It would modify the file itself, so plese backup first! Author: Tang Xiaofei Function: Batch resize photos, and also preserve original exif info. Only for Python 3 照片缩放批处理 警告:会直接修改原文件本身,所以需要手动备份一下! 目的:数码相机拍摄的照片尺寸过大,存贮起来很不方便,所以缩小一下尺寸方便保存。 用其他软件处理时会往往会丢失exif信息(相机拍摄时间等文件属性信息),本程序 仅缩小图像尺寸,仍然保留exif信息。 前提:安装pillow和piexif库,仅支持python 3 功能:批处理缩放照片,同时保留原exif信息,希望保留照相机拍摄的时间和一些参数
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { _reserved0: [u8; 0x0100], #[doc = "0x100..0x140 - Plaintext register %s"] pub plain_: [crate::Reg<plain_::PLAIN__SPEC>; 16], #[doc = "0x140 - Configures the size of target memory space"] pub linesize: crate::Reg<linesize::LINESIZE_SPEC>, #[doc = "0x144 - Configures the type of the external memory"] pub destination: crate::Reg<destination::DESTINATION_SPEC>, #[doc = "0x148 - Physical address"] pub physical_address: crate::Reg<physical_address::PHYSICAL_ADDRESS_SPEC>, #[doc = "0x14c - Activates AES algorithm"] pub trigger: crate::Reg<trigger::TRIGGER_SPEC>, #[doc = "0x150 - Release control"] pub release: crate::Reg<release::RELEASE_SPEC>, #[doc = "0x154 - Destroys control"] pub destroy: crate::Reg<destroy::DESTROY_SPEC>, #[doc = "0x158 - Status register"] pub state: crate::Reg<state::STATE_SPEC>, #[doc = "0x15c - Version register"] pub date: crate::Reg<date::DATE_SPEC>, } #[doc = "PLAIN_ register accessor: an alias for `Reg<PLAIN__SPEC>`"] pub type PLAIN_ = crate::Reg<plain_::PLAIN__SPEC>; #[doc = "Plaintext register %s"] pub mod plain_; #[doc = "LINESIZE register accessor: an alias for `Reg<LINESIZE_SPEC>`"] pub type LINESIZE = crate::Reg<linesize::LINESIZE_SPEC>; #[doc = "Configures the size of target memory space"] pub mod linesize; #[doc = "DESTINATION register accessor: an alias for `Reg<DESTINATION_SPEC>`"] pub type DESTINATION = crate::Reg<destination::DESTINATION_SPEC>; #[doc = "Configures the type of the external memory"] pub mod destination; #[doc = "PHYSICAL_ADDRESS register accessor: an alias for `Reg<PHYSICAL_ADDRESS_SPEC>`"] pub type PHYSICAL_ADDRESS = crate::Reg<physical_address::PHYSICAL_ADDRESS_SPEC>; #[doc = "Physical address"] pub mod physical_address; #[doc = "TRIGGER register accessor: an alias for `Reg<TRIGGER_SPEC>`"] pub type TRIGGER = crate::Reg<trigger::TRIGGER_SPEC>; #[doc = "Activates AES algorithm"] pub mod trigger; #[doc = "RELEASE register accessor: an alias for `Reg<RELEASE_SPEC>`"] pub type RELEASE = crate::Reg<release::RELEASE_SPEC>; #[doc = "Release control"] pub mod release; #[doc = "DESTROY register accessor: an alias for `Reg<DESTROY_SPEC>`"] pub type DESTROY = crate::Reg<destroy::DESTROY_SPEC>; #[doc = "Destroys control"] pub mod destroy; #[doc = "STATE register accessor: an alias for `Reg<STATE_SPEC>`"] pub type STATE = crate::Reg<state::STATE_SPEC>; #[doc = "Status register"] pub mod state; #[doc = "DATE register accessor: an alias for `Reg<DATE_SPEC>`"] pub type DATE = crate::Reg<date::DATE_SPEC>; #[doc = "Version register"] pub mod date;
namespace BraspagApiDotNetSdk.Contracts { public class CardOnFile { public string Usage { get; set; } public string Reason { get; set; } } }
using System; using System.Collections.Generic; using System.CodeDom.Compiler; using System.Linq; using System.Reflection; using System.Text; using Bramble.Core; using Microsoft.CSharp; using Amaranth.Util; namespace Amaranth.Engine { public class ItemScript { /// <summary> /// Creates a new ItemScript that executes the given C# script when used. /// </summary> public static ItemScript Create(string script) { // lazy compile it UncompiledScript uncompiled = new UncompiledScript(script); sUncompiledScripts.Add(uncompiled); return uncompiled.Script; } public bool Invoke(Entity user, Item item, Action action, Vec? target) { // lazy compile if needed if (mWrapper == null) { CompileScripts(); } return mWrapper.Invoke(user, item, action, target); } private static void CompileScripts() { string code = GenerateScriptClasses(); string[] referencedAssemblies = new string[] { "mscorlib.dll", "Amaranth.Engine.dll", "Amaranth.Util.dll" }; CompilerParameters parameters = new CompilerParameters(referencedAssemblies); CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); if (results.Errors.Count > 0) { Console.WriteLine(code); foreach (CompilerError error in results.Errors) { Console.WriteLine(error.ToString()); } } Assembly assembly = results.CompiledAssembly; // bind the existing ItemUses to their compiled scripts foreach (UncompiledScript script in sUncompiledScripts) { Type type = assembly.GetType("Amaranth.Engine.Compiled." + script.ClassName); ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); ItemScriptWrapper wrapper = (ItemScriptWrapper)constructor.Invoke(new object[0]); script.Script.mWrapper = wrapper; } // all compiled now sUncompiledScripts.Clear(); } private static string GenerateScriptClasses() { StringBuilder code = new StringBuilder(); code.AppendLine("using System;"); code.AppendLine("using System.Collections.Generic;"); code.AppendLine("using System.Text;"); code.AppendLine(""); code.AppendLine(""); code.AppendLine("namespace Amaranth.Engine.Compiled"); code.AppendLine("{"); foreach (UncompiledScript script in sUncompiledScripts) { code.AppendLine(" public class " + script.ClassName + " : ItemScriptWrapper"); code.AppendLine(" {"); code.AppendLine(" protected override bool Use()"); code.AppendLine(" {"); code.AppendLine(" // script:"); code.AppendLine(" " + script.SourceCode); code.AppendLine(""); code.AppendLine(" return true;"); code.AppendLine(" }"); code.AppendLine(" }"); } code.AppendLine("}"); return code.ToString(); } /// <summary> /// Can only be constructed by ItemUse.Create(). /// </summary> private ItemScript() { } private class UncompiledScript { public string ClassName { get { return "ItemScript_" + Index; } } public ItemScript Script; public int Index; public string SourceCode; public UncompiledScript(string sourceCode) { Index = sNextScriptIndex++; SourceCode = sourceCode; // if the code doesn't have an ending ;, add one if (!SourceCode.EndsWith(";")) { SourceCode += ";"; } Script = new ItemScript(); } private static int sNextScriptIndex = 1; } private static List<UncompiledScript> sUncompiledScripts = new List<UncompiledScript>(); private ItemScriptWrapper mWrapper; } public abstract class ItemScriptWrapper { public bool Invoke(Entity user, Item item, Action action, Vec? target) { mEntity = user; mItem = item; mAction = action; mTarget = target; return Use(); } protected abstract bool Use(); #region Base Item uses protected Item Item { get { return mItem; } } //### bob: should check type protected Hero Hero { get { return (Hero)mEntity; } } protected void GainHealth() { mAction.AddAction(new GainHealthAction(mEntity, Item.Attack)); } protected void Heal() { mAction.AddAction(new HealAction(mEntity, Item.Attack)); } protected void HealFull() { mAction.AddAction(new HealFullAction(mEntity)); } protected void Teleport(int distance) { mAction.AddAction(new TeleportAction(mEntity, distance)); } protected void MakeTownPortal() { mAction.AddAction(new CreatePortalAction(mEntity)); } protected void Haste(int boost) { mAction.AddAction(new HasteAction(mEntity, Item.Attack.Roll(), boost)); } protected void Light(int radius, string noun) { mAction.AddAction(new LightAction(mEntity, new Noun(noun), radius, Item.Attack)); } protected void Explode(int radius) { mAction.AddAction(new ExplodeAction(mEntity, mItem, radius)); } protected void DetectFeatures() { mAction.AddAction(new DetectFeaturesAction(mEntity)); } protected void DetectItems() { mAction.AddAction(new DetectItemsAction(mEntity)); } protected void CurePoison() { mAction.AddAction(new CurePoisonAction(mEntity)); } protected void CureDisease() { mAction.AddAction(new CureDiseaseAction(mEntity)); } protected void RestoreAll() { mAction.AddAction(new RestoreAllAction(Hero)); } protected void RestoreStrength() { mAction.AddAction(new RestoreAction(Hero, Hero.Stats.Strength)); } protected void RestoreAgility() { mAction.AddAction(new RestoreAction(Hero, Hero.Stats.Agility)); } protected void RestoreStamina() { mAction.AddAction(new RestoreAction(Hero, Hero.Stats.Stamina)); } protected void RestoreWill() { mAction.AddAction(new RestoreAction(Hero, Hero.Stats.Will)); } protected void RestoreIntellect() { mAction.AddAction(new RestoreAction(Hero, Hero.Stats.Intellect)); } protected void RestoreCharisma() { mAction.AddAction(new RestoreAction(Hero, Hero.Stats.Charisma)); } protected void GainStrength() { mAction.AddAction(new GainStatAction(Hero, Hero.Stats.Strength)); } protected void GainAgility() { mAction.AddAction(new GainStatAction(Hero, Hero.Stats.Agility)); } protected void GainStamina() { mAction.AddAction(new GainStatAction(Hero, Hero.Stats.Stamina)); } protected void GainWill() { mAction.AddAction(new GainStatAction(Hero, Hero.Stats.Will)); } protected void GainIntellect() { mAction.AddAction(new GainStatAction(Hero, Hero.Stats.Intellect)); } protected void GainCharisma() { mAction.AddAction(new GainStatAction(Hero, Hero.Stats.Charisma)); } protected void GainAll() { GainStrength(); GainAgility(); GainStamina(); GainWill(); GainIntellect(); GainCharisma(); } protected void SwapStrength() { mAction.AddAction(new SwapStatAction(Hero, Hero.Stats.Strength)); } protected void SwapAgility() { mAction.AddAction(new SwapStatAction(Hero, Hero.Stats.Agility)); } protected void SwapStamina() { mAction.AddAction(new SwapStatAction(Hero, Hero.Stats.Stamina)); } protected void SwapWill() { mAction.AddAction(new SwapStatAction(Hero, Hero.Stats.Will)); } protected void SwapIntellect() { mAction.AddAction(new SwapStatAction(Hero, Hero.Stats.Intellect)); } protected void SwapCharisma() { mAction.AddAction(new SwapStatAction(Hero, Hero.Stats.Charisma)); } protected void Bolt(string noun) { if (!mTarget.HasValue) throw new InvalidOperationException("Cannot use the Bolt() script with Items that do not have a target."); mAction.AddAction(new ElementBoltAction(mEntity, mTarget.Value, new Noun(noun), mItem.Type.Attack)); } protected void Beam(string noun) { if (!mTarget.HasValue) throw new InvalidOperationException("Cannot use the Beam() script with Items that do not have a target."); mAction.AddAction(new ElementBeamAction(mEntity, mTarget.Value, new Noun(noun), mItem.Type.Attack)); } protected void Ball(string noun, int radius) { if (!mTarget.HasValue) throw new InvalidOperationException("Cannot use the Ball() script with Items that do not have a target."); mAction.AddAction(new ElementBallAction(mEntity, mTarget.Value, radius, new Noun(noun), mItem.Type.Attack)); } protected void Cone(string noun, int radius) { if (!mTarget.HasValue) throw new InvalidOperationException("Cannot use the Cone() script with Items that do not have a target."); mAction.AddAction(new ElementConeAction(mEntity, mTarget.Value, radius, new Noun(noun), mItem.Type.Attack)); } protected void BallSelf(string noun, int radius) { //### bob: hack. figure out where the item is Vec pos = mItem.Position; if (mAction.Game.Hero.Inventory.Contains(mItem) || mAction.Game.Hero.Equipment.Contains(mItem)) { pos = mAction.Game.Hero.Position; } mAction.AddAction(new ElementBallAction(mEntity, pos, radius, new Noun(noun), mItem.Type.Attack)); } #endregion private Entity mEntity; private Item mItem; private Action mAction; private Vec? mTarget; } }
namespace DependencyInversion.Models.Strategies { using Contracts; public abstract class Strategy : IStrategy { public abstract int Calculate(int firstOperand, int secondOperand); } }
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' show Platform; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; void main() { testWidgets('Centered text', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: Container( width: 200.0, height: 100.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: const Text('Hello', textDirection: TextDirection.ltr, textAlign: TextAlign.center, style: TextStyle(color: Color(0xffff0000)), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.Centered.png'), ); await tester.pumpWidget( Center( child: RepaintBoundary( child: Container( width: 200.0, height: 100.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: const Text('Hello world how are you today', textDirection: TextDirection.ltr, textAlign: TextAlign.center, style: TextStyle(color: Color(0xffff0000)), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.Centered.wrap.png'), ); }, skip: !Platform.isLinux); testWidgets('Text Foreground', (WidgetTester tester) async { const Color black = Color(0xFF000000); const Color red = Color(0xFFFF0000); const Color blue = Color(0xFF0000FF); final Shader linearGradient = const LinearGradient( colors: <Color>[red, blue], ).createShader(Rect.fromLTWH(0.0, 0.0, 50.0, 20.0)); await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: RepaintBoundary( child: Text('Hello', textDirection: TextDirection.ltr, style: TextStyle( foreground: Paint() ..color = black ..shader = linearGradient ), ), ), ), ); await expectLater( find.byType(RepaintBoundary), matchesGoldenFile('text_golden.Foreground.gradient.png'), ); await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: RepaintBoundary( child: Text('Hello', textDirection: TextDirection.ltr, style: TextStyle( foreground: Paint() ..color = black ..style = PaintingStyle.stroke ..strokeWidth = 2.0 ), ), ), ), ); await expectLater( find.byType(RepaintBoundary), matchesGoldenFile('text_golden.Foreground.stroke.png'), ); await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: RepaintBoundary( child: Text('Hello', textDirection: TextDirection.ltr, style: TextStyle( foreground: Paint() ..color = black ..style = PaintingStyle.stroke ..strokeWidth = 2.0 ..shader = linearGradient ), ), ), ), ); await expectLater( find.byType(RepaintBoundary), matchesGoldenFile('text_golden.Foreground.stroke_and_gradient.png'), ); }, skip: !Platform.isLinux); testWidgets('Text Fade', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( backgroundColor: Colors.transparent, body: RepaintBoundary( child: Center( child: Container( width: 200.0, height: 200.0, color: Colors.green, child: Center( child: Container( width: 100.0, color: Colors.blue, child: const Text( 'Pp PPp PPPp PPPPp PPPPpp PPPPppp PPPPppppp ', style: TextStyle(color: Colors.black), maxLines: 3, overflow: TextOverflow.fade, ), ), ), ), ), ), ) ) ); await expectLater( find.byType(RepaintBoundary).first, matchesGoldenFile('text_golden.Fade.1.png'), ); }, skip: !Platform.isLinux); }
package main import ( "log" "time" //"strings" "os" "fmt" "strconv" zmq "github.com/pebbe/zmq4" "github.com/hashicorp/consul/api" "github.com/golang/protobuf/proto" "./OpWire" ) var ( dialTimeout = 2 * time.Second requestTimeout = 10 * time.Second ) func put(cli *api.Client, op *OpWire.Operation_Put, id uint32) *OpWire.Response { kv := cli.KV() p := &api.KVPair{Key: fmt.Sprintf("%v", op.Put.Key), Value: []byte(string(op.Put.Value))} st := time.Now() _, err := kv.Put(p, nil) end := time.Now() duration := end.Sub(st) var resp *OpWire.Response if(err != nil) { resp = &OpWire.Response { ResponseTime: duration.Seconds(), Err: err.Error(), Start: float64(st.UnixNano())/1e9, End: float64(end.UnixNano())/1e9, Id: id, } } else { resp = &OpWire.Response { ResponseTime: duration.Seconds(), Err: "None", Start: float64(st.UnixNano())/1e9, End: float64(end.UnixNano())/1e9, Id: id, } } return resp } func get(cli *api.Client, op *OpWire.Operation_Get, id uint32) *OpWire.Response { kv := cli.KV() st := time.Now() p, _, err := kv.Get(fmt.Sprintf("%v",op.Get.Key), nil) end := time.Now() duration := end.Sub(st) var resp *OpWire.Response if(err != nil) { resp = &OpWire.Response { ResponseTime: duration.Seconds(), Err: err.Error(), Start: float64(st.UnixNano()) / 1e9, End: float64(end.UnixNano()) / 1e9, Id: id, } } else if p!= nil { resp = &OpWire.Response { ResponseTime: duration.Seconds(), Err: "None", Start: float64(st.UnixNano()) / 1e9, End: float64(end.UnixNano()) / 1e9, Id: id, } } else{ resp = &OpWire.Response { ResponseTime: duration.Seconds(), Err: fmt.Sprintf("Key-Value Pair not found... (Key %v)", op.Get.Key), Start: float64(st.UnixNano()) / 1e9, End: float64(end.UnixNano()) / 1e9, Id: id, } } return resp } func ReceiveOp(socket *zmq.Socket) *OpWire.Operation{ payload, _ := socket.Recv(0) op := &OpWire.Operation{} if err := proto.Unmarshal([]byte(payload), op); err != nil { log.Fatalln("Failed to parse incomming operation") } return op } func marshall_response(resp *OpWire.Response) string { payload, err := proto.Marshal(resp) if err != nil { log.Fatalln("Failed to encode response: " + err.Error()) } return string(payload) } func main() { port := os.Args[1] //endpoints := strings.Split(os.Args[2], ",") tmpid, _ := strconv.Atoi(os.Args[3]) clientid := uint32(tmpid) socket, _ := zmq.NewSocket(zmq.REQ) defer socket.Close() // ca_port_http := strconv.FormatUint(uint64(60000 + clientid * 4), 10) // ca_port_lan := strconv.FormatUint(uint64(60000 + clientid * 4 + 1), 10) // ca_port_wan := strconv.FormatUint(uint64(60000 + clientid * 4 + 2), 10) // ca_port_dns := strconv.FormatUint(uint64(60000 + clientid * 4 + 3), 10) // conn, err := net.Dial("udp", "8.8.8.8:80") // defer conn.Close() // localAddr := conn.LocalAddr().(*net.UDPAddr) // client_agent := exec.Command( // "consul", "agent", // "-disable-host-node-id", "-name=np"+ca_port_http, // "-retry-join="+endpoints[0], // "-advertise="+localAddr, // "-data-dir=~/consul_data"+ca_port_http, // "-http-port="+ca_port_http, // "-serf-lan-port="+ca_port_lan, // "-serf-wan-port="+ca_port_wan, // "-dns-port="+ca_port_dns, // ) // client_agent.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} // client_agent.Start() // defer syscall.Kill(-client_agent.Process.Pid, syscall.SIGKILL) consulconfig := api.DefaultConfig() cli, err := api.NewClient(consulconfig) if(err != nil){ println(err) return } binding := "tcp://127.0.0.1:" + port socket.Connect(binding) socket.Send("", 0) for { Operation := ReceiveOp(socket) switch op := Operation.OpType.(type) { case *OpWire.Operation_Put: resp := put(cli, op, clientid) payload := marshall_response(resp) socket.Send(payload, 0) case *OpWire.Operation_Get: resp := get(cli, op, clientid) payload := marshall_response(resp) socket.Send(payload, 0) case *OpWire.Operation_Quit: return default: resp := &OpWire.Response { ResponseTime: -10000.0, Err: "Error: Operation was not found / supported", Start: 0.0, End: 0.0, Id: clientid, } payload := marshall_response(resp) socket.Send(payload, 0) break } } }
# Reference ```@meta CurrentModule = MLFlowClient ``` # Types TODO: Document accessors. ```@docs MLFlow MLFlowExperiment MLFlowRun MLFlowRunInfo MLFlowRunData MLFlowRunDataMetric MLFlowRunStatus MLFlowArtifactFileInfo MLFlowArtifactDirInfo ``` # Experiments ```@docs createexperiment getexperiment getorcreateexperiment listexperiments deleteexperiment ``` # Runs ```@docs createrun getrun updaterun deleterun searchruns logparam logmetric logartifact listartifacts ``` # Utilities ```@docs mlfget mlfpost uri generatefilterfromparams ```
module PicapMaps class Configuration attr_accessor :database_name def initialize @database_name = 'mongo_map' end end end
import { workerData, isMainThread, parentPort } from 'worker_threads'; /** * Function to define what should be executed inside the worker thread. * The async function will be executed as soon as the worker thread is created. * * @param {Function} job Async function to be executed in the worker * @author Karan Raina <[email protected]> * @created 27-DEC-2021 * * @example * * // This code will execute in a separate thread * const { defineWorker } = require('nodejs-threads'); * // OR * import { defineWorker } from 'nodejs-threads'; * defineWorker(async (payload) => { * console.log(payload); // Payload from the Primary thread is availbale here * * // Do any CPU intensive task here. * // The event loop in primary thread won't be blocked . * * let result = 0; * for (let i = 0; i < payload.range; i++) { * result += i; * } * console.log('COMPLETED'); * return result; * }); * * @returns Returns a promise which resolves to the result of the job */ async function defineWorker(job: Function): Promise<any> { // return if it is primary thread if (isMainThread) { return null; } const result = await job(workerData); if (parentPort) { parentPort.postMessage(result); } }; export default defineWorker;
# GD32 系列 BSP 制作教程 ## 1. BSP 框架介绍 BSP 框架结构如下图所示: ![BSP 框架图](./figures/frame.png) GD32的BSP架构主要分为三个部分:libraries、tools和具体的Boards,其中libraries包含了GD32的通用库,包括每个系列的HAL以及适配RT-Thread的drivers;tools是生成工程的Python脚本工具;另外就是Boards文件,当然这里的Boards有很多,我这里值列举了GD32407V-START。 ## 2. 知识准备 制作一个 BSP 的过程就是构建一个新系统的过程,因此想要制作出好用的 BSP,要对 RT-Thread 系统的构建过程有一定了解,需要的知识准备如下所示: - 掌握 GD32 系列 BSP 的使用方法 了解 BSP 的使用方法,可以阅读 [BSP 说明文档](../README.md) 中使用教程表格内的文档。 - 了解 Scons 工程构建方法 RT-Thread 使用 Scons 作为系统的构建工具,因此了解 Scons 的常用命令对制作新 BSP 是基本要求。 - 了解设备驱动框架 在 RT-Thread 系统中,应用程序通过设备驱动框架来操作硬件,因此了解设备驱动框架,对添加 BSP 驱动是很重要的。 - 了解 Kconfig 语法 RT-Thread 系统通过 menuconfig 的方式进行配置,而 menuconfig 中的选项是由 Kconfig 文件决定的,因此想要对 RT-Thread 系统进行配置,需要对 kconfig 语法有一定了解。 ## 3. BSP移植 ### 3.1 Keil环境准备 目前市面通用的MDK for ARM版本有Keil 4和Keil 5:使用Keil 4建议安装4.74及以上;使用Keil 5建议安装5.20以上版本。本文的MDK是5.30。 从MDK的官网可以下载得到MDK的安装包,然后安装即可。 [MDK下载地址](https://www.keil.com/download/product/) ![MDK_KEIL](./figures/mdk_keil.png) 安装完成后会自动打开,我们将其关闭。 接下来我们下载GD32F30x的软件支持包。 [下载地址](http://www.gd32mcu.com/cn/download) ![Download](./figures/dowmload.png) 下载好后双击GigaDevice.GD32F4xx_DFP.2.1.0.pack运行即可: ![install paxk](./figures/install_pack.png) 点击[Next]即可安装完成。 ![finish](./figures/pack_finish.png) 安装成功后,重新打开Keil,则可以在File->Device Database中出现Gigadevice的下拉选项,点击可以查看到相应的型号。 ![Gigadevice](./figures/Gigadevice.png) ### 3.2 BSP工程制作 **1.构建基础工程** 首先看看RT-Thread代码仓库中已有很多BSP,而我要移植的是Cortex-M4内核。这里我找了一个相似的内核,把它复制一份,并修改文件名为:gd32407v-start。这样就有一个基础的工程。然后就开始增删改查,完成最终的BSP,几乎所有的BSP的制作都是如此。 **2.修改BSP构建脚本** bsp/gd32/gd32407v-start/Kconfig修改后的内容如下: ```config mainmenu "RT-Thread Configuration" config BSP_DIR string option env="BSP_ROOT" default "." config RTT_DIR string option env="RTT_ROOT" default "../../.." config PKGS_DIR string option env="PKGS_ROOT" default "packages" source "$RTT_DIR/Kconfig" source "$PKGS_DIR/Kconfig" source "../libraries/Kconfig" source "board/Kconfig" ``` 该文件是获取所有路径下的Kconfig。 bsp/gd32/gd32407v-start/SConscript修改后的内容如下: ```python # for module compiling import os Import('RTT_ROOT') from building import * cwd = GetCurrentDir() objs = [] list = os.listdir(cwd) for d in list: path = os.path.join(cwd, d) if os.path.isfile(os.path.join(path, 'SConscript')): objs = objs + SConscript(os.path.join(d, 'SConscript')) Return('objs') ``` 该文件是用于遍历当前目录的所有文件夹。 bsp/gd32/gd32407v-start/SConstruct修改后的内容如下: ```python import os import sys import rtconfig if os.getenv('RTT_ROOT'): RTT_ROOT = os.getenv('RTT_ROOT') else: RTT_ROOT = os.path.normpath(os.getcwd() + '/../../..') sys.path = sys.path + [os.path.join(RTT_ROOT, 'tools')] try: from building import * except: print('Cannot found RT-Thread root directory, please check RTT_ROOT') print(RTT_ROOT) exit(-1) TARGET = 'rtthread.' + rtconfig.TARGET_EXT DefaultEnvironment(tools=[]) env = Environment(tools = ['mingw'], AS = rtconfig.AS, ASFLAGS = rtconfig.AFLAGS, CC = rtconfig.CC, CCFLAGS = rtconfig.CFLAGS, AR = rtconfig.AR, ARFLAGS = '-rc', CXX = rtconfig.CXX, CXXFLAGS = rtconfig.CXXFLAGS, LINK = rtconfig.LINK, LINKFLAGS = rtconfig.LFLAGS) env.PrependENVPath('PATH', rtconfig.EXEC_PATH) if rtconfig.PLATFORM == 'iar': env.Replace(CCCOM = ['$CC $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -o $TARGET $SOURCES']) env.Replace(ARFLAGS = ['']) env.Replace(LINKCOM = env["LINKCOM"] + ' --map rtthread.map') Export('RTT_ROOT') Export('rtconfig') SDK_ROOT = os.path.abspath('./') if os.path.exists(SDK_ROOT + '/libraries'): libraries_path_prefix = SDK_ROOT + '/libraries' else: libraries_path_prefix = os.path.dirname(SDK_ROOT) + '/libraries' SDK_LIB = libraries_path_prefix Export('SDK_LIB') # prepare building environment objs = PrepareBuilding(env, RTT_ROOT, has_libcpu=False) gd32_library = 'GD32F4xx_HAL' rtconfig.BSP_LIBRARY_TYPE = gd32_library # include libraries objs.extend(SConscript(os.path.join(libraries_path_prefix, gd32_library, 'SConscript'))) # include drivers objs.extend(SConscript(os.path.join(libraries_path_prefix, 'HAL_Drivers', 'SConscript'))) # make a building DoBuilding(TARGET, objs) ``` 该文件用于链接所有的依赖文件,并调用make进行编译。 **3.修改开发环境信息** bsp/gd32/gd32407v-start/cconfig.h修改后的内容如下: ```c #ifndef CCONFIG_H__ #define CCONFIG_H__ /* Automatically generated file; DO NOT EDIT. */ /* compiler configure file for RT-Thread in GCC*/ #define HAVE_NEWLIB_H 1 #define LIBC_VERSION "newlib 2.4.0" #define HAVE_SYS_SIGNAL_H 1 #define HAVE_SYS_SELECT_H 1 #define HAVE_PTHREAD_H 1 #define HAVE_FDSET 1 #define HAVE_SIGACTION 1 #define GCC_VERSION_STR "5.4.1 20160919 (release) [ARM/embedded-5-branch revision 240496]" #define STDC "2011" #endif ``` 该文件是是编译BSP的环境信息,需根据实际修改。 **4.修改KEIL的模板工程** 双击:template.uvprojx即可修改模板工程。 修改为对应芯片设备: ![Chip](./figures/chip.png) 修改FLASH和RAM的配置: ![storage](./figures/storage.png) 修改可执行文件名字: ![rename](./figures/rename.png) 修改默认调试工具:CMSIS-DAP Debugger。 ![Debug](./figures/debug.png) 修改编程算法:GD32F4xx FMC。 ![FMC](./figures/FMC.png) **5.修改board文件夹** (1) 修改bsp/gd32/gd32407v-start/board/linker_scripts/link.icf 修改后的内容如下: ``` /*###ICF### Section handled by ICF editor, don't touch! / /*-Editor annotation file-*/ /* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_0.xml" */ /*-Specials-*/ define symbol __ICFEDIT_intvec_start__ = 0x08000000; /*-Memory Regions-*/ define symbol __ICFEDIT_region_ROM_start__ = 0x08000000; define symbol __ICFEDIT_region_ROM_end__ = 0x082FFFFF; define symbol __ICFEDIT_region_RAM_start__ = 0x20000000; define symbol __ICFEDIT_region_RAM_end__ = 0x2002FFFF; /*-Sizes-*/ define symbol __ICFEDIT_size_cstack__ = 0x2000; define symbol __ICFEDIT_size_heap__ = 0x2000; / End of ICF editor section. ###ICF###*/ export symbol __ICFEDIT_region_RAM_end__; define symbol __region_RAM1_start__ = 0x10000000; define symbol __region_RAM1_end__ = 0x1000FFFF; define memory mem with size = 4G; define region ROM_region = mem:[from __ICFEDIT_region_ROM_start__ to __ICFEDIT_region_ROM_end__]; define region RAM_region = mem:[from __ICFEDIT_region_RAM_start__ to __ICFEDIT_region_RAM_end__]; define region RAM1_region = mem:[from __region_RAM1_start__ to __region_RAM1_end__]; define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; initialize by copy { readwrite }; do not initialize { section .noinit }; keep { section FSymTab }; keep { section VSymTab }; keep { section .rti_fn* }; place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; place in ROM_region { readonly }; place in RAM_region { readwrite, block CSTACK, block HEAP }; place in RAM1_region { section .sram }; ``` 该文件是IAR编译的链接脚本,根据《GD32F407xx_Datasheet_Rev2.1》可知,GD32F407VKT6的flash大小为3072KB,SRAM大小为192KB,因此需要设置ROM和RAM的起始地址和堆栈大小等。 (2) 修改bsp/gd32/gd32407v-start/board/linker_scripts/link.ld 修改后的内容如下: ``` /* Program Entry, set to mark it as "used" and avoid gc */ MEMORY { CODE (rx) : ORIGIN = 0x08000000, LENGTH = 3072k /* 3072KB flash */ DATA (rw) : ORIGIN = 0x20000000, LENGTH = 192k /* 192KB sram */ } ENTRY(Reset_Handler) _system_stack_size = 0x200; SECTIONS { .text : { . = ALIGN(4); _stext = .; KEEP(*(.isr_vector)) /* Startup code */ . = ALIGN(4); *(.text) /* remaining code */ *(.text.*) /* remaining code */ *(.rodata) /* read-only data (constants) */ *(.rodata*) *(.glue_7) *(.glue_7t) *(.gnu.linkonce.t*) /* section information for finsh shell */ . = ALIGN(4); __fsymtab_start = .; KEEP(*(FSymTab)) __fsymtab_end = .; . = ALIGN(4); __vsymtab_start = .; KEEP(*(VSymTab)) __vsymtab_end = .; . = ALIGN(4); /* section information for initial. */ . = ALIGN(4); __rt_init_start = .; KEEP(*(SORT(.rti_fn*))) __rt_init_end = .; . = ALIGN(4); . = ALIGN(4); _etext = .; } > CODE = 0 /* .ARM.exidx is sorted, so has to go in its own output section. */ __exidx_start = .; .ARM.exidx : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) /* This is used by the startup in order to initialize the .data secion */ _sidata = .; } > CODE __exidx_end = .; /* .data section which is used for initialized data */ .data : AT (_sidata) { . = ALIGN(4); /* This is used by the startup in order to initialize the .data secion */ _sdata = . ; *(.data) *(.data.*) *(.gnu.linkonce.d*) . = ALIGN(4); /* This is used by the startup in order to initialize the .data secion */ _edata = . ; } >DATA .stack : { . = . + _system_stack_size; . = ALIGN(4); _estack = .; } >DATA __bss_start = .; .bss : { . = ALIGN(4); /* This is used by the startup in order to initialize the .bss secion */ _sbss = .; *(.bss) *(.bss.*) *(COMMON) . = ALIGN(4); /* This is used by the startup in order to initialize the .bss secion */ _ebss = . ; *(.bss.init) } > DATA __bss_end = .; _end = .; /* Stabs debugging sections. */ .stab 0 : { *(.stab) } .stabstr 0 : { *(.stabstr) } .stab.excl 0 : { *(.stab.excl) } .stab.exclstr 0 : { *(.stab.exclstr) } .stab.index 0 : { *(.stab.index) } .stab.indexstr 0 : { *(.stab.indexstr) } .comment 0 : { *(.comment) } /* DWARF debug sections. * Symbols in the DWARF debugging sections are relative to the beginning * of the section so we begin them at 0. */ /* DWARF 1 */ .debug 0 : { *(.debug) } .line 0 : { *(.line) } /* GNU DWARF 1 extensions */ .debug_srcinfo 0 : { *(.debug_srcinfo) } .debug_sfnames 0 : { *(.debug_sfnames) } /* DWARF 1.1 and DWARF 2 */ .debug_aranges 0 : { *(.debug_aranges) } .debug_pubnames 0 : { *(.debug_pubnames) } /* DWARF 2 */ .debug_info 0 : { *(.debug_info .gnu.linkonce.wi.*) } .debug_abbrev 0 : { *(.debug_abbrev) } .debug_line 0 : { *(.debug_line) } .debug_frame 0 : { *(.debug_frame) } .debug_str 0 : { *(.debug_str) } .debug_loc 0 : { *(.debug_loc) } .debug_macinfo 0 : { *(.debug_macinfo) } /* SGI/MIPS DWARF 2 extensions */ .debug_weaknames 0 : { *(.debug_weaknames) } .debug_funcnames 0 : { *(.debug_funcnames) } .debug_typenames 0 : { *(.debug_typenames) } .debug_varnames 0 : { *(.debug_varnames) } } ``` 该文件是GCC编译的链接脚本,根据《GD32F407xx_Datasheet_Rev2.1》可知,GD32F407VKT6的flash大小为3072KB,SRAM大小为192KB,因此CODE和DATA 的LENGTH分别设置为3072KB和192KB,其他芯片类似,但其实地址都是一样的。 (3) 修改bsp/gd32/gd32407v-start/board/linker_scripts/link.sct 修改后的内容如下: ``` ; ************************************************************* ; *** Scatter-Loading Description File generated by uVision *** ; ************************************************************* LR_IROM1 0x08000000 0x00300000 { ; load region size_region ER_IROM1 0x08000000 0x00300000 { ; load address = execution address *.o (RESET, +First) *(InRoot$$Sections) .ANY (+RO) } RW_IRAM1 0x20000000 0x00030000 { ; RW data .ANY (+RW +ZI) } } ``` 该文件是MDK的连接脚本,根据《GD32F407xx_Datasheet_Rev2.1》手册,因此需要将 LR_IROM1 和 ER_IROM1 的参数设置为 0x00300000;RAM 的大小为192k,因此需要将 RW_IRAM1 的参数设置为 0x00030000。 (4) 修改bsp/gd32/gd32407v-start/board/board.h文件 修改后内容如下: ```c #ifndef __BOARD_H__ #define __BOARD_H__ #include "gd32f4xx.h" #include "drv_usart.h" #include "drv_gpio.h" #include "gd32f4xx_exti.h" #define EXT_SDRAM_BEGIN (0xC0000000U) /* the begining address of external SDRAM */ #define EXT_SDRAM_END (EXT_SDRAM_BEGIN + (32U * 1024 * 1024)) /* the end address of external SDRAM */ // <o> Internal SRAM memory size[Kbytes] <8-64> // <i>Default: 64 #ifdef __ICCARM__ // Use *.icf ram symbal, to avoid hardcode. extern char __ICFEDIT_region_RAM_end__; #define GD32_SRAM_END &__ICFEDIT_region_RAM_end__ #else #define GD32_SRAM_SIZE 192 #define GD32_SRAM_END (0x20000000 + GD32_SRAM_SIZE * 1024) #endif #ifdef __CC_ARM extern int Image$$RW_IRAM1$$ZI$$Limit; #define HEAP_BEGIN (&Image$$RW_IRAM1$$ZI$$Limit) #elif __ICCARM__ #pragma section="HEAP" #define HEAP_BEGIN (__segment_end("HEAP")) #else extern int __bss_end; #define HEAP_BEGIN (&__bss_end) #endif #define HEAP_END GD32_SRAM_END #endif ``` 值得注意的是,不同的编译器规定的堆栈内存的起始地址 HEAP_BEGIN 和结束地址 HEAP_END。这里 HEAP_BEGIN 和 HEAP_END 的值需要和前面的链接脚本是一致的,需要结合实际去修改。 (5) 修改bsp/gd32/gd32407v-start/board/board.c文件 修改后的文件如下: ```c #include <stdint.h> #include <rthw.h> #include <rtthread.h> #include <board.h> /** * @brief This function is executed in case of error occurrence. * @param None * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler */ /* User can add his own implementation to report the HAL error return state */ while (1) { } /* USER CODE END Error_Handler */ } /** System Clock Configuration */ void SystemClock_Config(void) { SysTick_Config(SystemCoreClock / RT_TICK_PER_SECOND); NVIC_SetPriority(SysTick_IRQn, 0); } /** * This is the timer interrupt service routine. * */ void SysTick_Handler(void) { /* enter interrupt */ rt_interrupt_enter(); rt_tick_increase(); /* leave interrupt */ rt_interrupt_leave(); } /** * This function will initial GD32 board. */ void rt_hw_board_init() { /* NVIC Configuration */ #define NVIC_VTOR_MASK 0x3FFFFF80 #ifdef VECT_TAB_RAM /* Set the Vector Table base location at 0x10000000 */ SCB->VTOR = (0x10000000 & NVIC_VTOR_MASK); #else /* VECT_TAB_FLASH */ /* Set the Vector Table base location at 0x08000000 */ SCB->VTOR = (0x08000000 & NVIC_VTOR_MASK); #endif SystemClock_Config(); #ifdef RT_USING_COMPONENTS_INIT rt_components_board_init(); #endif #ifdef RT_USING_CONSOLE rt_console_set_device(RT_CONSOLE_DEVICE_NAME); #endif #ifdef BSP_USING_SDRAM rt_system_heap_init((void *)EXT_SDRAM_BEGIN, (void *)EXT_SDRAM_END); #else rt_system_heap_init((void *)HEAP_BEGIN, (void *)HEAP_END); #endif } ``` 该文件重点关注的就是SystemClock_Config配置,SystemCoreClock的定义在system_gd32f4xx.c中定义的。 (6) 修改bsp/gd32/gd32407v-start/board/Kconfig文件 修改后内容如下: ```config menu "Hardware Drivers Config" config SOC_GD32407V bool select SOC_SERIES_GD32F4 select RT_USING_COMPONENTS_INIT select RT_USING_USER_MAIN default y menu "Onboard Peripheral Drivers" endmenu menu "On-chip Peripheral Drivers" config BSP_USING_GPIO bool "Enable GPIO" select RT_USING_PIN default y menuconfig BSP_USING_UART bool "Enable UART" default y select RT_USING_SERIAL if BSP_USING_UART config BSP_USING_UART1 bool "Enable UART1" default y config BSP_UART1_RX_USING_DMA bool "Enable UART1 RX DMA" depends on BSP_USING_UART1 && RT_SERIAL_USING_DMA default n endif menuconfig BSP_USING_SPI bool "Enable SPI BUS" default n select RT_USING_SPI if BSP_USING_SPI config BSP_USING_SPI1 bool "Enable SPI1 BUS" default n config BSP_SPI1_TX_USING_DMA bool "Enable SPI1 TX DMA" depends on BSP_USING_SPI1 default n config BSP_SPI1_RX_USING_DMA bool "Enable SPI1 RX DMA" depends on BSP_USING_SPI1 select BSP_SPI1_TX_USING_DMA default n endif menuconfig BSP_USING_I2C1 bool "Enable I2C1 BUS (software simulation)" default n select RT_USING_I2C select RT_USING_I2C_BITOPS select RT_USING_PIN if BSP_USING_I2C1 config BSP_I2C1_SCL_PIN int "i2c1 scl pin number" range 1 216 default 24 config BSP_I2C1_SDA_PIN int "I2C1 sda pin number" range 1 216 default 25 endif source "../libraries/HAL_Drivers/Kconfig" endmenu menu "Board extended module Drivers" endmenu endmenu ``` 这个文件就是配置板子驱动的,这里可根据实际需求添加。 (7) 修改bsp/gd32/gd32407v-start/board/SConscript文件 修改后内容如下: ```python import os import rtconfig from building import * Import('SDK_LIB') cwd = GetCurrentDir() # add general drivers src = Split(''' board.c ''') path = [cwd] startup_path_prefix = SDK_LIB if rtconfig.CROSS_TOOL == 'gcc': src += [startup_path_prefix + '/GD32F4xx_HAL/CMSIS/GD/GD32F4xx/Source/GCC/startup_gd32f4xx.S'] elif rtconfig.CROSS_TOOL == 'keil': src += [startup_path_prefix + '/GD32F4xx_HAL/CMSIS/GD/GD32F4xx/Source/ARM/startup_gd32f4xx.s'] elif rtconfig.CROSS_TOOL == 'iar': src += [startup_path_prefix + '/GD32F4xx_HAL/CMSIS/GD/GD32F4xx/Source/IAR/startup_gd32f4xx.s'] CPPDEFINES = ['GD32F407xx'] group = DefineGroup('Drivers', src, depend = [''], CPPPATH = path, CPPDEFINES = CPPDEFINES) Return('group') ``` 该文件主要添加board文件夹的.c文件和头文件路径。另外根据开发环境选择相应的汇编文件,和前面的libraries的SConscript语法是一样,文件的结构都是类似的,这里就没有注释了。 到这里,基本所有的依赖脚本都配置完成了,接下来将通过menuconfig配置工程。 **6.menuconfig配置** 关闭套接字抽象层。 ![Disable socket](./figures/disable_socket.png) 关闭网络设备接口。 ![Disable net](./figures/disable_net.png) 关闭LWIP协议栈。 ![Disable lwip](./figures/disable_lwip.png) GD32407V-START板载没有以太网,因此这里主要是关闭网络相关的内容,当然GD32407V-START的资源丰富,不关这些其实也不影响,如果是其他MCU,根据实际需求自行修改吧。 **7.驱动修改** 一个基本的BSP中,串口是必不可少的,所以还需要编写串口驱动,这里使用的串口2作为调试串口。 板子上还有LED灯,主要要编写GPIO驱动即可。 关于串口和LED的驱动可以查看源码,这里就不贴出来了。 **8.应用开发** 笔者在applications的main.c中添加LED的应用代码, ```c #include <stdio.h> #include <rtthread.h> #include <rtdevice.h> #include <board.h> /* defined the LED2 pin: PC6 */ #define LED2_PIN GET_PIN(C, 6) int main(void) { int count = 1; /* set LED2 pin mode to output */ rt_pin_mode(LED2_PIN, PIN_MODE_OUTPUT); while (count++) { rt_pin_write(LED2_PIN, PIN_HIGH); rt_thread_mdelay(500); rt_pin_write(LED2_PIN, PIN_LOW); rt_thread_mdelay(500); } return RT_EOK; } ``` 当然,这需要GPIO驱动的支持。 **9.使用ENV编译工程** 在env中执行:scons ![scons](./figures/scons.png) 编译成功打印信息如下: ![scons_success](./figures/scons_success.png) **10.使用env生成MDK工程** 在env中执行:scons --target=mdk5 ![scons_mdk5](./figures/scons_mdk5.png) 生成MDK工程后,打开MDK工程进行编译 ![MDK Build](./figures/MDK_Build.png) 成功编译打印信息如下: ![MDK Build success](./figures/MDK_Build_Success.png) ### 3.3 使用GD-Link 下载调试GD32 前面使用ENV和MDK成功编译可BSP,那么接下来就是下载调试环节,下载需要下载器,而GD32部分开发板自带GD-link,可以用开发板上自带的GD-link调试仿真代码,不带的可外接GD-link模块,还是很方便的。具体操作方法如下。 1.第一次使用GD-link插入电脑后,会自动安装驱动。 在Options for Target -> Debug 中选择“CMSIS-DAP Debugger”,部分客户反馈找不到这一驱动器选项,那是因为MDK版本过低,只有Keil4.74以上的版本和Keil5才支持CMSIS-DAP Debugger选项。 ![CMSIS-DAP Debugger](./figures/CMSIS-DAP_Debugger.png) 2.在Options for Target -> Debug ->Settings勾选SWJ、 Port选择 SW。右框IDcode会出现”0xXBAXXXXX”。 ![setting1](./figures/setting1.png) 3.在Options for Target -> Debug ->Settings -> Flash Download中添加GD32的flash算法。 ![setting2](./figures/setting2.png) 4.单击下图的快捷方式“debug”, 即可使用GD-Link进行仿真。 ![GD link debug](./figures/gdlink_debug.png) 当然啦,也可使用GD-Link下载程序。 ![GD link download](./figures/gdlink_download.png) 下载程序成功后,打印信息如下: ![download success](./figures/download_success.png) 接上串口,打印信息如下: ![UART print](./figures/com_print.png) 同时LED会不断闪烁。 ### 3.4 RT-Thread studio开发 当然,该工程也可导出使用rt-thread studio开发。 先使用scons --dist导出工程。 ![scons dist](./figures/scons_dist.png) 再将工程导入rt-thread studio中 ![import_rt-thread_studio](./figures/import_rt-thread_studio.png) 最后,就可在rt-thread studio就可进行开发工作了。 ![rt-thread_studio](./figures/rt-thread_studio.png) ## 4. 规范 本章节介绍 RT-Thread GD32 系列 BSP 制作与提交时应当遵守的规范 。开发人员在 BSP 制作完成后,可以根据本规范提出的检查点对制作的 BSP 进行检查,确保 BSP 在提交前有较高的质量 。 ### 4.1 BSP 制作规范 GD32 BSP 的制作规范主要分为 3 个方面:工程配置,ENV 配置和 IDE 配置。在已有的 GD32 系列 BSP 的模板中,已经根据下列规范对模板进行配置。在制作新 BSP 的过程中,拷贝模板进行修改时,需要注意的是不要修改这些默认的配置。BSP 制作完成后,需要对新制作的 BSP 进行功能测试,功能正常后再进行代码提交。 下面将详细介绍 BSP 的制作规范。 #### 4.1.1 工程配置 - 遵从RT-Thread 编码规范,代码注释风格统一 - main 函数功能保持一致 - 如果有 LED 的话,main 函数里**只放一个** LED 1HZ 闪烁的程序 - 在 `rt_hw_board_init` 中需要完成堆的初始化:调用 `rt_system_heap_init` - 默认只初始化 GPIO 驱动和 FinSH 对应的串口驱动,不使用 DMA - 当使能板载外设驱动时,应做到不需要修改代码就能编译下载使用 - 提交前应检查 GCC/MDK/IAR 三种编译器直接编译或者重新生成后编译是否成功 - 使用 `dist` 命令对 BSP 进行发布,检查使用 `dist` 命令生成的工程是否可以正常使用 #### 4.1.2 ENV 配置 - 系统心跳统一设置为 1000(宏:RT_TICK_PER_SECOND) - BSP 中需要打开调试选项中的断言(宏:RT_DEBUG) - 系统空闲线程栈大小统一设置为 256(宏:IDLE_THREAD_STACK_SIZE) - 开启组件自动初始化(宏:RT_USING_COMPONENTS_INIT) - 需要开启 user main 选项(宏:RT_USING_USER_MAIN) - 默认关闭 libc(宏:RT_USING_LIBC) - FinSH 默认只使用 MSH 模式(宏:FINSH_USING_MSH_ONLY) #### 4.1.3 IDE 配置 - 使能下载代码后自动运行 - 使能 C99 支持 - 使能 One ELF Section per Function(MDK) - MDK/IAR 生成的临时文件分别放到build下的 MDK/IAR 文件夹下 - MDK/GCC/IAR 生成 bin 文件名字统一成 rtthread.bin ### 4.2 BSP 提交规范 - 提交前请认真修改 BSP 的 README.md 文件,README.md 文件的外设支持表单只填写 BSP 支持的外设,可参考其他 BSP 填写。查看文档[《GD32系列驱动介绍》](./GD32系列驱动介绍.md)了解驱动分类。 - 提交 BSP 分为 2 个阶段提交: - 第一阶段:基础 BSP 包括串口驱动和 GPIO 驱动,能运行 FinSH 控制台。完成 MDK4、MDK5 、IAR 和 GCC 编译器支持,如果芯片不支持某款编译器(比如MDK4)可以不用做。 BSP 的 README.md 文件需要填写第二阶段要完成的驱动。 - 第二阶段:完成板载外设驱动支持,所有板载外设使用 menuconfig 配置后就能直接使用。若开发板没有板载外设,则此阶段可以不用完成。不同的驱动要分开提交,方便 review 和合并。 - 只提交 BSP 必要的文件,删除无关的中间文件,能够提交的文件请对照其他 BSP。 - 提交 GD32 不同系列的 Library 库时,请参考 f1/f4 系列的 HAL 库,删除多余库文件 - 提交前要对 BSP 进行编译测试,确保在不同编译器下编译正常 - 提交前要对 BSP 进行功能测试,确保 BSP 的在提交前符合工程配置章节中的要求
--- name: New feature about: Suggest an idea for this project title: '' labels: Feature assignees: '' --- ### Problem What problem this feature is going to solve. Why this problem is important ### Solution Proposed solution: architecture, implementation details etc
class Order < ActiveRecord::Base belongs_to :customer belongs_to :status has_many :line_items validates :status_id, :presence => true validates :order_total, :presence => true, :numericality => { :greater_than_or_equal_to => 0 } validates :gst_rate, :allow_nil => true, :numericality => { :greater_than_or_equal_to => 0 } validates :hst_rate, :allow_nil => true, :numericality => { :greater_than_or_equal_to => 0 } validates :pst_rate, :allow_nil => true, :numericality => { :greater_than_or_equal_to => 0 } attr_accessible :gst_rate, :hst_rate, :pst_rate, :status_id, :order_total, :customer_id end
<?php namespace User\Storage; use Laminas\Authentication\AuthenticationService; class IdentityManager implements IdentityManagerInterface { protected $authService; public function __construct(AuthenticationService $authService) { $this->authService = $authService; } public function getAuthService() { return $this->authService; } public function login($identity, $credential) { $this->getAuthService() ->getAdapter() ->setIdentity($identity) ->setCredential($credential); $result = $this->getAuthService()->authenticate(); return $result; } public function logout() { $this->getAuthService() ->getStorage() ->clear(); } public function hasIdentity() { return $this->getAuthService()->hasIdentity(); } public function storeIdentity(array $identity) { $this->getAuthService() ->getStorage() ->write($identity); } public function getIdentity() { $sessionId = $this->getAuthService() ->getStorage() ->getSessionId(); return $this->getAuthService() ->getStorage() ->read($sessionId); } }
package app.cn.extra.mall.merchant.event; public class PendingOrderFragmentEvent { }
package ru.job4j.comparator; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.MatcherAssert.assertThat; /** * Test class. * *@author John Ivanov ([email protected]) *@version $Id$ *@since 05.02.2019 */ public class StringsCompareTest { @Test public void whenStringsAreEqualThenZero() { ListCompare compare = new ListCompare(); int rst = compare.compare( "Ivanov", "Ivanov" ); assertThat(rst, is(0)); } @Test public void whenLeftLessThanRightResultShouldBeMinusOne() { ListCompare compare = new ListCompare(); int rst = compare.compare( "Ivanov", "Ivanova" ); assertThat(rst, is(-1)); } @Test public void whenLeftGreaterThanRightResultShouldBeOne() { ListCompare compare = new ListCompare(); int rst = compare.compare( "Ivanovsky", "Ivanov" ); assertThat(rst, is(1)); } @Test public void whenFirstCharLeftGreaterThanRightResultShouldBePositive() { ListCompare compare = new ListCompare(); int rst = compare.compare( "Petrov", "Ivanova" ); assertThat(rst, greaterThan(0)); } @Test public void whenSecondCharOfLeftGreaterThanRightShouldBePositive() { ListCompare compare = new ListCompare(); int rst = compare.compare( "Petrov", "Patrov" ); //System.out.println(" 5 : " + rst); assertThat(rst, greaterThan(0)); } @Test public void whenThirdCharOfLeftLessThanRightShouldBeNegative() { ListCompare compare = new ListCompare(); int rst = compare.compare( "Pearova", "Petrov" ); //System.out.println(" 6 : " + rst); assertThat(rst, lessThan(0)); } }
using System; using System.IO; using System.Linq; namespace UnityDarkSkin.Lib { public class Patcher { public string FilePath { get; } public Version CurrentVersion { get; set; } public ThemeType CurrentTheme { get; private set; } private bool IsLoaded { get => Data != null; } private byte[] Data { get; set; } private int _offset = 0; public Patcher(string path) { FilePath = path; } public void Reset() { _offset = 0; } public void Load() { if (!File.Exists(FilePath)) throw new FileNotFoundException("File doesn't exist"); Data = File.ReadAllBytes(FilePath); } public ThemeType SetTheme(ThemeType theme) { if (!File.Exists(FilePath)) throw new FileNotFoundException("File doesn't exist"); if (CurrentVersion == null) throw new InvalidOperationException("Version is not detected"); if (_offset == 0) DetectTheme(CurrentVersion); var bytes = CurrentVersion.GetBytes(theme); if (_offset + bytes.Length < Data.Length) { for (int i = 0; i < bytes.Length; ++i) { Data[_offset + i] = bytes[i]; } } return DetectTheme(CurrentVersion); } // Search in bytes: O(N) // Returns offset of first byte in query or -1 private int Search(byte[] search, int offset = 0) { if (!IsLoaded) throw new InvalidOperationException("File is not loaded"); // int num = -1; if (Data.Length > 0 && search.Length > 0 && offset <= Data.Length - search.Length && Data.Length >= search.Length) { for (int i = offset; i <= Data.Length - search.Length; ++i) { if (Data[i] == search[0]) { if (Data.Length > 1) { bool flag = true; for (int j = 1; j < search.Length; ++j) { if (Data[i + j] != search[j]) { flag = false; break; } } if (flag) { num = i; break; } } else { num = i; break; } } } } return num; } public Version DetectVersion() { if (!IsLoaded) throw new InvalidOperationException("File is not loaded"); // foreach (Version version in Versions.Get().Reverse()) { int light = Search(version.LightBytes); int dark = Search(version.DarkBytes); bool isLight = light != -1; bool isDark = dark != -1; if (isLight || isDark) { _offset = Math.Max(light, dark); CurrentVersion = version; return version; } } return null; } public ThemeType DetectTheme(Version version) { bool light = Search(version.LightBytes, _offset) != -1; bool dark = Search(version.DarkBytes, _offset) != -1; if (light || dark) CurrentTheme = light ? ThemeType.Light : ThemeType.Dark; else CurrentTheme = ThemeType.None; return CurrentTheme; } public void Save() { if (!IsLoaded) throw new InvalidOperationException("File is not loaded"); File.WriteAllBytes(FilePath, Data); } public void MakeBackup() { if (!IsLoaded) throw new InvalidOperationException("File is not loaded"); string fileDir = Path.GetDirectoryName(FilePath); string fileName = Path.GetFileName(FilePath); DateTime date = DateTime.Now; string NewFileName = $"Backup_{date.Day}-{date.Month}-{date.Year}_{date.Hour}-{date.Minute}-{date.Second}_{fileName}"; string newPath = Path.Combine(fileDir, NewFileName); File.WriteAllBytes(newPath, Data); } public void RestoreBackup(string file) { if (!IsLoaded) throw new InvalidOperationException("File is not loaded"); File.Delete(FilePath); File.Move(file, FilePath); //throw new NotImplementedException(); } } public enum ThemeType { None = 0, Light = 1, Dark = 2 } }
package org.cartagena.tool.core.http.json4s import org.cartagena.tool.core.http.json4s.Json4sTestUtil._ import org.cartagena.tool.core.registry.Json4sRegistryTest import org.scalatest.{FlatSpec, Matchers} class Json4sClientTest extends FlatSpec with Matchers with Json4sRegistryTest { override private[core] val json4sClient = new Json4sClientWithMyDefaultFormats "formats" should "return configured Json4s Formats" in { // when val actual = json4sClient.formats // then actual shouldBe a[MyFormats1.type] } "setFormats" should "set new Json4s Formats" in { // given val newFormats = MyFormats2 // when json4sClient setFormats newFormats // then json4sClient.formats shouldBe a[MyFormats2.type] } "addSerializers" should "add custom Json serializers to Json4s Formats" in { // given val serializers = MySerializer1 :: MySerializer2 :: Nil // when json4sClient addSerializers serializers // then json4sClient.formats.customSerializers should contain theSameElementsInOrderAs serializers } }
package pathroute import ( "fmt" . "github.com/mailgun/vulcand/Godeps/_workspace/src/github.com/mailgun/vulcan/location" . "github.com/mailgun/vulcand/Godeps/_workspace/src/github.com/mailgun/vulcan/netutils" . "github.com/mailgun/vulcand/Godeps/_workspace/src/github.com/mailgun/vulcan/request" "github.com/mailgun/vulcand/Godeps/_workspace/src/github.com/mailgun/vulcan/testutils" . "github.com/mailgun/vulcand/Godeps/_workspace/src/gopkg.in/check.v1" "net/http" "testing" ) func TestPathRoute(t *testing.T) { TestingT(t) } type MatchSuite struct { } var _ = Suite(&MatchSuite{}) func (s *MatchSuite) SetUpSuite(c *C) { } func (s *MatchSuite) TestRouteEmpty(c *C) { m := NewPathRouter() out, err := m.Route(request("http://google.com/")) c.Assert(err, IsNil) c.Assert(out, Equals, nil) } func (s *MatchSuite) TestRemoveNonExistent(c *C) { m := NewPathRouter() c.Assert(m.RemoveLocation(m.GetLocationByPattern("ooo")), Not(Equals), nil) } func (s *MatchSuite) TestAddTwice(c *C) { m := NewPathRouter() loc := &Loc{Name: "a"} c.Assert(m.AddLocation("/a", loc), IsNil) c.Assert(m.AddLocation("/a", loc), Not(Equals), nil) } func (s *MatchSuite) TestSingleLocation(c *C) { m := NewPathRouter() loc := &Loc{Name: "a"} c.Assert(m.AddLocation("/", loc), IsNil) out, err := m.Route(request("http://google.com/")) c.Assert(err, IsNil) c.Assert(out, Equals, loc) } func (s *MatchSuite) TestEmptyPath(c *C) { m := NewPathRouter() loc := &Loc{Name: "a"} c.Assert(m.AddLocation("/", loc), IsNil) out, err := m.Route(request("http://google.com")) c.Assert(err, IsNil) c.Assert(out, Equals, loc) } func (s *MatchSuite) TestMatchNothing(c *C) { m := NewPathRouter() loc := &Loc{Name: "a"} c.Assert(m.AddLocation("/", loc), IsNil) out, err := m.Route(request("http://google.com/hello/there")) c.Assert(err, IsNil) c.Assert(out, Equals, nil) } // Make sure we'll match request regardless if it has trailing slash or not func (s *MatchSuite) TestTrailingSlashes(c *C) { m := NewPathRouter() loc := &Loc{Name: "a"} c.Assert(m.AddLocation("/a/b", loc), IsNil) out, err := m.Route(request("http://google.com/a/b")) c.Assert(err, IsNil) c.Assert(out, Equals, loc) out, err = m.Route(request("http://google.com/a/b/")) c.Assert(err, IsNil) c.Assert(out, Equals, loc) } // If users added trailing slashes the request will require them to match request func (s *MatchSuite) TestPatternTrailingSlashes(c *C) { m := NewPathRouter() loc := &Loc{Name: "a"} c.Assert(m.AddLocation("/a/b/", loc), IsNil) out, err := m.Route(request("http://google.com/a/b")) c.Assert(err, IsNil) c.Assert(out, Equals, nil) out, err = m.Route(request("http://google.com/a/b/")) c.Assert(err, IsNil) c.Assert(out, Equals, loc) } func (s *MatchSuite) TestMultipleLocations(c *C) { m := NewPathRouter() locA := &Loc{Name: "a"} locB := &Loc{Name: "b"} c.Assert(m.AddLocation("/a/there", locA), IsNil) c.Assert(m.AddLocation("/c", locB), IsNil) out, err := m.Route(request("http://google.com/a/there")) c.Assert(err, IsNil) c.Assert(out, Equals, locA) out, err = m.Route(request("http://google.com/c")) c.Assert(err, IsNil) c.Assert(out, Equals, locB) } func (s *MatchSuite) TestChooseLongest(c *C) { m := NewPathRouter() locA := &Loc{Name: "a"} locB := &Loc{Name: "b"} c.Assert(m.AddLocation("/a/there", locA), IsNil) c.Assert(m.AddLocation("/a", locB), IsNil) out, err := m.Route(request("http://google.com/a/there")) c.Assert(err, IsNil) c.Assert(out, Equals, locA) out, err = m.Route(request("http://google.com/a")) c.Assert(err, IsNil) c.Assert(out, Equals, locB) } func (s *MatchSuite) TestRemove(c *C) { m := NewPathRouter() locA := &Loc{Name: "a"} locB := &Loc{Name: "b"} c.Assert(m.AddLocation("/a", locA), IsNil) c.Assert(m.AddLocation("/b", locB), IsNil) out, err := m.Route(request("http://google.com/a")) c.Assert(err, IsNil) c.Assert(out, Equals, locA) out, err = m.Route(request("http://google.com/b")) c.Assert(err, IsNil) c.Assert(out, Equals, locB) // Remove the location and make sure the matcher is still valid c.Assert(m.RemoveLocation(m.GetLocationByPattern("/b")), IsNil) out, err = m.Route(request("http://google.com/a")) c.Assert(err, IsNil) c.Assert(out, Equals, locA) out, err = m.Route(request("http://google.com/b")) c.Assert(err, IsNil) c.Assert(out, Equals, nil) } func (s *MatchSuite) TestAddBad(c *C) { m := NewPathRouter() locA := &Loc{Name: "a"} locB := &Loc{Name: "b"} c.Assert(m.AddLocation("/a/there", locA), IsNil) out, err := m.Route(request("http://google.com/a/there")) c.Assert(err, IsNil) c.Assert(out, Equals, locA) c.Assert(m.AddLocation("--(", locB), Not(Equals), nil) out, err = m.Route(request("http://google.com/a/there")) c.Assert(err, IsNil) c.Assert(out, Equals, locA) } func (s *MatchSuite) BenchmarkMatching(c *C) { rndString := testutils.NewRndString() m := NewPathRouter() loc := &Loc{Name: "a"} for i := 0; i < 100; i++ { err := m.AddLocation(rndString.MakePath(20, 10), loc) c.Assert(err, IsNil) } req := request(fmt.Sprintf("http://google.com/%s", rndString.MakePath(20, 10))) for i := 0; i < c.N; i++ { m.Route(req) } } func request(url string) Request { u := MustParseUrl(url) return &BaseRequest{ HttpRequest: &http.Request{URL: u}, } }
package com.donetmvc.honey.miao import com.donetmvc.honey.miao.business.home.HomeFragment import com.donetmvc.honey.miao.core.activity.ProxyActivity import com.donetmvc.honey.miao.core.fragments.BaseFragment class MainActivity : ProxyActivity() { override fun setRootFragment(): BaseFragment? { return HomeFragment() } }
<?php use Doctrine\Common\Collections\ArrayCollection; /** * @Entity * @Table(name = "projects") */ class Project { /** * @Id * @Column(type = "integer") * @GeneratedValue */ public $id; /** * @Column(type = "string") */ public $name; /** * @Column(type = "string") */ public $description; /** * @OneToOne(targetEntity="Group", cascade="all") */ public $group; /** * @OneToMany(targetEntity="Entry", mappedBy="project", cascade="all") */ public $entries; /** * @OneToOne(targetEntity="Client", cascade="all") */ public $client; /** * @Column(type="string") */ public $start; /** * @Column(type="string") */ public $stop; public function __construct() { $this->entries = new ArrayCollection(); } function set_name($name) { $this->name = $name; } function set_decription($description) { $this->description = $description; } function set_group($group) { $this->group = $group; } function set_entries($entries) { $this->entries = $entries; } function set_client($client) { $this->client = $client; } function set_start($start) { $this->start = $start; } function set_stop($stop) { $this->stop = $stop; } } ?>
import Tool from '../utils/Tools'; export default class AudioFileDrop { public onMediaElementDropped: (source: string) => void; constructor() { const dropzone = Tool.$dom("dropzone"); dropzone.addEventListener("dragenter", this.handlerDragEnter, false); dropzone.addEventListener("dragover", this.handleDragOver, false); dropzone.addEventListener("dragleave", this.handlerDragLeave, false); dropzone.addEventListener("drop", this.handleFileDrop, false); } public register(x: (source: string) => void) { this.onMediaElementDropped = x; } private handlerDragEnter = (event) => { Tool.$dom("dropzone").style.border = "2px dashed purple"; } private handlerDragLeave = (event) => { Tool.$dom("dropzone").style.border = "2px dashed grey"; } private handleFileDrop = (event) => { event.stopPropagation(); event.preventDefault(); Tool.$dom("dropzone").style.border = "2px dashed green"; let $fileName = Tool.$dom("droped-file-name"); $fileName.textContent = `Name: ${event.dataTransfer.files[0].name}`; const file = event.dataTransfer.files[0]; if (!file.type.match("audio.*")) { $fileName.textContent = `ERROR! ${file.name} is not a valid audio file.`; return; } else { $fileName.textContent = `Name: ${file.name} (${file.type}, ${file.size} bytes) Now hit play!`; } // this.audioElement.src = window.URL.createObjectURL(file); const src = window.URL.createObjectURL(file); this.onMediaElementDropped(src); } private handleDragOver = (event) => { event.stopPropagation(); event.preventDefault(); event.dataTransfer.dropEffect = "copy"; Tool.$dom("dropzone").style.border = "2px dashed purple"; } }
truncate concept_relationship_stage ; insert into concept_relationship_stage ( concept_id_1, concept_id_2, concept_code_1, concept_code_2, vocabulary_id_1, vocabulary_id_2, relationship_id, valid_start_date, valid_end_date, invalid_reason ) select distinct null :: int4, null :: int4, cs.concept_code, c.concept_code, cs.vocabulary_id, c.vocabulary_id, rel_id, to_date ('19700101', 'yyyyddmm'), to_date ('20993112', 'yyyyddmm'), null :: varchar from concept_stage cs join mappings m on m.procedure_id = cs.concept_id join concept c on m.snomed_id = c.concept_id ; drop table if exists attr_insert ; create table attr_insert ( icd_code varchar, relationship_id varchar, attribute_id int4 ) ; -- explain insert into attr_insert --first, inherit all attributes from SNOMED ancestors; if SNOMED attribute is a descendant it will be used instead /*with attr_replace as ( select i.procedure_id, a.descendant_concept_id, i.attribute_id from icd10mappings i join ancestor_snomed a on i.attribute_id = a.ancestor_concept_id and i.concept_class_id != 'Procedure' )*/ select --distinct cs.concept_code, --by using code instead of id, we circumvent the need for SPLITTER table reusal sr.relationship_id, -- coalesce (ar.attribute_id, sr.concept_id_2) sr.concept_id_2 from mappings m join concept_stage cs on cs.concept_id = m.procedure_id join snomed_relationship sr on m.snomed_id = sr.concept_id_1 --Replace procedures' attributes with descendants when such are present in icd10mappings /*left join attr_replace ar on ar.procedure_id = cs.concept_id and sr.concept_id_2 = ar.descendant_concept_id*/ ; create index idx_attr_insert on attr_insert (icd_code,attribute_id) ; analyze attr_insert ; --remove duplicates --actually faster now --also eliminates has dir X/ has indir X -- DIRTY! delete from attr_insert a where exists ( select from attr_insert where (icd_code,attribute_id) = (a.icd_code,a.attribute_id) and a.ctid > ctid -- hardware adress ) ; -- Now get attributes from icd10mappings insert into attr_insert select distinct --attribute_id, attribute_name, concept_class_id procedure_code, null :: varchar, attribute_id from icd10mappings i where (i.procedure_code, i.attribute_id) not in (select icd_code,attribute_id from attr_insert) and i.concept_class_id not in ('Procedure', 'Context-dependent') --procedures too ; --if attribute has only one type of relations in concept_relationship table, pick it up with no_alts as ( select ai.attribute_id from snomed_relationship r join attr_insert ai on ai.relationship_id is null and ai.attribute_id = r.concept_id_2 group by ai.attribute_id having count (distinct r.relationship_id) = 1 ) update attr_insert set relationship_id = (select distinct relationship_id from snomed_relationship where concept_id_2 = attribute_id) where relationship_id is null and attribute_id in (select attribute_id from no_alts) ; update attr_insert set relationship_id = ( select case concept_class_id when 'Body Structure' then 'Has dir proc site' when 'Clinical Finding' then 'Has focus' when 'Observable Entity' then 'Has focus' when 'Pharma/Biol Product' then 'Using subst' when 'Physical Force' then 'Using energy' when 'Physical Object' then 'Using device' when 'Specimen' then 'Has specimen' when 'Substance' then 'Using subst' when 'Qualifier Value' then 'Has property' else 'Has component' --no other classes currently found end from concept where concept_id = attribute_id ) where relationship_id is null ; delete from attr_insert a where exists ( select from attr_insert x join ancestor_snomed s on s.descendant_concept_id = x.attribute_id and s.ancestor_concept_id = a.attribute_id and s.min_levels_of_separation != 0 where x.icd_code = a.icd_code --and x.relationship_id = a.relationship_id ) ; insert into concept_relationship_stage ( concept_id_1, concept_id_2, concept_code_1, concept_code_2, vocabulary_id_1, vocabulary_id_2, relationship_id, valid_start_date, valid_end_date, invalid_reason ) select null :: int4, null :: int4, a.icd_code, c.concept_code, 'ICD10PCS', c.vocabulary_id, a.relationship_id, to_date ('19700101', 'yyyyddmm'), to_date ('20993112', 'yyyyddmm'), null :: varchar from attr_insert a join concept c on c.concept_id = a.attribute_id ; delete from concept_relationship_stage i where exists ( select from concept_relationship_stage x where i.concept_code_1 = x.concept_code_1 and i.concept_code_2 = x.concept_code_2 and x.ctid > i.ctid ) ; --6. Add "subsumes" relationship between concepts where the concept_code is like of another CREATE INDEX IF NOT EXISTS trgm_idx ON concept_stage USING GIN (concept_code devv5.gin_trgm_ops); --for LIKE patterns INSERT INTO concept_relationship_stage ( concept_code_1, concept_code_2, vocabulary_id_1, vocabulary_id_2, relationship_id, valid_start_date, valid_end_date, invalid_reason ) SELECT c1.concept_code AS concept_code_1, c2.concept_code AS concept_code_2, c1.vocabulary_id AS vocabulary_id_1, c1.vocabulary_id AS vocabulary_id_2, 'Subsumes' AS relationship_id, ( SELECT latest_update FROM vocabulary WHERE vocabulary_id = c1.vocabulary_id ) AS valid_start_date, TO_DATE('20991231', 'yyyymmdd') AS valid_end_date, NULL AS invalid_reason FROM concept_stage c1, concept_stage c2 WHERE c2.concept_code LIKE c1.concept_code || '_' AND c1.concept_code <> c2.concept_code /* AND NOT EXISTS ( SELECT 1 FROM concept_relationship_stage r_int WHERE r_int.concept_code_1 = c1.concept_code AND r_int.concept_code_2 = c2.concept_code AND r_int.relationship_id = 'Subsumes' )*/ -- limit 100 ; DROP INDEX trgm_idx; ; --deprecate every old relationship entry; insert into concept_relationship_stage ( concept_code_1, concept_code_2, vocabulary_id_1, vocabulary_id_2, relationship_id, valid_start_date, valid_end_date, invalid_reason ) -- explain select c1.concept_code, c2.concept_code, c1.vocabulary_id, c2.vocabulary_id, cr.relationship_id, cr.valid_start_date, current_date - 1 as valid_end_date, 'D' from concept_relationship cr join concept c1 on c1.vocabulary_id = 'ICD10PCS' and c1.concept_id = cr.concept_id_1 join concept c2 on c2.vocabulary_id in (/*'ICD10PCS',*/ 'SNOMED') and c2.concept_id = cr.concept_id_2 and cr.relationship_id not in ('Maps to', 'Mapped from') where ( c1.concept_code, c2.concept_code, c1.vocabulary_id, c2.vocabulary_id, cr.relationship_id ) not in ( select concept_code_1, concept_code_2, vocabulary_id_1, vocabulary_id_2, relationship_id from concept_relationship_stage r /* union all select concept_code_2, concept_code_1, vocabulary_id_2, vocabulary_id_1, reverse_relationship_id from concept_relationship_stage r join relationship using (relationship_id)*/ ) ; --7. Add ICD10CM to RxNorm manual mappings -- DO $_$ -- BEGIN -- PERFORM VOCABULARY_PACK.ProcessManualRelationships(); -- END $_$; --8. Working with replacement mappings DO $_$ BEGIN PERFORM VOCABULARY_PACK.CheckReplacementMappings(); END $_$; --9. Deprecate 'Maps to' mappings to deprecated and upgraded concepts DO $_$ BEGIN PERFORM VOCABULARY_PACK.DeprecateWrongMAPSTO(); END $_$; --10. Add mapping from deprecated to fresh concepts DO $_$ BEGIN PERFORM VOCABULARY_PACK.AddFreshMAPSTO(); END $_$; --11. Delete ambiguous 'Maps to' mappings DO $_$ BEGIN PERFORM VOCABULARY_PACK.DeleteAmbiguousMAPSTO(); END $_$; truncate concept_relationship_manual; insert into concept_relationship_manual (concept_code_1,concept_code_2,vocabulary_id_1,vocabulary_id_2,relationship_id,valid_start_date,valid_end_date,invalid_reason) select concept_code_1,concept_code_2,vocabulary_id_1,vocabulary_id_2,relationship_id,valid_start_date,valid_end_date,invalid_reason from concept_relationship_stage
RSpec.describe Shopee::Api do it "has a version number" do expect(Shopee::VERSION).not_to be nil end describe "instance" do it "invalid params" do expect { Shopee::Api.new({}) }.to raise_error(ArgumentError) end it "valid params" do Shopee::Api.new({ partner_id: ENV["PARTNER_ID"], partner_key: ENV["PARTNER_KEY"], redirect_uri: ENV["REDIRECT_URI"], shopid: ENV["SHOPID"] }) end end end
import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger fun main() { val latch = CountDownLatch(10_000) val c = AtomicInteger() val start = System.currentTimeMillis() for (i in 1..10_000) { GlobalScope.launch { c.incrementAndGet() delay(100) c.incrementAndGet() latch.countDown() } } latch.await(10, TimeUnit.SECONDS) println("Executed ${c.get() / 2} coroutines in ${System.currentTimeMillis() - start}ms") }
<?php function Import($class) { include $class . '.php'; } spl_autoload_register('autoload'); $file = new File(); $array = $file::readCSVtoArray("../data/shoe.csv"); $obj = new CreateSQLTable(); $obj->createTaskTable($array[1],$array[0]);
package org.anowls.sys.domain import io.swagger.annotations.ApiModel import io.swagger.annotations.ApiModelProperty import org.hibernate.validator.constraints.Length import org.hibernate.validator.constraints.NotBlank import javax.persistence.Column import javax.persistence.Table @ApiModel(value = "功能项") @Table(name = "sys_feature") open class Feature( @ApiModelProperty(value = "应用id", required = true) @Column(name = "app_id") var appId: String = "", @ApiModelProperty(value = "模块id", required = true) @Column(name = "sm_id") var smId: String = "", @NotBlank(message = "功能编码必填!") @Length(max = 100, message = "功能编码长度不能超过100位!") @ApiModelProperty(value = "编码", required = true) @Column(name = "sf_code") var sfCode: String = "", @ApiModelProperty(value = "名称", required = true) @NotBlank(message = "功能名称必填!") @Length(max = 100, message = "功能名称长度不能超过100位!") @Column(name = "sf_name") var sfName: String = "", @ApiModelProperty(value = "描述") @Length(max = 150, message = "功能描述长度不能超过150位!") @Column(name = "sf_desc") var sfDesc: String? = null, @ApiModelProperty(value = "控制层名称", required = true) @Length(max = 150, message = "控制层名称长度不能超过150位!") @Column(name = "controller_name") var controllerName: String? = null, @ApiModelProperty(value = "Action名称", required = true) @Length(max = 150, message = "Action名称长度不能超过150位!") @Column(name = "action_name") var actionName: String? = null, @ApiModelProperty(value = "请求地址", required = true) @Length(max = 150, message = "请求地址长度不能超过150位!") @Column(name = "request_url") var requestUrl: String? = null, @ApiModelProperty(value = "是否菜单项 默认 0", required = true) @Column(name = "is_menu") var isMenu: Int = 0, @ApiModelProperty(value = "状态 (1 启用 0 停用) 默认1", required = true) @Column(name = "status") var status: Int = 1, @ApiModelProperty(value = "功能类型 (1 功能 2 小部件) 默认1", required = true) @Column(name = "sf_type") var sfType: Int = 1 ) : BaseDomain()
<ul> <li> <div class="image-wrap"><img src="bootstrap/img/mimos/nextflix-1.png"/></div> <div class="info"> <span class="school">NEXTFLIX</span> </div> </li> <li> <div class="image-wrap"><img src="bootstrap/img/mimos/uber-1.png"/></div> <div class="info"> <span class="school">UBER</span> </div> </li> <li> <div class="image-wrap"><img src="bootstrap/img/mimos/cinema-1.png"/></div> <div class="info"> <span class="school">CINEMA</span> </div> </li> <li> <div class="image-wrap"><img src="bootstrap/img/mimos/livros.png"/></div> <div class="info"> <span class="school">LIVROS</span> </div> </li> <li> <div class="image-wrap"><img src="bootstrap/img/mimos/congresso-cientifico.png"/></div> <div class="info"> <span class="school">CONGRESSO <br>CIENTIFICO</span> </div> </li> <li> <div class="image-wrap"><img src="bootstrap/img/mimos/spotify.png"/></div> <div class="info"> <span class="school">SPOTIFY</span> </div> </li> </ul>
# @type var x: Hash[Symbol, String?] x = { foo: "foo" } x = { foo: nil } x = { foo: 3 }
describe FastlaneCI do describe "docs" do Dir["app/features/*"].each do |feature_directory| next unless File.directory?(feature_directory) it "#{feature_directory} has a README.md" do readme_path = File.join(feature_directory, "README.md") expect(File.exist?(readme_path)).to eq(true), <<~MESSAGE Every directory in the `feature` area must have a README.md describing the scope and responsibilities of the classes (#{feature_directory}) MESSAGE content = File.read(readme_path) expect(content.length).to be > 20 expect(content).to start_with("# `#{feature_directory.gsub('app/', '')}`") end end Dir["app/services/*"].each do |service_directory| next unless File.directory?(service_directory) it "#{service_directory} has a README.md" do readme_path = File.join(service_directory, "README.md") expect(File.exist?(readme_path)).to eq(true), <<~MESSAGE Every directory in the `feature` area must have a README.md describing the scope and responsibilities of the classes (#{service_directory}) MESSAGE content = File.read(readme_path) expect(content).to start_with("# `#{service_directory.gsub('app/', '')}`") expect(content.length).to be > 20 end end end end
<?php /** * Easy permissions for users. * Copyright (c) 2017, Zdeněk Papučík */ namespace Component\Acl\Control; use Component\Acl\Entity; use Component\Acl\Repository; use Nette\Application\UI; /** * Permissions control. */ class Permissions extends Base { /** * @var Entity\Permissions */ private $entity; /** * @var Repository\Roles */ private $roles; /** * @var Repository\Resources */ private $resources; /** * @var Repository\Privileges */ private $privileges; /** * @var Repository\Permissions */ private $permissions; public function __construct( Entity\Permissions $entity, Repository\Roles $roles, Repository\Resources $resources, Repository\Privileges $privileges, Repository\Permissions $permissions) { $this->entity = $entity; $this->roles = $roles; $this->resources = $resources; $this->privileges = $privileges; $this->permissions = $permissions; } public function render() { $template = $this->template; $template->roles = $this->roles->findRoles(); $template->rules = $this->permissions->rules(); $template->privileges = $this->permissions->privileges(); $template->resources = $this->permissions->resources(); $template->form = $this['factory']; $template->setFile(__DIR__ . '/../templates/acl.permissions.latte'); $template->setTranslator($this->translator()); $template->render(); } /** * @return UI\Form */ protected function createComponentFactory() { $form = $this->createForm(); $form->setTranslator($this->translator()); $roles = []; foreach ($this->roles->all() as $role) { $roles[$role->roleId] = $role->name; } $form->addSelect('roleId', 'form.role', $roles) ->setPrompt('form.select.role.permissions') ->setRequired('form.required'); $resources = []; foreach ($this->resources->all() as $resource) { $resources[$resource->resourceId] = $resource->name; } $form->addSelect('resourceId', 'form.resource', $resources) ->setPrompt('form.select.resource') ->setRequired('form.required'); $privileges = []; foreach ($this->privileges->all() as $privilege) { $privileges[$privilege->privilegeId] = $privilege->name; } $form->addSelect('privilegeId', 'form.privilege', $privileges) ->setPrompt('form.select.privilege') ->setRequired('form.required'); $allowed = [ 'yes' => 'form.allowed.yes', 'no' => 'form.allowed.no' ]; $form->addSelect('allowed', 'form.allowed', $allowed) ->setPrompt('form.select.allowed') ->setRequired('form.required'); $form->addHidden('id'); $form->addSubmit('send', 'form.send'); $signal = $this->getSignal(); if ($signal) { if (in_array('edit', $signal)) { $item = $this->permissions->find($this->getParameter('id')); $form->setDefaults($item); } } $form->onSuccess[] = [$this, 'process']; return $form; } public function process(UI\Form $form) { $values = $form->values; $entity = $this->entity; $entity->setId($values->id); $entity->roleId = $values->roleId; $entity->resourceId = $values->resourceId; $entity->privilegeId = $values->privilegeId; $entity->allowed = $values->allowed; $this->permissions->save($entity); $values->id ? $this->flashMessage($this->translate('message.update.permissions')) : $this->flashMessage($this->translate('message.insert.permissions'), 'success'); if ($this->isAjax()) { $form->setValues([], true); $this->redrawControl('items'); $this->redrawControl('factory'); } } /** * @param int $id */ public function handleEdit($id = 0) { $item = $this->permissions->find($id); $item ?: $this->error(); $form = $this['factory']; $form['send']->caption = 'form.send.update'; if ($this->isAjax()) { $this->presenter->payload->toggle = 'permissions'; $this->redrawControl('items'); $this->redrawControl('factory'); } } /** * @param int $id */ public function handleDelete($id = 0) { $item = $this->permissions->find($id); $item ?: $this->error(); $this->permissions->delete($id); $this->flashMessage($this->translate('message.delete.permissions')); if ($this->isAjax()) { $this->redrawControl('items'); $this->redrawControl('factory'); } } }
--- layout: post title: "About Me" excerpt: "Tentang Nadia Gustiana" tags: [sample post] comments: true image: feature: web2.jpg credit: Nadia Gustiana creditlink: http://nadiagustiana.github.io/ --- <p>BIODATA</p> <p>Nama : Nadia Gustiana</p> <p>TTL : Rantauprapat, 24 Januari 1995</p> <p>Jurusan : <a href= "http://sif.uin-suska.ac.id/">Sistem Informasi</a></p> <p>Fakultas : <a href= "http://fst.uin-suska.ac.id/">Sains dan teknologi</a></p> <p>Universitas : <a href= "http://uin-suska.ac.id/">Universitas Islam Negeri Sultan Syarif Kasim Riau</a></p> <p>Angkatan : 2013</p> <p>Kelas : A</p>
const debug = require('debug')('user-service:initDb') const path = require('path') let migrationRetries = 2 const runMigrations = async db => { try { await db.migrate.latest({ directory: path.join(__dirname, '..', '..', 'migrations') }) debug('DB Migrations Ran', `Environment: ${process.env.NODE_ENV}`) } catch (err) { debug(`Migrations failed will retry ${migrationRetries + 1} more times starting in 5 seconds.`) if (migrationRetries >= 0) { setTimeout(() => { migrationRetries-- runMigrations(db) }, 5000) } } } const initDb = async (db) => { try { // check the connection debug('Testing Database Connection') await db.raw('select 1+1 as result') debug('Database Connection Successful') // run migrations await runMigrations(db) } catch (err) { debug(err) throw new Error(err) } } module.exports = initDb
@testset "971.flip-binary-tree-to-match-preorder-traversal.jl" begin @test flip_match_voyage(TreeNode(1, TreeNode(2), nothing), [2, 1]) == [-1] @test flip_match_voyage(TreeNode(1, TreeNode(2), TreeNode(3)), [1, 3, 2]) == [1] @test flip_match_voyage(TreeNode(1, TreeNode(2), TreeNode(3)), [1, 2, 3]) == Int[] end
maintainer "Heavy Water Software Inc." maintainer_email "[email protected]" license "Apache 2.0" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "3.1.2" description "Installs/Configures graphite" depends "python" depends "apache2" depends "runit" depends "ganglia" depends "install_from" depends "silverware" recipe "graphite::carbon", "Carbon" recipe "graphite::default", "Base configuration for graphite" recipe "graphite::ganglia", "Ganglia" recipe "graphite::dashboard", "Web Dashboard" recipe "graphite::whisper", "Whisper" %w[ debian ubuntu ].each do |os| supports os end attribute "graphite/conf_dir", :display_name => "", :description => "", :default => "/etc/graphite/" attribute "graphite/home_dir", :display_name => "", :description => "", :default => "/usr/local/share/graphite/" attribute "graphite/data_dir", :display_name => "", :description => "", :default => "/var/lib/graphite/storage/" attribute "graphite/log_dir", :display_name => "", :description => "", :default => "/var/log/graphite/" attribute "graphite/pid_dir", :display_name => "", :description => "", :default => "/var/run/graphite" attribute "graphite/user", :display_name => "", :description => "", :default => "www-data" attribute "graphite/carbon/line_rcvr_addr", :display_name => "", :description => "", :default => "127.0.0.1" attribute "graphite/carbon/pickle_rcvr_addr", :display_name => "", :description => "", :default => "127.0.0.1" attribute "graphite/carbon/cache_query_addr", :display_name => "", :description => "", :default => "127.0.0.1" attribute "graphite/carbon/user", :display_name => "", :description => "", :default => "www-data" attribute "graphite/carbon/version", :display_name => "", :description => "", :default => "0.9.7" attribute "graphite/carbon/release_url", :display_name => "", :description => "", :default => "http://launchpadlibrarian.net/61904798/carbon-0.9.7.tar.gz" attribute "graphite/carbon/release_url_checksum", :display_name => "", :description => "", :default => "ba698aca" attribute "graphite/whisper/version", :display_name => "", :description => "", :default => "0.9.7" attribute "graphite/whisper/release_url", :display_name => "", :description => "", :default => "http://launchpadlibrarian.net/61904764/whisper-0.9.7.tar.gz" attribute "graphite/whisper/release_url_checksum", :display_name => "", :description => "", :default => "c6272ad6" attribute "graphite/dashboard/version", :display_name => "", :description => "", :default => "0.9.7c" attribute "graphite/dashboard/release_url", :display_name => "", :description => "", :default => "http://launchpadlibrarian.net/62379635/graphite-web-0.9.7c.tar.gz" attribute "graphite/dashboard/release_url_checksum", :display_name => "", :description => "", :default => "a3e16265" attribute "users/graphite/uid", :display_name => "", :description => "", :default => "446" attribute "groups/graphite/gid", :display_name => "", :description => "", :default => "446"
#!/bin/sh git clone -b 1.13.0 --depth=1 https://github.com/telefonicaid/iotagent-json.git cd iotagent-json/docker sudo docker build -t iotagent-json:1.13.0 . sudo docker images | grep iotagent-json
# CentOS 7 Packaging Packages for the latest stable release or the currently cloned source can be built using GNU Make. An RPM build environment will be created under the current users home directory. Packages will reside in $(HOME)/rpmbuild/RPMS/x86_64. ## Prerequisites $ sudo yum install rpm-build redhat-rpm-config rpmdevtools yum-utils ## Package Stable $ sudo yum-builddep kismet.spec $ make ## Package Source Snapshot $ make spec $ sudo yum-builddep kismet-git.spec $ make snapshot
module RETS4R class Client class ObjectHeader < Hash include Net::HTTPHeader def initialize(raw_header) initialize_http_header( raw_header ) end end # Represents a RETS object (as returned by the get_object) transaction. class DataObject attr_accessor :header, :data alias :type :header alias :info :type def initialize(headers, data) @header = ObjectHeader.new(headers) @data = data end def success? return true if self.data return false end end end end
plugins { id("java.infra") } dependencies { implementation("org.springframework.cloud:spring-cloud-starter-config") implementation("org.springframework.cloud:spring-cloud-starter-netflix-eureka-server") } tasks.bootJar { archiveFileName.set("registry.jar") launchScript() }
package com.inari.experimental.maxonmoon; import com.badlogic.gdx.Input; import com.inari.commons.geom.PositionF; import com.inari.commons.geom.Rectangle; import com.inari.commons.graphics.RGBColor; import com.inari.experimental.maxonmoon.TileLayerMapping.GameLayer; import com.inari.firefly.asset.Asset; import com.inari.firefly.control.Controller; import com.inari.firefly.control.task.Task; import com.inari.firefly.controller.view.SimpleCameraController; import com.inari.firefly.graphics.TextureAsset; import com.inari.firefly.graphics.sprite.SpriteAsset; import com.inari.firefly.graphics.view.Layer; import com.inari.firefly.graphics.view.View; import com.inari.firefly.system.external.FFInput; import com.inari.firefly.system.external.FFInput.ButtonType; public final class LoadGame extends Task { protected LoadGame( int id ) { super( id ); } @Override public final void runTask() { createInput(); createViews(); loadAssets(); } private void loadAssets() { context.getComponentBuilder( Asset.TYPE_KEY, TextureAsset.class ) .set( TextureAsset.NAME, Names.TEXTURES.GAME_TILE_TEXTURE ) .set( TextureAsset.RESOURCE_NAME, "assets/maxonmoon/MaxOnMoonTiles.png" ) .activate(); for ( TileSetA tile : TileSetA.values() ) { context.getComponentBuilder( Asset.TYPE_KEY, SpriteAsset.class ) .set( SpriteAsset.NAME, tile.name() ) .set( SpriteAsset.TEXTURE_ASSET_NAME, Names.TEXTURES.GAME_TILE_TEXTURE ) .set( SpriteAsset.TEXTURE_REGION, new Rectangle( tile.textureXPos * 8, tile.textureYPos * 8, 8, 8 ) ) .set( SpriteAsset.HORIZONTAL_FLIP, tile.flipHorizontal ) .set( SpriteAsset.VERTICAL_FLIP, tile.flipVertical ) .activate(); } TileLayerMapping tileLayerMapping = new TileLayerMapping(); tileLayerMapping.init( context ); context.setProperty( Names.PROPERTIES.TILE_LAYER_MAPPING_KEY, tileLayerMapping ); // Player Assets context.getComponentBuilder( Asset.TYPE_KEY, PlayerAsset.class ) .activate(); // activate the player: this may happen later when loading the room!? PlayerAsset playerAsset = context.getSystemComponent( Asset.TYPE_KEY, Names.PLAYER.NAME, PlayerAsset.class ); playerAsset.activate( context ); Room room0 = new Room0(); room0.loadRoom( context ); } private void createViews() { Integer _zoomFactor = context.getProperty( Names.PROPERTIES.ZOOM_FACTOR_TYPE_KEY ); int zoomFactor = _zoomFactor != null? _zoomFactor.intValue() : 4; float zoom = 1f / zoomFactor; int one = 8 * zoomFactor; int width = 20 * one; int height = 15 * one; context.getComponentBuilder( Controller.TYPE_KEY, SimpleCameraController.class ) .set( SimpleCameraController.NAME, Names.CONTROLLER.GAME_CAMERA_CONTROLLER ) .build(); context.getComponentBuilder( View.TYPE_KEY ) .set( View.NAME, Names.VIEWS.GAME_STATUS_VIEW ) .set( View.BOUNDS, new Rectangle( 0, 0, width, one ) ) .set( View.WORLD_POSITION, new PositionF( 0, 0 ) ) .set( View.CLEAR_COLOR, new RGBColor( 0f, 0f, 0f, 1f ) ) .set( View.ZOOM, zoom ) .activate(); context.getComponentBuilder( View.TYPE_KEY ) .set( View.NAME, Names.VIEWS.GAME_MAIN_VIEW ) .set( View.BOUNDS, new Rectangle( 0, one, width, height ) ) .set( View.WORLD_POSITION, new PositionF( 0, 0 ) ) .set( View.CLEAR_COLOR, new RGBColor( .8f, .8f, .8f, 1 ) ) .set( View.ZOOM, zoom ) .set( View.LAYERING_ENABLED, true ) .set( View.CONTROLLER_NAME, Names.CONTROLLER.GAME_CAMERA_CONTROLLER ) .activate(); for ( GameLayer layer : GameLayer.values() ) { context.getComponentBuilder( Layer.TYPE_KEY ) .set( Layer.VIEW_NAME, Names.VIEWS.GAME_MAIN_VIEW ) .set( Layer.NAME, layer.name() ) .build(); } context.getComponentBuilder( View.TYPE_KEY ) .set( View.NAME, Names.VIEWS.GAME_INVENTORY_VIEW ) .set( View.BOUNDS, new Rectangle( 0, 16 * one, width, one ) ) .set( View.WORLD_POSITION, new PositionF( 0, 0 ) ) .set( View.CLEAR_COLOR, new RGBColor( 0f, 0f, 0f, 0f ) ) .set( View.ZOOM, zoom ) .activate(); } private void createInput() { FFInput input = context.getInput(); input.mapKeyInput( ButtonType.UP, Input.Keys.W ); input.mapKeyInput( ButtonType.DOWN, Input.Keys.S ); input.mapKeyInput( ButtonType.RIGHT, Input.Keys.D ); input.mapKeyInput( ButtonType.LEFT, Input.Keys.A ); input.mapKeyInput( ButtonType.FIRE_1, Input.Keys.SPACE ); input.mapKeyInput( ButtonType.ENTER, Input.Keys.ENTER ); input.mapKeyInput( ButtonType.QUIT, Input.Keys.ESCAPE ); } }
<?php /** * Created by PhpStorm. * User: macbook * Date: 2020-02-15 * Time: 22:17 */ namespace api\sns\controller; use api\sns\model\SnsTopicFollowModel; use api\sns\model\SnsTopicModel; use api\sns\service\TopicService; use api\sns\validate\IdMustValidate; use api\sns\validate\TopicFiledValidate; use cmf\controller\RestUserBaseController; class TopicController extends RestUserBaseController { /** * POST 添加 */ public function add() { if ($this->request->isPost()) { $params = $this->request->post(); $validate = new TopicFiledValidate(); if (!$validate->scene('add')->check($params)) { $this->error($validate->getError()); } // 先判断话题名称是否已经存在 $findTopic = SnsTopicModel::where('title', $params['title'])->find(); if ($findTopic) { $this->error('该话题已存在'); } $topic = SnsTopicModel::create([ 'title' => $params['title'], 'des' => $params['des'], 'icon_path' => $params['icon_path'], 'follow_name' => $params['follow_name'], 'create_uid'=> $this->userId, 'type' => 0, // 未审核 ]); if ($topic) { $this->success('添加成功,等待审核', $topic); } $this->error('添加失败'); } } /** * GET 获取所有我创建的话题 */ public function myTopics() { if ($this->request->isGet()) { $params = [ 'create_uid' => $this->userId, ]; $topicService = new TopicService(); $result = $topicService->topicList($params); $this->success('成功', $result); } } /** * GET 获取所有我关注的话题 */ public function follow() { if ($this->request->isGet()) { $topicFollow = new SnsTopicFollowModel(); $result = $topicFollow ->with(['topic']) ->where('user_id', $this->userId) ->order('create_at', 'desc') ->select(); $this->success('获取成功', $result); } } /** * 获取为我推荐的话题 */ public function recommend() { // 1、我没有关注的 // 2、我可能关注的 } }
#!/usr/bin/env bash set -euo pipefail experiment_dir=$1 #"/home/joe/professional/research/NUFEB-cyanobacteria/data/exploratory/fourth_test_with_dist/" find $experiment_dir -type d -wholename '*Run_[0-9]*_[0-9]*/Results/shape*' -exec echo {} > sim_dirs.txt \; # choosing to do these as two separate blocks, one for atom size metadata # and one for point pattern metadta. Could interleave but messy. There # is some repeated code which could probably be pulled into a function # gather the atom size metadata first_dir="$(head -n 1 sim_dirs.txt)" header="$(head -n 1 $first_dir"/atom_sizes.csv")" echo $header > gathered_atom_sizes.csv for p in `cat sim_dirs.txt` do p1="$(dirname "$p")" p2="$(dirname "$p1")" runname="$(basename "$p2")" file=$p"/atom_sizes.csv" tail -n +2 $file >> gathered_atom_sizes.csv done # gather the point pattern metadata first_dir="$(head -n 1 sim_dirs.txt)" header="$(head -n 1 $first_dir"/spatial_distribution.csv")" echo $header > gathered_spatial_distributions.csv for p in `cat sim_dirs.txt` do p1="$(dirname "$p")" p2="$(dirname "$p1")" runname="$(basename "$p2")" file=$p"/spatial_distribution.csv" tail -n +2 $file >> gathered_spatial_distributions.csv done
<?php namespace Victorlap\Mapp\Tests\Stubs; use Victorlap\Mapp\Attributes\ListAttribute; class Company { public string $name; public Address $address; /** * @var Employee[] */ #[ListAttribute(Employee::class)] public array $employees; }
package org.watsi.device.factories import org.threeten.bp.Clock import org.threeten.bp.Instant import org.watsi.device.db.daos.PriceScheduleDao import org.watsi.device.db.models.PriceScheduleModel import java.util.UUID object PriceScheduleModelFactory { fun build( id: UUID = UUID.randomUUID(), issuedAt: Instant = Instant.now(), billableId: UUID = UUID.randomUUID(), price: Int = 10, previousPriceScheduleModelId: UUID? = null, createdAt: Instant? = null, updatedAt: Instant? = null, clock: Clock = Clock.systemUTC() ): PriceScheduleModel { val now = Instant.now(clock) return PriceScheduleModel( id = id, issuedAt = issuedAt, billableId = billableId, price = price, previousPriceScheduleId = previousPriceScheduleModelId, createdAt = now, updatedAt = now ) } fun create( priceScheduleDao: PriceScheduleDao, id: UUID = UUID.randomUUID(), issuedAt: Instant = Instant.now(), billableId: UUID = UUID.randomUUID(), price: Int = 10, previousPriceScheduleModelId: UUID? = null, createdAt: Instant? = null, updatedAt: Instant? = null, clock: Clock = Clock.systemUTC() ): PriceScheduleModel { val model = build( id = id, issuedAt = issuedAt, billableId = billableId, price = price, previousPriceScheduleModelId = previousPriceScheduleModelId, createdAt = createdAt, updatedAt = updatedAt, clock = clock ) priceScheduleDao.insert(model) return model } }
class CreatePeople < ActiveRecord::Migration[5.2] def change create_table :people do |t| t.string :document_number, index: { unique: true }, null: false t.string :name, null: false t.string :lastname, null: true t.date :born_date, null: true t.timestamp :deleted_at # soft deleted t.timestamps end end end
qm destroy 9000 qm create 9000 --name "ubuntu-2110-cloudinit-template" --memory 2048 --net0 virtio,bridge=vmbr0 qm importdisk 9000 ubuntu-21.10-server-cloudimg-amd64.qcow2 local-lvm qm set 9000 --scsihw virtio-scsi-pci --scsi0 local-lvm:vm-9000-disk-0 qm set 9000 --ide2 local-lvm:cloudinit qm set 9000 --boot c --bootdisk scsi0 qm set 9000 --serial0 socket --vga serial0 qm template 9000
package org.scalaide.extensions package saveactions import org.scalaide.core.text.Remove import org.scalaide.util.eclipse.RegionUtils._ object RemoveDuplicatedEmptyLinesSetting extends SaveActionSetting( id = ExtensionSetting.fullyQualifiedName[RemoveDuplicatedEmptyLines], name = "Remove duplicated empty lines", description = "Removes duplicated (consecutive) empty lines.", codeExample = """|class Test { | | | | val value = 0 | |}""".stripMargin ) trait RemoveDuplicatedEmptyLines extends SaveAction with DocumentSupport { override def setting = RemoveDuplicatedEmptyLinesSetting override def perform() = { val emptyLines = document.lines.zipWithIndex.filter { case (r, _) => r.trimRight(document).length == 0 } def removedLines = emptyLines.sliding(2) flatMap { case Seq((l1, i1), (l2, i2)) => if (i1+1 == i2) Seq(Remove(l1.start, l1.end+1)) else Seq() } if (emptyLines.lengthCompare(1) == 0) Nil else removedLines.toList } }
-- file:plpgsql.sql ln:1337 expect:true insert into PSlot values ('PS.first.tb2', 'PF1_2', '', '')
import { By, until } from 'selenium-webdriver'; import { imageSnapshotOptions, timeouts } from './constants.json'; import minNumActivitiesShown from './setup/conditions/minNumActivitiesShown'; import scrollToBottomCompleted from './setup/conditions/scrollToBottomCompleted'; import uiConnected from './setup/conditions/uiConnected'; // selenium-webdriver API doc: // https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebDriver.html // jest.setTimeout(timeouts.test); jest.setTimeout(15000); describe('hero card actions', () => { let driver; async function clickHeroCardButton(nthChild) { await driver.wait( () => driver.executeScript(nthChild => { const button = document.querySelector('.ac-actionSet button:nth-of-type(' + nthChild + ')'); button && button.click(); return button; }, nthChild), timeouts.ui ); } beforeEach(async () => { const setup = await setupWebDriver({ useProductionBot: true }); driver = setup.driver; await driver.wait(uiConnected(), timeouts.directLine); await setup.pageObjects.sendMessageViaSendBox('herocardactions'); await driver.wait(minNumActivitiesShown(2), timeouts.directLine); }); test('imBack', async () => { await clickHeroCardButton(1); await driver.wait(minNumActivitiesShown(4), timeouts.directLine); await driver.wait(scrollToBottomCompleted(), timeouts.scrollToBottom); expect(await driver.takeScreenshot()).toMatchImageSnapshot(imageSnapshotOptions); }); test('postBack (string)', async () => { await clickHeroCardButton(2); await driver.wait(minNumActivitiesShown(3), timeouts.directLine); await driver.wait(scrollToBottomCompleted(), timeouts.scrollToBottom); expect(await driver.takeScreenshot()).toMatchImageSnapshot(imageSnapshotOptions); }); test('postBack (JSON)', async () => { await clickHeroCardButton(3); await driver.wait(minNumActivitiesShown(3), timeouts.directLine); await driver.wait(scrollToBottomCompleted(), timeouts.scrollToBottom); expect(await driver.takeScreenshot()).toMatchImageSnapshot(imageSnapshotOptions); }); test('messageBack (displayText + text + value)', async () => { await clickHeroCardButton(4); await driver.wait(minNumActivitiesShown(4), timeouts.directLine); await driver.wait(scrollToBottomCompleted(), timeouts.scrollToBottom); expect(await driver.takeScreenshot()).toMatchImageSnapshot(imageSnapshotOptions); }); test('messageBack (displayText + text)', async () => { await clickHeroCardButton(5); await driver.wait(minNumActivitiesShown(4), timeouts.directLine); await driver.wait(scrollToBottomCompleted(), timeouts.scrollToBottom); expect(await driver.takeScreenshot()).toMatchImageSnapshot(imageSnapshotOptions); }); test('messageBack (value)', async () => { await clickHeroCardButton(6); await driver.wait(minNumActivitiesShown(3), timeouts.directLine); await driver.wait(scrollToBottomCompleted(), timeouts.scrollToBottom); expect(await driver.takeScreenshot()).toMatchImageSnapshot(imageSnapshotOptions); }); });
import numpy as np from panel.planet_data import PLANET_DATA from panel.telemetry.telemetry import Telemetry class EllipseData(Telemetry): @property def _c(self): return (self.apoapsis - self.periapsis) / 2.0 @property def focus_x(self): return self._c @property def focus_y(self): return 0 @property def width(self): return 2 * self.semi_major_axis @property def height(self): return 2 * self.semi_minor_axis @property def proj_equ_width(self): x, y = self.projection(self.width, 0) return np.sqrt(x**2 + y**2) @property def proj_equ_height(self): x, y = self.projection(0, self.height) return np.sqrt(x**2 + y**2)
import { Manager, Socket } from 'socket.io-client'; import { Utils } from './Utils'; export default class SocketIOClient { private static instance: SocketIOClient; private socketIO: Socket; // eslint-disable-next-line no-useless-constructor private constructor() {} public get socket() { if (this.socketIO) { return this.socketIO; } return null; } public static getInstance(): SocketIOClient { if (!SocketIOClient.instance) { SocketIOClient.instance = new SocketIOClient(); } return SocketIOClient.instance; } public connectAuthenticated(serverURL: string, token: string, connectCallback: () => void = () => { }) { // Check if (!this.socketIO && serverURL && token) { // Init and connect Socket IO client const manager = new Manager(serverURL, { query: { auth_token: token }, transports: ['websocket'], }); this.socketIO = manager.socket('/'); } else if (this.socketIO?.disconnected) { // Connect Socket IO this.socketIO.connect(); } else { Utils.consoleDebugLog('SocketIO client connection: missing serverURL and token arguments'); } this.socketIO.on('connect', () => { Utils.consoleDebugLog(`SocketIO client is connected`); connectCallback(); }); this.socketIO.on('authenticated', (data) => { Utils.consoleDebugLog(data?.message); }); this.socketIO.on('connect_timeout', (timeout) => { Utils.consoleDebugLog(`SocketIO client connection timeout: ${timeout}`); }); this.socketIO.on('connect_error', (error) => { Utils.consoleDebugLog(`SocketIO client connect error: ${error}`); }); this.socketIO.on('reconnecting', (attempt) => { Utils.consoleDebugLog(`SocketIO client #${attempt} try to reconnect`); }); this.socketIO.on('reconnect_error', (error) => { Utils.consoleDebugLog(`SocketIO client reconnect error: ${error}`); }); } public disconnect() { if (this.socketIO) { this.socketIO.disconnect(); } this.socketIO = null; } }
package ru.otus.vsh.hw16.messagesystem.client; import org.springframework.stereotype.Component; import ru.otus.vsh.hw16.messagesystem.common.MessageData; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Component public class CallbackRegistryImpl implements CallbackRegistry { private final Map<CallbackId, MessageCallback<? extends MessageData>> callbackRegistry = new ConcurrentHashMap<>(); @Override public <T extends MessageData> void put(CallbackId id, MessageCallback<T> callback) { callbackRegistry.put(id, callback); } @SuppressWarnings("unchecked") @Override public <T extends MessageData> MessageCallback<T> getAndRemove(CallbackId id) { return (MessageCallback<T>) callbackRegistry.remove(id); } }
# Twitter WikidataMeter Bot I'm the code, and deployment of Twitter bot [WikidataMeter](https://twitter.com/WikidataMeter). I tweet a few fun things about Wikidata as it grows. ## Tweets Feel free to suggest more tweets by creating an Github issue. ### Everytime another 1,000,000 edits happens Bot checks this data every 30 minutes, the value that is checked is live. ![](https://i.imgur.com/Nr9MSVQ.png) ### Everytime Item count crosses a 1,000,000 boundary Bot checks this data every 30 minutes, the value that is checked is calculated once a day. Screenshot comming soon... ### Everytime Property count crosses a 100 boundary Bot checks this data every 30 minutes, the value that is checked is calculated once a day. Screenshot comming soon... ### Everytime Lexeme count crosses a 10,000 boundary Bot checks this data every 30 minutes, the value that is checked is calculated once a day. Screenshot comming soon... ## Development You'll need to install my dependencies using composer. ```sh composer install ``` And in order to fully integrate with the services you'll need to populate a `.env` file. Checkout `.env.example` for what is needed. Then just run the main script. ```sh php run.php ``` ## Deployment I run on Github Actions on a cron using a docker container. You can build the docker container using the following. ```sh docker build . -t twitter-wikidatameter ``` ## Makes use of Services: - [Github Actions](https://github.com/features/actions) - Building Docker images & running the cron for the bot - [Wikidata](https://www.wikidata.org) - Getting the edit data (live) - [Wikimedia Graphite](graphite.wikimedia.org) - Getting entity count data (daily) - [JSONStorage.net](https://www.jsonstorage.net/) - Some persistence between runs - [Twitter](https://www.twitter.com) - For publishing the tweets Libraries: - [addwiki/mediawiki-api-base](https://github.com/addwiki/mediawiki-api-base) - Talking to the Wikidata API - [atymic/twitter](https://github.com/atymic/twitter) - Talking to the Twitter API - [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv) - Reading env vars from a .env file - [guzzlehttp/guzzle](https://github.com/guzzle/guzzle) - Talking to the JSONStorage.net API
import React, { useState } from "react"; import Slider from "@material-ui/core/Slider"; import { makeStyles, withStyles } from "@material-ui/core/styles"; import { useSelector } from "react-redux"; import Tooltip from "@material-ui/core/Tooltip"; import moment from "moment"; import { useTranslation } from "react-i18next"; import { useThunkDispatch } from "../useThunkDispatch"; import { formatNowMinusDays, plusDays } from "../lib/formatUTCDate"; import { State } from "../state"; import { AppApi } from "../state/app"; import { config } from "app-config/index"; import { diffDays } from "../lib/diff-days"; export type Props = { onChange?: Function | null; }; const TouchSlider = withStyles({ thumb: { height: 28, width: 28, marginTop: -14, marginLeft: -14, }, mark: { height: 8, width: 1, marginTop: -3, }, })(Slider); const useStyles = makeStyles((theme) => ({ slider: { touchAction: "none", pointerEvents: "initial", }, [theme.breakpoints.down("xs")]: { slider: { display: "none", }, }, })); const MAX_SLIDER_VALUE = 0; let timeout: any = 0; export function TimeRangeSlider({ onChange = () => {} }: Props) { const classes = useStyles(); const dispatch = useThunkDispatch(); const currentDate = useSelector((state: State) => state.app.currentDate); const [value, setValue] = useState<number>(() => { const today = moment.utc(); const diff = diffDays(today, currentDate); return Math.min(diff, MAX_SLIDER_VALUE); }); function valuetext(value) { return formatNowMinusDays(value); } function onSliderChange(event, value) { setValue(value); } function onDayChange(event, value) { const newDate = plusDays(value); const diff = diffDays(newDate, currentDate); if (diff === 0) { return; } clearTimeout(timeout); timeout = setTimeout( (t) => { (onChange as Function)(newDate); dispatch(AppApi.setCurrentDate(newDate)); }, 150, timeout, ); } return ( <TouchSlider className={classes.slider} defaultValue={0} value={value} getAriaValueText={valuetext} onChange={onSliderChange} onChangeCommitted={onDayChange} aria-labelledby="discrete-slider-small-steps" step={1} marks min={-15} max={0} valueLabelDisplay="auto" ValueLabelComponent={ValueLabelComponent} /> ); } export type ValueLabelComponentProps = { children: any; open: boolean; value: number; }; const SliderLabelTooltip = withStyles({ tooltip: { fontSize: 20, marginBottom: 30, }, })(Tooltip); function ValueLabelComponent({ children, open, value }: ValueLabelComponentProps) { const currentVisual = useSelector((state: State) => state.app.currentVisual); const visual = config.visuals[currentVisual]; const { t } = useTranslation(["translation"]); const dateValue = typeof visual.dateFormat === "function" ? visual.dateFormat(t, { date: plusDays(value).toDate() }) : moment(plusDays(value)).format(visual.dateFormat); return ( <SliderLabelTooltip open={open} enterTouchDelay={0} placement="top" title={dateValue}> {children} </SliderLabelTooltip> ); }
import type { TileDocument } from '@ceramicnetwork/stream-tile' import type { Schema } from '@glazed/types' export type CollectionContent = { sliceMaxItems: number slicesCount: number } export type CollectionDoc = TileDocument<CollectionContent> export type CollectionSchema = Schema<CollectionContent> export type SliceContent<Item> = { collection: string sliceIndex: number contents: Array<Item | null> } export type SliceDoc<Item> = TileDocument<SliceContent<Item>> export type SliceSchema<Item> = Schema<SliceContent<Item>>
/* * @Date: 2021-04-04 19:01:23 * @Author: Mengsen Wang * @LastEditors: Mengsen Wang * @LastEditTime: 2021-04-04 19:15:06 */ #[allow(non_snake_case)] fn longest_common_subsequence(text1: String, text2: String) -> i32 { let N = text1.len(); let M = text2.len(); let mut dp = vec![vec![0; M + 1]; N + 1]; for i in 0..N { for j in 0..M { if text1.as_bytes()[i] == text2.as_bytes()[j] { dp[i + 1][j + 1] = dp[i][j] + 1; } else { dp[i + 1][j + 1] = dp[i][j + 1].max(dp[i + 1][j]); } } } dp[N][M] } fn main() { let text1 = "abcde".to_string(); let text2 = "ace".to_string(); assert_eq!(longest_common_subsequence(text1, text2), 3); let text1 = "abc".to_string(); let text2 = "abc".to_string(); assert_eq!(longest_common_subsequence(text1, text2), 3); let text1 = "abc".to_string(); let text2 = "def".to_string(); assert_eq!(longest_common_subsequence(text1, text2), 0); }
<?php namespace App\Http\Controllers; use App\Label; use App\Photo; use App\Room; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Response; class HomeController extends Controller { function home() { $data['title'] = 'My home page'; $data['currentView'] = 'home'; return view('frontend', $data); } }
DROP TABLE IF EXISTS `persons`; CREATE TABLE `persons` ( `email` varchar(100), `id` int NOT NULL, `nick` varchar(100), PRIMARY KEY (`id`) );
module.exports = function ajaxRequest(conf) { return new Promise((ok, ko) => { conf.onerror = (err) => ko(err); conf.onload = (res) => res.status < 400 ? ok(res) : ko(`${res.status} - ${res.statusText}`); GM_xmlhttpRequest(conf); }) .then(res=>res.response); };
### Class in Production import pickle class RentPrices(object): def __init__(self): self.one_hot_enc = pickle.load(open('parameters/one_hot_enc.pkl','rb')) self.stand_scaler = pickle.load(open('parameters/stand_scaler.pkl','rb')) def data_preparation(self, df): # One_Hot_Encoding X1 = self.one_hot_enc.transform(df) # Standard_Scaler X = self.stand_scaler.transform(X1) return X
package org.scaffoldeditor.cmd.commands; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.tree.LiteralCommandNode; import static org.scaffoldeditor.cmd.CommandUtil.*; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import org.scaffoldeditor.cmd.CommandUtil; import org.scaffoldeditor.cmd.ScaffoldCommandSource; import org.scaffoldeditor.cmd.ScaffoldTerminalContext; import org.scaffoldeditor.cmd.arguments.PathArgumentType; import org.scaffoldeditor.scaffold.core.Constants; import org.scaffoldeditor.scaffold.core.Project; import static com.mojang.brigadier.arguments.StringArgumentType.*; public class ProjectCommand { public static void register(CommandDispatcher<ScaffoldCommandSource> dispatcher) { LiteralCommandNode<ScaffoldCommandSource> project = literal("project").build(); build(project); dispatcher.getRoot().addChild(project); } private static void build(LiteralCommandNode<ScaffoldCommandSource> root) { LiteralCommandNode<ScaffoldCommandSource> open = literal("open") .then(CommandUtil.argument("path", PathArgumentType.path()) .executes(command -> { Path path = PathArgumentType.getPath(command, "path"); command.getSource().getOut().println("Opening project..."); try { command.getSource().getContext().loadProject(path.toString()); } catch (IOException e) { command.getSource().printError("Error opening project: " + e.getLocalizedMessage()); return 0; } command.getSource().getOut().println("Opened project at " + path); return 1; })).build(); LiteralCommandNode<ScaffoldCommandSource> get = literal("get") .executes(command -> { ScaffoldCommandSource source = command.getSource(); Project project = source.getContext().getProject(); if (project == null) { source.getOut().println("There is no project currently loaded."); } else { source.getOut().println("Project Folder: '"+project.getProjectFolder()+"'"); } return 1; }).build(); LiteralCommandNode<ScaffoldCommandSource> close = literal("close") .executes(command -> { ScaffoldTerminalContext context = command.getSource().getContext(); if (context.getProject() == null) { command.getSource().getOut().println("No project open."); return 0; } if (context.getLevel() != null) { command.getSource().getOut().print("Closing level..."); } context.setProject(null); command.getSource().getOut().println("Project closed."); return 1; }).build(); LiteralCommandNode<ScaffoldCommandSource> init = literal("init") .then(argument("title", StringArgumentType.string()).then(argument("path", StringArgumentType.greedyString()) .executes(command -> { Path path = Paths.get(getString(command, "path")); if (path.resolve(Constants.GAMEINFONAME).toFile().exists()) { command.getSource().getOut().println("Project already exists at "+path); return 0; } command.getSource().getOut().println("Initializing project at "+path+"..."); try { Project project = Project.init(path.toString(), getString(command, "title")); command.getSource().getContext().setProject(project); } catch (IOException e) { command.getSource().printError("Error initializing project: " + e.getLocalizedMessage()); return 0; } return 1; }))).build(); root.addChild(open); root.addChild(close); root.addChild(init); root.addChild(get); } }
package model import ( . "github.com/smartystreets/goconvey/convey" "testing" ) func TestRingConnected(t *testing.T) { lines := []string{"abh", "acgi", "adfj", "aek", "bcde", "hgfe", "hijk"} ring_connected := ringOrderConnected(lines) Convey("TestRingConnected", t, func() { Convey("succ", func() { So(ring_connected([]Point("abc")...), ShouldBeTrue) So(ring_connected([]Point("bcgh")...), ShouldBeTrue) So(ring_connected([]Point("cdfg")...), ShouldBeTrue) So(ring_connected([]Point("abeg")...), ShouldBeTrue) So(ring_connected([]Point("abhg")...), ShouldBeTrue) So(ring_connected([]Point("defj")...), ShouldBeTrue) }) Convey("failed", func() { So(ring_connected([]Point("acf")...), ShouldBeFalse) So(ring_connected([]Point("bcg")...), ShouldBeFalse) So(ring_connected([]Point("defk")...), ShouldBeFalse) }) }) } func TestHasCrossConnected(t *testing.T) { lines := []string{"abh", "acgi", "adfj", "aek", "bcde", "hgfe", "hijk"} cross_connected := hasCrossConnected(lines) Convey("TestHasCrossConnected", t, func() { Convey("succ", func() { So(cross_connected("ag", "bd"), ShouldBeTrue) So(cross_connected("af", "ce"), ShouldBeTrue) So(cross_connected("af", "be"), ShouldBeTrue) So(cross_connected("ai", "eh"), ShouldBeTrue) }) Convey("failed", func() { So(cross_connected("bc", "hg"), ShouldBeFalse) So(cross_connected("fj", "ek"), ShouldBeFalse) }) }) }
# An irrational decimal fraction is created by concatenating the positive integers: # 0.12345678910_1_112131415161718192021... # It can be seen that the 12th digit of the fractional part is 1. # If dn represents the nth digit of the fractional part, find the value of the following expression. # d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 d = '' l = 1 ans = 1 for i in range(300000): d += str(i) if len(d) > l: # print(d[l]) ans *= int(d[l]) l *= 10 print(ans)
package com.parimatch.codegenextension import javax.lang.model.element.AnnotationMirror import javax.lang.model.element.AnnotationValue import kotlin.reflect.KProperty1 fun AnnotationMirror.getAnnotationValueAsString(property: KProperty1<*, *>): String? { return this.getAnnotationValueAsString(property.name) } fun AnnotationMirror.getAnnotationValueAsString(key: String): String? { return this.getAnnotationValue(key)?.value?.toString() } fun AnnotationMirror.getAnnotationValue(key: String): AnnotationValue? { for ((element, value) in this.elementValues) { if (element!!.simpleName.toString() == key) { return value } } return null }
module FullMetalBody module Internal class InputStringValidator < ActiveModel::EachValidator DEFAULT_MAX_LENGTH = 1024 def check_validity! if options[:max_length] value = options[:max_length] raise ArgumentError, ":max_length must be a non-negative Integer" unless value.is_a?(Integer) && value >= 0 end end def validate_each(record, attribute, value) return if value.nil? if value.is_a?(Array) value.each do |v| validate_value(record, attribute, v.dup) end else validate_value(record, attribute, value.dup) end end def validate_value(record, attribute, value) max_length = options[:max_length] || DEFAULT_MAX_LENGTH # type unless value.is_a? String return record.errors.add(attribute, :wrong_type, value: value) end # length if value.size > max_length return record.errors.add(attribute, :too_long, value: byteslice(value), count: value.size) end # encoding original_encoding = value.encoding.name unless value.force_encoding('UTF-8').valid_encoding? return record.errors.add(attribute, :wrong_encoding, value: byteslice(value), encoding: original_encoding) end # cntrl # Replace and delete line feed codes and horizontal tabs (vertical tabs are not) value = value.gsub(/\R|\t/, '') if /[[:cntrl:]]/.match?(value) record.errors.add(attribute, :include_cntrl, value: byteslice(value)) end end def byteslice(value) value.byteslice(0, 1024) end end end end
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package pt.rupeal.invoicexpress; public final class R { public static final class attr { } public static final class color { public static final int actionBar_tabBar_background=0x7f050001; public static final int actionBar_tabBar_darker_line=0x7f050003; /** color name="actionBar_tabBar_lighter_line">#434343</color> <color name="actionBar_tabBar_darker_line">#000000</colo r */ public static final int actionBar_tabBar_lighter_line=0x7f050002; public static final int actionBar_title_textColor=0x7f050000; public static final int background=0x7f050004; public static final int button_background=0x7f050005; public static final int button_text_color=0x7f050006; /** dashboard top debtors */ public static final int dashboard_debtor_1=0x7f05002b; public static final int dashboard_debtor_2=0x7f05002c; public static final int dashboard_debtor_3=0x7f05002d; public static final int dashboard_debtor_4=0x7f05002e; public static final int dashboard_debtor_5=0x7f05002f; public static final int dashboard_debtor_border=0x7f050032; public static final int dashboard_green_color=0x7f050023; public static final int dashboard_labels=0x7f050026; public static final int dashboard_legend_background=0x7f050027; public static final int dashboard_line_horizontal=0x7f050025; public static final int dashboard_no_debtors=0x7f050030; public static final int dashboard_no_debtors_center=0x7f050031; public static final int dashboard_quarterly_legend_bullet_color=0x7f050029; public static final int dashboard_quarterly_legend_color=0x7f05002a; /** dashboard quarterly */ public static final int dashboard_quarterly_number_background=0x7f050028; public static final int dashboard_red_color=0x7f050024; /** dashboard */ public static final int dashboard_white_color=0x7f050022; public static final int details_text=0x7f050011; public static final int details_text_2=0x7f050012; public static final int details_text_3=0x7f050013; public static final int dialog_title_background=0x7f050020; public static final int dialog_title_text_color=0x7f050021; public static final int documents_button_image_background=0x7f050007; public static final int documents_button_image_background_pressed=0x7f050008; public static final int documents_button_label_background=0x7f050009; public static final int documents_button_label_background_pressed=0x7f05000a; /** color name="documents_list_empty_title">#313131</color */ public static final int documents_list_empty_title=0x7f05000b; public static final int documents_list_empty_title_shadow=0x7f05000c; public static final int documents_over_due_normal=0x7f05000d; public static final int documents_over_due_red=0x7f05000e; public static final int green_normal=0x7f050017; public static final int green_normal_2=0x7f050018; public static final int green_shadow=0x7f050019; /** horizontal scroll */ public static final int horizontal_navigation_bar_background=0x7f050014; public static final int horizontal_navigation_bar_text=0x7f050015; /** item */ public static final int item_details_title_background=0x7f050016; public static final int line_seperator=0x7f05001a; public static final int line_seperator_bottom=0x7f05001c; public static final int line_seperator_bottom_black=0x7f05001e; public static final int line_seperator_top=0x7f05001b; public static final int line_seperator_top_black=0x7f05001d; public static final int pressed_invoicexpress=0x7f050033; public static final int sub_titles_text=0x7f05000f; public static final int sub_titles_text_line_seperator=0x7f050010; public static final int text_color=0x7f05001f; } public static final class drawable { public static final int ab_bottom_solid_invoicexpress=0x7f020000; public static final int ab_solid_invoicexpress=0x7f020001; public static final int ab_stacked_solid_invoicexpress=0x7f020002; public static final int ab_transparent_invoicexpress=0x7f020003; public static final int actionbar_tabbar_background=0x7f020004; public static final int amostra=0x7f020005; public static final int bg_actionbar=0x7f020006; public static final int bg_login=0x7f020007; public static final int bg_top=0x7f020008; public static final int bullet_gray=0x7f020009; public static final int bullet_green=0x7f02000a; public static final int bullet_red=0x7f02000b; public static final int bullet_white=0x7f02000c; public static final int dashboar_2=0x7f02000d; public static final int dashboard1_amostra=0x7f02000e; public static final int dashboard1_sample=0x7f02000f; public static final int dashboard2_amostra=0x7f020010; public static final int dashboard2_sample=0x7f020011; public static final int dashboard3_amostra=0x7f020012; public static final int dashboard3_sample=0x7f020013; public static final int dashboard_=0x7f020014; public static final int dashboard_1=0x7f020015; public static final int dashboard_2=0x7f020016; public static final int dashboard_3=0x7f020017; public static final int dashboard_4=0x7f020018; public static final int dashboard_5=0x7f020019; public static final int doc_type_icon_1=0x7f02001a; public static final int doc_type_icon_2=0x7f02001b; public static final int doc_type_icon_3=0x7f02001c; public static final int doc_type_icon_4=0x7f02001d; public static final int doc_type_icon_5=0x7f02001e; public static final int edit_text_background_invoicexpress=0x7f02001f; public static final int ic_action_refresh=0x7f020020; public static final int ic_action_search=0x7f020021; public static final int ic_content_email=0x7f020022; public static final int ic_device_access_call=0x7f020023; public static final int ic_launcher=0x7f020024; public static final int ic_navigation_refresh=0x7f020025; public static final int icon=0x7f020026; public static final int icon_1=0x7f020027; public static final int icon_1_selected=0x7f020028; public static final int icon_2=0x7f020029; public static final int icon_2_selected=0x7f02002a; public static final int icon_3=0x7f02002b; public static final int icon_3_selected=0x7f02002c; public static final int icon_3_unselected=0x7f02002d; public static final int icon_4=0x7f02002e; public static final int icon_4_selected=0x7f02002f; public static final int icon_document_1=0x7f020030; public static final int icon_document_2=0x7f020031; public static final int icon_document_3=0x7f020032; public static final int icon_document_4=0x7f020033; public static final int icon_document_5=0x7f020034; public static final int icon_greater=0x7f020035; public static final int icon_logo=0x7f020036; public static final int icon_overdue=0x7f020037; public static final int icon_status_1=0x7f020038; public static final int icon_status_2=0x7f020039; public static final int icon_status_3=0x7f02003a; public static final int icon_status_4=0x7f02003b; public static final int icon_status_5=0x7f02003c; public static final int ix_logo_bg=0x7f02003d; public static final int list_focused_invoicexpress=0x7f02003e; public static final int menu_dropdown_panel_invoicexpress=0x7f02003f; public static final int menu_hardkey_panel_invoicexpress=0x7f020040; public static final int multibanco=0x7f020041; public static final int navigation_next_item=0x7f020042; public static final int pager_title_strip_background=0x7f020043; public static final int pressed_background_invoicexpress=0x7f020044; public static final int pressed_background_links=0x7f020045; public static final int progress_bg_invoicexpress=0x7f020046; public static final int progress_horizontal_invoicexpress=0x7f020047; public static final int progress_primary_invoicexpress=0x7f020048; public static final int progress_secondary_invoicexpress=0x7f020049; public static final int quarterly_bullet_legend=0x7f02004a; public static final int sample=0x7f02004b; public static final int selectable_background_invoicexpress=0x7f02004c; public static final int selectable_documents_types=0x7f02004d; public static final int social_send_now=0x7f02004e; public static final int spinner_ab_default_invoicexpress=0x7f02004f; public static final int spinner_ab_disabled_invoicexpress=0x7f020050; public static final int spinner_ab_focused_invoicexpress=0x7f020051; public static final int spinner_ab_pressed_invoicexpress=0x7f020052; public static final int spinner_background_ab_invoicexpress=0x7f020053; public static final int tab_indicator_ab_invoicexpress=0x7f020054; public static final int tab_selected_focused_invoicexpress=0x7f020055; public static final int tab_selected_invoicexpress=0x7f020056; public static final int tab_selected_pressed_invoicexpress=0x7f020057; public static final int tab_unselected_focused_invoicexpress=0x7f020058; public static final int tab_unselected_pressed_invoicexpress=0x7f020059; public static final int textfield_activated_invoicexpress=0x7f02005a; public static final int textfield_default_invoicexpress=0x7f02005b; public static final int textfield_disabled_focused_invoicexpress=0x7f02005c; public static final int textfield_disabled_invoicexpress=0x7f02005d; public static final int textfield_focused_invoicexpress=0x7f02005e; public static final int textfield_multiline_activated_invoicexpress=0x7f02005f; public static final int textfield_multiline_default_invoicexpress=0x7f020060; public static final int textfield_multiline_disabled_focused_invoicexpress=0x7f020061; public static final int textfield_multiline_disabled_invoicexpress=0x7f020062; public static final int textfield_multiline_focused_invoicexpress=0x7f020063; public static final int textfield_search_default_invoicexpress=0x7f020064; public static final int textfield_search_selected_invoicexpress=0x7f020065; public static final int textfield_searchview_invoicexpress=0x7f020066; public static final int top5_circle_bg=0x7f020067; public static final int top5_circle_sample=0x7f020068; public static final int v=0x7f020069; } public static final class id { public static final int about=0x7f0900ae; public static final int about_image=0x7f090002; public static final int about_invoiceXpress=0x7f090003; public static final int about_line_bottom=0x7f090001; public static final int about_line_top=0x7f090000; public static final int about_link=0x7f090005; public static final int about_rights=0x7f090006; public static final int about_support=0x7f090007; public static final int about_version=0x7f090004; public static final int account=0x7f0900aa; public static final int account_details_address=0x7f09000e; public static final int account_details_address_layout=0x7f09000d; public static final int account_details_address_line_seperator=0x7f09000f; public static final int account_details_currency=0x7f090017; public static final int account_details_currency_subtitle=0x7f090016; public static final int account_details_email=0x7f090014; public static final int account_details_email_line_seperator=0x7f090015; public static final int account_details_fax=0x7f090012; public static final int account_details_fax_line_seperator=0x7f090013; public static final int account_details_general_subtitle=0x7f09000c; public static final int account_details_phone=0x7f090010; public static final int account_details_phone_line_seperator=0x7f090011; public static final int account_details_title_entity=0x7f090009; public static final int account_details_title_name=0x7f090008; public static final int account_details_type=0x7f09000b; public static final int account_details_type_subtitle=0x7f09000a; public static final int accounts=0x7f090018; public static final int active_account=0x7f0900ab; public static final int body=0x7f09008b; public static final int button_image=0x7f09008d; public static final int button_image_layout=0x7f09008c; public static final int button_label=0x7f09008f; public static final int button_label_layout=0x7f09008e; public static final int change_account=0x7f0900ac; public static final int contact_details_address=0x7f090026; public static final int contact_details_address_layout=0x7f090025; public static final int contact_details_address_layout_line=0x7f090029; public static final int contact_details_button=0x7f09001b; public static final int contact_details_country=0x7f090028; public static final int contact_details_email=0x7f09002e; public static final int contact_details_email_line=0x7f09002f; public static final int contact_details_fax=0x7f09002c; public static final int contact_details_fax_line=0x7f09002d; public static final int contact_details_general_subtitle=0x7f090024; public static final int contact_details_nif=0x7f090031; public static final int contact_details_nif_layout=0x7f090030; public static final int contact_details_nif_layout_line=0x7f090032; public static final int contact_details_phone=0x7f09002a; public static final int contact_details_phone_line=0x7f09002b; public static final int contact_details_postal_code=0x7f090027; public static final int contact_details_preferred_email=0x7f090022; public static final int contact_details_preferred_email_line=0x7f090023; public static final int contact_details_preferred_name=0x7f09001e; public static final int contact_details_preferred_name_layout=0x7f09001d; public static final int contact_details_preferred_name_layout_line=0x7f09001f; public static final int contact_details_preferred_phone=0x7f090020; public static final int contact_details_preferred_phone_line=0x7f090021; public static final int contact_details_preferred_subtitle=0x7f09001c; public static final int contact_details_title_name=0x7f090019; public static final int contact_details_title_name_image=0x7f09001a; public static final int contact_list_letter=0x7f090035; public static final int contact_name=0x7f090036; public static final int contacts_list=0x7f090034; public static final int content=0x7f090037; public static final int create_account=0x7f0900a8; public static final int dashboard_invoicing_sample=0x7f09003b; public static final int dashboard_pager=0x7f090038; public static final int dashboard_pager_title_strip=0x7f090039; public static final int dashboard_quarterly_first_invoicing=0x7f0900b3; public static final int dashboard_quarterly_first_vat=0x7f0900b4; public static final int dashboard_quarterly_first_yoy=0x7f0900b5; public static final int dashboard_quarterly_forth_invoicing=0x7f0900bf; public static final int dashboard_quarterly_forth_vat=0x7f0900c0; public static final int dashboard_quarterly_forth_yoy=0x7f0900c1; public static final int dashboard_quarterly_legend_title=0x7f0900c3; public static final int dashboard_quarterly_legend_title_layout=0x7f0900c2; public static final int dashboard_quarterly_legend_title_layout_line_bottom=0x7f0900c4; public static final int dashboard_quarterly_row_0=0x7f0900b1; public static final int dashboard_quarterly_row_1=0x7f0900b2; public static final int dashboard_quarterly_row_2=0x7f0900b6; public static final int dashboard_quarterly_row_3=0x7f0900ba; public static final int dashboard_quarterly_row_4=0x7f0900be; public static final int dashboard_quarterly_second_invoicing=0x7f0900b7; public static final int dashboard_quarterly_second_vat=0x7f0900b8; public static final int dashboard_quarterly_second_yoy=0x7f0900b9; public static final int dashboard_quarterly_table_layout=0x7f0900b0; public static final int dashboard_quarterly_third_invoicing=0x7f0900bb; public static final int dashboard_quarterly_third_vat=0x7f0900bc; public static final int dashboard_quarterly_third_yoy=0x7f0900bd; public static final int dashboard_quarterly_title=0x7f0900af; public static final int dashboard_sample=0x7f09003a; public static final int details_horizontal_separator=0x7f090042; public static final int details_image=0x7f090041; public static final int details_label=0x7f090040; public static final int details_value=0x7f09003f; public static final int details_value_label_image_layout=0x7f09003e; public static final int dialogProgressBar=0x7f090044; public static final int dialogProgressBar_Layout=0x7f090043; public static final int doc_ammount=0x7f090073; public static final int doc_client=0x7f090076; public static final int doc_client_date=0x7f090077; public static final int doc_detail_atm=0x7f090067; public static final int doc_detail_atm_layout=0x7f090066; public static final int doc_details_beforeTaxes_label=0x7f09005e; public static final int doc_details_beforeTaxes_value=0x7f09005f; public static final int doc_details_cancel_dialog_justification=0x7f09006b; public static final int doc_details_date_label=0x7f090052; public static final int doc_details_date_value=0x7f090053; public static final int doc_details_discount_label=0x7f09005c; public static final int doc_details_discount_value=0x7f09005d; public static final int doc_details_dueDate_label=0x7f090054; public static final int doc_details_dueDate_value=0x7f090055; public static final int doc_details_image_link_name=0x7f09004e; public static final int doc_details_image_title=0x7f090047; public static final int doc_details_invEnt=0x7f090068; public static final int doc_details_invMon=0x7f09006a; public static final int doc_details_invRef=0x7f090069; public static final int doc_details_items=0x7f090057; public static final int doc_details_items_subtitle=0x7f090056; public static final int doc_details_name=0x7f09004d; public static final int doc_details_name_layout=0x7f09004c; public static final int doc_details_notes=0x7f090064; public static final int doc_details_notes_label=0x7f090063; public static final int doc_details_payment_label=0x7f090065; public static final int doc_details_sequenceNumber_label=0x7f090050; public static final int doc_details_sequenceNumber_value=0x7f090051; public static final int doc_details_status=0x7f090048; public static final int doc_details_sum_label=0x7f09005a; public static final int doc_details_sum_value=0x7f09005b; public static final int doc_details_taxes_label=0x7f090060; public static final int doc_details_taxes_value=0x7f090061; public static final int doc_details_title_bottom=0x7f090049; public static final int doc_details_title_line1_bottom=0x7f090046; public static final int doc_details_title_line1_top=0x7f090045; public static final int doc_details_title_line2_bottom=0x7f09004a; public static final int doc_details_title_line2_top=0x7f09004b; public static final int doc_details_total_value=0x7f090062; public static final int doc_details_values=0x7f090059; public static final int doc_details_values_subtitle=0x7f090058; public static final int doc_details_vertical_line_link_name=0x7f09004f; public static final int doc_due_date=0x7f090074; public static final int doc_first_row=0x7f09007f; public static final int doc_forth_row=0x7f090088; public static final int doc_image_due_date=0x7f090075; public static final int doc_second_row=0x7f090082; public static final int doc_start_date=0x7f090078; public static final int doc_status=0x7f090070; public static final int doc_third_row=0x7f090085; public static final int doc_type=0x7f09006f; public static final int doc_type_all=0x7f09007e; public static final int doc_type_cash=0x7f090083; public static final int doc_type_credit=0x7f090084; public static final int doc_type_debit=0x7f090086; public static final int doc_type_invoice=0x7f090080; public static final int doc_type_receipt=0x7f090087; public static final int doc_type_simple_invoice=0x7f090081; public static final int documents_list=0x7f09006c; public static final int documents_more_docs_downloaded=0x7f09007c; public static final int documents_more_docs_to_upload=0x7f09007d; public static final int email_subject=0x7f09008a; public static final int email_tab=0x7f0900c8; public static final int email_to=0x7f090089; public static final int invoiceXpress=0x7f0900ad; public static final int item_details_description_subtitle=0x7f090093; public static final int item_details_description_value=0x7f090094; public static final int item_details_discounts_label=0x7f09009d; public static final int item_details_discounts_value=0x7f09009e; public static final int item_details_name_subtitle=0x7f090091; public static final int item_details_name_value=0x7f090092; public static final int item_details_quantity_label=0x7f090099; public static final int item_details_quantity_value=0x7f09009a; public static final int item_details_taxes_label=0x7f09009b; public static final int item_details_taxes_value=0x7f09009c; public static final int item_details_title=0x7f090090; public static final int item_details_total_value=0x7f09009f; public static final int item_details_unitPrice_label=0x7f090097; public static final int item_details_unitPrice_value=0x7f090098; public static final int item_details_values=0x7f090096; public static final int item_details_values_subtitle=0x7f090095; public static final int link_image=0x7f0900a1; public static final int link_label=0x7f0900a0; public static final int link_value=0x7f0900a3; public static final int link_vertical_line=0x7f0900a2; public static final int login=0x7f0900a7; public static final int login_email=0x7f0900a5; public static final int login_image=0x7f0900a4; public static final int login_password=0x7f0900a6; public static final int logout=0x7f0900a9; public static final int no_documents_image_background=0x7f090033; public static final int pager=0x7f09007a; public static final int pager_layout=0x7f090079; public static final int pager_title_strip=0x7f09007b; public static final int refresh_tab=0x7f0900c5; public static final int search_tab=0x7f0900c6; public static final int send_email=0x7f0900c7; public static final int status=0x7f09006e; public static final int sub_title_text_view_1=0x7f09003c; public static final int sub_title_text_view_2=0x7f09003d; public static final int widget32=0x7f09006d; public static final int widget34=0x7f090072; public static final int widget35=0x7f090071; } public static final class layout { public static final int about=0x7f030000; public static final int account_details=0x7f030001; public static final int accounts=0x7f030002; public static final int activity_main=0x7f030003; public static final int contact_details=0x7f030004; public static final int contacts_list_empty=0x7f030005; public static final int contacts_list_fragment=0x7f030006; public static final int contacts_list_row_fragment=0x7f030007; public static final int content=0x7f030008; public static final int dashboard=0x7f030009; public static final int dashboard_charts=0x7f03000a; public static final int dashboard_invoicing_sample=0x7f03000b; public static final int details_sub_title=0x7f03000c; public static final int details_value_label_image_row=0x7f03000d; public static final int dialog_progress=0x7f03000e; public static final int document_detail=0x7f03000f; public static final int document_detail_cancel_dialog=0x7f030010; public static final int documents_list=0x7f030011; public static final int documents_list_empty=0x7f030012; public static final int documents_list_row=0x7f030013; public static final int documents_main=0x7f030014; public static final int documents_more=0x7f030015; public static final int documents_types=0x7f030016; public static final int email=0x7f030017; public static final int image_button=0x7f030018; public static final int item_details=0x7f030019; public static final int link=0x7f03001a; public static final int link_two_labels=0x7f03001b; public static final int login=0x7f03001c; public static final int more=0x7f03001d; public static final int quarterly=0x7f03001e; } public static final class menu { public static final int action_bar_accounts=0x7f080000; public static final int action_bar_contact_details=0x7f080001; public static final int action_bar_contacts_list=0x7f080002; public static final int action_bar_dashboard=0x7f080003; public static final int action_bar_document_details=0x7f080004; public static final int action_bar_documents_list=0x7f080005; public static final int action_bar_email=0x7f080006; } public static final class string { public static final int about_button=0x7f06005f; /** ABOUT ABOUT */ public static final int about_invoiceXpress=0x7f06005b; public static final int about_link=0x7f06005d; public static final int about_support=0x7f06005e; public static final int about_version=0x7f06005c; public static final int app_name=0x7f060001; public static final int conctacs_actionBar_title=0x7f06000c; /** Contact details Contact details */ public static final int contact_details_button=0x7f06000f; public static final int contact_details_ic_email_access_description=0x7f060047; public static final int contact_details_ic_phone_access_description=0x7f060046; public static final int contact_details_name=0x7f060011; public static final int contact_details_nif=0x7f060015; public static final int contact_details_preferred_title=0x7f060010; public static final int contacts=0x7f060006; /** Contacts list Contacts list */ public static final int contacts_list_empty=0x7f06000e; public static final int currency=0x7f060002; /** Action Bar titles Action Bar titles */ public static final int dashBoard_actionBar_title=0x7f06000a; /** DASHBOARD DASHBOARD */ public static final int dashboard_invoicing=0x7f060065; public static final int dashboard_legend_onTime=0x7f06006c; public static final int dashboard_legend_overdue=0x7f06006d; public static final int dashboard_legend_settled=0x7f06006b; public static final int dashboard_legend_total=0x7f06006a; public static final int dashboard_quarterly=0x7f060067; public static final int dashboard_quarterly_VAT=0x7f06006f; public static final int dashboard_quarterly_YOY=0x7f060070; public static final int dashboard_quarterly_first=0x7f060071; public static final int dashboard_quarterly_forth=0x7f060074; public static final int dashboard_quarterly_invoicing=0x7f06006e; public static final int dashboard_quarterly_legend_tilte=0x7f060075; public static final int dashboard_quarterly_second=0x7f060072; public static final int dashboard_quarterly_third=0x7f060073; public static final int dashboard_title=0x7f060069; public static final int dashboard_top5debtors=0x7f060068; public static final int dashboard_topdebtors_legend_tilte_1=0x7f060076; public static final int dashboard_topdebtors_legend_tilte_2=0x7f060077; public static final int dashboard_treasury=0x7f060066; public static final int details_address=0x7f060014; public static final int details_currency_subTitle=0x7f060019; public static final int details_email=0x7f060013; public static final int details_fax=0x7f060016; public static final int details_general_subTitle=0x7f060017; public static final int details_image_description=0x7f060045; public static final int details_phone=0x7f060012; public static final int details_type_subTitle=0x7f060018; public static final int dialog_exit_no=0x7f060009; public static final int dialog_exit_title=0x7f060007; public static final int dialog_exit_yes=0x7f060008; public static final int doc_details_cancel_dialog_cancel=0x7f06002d; public static final int doc_details_cancel_dialog_hint=0x7f06002f; public static final int doc_details_cancel_dialog_ok=0x7f06002e; /** Document Details Cancel Dialog Document Details Cancel Dialog */ public static final int doc_details_cancel_dialog_title=0x7f06002c; public static final int doc_details_date_label=0x7f06002a; public static final int doc_details_dueDate_label=0x7f06002b; /** Document Details Document Details */ public static final int doc_details_final_costumer=0x7f060028; public static final int doc_details_items_subtitle_Left=0x7f060048; public static final int doc_details_items_subtitle_Right=0x7f060049; public static final int doc_details_notes_label=0x7f060050; public static final int doc_details_payment_label=0x7f060051; public static final int doc_details_sequenceNumber_label=0x7f060029; public static final int doc_details_values_before_taxes=0x7f06004d; public static final int doc_details_values_discount=0x7f06004c; public static final int doc_details_values_subtitle=0x7f06004a; public static final int doc_details_values_sum=0x7f06004b; public static final int doc_details_values_taxes=0x7f06004e; public static final int doc_details_values_total=0x7f06004f; /** Documents filters Documents filters */ public static final int doc_filter_all=0x7f060025; public static final int doc_filter_archived=0x7f060027; public static final int doc_filter_expired=0x7f060026; public static final int doc_list_empty=0x7f06001d; public static final int doc_more_downloaded=0x7f06001b; /** Documents list Documents list */ public static final int doc_more_title=0x7f06001a; public static final int doc_more_to_upload=0x7f06001c; /** Document status Document status */ public static final int doc_status_canceled=0x7f060030; public static final int doc_status_deleted=0x7f060036; public static final int doc_status_draft=0x7f060031; public static final int doc_status_final=0x7f060032; /** Document status label Gui, Document Details Fragment Document status label Gui, Document Details Fragment */ public static final int doc_status_gui_canceled=0x7f060037; public static final int doc_status_gui_draft=0x7f060038; public static final int doc_status_gui_final=0x7f060039; public static final int doc_status_gui_secondCopy=0x7f06003a; public static final int doc_status_gui_settled=0x7f06003b; public static final int doc_status_secondCopy=0x7f060033; public static final int doc_status_settled=0x7f060034; public static final int doc_status_unsettled=0x7f060035; /** Documents types itnerface Documents types itnerface */ public static final int doc_type_all=0x7f06001e; public static final int doc_type_cash=0x7f060021; public static final int doc_type_credit=0x7f060022; public static final int doc_type_debit=0x7f060023; public static final int doc_type_invoice=0x7f06001f; public static final int doc_type_receipt=0x7f060024; public static final int doc_type_simple_invoice=0x7f060020; public static final int documents_actionBar_title=0x7f06000b; public static final int email=0x7f060005; public static final int email_body=0x7f060062; public static final int email_body_message=0x7f060063; public static final int email_subject=0x7f060061; public static final int email_successfull_message=0x7f060064; /** EMAIL EMAIL */ public static final int email_to=0x7f060060; public static final int empty=0x7f060000; public static final int error_account_blocked=0x7f060082; public static final int error_account_switch_unexpected=0x7f06008a; /** Error More Accounts Error More Accounts */ public static final int error_accounts_unexpected=0x7f060089; /** Error ActionBar navigation Error ActionBar navigation */ public static final int error_actionbar_navigation=0x7f060078; /** Error Messages Authentication Error Messages Authentication */ public static final int error_bad_credentials=0x7f06007c; public static final int error_cant_login_unexpected=0x7f06007f; public static final int error_change_status_already_sent_to_at=0x7f060088; public static final int error_change_status_cancel_empty_message=0x7f060087; public static final int error_change_status_date=0x7f060086; /** Error Documents change status Error Documents change status */ public static final int error_change_status_unexpected=0x7f060085; public static final int error_contact_unexpected=0x7f06007a; /** Error Contacts Error Contacts */ public static final int error_contacts_unexpected=0x7f060079; public static final int error_documents_roles=0x7f060084; /** Error Documents Error Documents */ public static final int error_documents_unexpected=0x7f060083; public static final int error_fields_mandatory=0x7f060080; /** Error Dashboard Error Dashboard */ public static final int error_get_dashboard_unexpected=0x7f06007b; public static final int error_invalid_params=0x7f06007d; public static final int error_invalid_username=0x7f060081; /** Error parser Error parser */ public static final int error_parser_xml_unexpected=0x7f06008c; /** Error Send Email Error Send Email */ public static final int error_send_email_unexpected=0x7f06008b; public static final int error_there_arent_active_accounts=0x7f06007e; public static final int image_description=0x7f060044; public static final int item_details_description=0x7f06003d; public static final int item_details_discounts_label=0x7f060043; /** Item details Item details */ public static final int item_details_name=0x7f06003c; public static final int item_details_quantity_label=0x7f060041; public static final int item_details_taxes_label=0x7f060042; public static final int item_details_total=0x7f06003f; public static final int item_details_unitPrice_label=0x7f060040; public static final int item_details_values=0x7f06003e; public static final int login=0x7f060059; public static final int login_create_aacount=0x7f06005a; /** LOGIN LOGIN */ public static final int login_email=0x7f060057; public static final int login_password=0x7f060058; public static final int more_about=0x7f060056; public static final int more_account=0x7f060053; public static final int more_actionBar_title=0x7f06000d; public static final int more_change_account=0x7f060054; public static final int more_invoiceXpress=0x7f060055; /** MORE MORE */ public static final int more_logout=0x7f060052; public static final int refresh=0x7f060004; public static final int search=0x7f060003; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f070000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f070001; public static final int Theme_invoicexpress=0x7f070002; /** this style is only referenced in a Light.DarkActionBar based theme */ public static final int Theme_invoicexpress_widget=0x7f07000b; public static final int Theme_invoicexpress_no_ActionBar=0x7f07000c; public static final int invoicexpress_ActionBarTabBar=0x7f070007; public static final int invoicexpress_ActionBarTabStyle=0x7f070008; public static final int invoicexpress_ActionBarTab_TitleTextStyle=0x7f070009; public static final int invoicexpress_DropDownListView=0x7f070006; public static final int invoicexpress_DropDownNav=0x7f07000a; public static final int invoicexpress_EditText=0x7f07000d; public static final int invoicexpress_PopupMenu=0x7f070005; public static final int invoicexpress_solid_ActionBar=0x7f070003; public static final int invoicexpress_transparent_ActionBar=0x7f070004; } public static final class xml { public static final int authenticator=0x7f040000; } }
--- title: A complete break down of tags: - May 1907 --- A complete break down of the wrecker's salvage from the Hannah M. Bell. [Details to each person involved.] Newspapers: **Daily Miami Metropolis, The Miami Metropolis (daily), The Daily Metropolis or Miami Daily Metropolis** Page: **1**, Section: **N/A**
# frozen_string_literal: true require 'rails_helper' RSpec.feature 'Correction creation' do given(:answer) { FactoryGirl.create(:answer) } context 'When the user is not signed in' do scenario "It doesn't have a correction creation button" do visit_answer_path within_answer do expect(page).not_to have_css('.correction-form-btn') end end end context 'When the user is signed in' do background do login_as answer.author visit_answer_path end scenario 'Creating an invalid correction' do within_answer do click_link I18n.t('answers.answer.suggest_correction') within_correction_form do fill_in 'correction[text]', with: 'too short' click_button I18n.t('answers.answer.suggest_correction') expect(page).to have_css('.error_messages') end end end scenario 'Creating a valid correction' do correction_text = 'correction' * 5 within_answer do click_link I18n.t('answers.answer.suggest_correction') within_correction_form do fill_in 'correction[text]', with: correction_text click_button I18n.t('answers.answer.suggest_correction') expect(page).not_to have_css('.error_messages') end expect(page).to have_text(I18n.t('answers.corrections_meta.pending_corrections', count: 1)) expect(page).to have_css('.correction.pending', count: 1, text: correction_text) end end end def visit_answer_path visit answer_permalink_path(answer.id) end def within_answer(&block) within(".answer[data-id='#{answer.id}']", &block) end def within_correction_form(&block) within('.correction-form', &block) end end
/* ECMAScript 5 added a lot of new Object Methods to JavaScript: */ // Adding or changing an object property Object.defineProperty(object, property, descriptor) // Adding or changing many object properties Object.defineProperties(object, descriptors) // Accessing Properties Object.getOwnPropertyDescriptor(object, property) // Returns all properties as an array Object.getOwnPropertyNames(object) // Returns enumerable properties as an array Object.keys(object) // Accessing the prototype Object.getPrototypeOf(object) // Prevents adding properties to an object Object.preventExtensions(object) // Returns true if properties can be added to an object Object.isExtensible(object) // Prevents changes of object properties (not values) Object.seal(object) // Returns true if object is sealed Object.isSealed(object) // Prevents any changes to an object Object.freeze(object) // Returns true if object is frozen Object.isFrozen(object) /* *** Changing Meta Data *** ES5 allows the following property meta data to be changed: writable : true // Property value can be changed enumerable : true // Property can be enumerated configurable : true // Property can be reconfigured writable : false // Property value can not be changed enumerable : false // Property can be not enumerated configurable : false // Property can be not reconfigured */ //This example makes language read-only: Object.defineProperty(person, "language", {writable:false}); //This example makes language not enumerable: Object.defineProperty(person, "language", {enumerable:false}); /* *** Listing All Properties *** This example list all properties of an object: */ Object.getOwnPropertyNames(person); // Returns an array of properties
export class Float extends Number { constructor(a) { var temp = new Float32Array(1); temp[0] = +a; super(temp[0]); this._f = temp[0]; this._d = a; } toString() { var temp = new Float64Array(1); temp[0] = +this._d; return temp[0].toString(); } valueOf() { return this._f; } } export default Float;
require 'active_record' unless defined? ActiveRecord module LoadMore def self.configure(&block) yield @config ||= LoadMore::Configuration.new end def self.config @config end class Configuration include ActiveSupport::Configurable config_accessor :load_limit config_accessor :sort_column config_accessor :sort_method end module ActiveRecord extend ActiveSupport::Concern included do end module ClassMethods def load_limit=(limit) @@load_limit = limit end def load_limit defined?(@@load_limit) ? @@load_limit : LoadMore.config.load_limit end def sort_column=(col) @@sort_column = col end def sort_column defined?(@@sort_column) ? @@sort_column : LoadMore.config.sort_column end def sort_method=(method) @@sort_method = method end def sort_method defined?(@@sort_method) ? @@sort_method : LoadMore.config.sort_method end def load_more(options = {}) load_limit = options.delete(:load_limit) || self.load_limit sort_column = options.delete(:sort_column) || self.sort_column sort_method = options.delete(:sort_method) || self.sort_method last_load_id = options.delete(:last_load) rel = order(sort_column => sort_method).limit(load_limit) if last_load_id where_query = if sort_method == :desc "#{self.table_name}.#{sort_column} < ?" else "#{self.table_name}.#{sort_column} > ?" end rel = rel.where(where_query, last_load_id) end rel end def last_load(id = nil) load_more(last_load: id) end end end end LoadMore.configure do |config| config.load_limit = 10 config.sort_column = :id config.sort_method = :desc end ActiveRecord::Base.send :include, LoadMore::ActiveRecord
{!! Form::open([ 'url' => $url, 'method' => $method ]) !!} {{ csrf_field() }} <div class="form-group form-animate-text" style="margin-top:40px !important;"> {{Form::text('descripcion',$colegio->descripcion,['class' => 'form-text'])}} <span class="bar"></span> <label style="color:green">Descripción</label> </div> <div class="form-group form-animate-text" style="margin-top:40px !important;"> {{Form::text('direccion',$colegio->direccion,['class' => 'form-text']) }} <span class="bar"></span> <label style="color:green">Dirección</label> </div> <div class="form-group form-animate-text" style="margin-top:40px !important;"> {{Form::text('telefono',$colegio->telefono,['class' => 'form-text']) }} <span class="bar"></span> <label style="color:green">Teléfono</label> </div> <div class="col-md-6"> <a href="{{url('/colegios')}}" class="btn btn-primary ripple btn-3d">Volver</a> </div> <div class="col-md-6"> <input type="submit" Value="Cargar" class="btn btn-success ripple btn-3d"> </div> {!! Form::close() !!}
'use strict' const PersonalityInsightsV3 = require('watson-developer-cloud/personality-insights/v3') const personalityInsights = new PersonalityInsightsV3({ version: '2016-10-19', username: process.env.WATSON_PERSONALITY_USERNAME, password: process.env.WATSON_PERSONALITY_PASSWORD, url: process.env.WATSON_PERSONALITY_URL }) module.exports = function (WatsonPersonality) { WatsonPersonality.getProfile = function (msg, cb) { personalityInsights.profile(msg, function (err, resp) { if (err) return cb(err) cb(null, resp) }) } }
package kiwi.widgets.equity; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.imageio.ImageIO; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import kiwi.api.content.ContentItemService; import kiwi.api.equity.EquityService; import kiwi.model.content.ContentItem; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.log.Log; @Name("kiwi.widgets.equityBubbleWebService") @Scope(ScopeType.STATELESS) @Path("/widgets/ceq/buble") public class EquityBubbleWebService { @Logger Log log; @In private EquityService equityService; @In private ContentItemService contentItemService; @GET @Path("/image") @Produces("image/png") public byte[] getBubble(@QueryParam("uri") String uri) { ContentItem ci = contentItemService.getContentItemByUri(uri); BufferedImage img = EquityBubble.getImageFor(equityService, ci); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { ImageIO.write(img, "png", os); } catch (IOException e) { e.printStackTrace(); } return os.toByteArray(); } }
# frozen_string_literal: true # Delivers the magic links to let people join the site or log back in class MagicLinkMailer < ApplicationMailer default from: "Seasoning <[email protected]>" def welcome_email(recipient, token) @token = token mail( to: recipient, subject: "Welcome to Seasoning!" ) end def log_in_email(recipient, token) @token = token @greeting = [ "Oh good, the commercials are over, come back in!", "Welcome back to Seasoning!" ].sample mail( to: recipient, subject: "Welcome back to Seasoning!" ) end end
(ns report-classifier.core (:require [clojure.java.io :as io] [clojure.edn :as edn] [report-classifier.watson :as watson] [clojure.string :as str])) (def classifier-ids ["f33041x451-nlc-442" "f33041x451-nlc-450"]) (defn theme->clusters [theme] (println "THEME" theme) (let [mapping {"Recovery and Reconstruction" [:shelter :early-recovery :logistics] "Water Sanitation Hygiene" [:water-sanitation] "Coordination" [:coordination] "Health" [:health :nutrition] "Shelter and Non-Food Items", [:shelter] "Food and Nutrition" [:food-security :nutrition] "Education" [:education] "Safety and Security" [:protection :logistics] "Logistics and Telecommunications" [:emergency-telecommunications] "Protection and Human Rights" [:protection]}] (get mapping theme []))) (defn- top-classes [config text] (map #(-> (watson/classify (:watson config) % text) :body :top_class) classifier-ids)) (defn classify [config text] (distinct (mapcat theme->clusters (top-classes config text)))) ;; Usage: lein run config.edn Text to classify here (defn -main [& args] (if-let [config-file (first args)] (let [config (-> config-file io/file slurp edn/read-string)] (clojure.pprint/pprint (classify config (str/join " " (drop 2 args))))) (println "Specify EDN config file")))
#!/bin/bash set -o errexit set -o pipefail set -o nounset #set -o xtrace # Get the repo and build directories repo_dir=$(dirname $0) build_dir=$1 mkdir -p $build_dir ### CODE MOBILITY SERVER cd ${repo_dir}/src/mobility_server make -f Makefile.linux_x86 clean all > /dev/null mv ${repo_dir}/src/mobility_server/mobility_server ${build_dir}
export default class TimeConversions{ constructor(unixTime) { this.date = new Date(unixTime * 1000) this.dayOfMonth = this.date.getDate(); this.month = this.date.getMonth() +1; this.year = this.date.getFullYear(); } formatTime() { return `${this.month}/${this.dayOfMonth}/${this.year}`; } }
function primeiraFuncao() { document.write(`Primeira função <br>`); } function mostrar(valor1, valor2){ window.alert(valor1); document.write(valor2); } function campo(valor){ alert(valor) } function inicio(){ alert("Ola"); }
$here = Split-Path -Path $MyInvocation.MyCommand.Path -Parent; $pluginRoot = Split-Path -Path $here -Parent; $testRoot = Split-Path -Path $pluginRoot -Parent; $moduleRoot = Split-Path -Path $testRoot -Parent; Import-Module "$moduleRoot\PScribo.psm1" -Force; InModuleScope 'PScribo' { Describe 'Plugins\Html\Out-HtmlDocument' { $path = (Get-PSDrive -Name TestDrive).Root It 'warns when 7 nested sections are defined' { $testDocument = Document -Name 'IllegalNestedSections' -ScriptBlock { Section -Name 'Level1' { Section -Name 'Level2' { Section -Name 'Level3' { Section -Name 'Level4' { Section -Name 'Level5' { Section -Name 'Level6' { Section -Name 'Level7' { } } } } } } } } { $testDocument | Out-HtmlDocument -Path $path -WarningAction Stop 3>&1 } | Should Throw '6 heading' } It 'calls Out-HtmlSection' { Mock -CommandName Out-HtmlSection Document -Name 'TestDocument' -ScriptBlock { Section -Name 'TestSection' -ScriptBlock { } } | Out-HtmlDocument -Path $path Assert-MockCalled -CommandName Out-HtmlSection -Exactly 1; } It 'calls Out-HtmlParagraph' { Mock -CommandName Out-HtmlParagraph Document -Name 'TestDocument' -ScriptBlock { Paragraph 'TestParagraph' } | Out-HtmlDocument -Path $path Assert-MockCalled -CommandName Out-HtmlParagraph -Exactly 1 } It 'calls Out-HtmlTable' { Mock -CommandName Out-HtmlTable Document -Name 'TestDocument' -ScriptBlock { Get-Process | Select-Object -First 1 | Table 'TestTable' } | Out-HtmlDocument -Path $path Assert-MockCalled -CommandName Out-HtmlTable -Exactly 1 } It 'calls Out-HtmlLineBreak' { Mock -CommandName Out-HtmlLineBreak Document -Name 'TestDocument' -ScriptBlock { LineBreak; } | Out-HtmlDocument -Path $path Assert-MockCalled -CommandName Out-HtmlLineBreak -Exactly 1 } It 'calls Out-HtmlPageBreak' { Mock -CommandName Out-HtmlPageBreak Document -Name 'TestDocument' -ScriptBlock { PageBreak; } | Out-HtmlDocument -Path $path Assert-MockCalled -CommandName Out-HtmlPageBreak -Exactly 1 } It 'calls Out-HtmlTOC' { Mock -CommandName Out-HtmlTOC Document -Name 'TestDocument' -ScriptBlock { TOC -Name 'TestTOC'; } | Out-HtmlDocument -Path $path Assert-MockCalled -CommandName Out-HtmlTOC -Exactly 1 } It 'calls Out-HtmlBlankLine' { Mock -CommandName Out-HtmlBlankLine Document -Name 'TestDocument' -ScriptBlock { BlankLine; } | Out-HtmlDocument -Path $path Assert-MockCalled -CommandName Out-HtmlBlankLine -Exactly 1 } It 'calls Out-HtmlBlankLine twice' { Mock -CommandName Out-HtmlBlankLine Document -Name 'TestDocument' -ScriptBlock { BlankLine; BlankLine; } | Out-HtmlDocument -Path $path Assert-MockCalled -CommandName Out-HtmlBlankLine -Exactly 3 ## Mock calls are cumalative } } }
#include <iostream> #include "List.h" using namespace std; List::List() { this->arr = new int[2]; this->capacity = 2; this->index = 0; } List::List(const List& list) { this->arr = new int[list.capacity]; this->capacity = list.capacity; this->index = list.index; } List::~List() { delete[] this->arr; } void List::add(int num) { if (this->capacity==this->index) { doubleArray(); } this->arr[this->index] = num; index++; } void List::insertAt(int index,int value) { if (!checkIndex(index)) { cout << "Invalid index!" << endl; } else { if ((this->index + 1) == this->capacity) { doubleArray(); } this->index++; for (int i = this->index - 1; i > index; i--) { this->arr[i] = this->arr[i - 1]; } this->arr[index] = value; } } void List::removeAt(int index) { if (!checkIndex(index)) { cout << "Invalid index!" << endl; } else { for (int i = index; i < this->index; i++) { this->arr[i] = this->arr[i + 1]; } this->index--; } } void List::doubleArray() { int newCapacity = this->capacity * 2; int* temp = new int[newCapacity]; for (int i = 0; i < this->capacity; i++) { temp[i] = this->arr[i]; } delete[] this->arr; this->arr = new int[newCapacity]; for (int i = 0; i < this->capacity; i++) { this->arr[i] = temp[i]; } delete[] temp; this->capacity = newCapacity; } int List::Count() { return this->index; } int List::getAt(int position) { if (!checkIndex(position)) { cout << "Invalid index!" << endl; } else { return this->arr[position]; } } bool List::checkIndex(int index) { if (index>=0&&index<this->index) { return true; } else { return false; } }
export function polyfill(runAppFn) { // https://github.com/emmenko/redux-react-router-async-example/blob/master/lib/index.js // https://github.com/babotech/react-intlable/blob/master/src/ready.js document.addEventListener('DOMContentLoaded', () => { if (!global.Intl) { require.ensure([ 'intl', 'intl/locale-data/jsonp/zh.js', 'intl/locale-data/jsonp/en.js', ], (require) => { require('intl'); require('intl/locale-data/jsonp/zh'); require('intl/locale-data/jsonp/en'); runAppFn(); }); } else { runAppFn(); } }); } export function format(messages) { return (intl, descriptor, values) => { if (!intl || !messages[descriptor]) { return descriptor; } return intl.formatMessage(messages[descriptor], values); }; } export function formati18n(messages) { return intl => (descriptor, values) => { if (!intl || !messages[descriptor]) { return descriptor; } return intl.formatMessage(messages[descriptor], values); }; }
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class StoreCronTask extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * 获取适用于请求的验证规则 * * @return array */ public function rules() { return [ 'LineInfo' => 'required|string|between:2,80', 'cid' => 'required|max:255', 'LineGuid' => 'required|max:255', 'is_task' => 'required', 'start_at' => 'required', 'end_at' => 'required', 'account' => [ 'sometimes', 'regex:/^1[3-9][0-9]\d{4,8}|(\w)+(\.\w+)*@(\w)+((\.\w+)+)|[0-9a-zA-Z_]+$/' // 验证账号可以为 手机号,邮箱或字符串 ] ]; } /** * 中文错误提示 * @return array */ public function messages() { return [ 'LineInfo.required' => '线路名称不能为空', 'LineInfo.string' => '线路名称必须是字符串', 'LineInfo.between' => '线路名称输入有误', 'cid.required' => 'cid 不能为空', 'cid.max' => 'cid 输入有误', 'LineGuid.required' => 'LineGuid 不能为空', 'LineGuid.max' => 'LineGuid 输入有误', 'is_task.required' => '是否启动必须选择', 'start_at.required' => '启动时间不能为空', 'end_at.required' => '结束时间不能为空', 'account.regex' => 'account 输入有误', ]; } }
#!/bin/sh # Set your CLASSPATH variable to the directory where the TLA+ tools are # installed. # Number of worker threads WORKERS=1 java tlc2.TLC criticalsection3.tla -config criticalsection3.cfg -workers $WORKERS -modelcheck -deadlock
/* * @file define.go * @brief 类型名称别名 * * @author kunliu2 * @version 1.0 * @date 2017.12 */ package xsf import ( "git.xfyun.cn/AIaaS/xsf-external/utils" ) type Logger = utils.Logger type Span = utils.Span type CfgMode = utils.CfgMode type CfgOpt = utils.CfgOpt type CfgOption = utils.CfgOption type FindManger = utils.FindManger
import { DestinyCharacterProgressionComponent, DestinyProgressionDefinition, DestinySeasonDefinition } from 'bungie-api-ts/destiny2'; import { D2ManifestDefinitions } from '../../destiny2/d2-definitions'; /** * Figure out whether a character has the "well rested" buff, which applies a 2x XP boost * for the first 5 season levels each week. Ideally this would just come back in the response, * but instead we have to calculate it from the weekly XP numbers. */ export function isWellRested( defs: D2ManifestDefinitions, season: DestinySeasonDefinition | undefined, characterProgression: DestinyCharacterProgressionComponent ): { wellRested: boolean; progress?: number; requiredXP?: number; } { if (!season || !season.seasonPassProgressionHash) { return { wellRested: false }; } const seasonProgressDef = defs.Progression.get(season.seasonPassProgressionHash); const seasonProgress = characterProgression.progressions[season.seasonPassProgressionHash]; const progress = seasonProgress.weeklyProgress; const requiredXP = xpRequiredForLevel(seasonProgress.level, seasonProgressDef) + xpRequiredForLevel(seasonProgress.level - 1, seasonProgressDef) + xpRequiredForLevel(seasonProgress.level - 2, seasonProgressDef) + xpRequiredForLevel(seasonProgress.level - 3, seasonProgressDef) + xpRequiredForLevel(seasonProgress.level - 4, seasonProgressDef); // Have you gained XP equal to three full levels worth of XP? return { wellRested: progress < requiredXP, progress, requiredXP }; } /** * How much XP was required to achieve the given level? */ function xpRequiredForLevel(level: number, progressDef: DestinyProgressionDefinition) { const stepIndex = Math.min(Math.max(1, level), progressDef.steps.length - 1); return progressDef.steps[stepIndex].progressTotal; }
#------------------------------------------------------------------------ # (The MIT License) # # Copyright (c) 2008-2011 Rhomobile, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # http://rhomobile.com #------------------------------------------------------------------------ # This module represents the rhodes mini OM require 'rhom/rhom_object_factory' require 'rhom/rhom_object' require 'rhom/rhom_model' module Rhom class RecordNotFound < StandardError end class Rhom attr_accessor :factory @@orm_instance = nil def self.get_instance @@orm_instance ||= self.new end def initialize @factory = RhomObjectFactory.new end class << Rhom def client_id if ::Rho::RHO.use_new_orm ::Rho::NewORM.getClientId else c_id = ::Rho::RHO.get_user_db().select_from_table('client_info','client_id')[0] c_id.nil? ? nil : c_id['client_id'] end end def have_local_changes if ::Rho::RHO.use_new_orm ::Rho::NewORM.haveLocalChanges else #TODO: enumerate all sync sources, create array of partitions and run query for all partition. res = ::Rho::RHO.get_user_db().execute_sql("SELECT object FROM changed_values WHERE sent<=1 LIMIT 1 OFFSET 0") return res.length > 0 end end def database_local_reset() puts "database_local_reset" #load all partitions unless ::Rho::RHO.use_new_orm Rho::RHO.load_all_sources ::Rho::RHO.get_db_partitions().each do |partition, db| next if partition != 'local' db.destroy_tables( :exclude => ['sources','client_info'] ) end hash_migrate = {} ::Rho::RHO.init_schema_sources(hash_migrate) else ::Rho::NewORM.databaseLocalReset end end def database_client_reset(reset_local_models=true) #load all partitions Rho::RHO.load_all_sources if defined?(RHOCONNECT_CLIENT_PRESENT) old_interval = Rho::RhoConnectClient.set_pollinterval(0) Rho::RhoConnectClient.stop_sync end params = ["", "", 0] ::Rho::RHO.get_user_db().execute_sql("UPDATE client_info SET client_id=?, token=?, token_sent=?", params) if ( Rho::RhoConfig.exists?('bulksync_state') ) Rho::RhoConfig.bulksync_state='0' end ::Rho::RHO.get_db_partitions().each do |partition, db| next if !reset_local_models && partition == 'local' db.execute_sql("UPDATE sources SET token=0") db.destroy_tables( :exclude => (['sources','client_info']) ) end hash_migrate = {} ::Rho::RHO.init_schema_sources(hash_migrate) if defined?(RHOCONNECT_CLIENT_PRESENT) Rho::RhoConnectClient.set_pollinterval(old_interval) end end def database_full_reset_ex(*args) puts "database_full_reset_ex #{args}" if (args.count == 0 || !args[0][:models]) database_full_reset( args.count > 0 && !args[0][:reset_client_info].nil?() ? args[0][:reset_client_info] : false, args.count > 0 && !args[0][:reset_local_models].nil?() ? args[0][:reset_local_models] : true ) return end raise ArgumentError, "reset_client_info should not be true if reset selected models" if args.count > 0 && args[0][:reset_client_info] #load all partitions Rho::RHO.load_all_sources if defined?(RHOCONNECT_CLIENT_PRESENT) old_interval = Rho::RhoConnectClient.pollInterval Rho::RhoConnectClient.pollInterval = 0 Rho::RhoConnectClient.stop_sync end ::Rho::RHO.get_user_db().execute_sql("UPDATE client_info SET reset=1") Rho::RhoConfig.reset_models = "" args[0][:models].each do |src_name| db = ::Rho::RHO.get_src_db(src_name) src_partition = Rho::RhoConfig.sources[src_name]['partition'] is_schema_source = !Rho::RhoConfig.sources[src_name]['schema'].nil? next if !args[0][:reset_local_models] && src_partition == 'local' if (src_partition != 'local') # build comma-separated string of models Rho::RhoConfig.reset_models += "," unless Rho::RhoConfig.reset_models.size == 0 Rho::RhoConfig.reset_models += "#{src_name}" end begin db.start_transaction db.execute_sql("UPDATE sources SET token=0 WHERE name = ?", src_name ) if is_schema_source db.execute_sql("DELETE FROM #{src_name}") else db.execute_sql("DELETE FROM object_values WHERE source_id=?", Rho::RhoConfig.sources[src_name]['source_id'].to_i) end db.commit rescue Exception => e puts 'database_full_reset_ex Exception: ' + e.inspect db.rollback raise end end #hash_migrate = {} #::Rho::RHO.init_schema_sources(hash_migrate) if defined?(RHOCONNECT_CLIENT_PRESENT) Rho::RhoConnectClient.pollInterval = old_interval end end def database_full_reset(reset_client_info=false, reset_local_models=true) puts "database_full_reset : reset_client_info=#{reset_client_info}, reset_local_models=#{reset_local_models}" #load all partitions Rho::RHO.load_all_sources if defined?(RHOCONNECT_CLIENT_PRESENT) old_interval = Rho::RhoConnectClient.pollInterval = 0 Rho::RhoConnectClient.stop_sync end ::Rho::RHO.get_user_db().execute_sql("UPDATE client_info SET reset=1") if ( Rho::RhoConfig.exists?('bulksync_state') ) Rho::RhoConfig.bulksync_state='0' end ::Rho::RHO.get_db_partitions().each do |partition, db| next if !reset_local_models && partition == 'local' db.execute_sql("UPDATE sources SET token=0") db.destroy_tables( :exclude => (reset_client_info ? ['sources'] : ['sources','client_info']) ) end if ( reset_client_info && Rho::RhoConfig.exists?('push_pin') ) Rho::RhoConfig.push_pin='' end hash_migrate = {} ::Rho::RHO.init_schema_sources(hash_migrate) if defined?(RHOCONNECT_CLIENT_PRESENT) Rho::RhoConnectClient.pollInterval = old_interval end end def database_full_reset_and_logout database_full_reset if defined?(RHOCONNECT_CLIENT_PRESENT) Rho::RhoConnectClient.logout end end def database_fullclient_reset_and_logout database_full_reset(true) if defined?(RHOCONNECT_CLIENT_PRESENT) Rho::RhoConnectClient.logout end end def database_export(partition) db = ::Rho::RHO::get_db_partitions[partition] if db db.export end end def database_import(partition, zipName) db = ::Rho::RHO::get_db_partitions[partition] if db db.import(zipName) end end def search(args) #TODO : remove it, use Rho::RhoConnectClient.search if defined?(RHOCONNECT_CLIENT_PRESENT) src_ar = args[:sources] #check sources raise ArgumentError, "no sources on search" if src_ar.nil? or src_ar.length == 0 src_ar.each do |src_name| raise ArgumentError, "no sources on search" if Rho::RhoConfig::sources[src_name].nil? end Rho::RhoConnectClient.search(args) end end end #class methods end # Rhom end # Rhom
<?php session_start(); $con = new mysqli('localhost', 'root', '', 'foog_db'); $email = $_POST['email']; $pass = $_POST['password']; $s = "select * from user where email = '$email'and password = '$pass'"; $result = mysqli_query($con, $s); //Checking if the name is already used or not $num = mysqli_num_rows($result); $data = mysqli_fetch_assoc($result); if($num == 1){ // $_SESSION['email'] = $email; header('location:../index.php'); $_SESSION['success'] = "<a href='logout.php'>Log out</a>"; $_SESSION['change-login'] = '<a href="products.php" class="button">Shop Now</a>'; $_SESSION['account-manipulate'] = '<li><a href="account.php" class="fas fa-user-circle"></a></li'; $_SESSION['email'] = $email; $_SESSION['cart-nav'] = '<a href="cart.php" class="fas fa-shopping-cart">'; $_SESSION['add-cart'] = '<input type="submit" class="btn" value="add to cart" name="add_to_cart">'; $_SESSION['go-to-products'] = '<a href="products.php" class="btn">Go To Products</a>'; $_SESSION['user_id'] = $data['user_id']; } else{ header('location:../loginError.php'); } ?>
package be.vlproject.egcevent.security.dto; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonTypeInfo; @JsonTypeInfo( use = JsonTypeInfo.Id.NONE, include = JsonTypeInfo.As.EXISTING_PROPERTY ) @JsonIgnoreProperties(ignoreUnknown = true) public abstract class JwtValidateResponseDtoMixin { @JsonCreator JwtValidateResponseDtoMixin(boolean valid) {} }
import Cabin from "./Cabin" export {ICabin} from "./Cabin" export default Cabin
-module(case02). -export([main/0]). f_case(N) -> case N of N when is_number(N) -> {number, N}; N when is_atom(N) -> {atom, N}; N when is_list(N) -> {list, N}; N when is_tuple(N) -> {tuple, N}; Stg -> {something_else, Stg} end. my_map(_Mapper, []) -> []; my_map(Mapper, List) -> my_map_impl(Mapper, List, []). my_map_impl(_Mapper, [], Acc) -> my_rev(Acc); my_map_impl(Mapper, [H|T], Acc) -> my_map_impl(Mapper, T, [Mapper(H) | Acc]). my_rev([]) -> []; my_rev(List) -> my_rev_impl([], List). my_rev_impl(Acc, []) -> Acc; my_rev_impl(Acc, [H|T]) -> my_rev_impl([H | Acc], T). main() -> Fun = fun (X) when is_integer(X) -> X+1; (X) when is_float(X) -> X*X; (X) -> X end, my_map(fun(X) -> f_case(Fun(X)) end, [3, 1.5, hello, [], {}]).
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using Woc.Book.Base.BusinessEntity; using Woc.Book.Base.Service; namespace Woc.Book.Base { public class AccessLevelController { public List<AccessLevels> GetData() { AccessLevelService accessLevelService = new AccessLevelService(); List<AccessLevels> ListAccessLevels = new List<AccessLevels>(); DataTable table = new DataTable(); table = accessLevelService.GetAccessLevel(); AccessLevels accessLevels; foreach (DataRow row in table.Rows) { accessLevels = new AccessLevels(); accessLevels.AccessLevelID = (Guid)row["AccessLevelID"]; accessLevels.AccessLevel = row["AccessLevel"].ToString(); ListAccessLevels.Add(accessLevels); } return ListAccessLevels; } } }
package io.joern.kotlin2cpg.querying import io.joern.kotlin2cpg.Kt2CpgTestContext import io.shiftleft.semanticcpg.language._ import io.shiftleft.codepropertygraph.generated.Operators import org.scalatest.freespec.AnyFreeSpec import org.scalatest.matchers.should.Matchers class ComparisonOperatorTests extends AnyFreeSpec with Matchers { "CPG for code with simple comparison operator usage" - { lazy val cpg = Kt2CpgTestContext.buildCpg(""" |fun main(args : Array<String>): Int { | val x: Int = 1 | val y: Int = 2 | | if (x == 1) { | return 2 | } | | if (x != 1) { | return 1 | } | | if (x < 1) { | return 3 | } | | if (x <= 1) { | return 4 | } | | if (x > 1) { | return 5 | } | | if (x >= 1) { | return 6 | } |} |""".stripMargin) "should have a non-0 number of CALL nodes" in { cpg.call.size should not be 0 } "should contain a call node for the `equals` operator" in { cpg.call(Operators.equals).size should not be 0 } "should contain a call node for the `notEquals` operator" in { cpg.call(Operators.notEquals).size should not be 0 } "should contain a call node for the `greaterThan` operator" in { cpg.call(Operators.greaterThan).size should not be 0 } "should contain a call node for the `greaterEqualsThan` operator" in { cpg.call(Operators.greaterEqualsThan).size should not be 0 } "should contain a call node for the `lessThan` operator" in { cpg.call(Operators.lessThan).size should not be 0 } "should contain a call node for the `lessEqualsThan` operator" in { cpg.call(Operators.lessEqualsThan).size should not be 0 } } }
package net.leonini.passwordgrids import org.scalatest._ class PasswordSpec extends FlatSpec with Matchers { def randomString(n: Int): String = { n match { case 1 => util.Random.nextPrintableChar.toString case _ => util.Random.nextPrintableChar.toString ++ randomString(n-1).toString } } "A Grid" should "throw IllegalArgumentException if alphabet is empty" in { a [IllegalArgumentException] should be thrownBy { val g = new Grid("test", "", 0) } } "A Grid" should "throw IllegalArgumentException if alphabet is too long" in { a [IllegalArgumentException] should be thrownBy { val g = new Grid("test", randomString(256), 0) } } "A Grid" should "throw IllegalArgumentException if hash size is too small for grid size" in { a [IllegalArgumentException] should be thrownBy { val g = new Grid("test", randomString(255), 9) } } }
using System; namespace Zw.EliteExx.Core.Config { public class Env { public string AppFolder { get; } public Env(string appFolder) { this.AppFolder = appFolder; } } }
package org.openstreetmap.atlas.tags.annotations.validation; import java.util.Optional; import org.junit.Assert; import org.junit.Test; import org.openstreetmap.atlas.tags.BuildingTag; import org.openstreetmap.atlas.tags.annotations.Tag; import org.openstreetmap.atlas.tags.annotations.TagKey; import org.openstreetmap.atlas.utilities.testing.TestTaggable; /** * Test case for verifying reflections-based enum value parsing * * @author cstaylor */ public class FromEnumTestCase { /** * Private tag used for with=enum testing * * @author cstaylor */ @Tag(with = { EightBall.class }) public interface DisusedEightBall { @TagKey String KEY = "disused:eightball"; } /** * Private tag used for test case * * @author cstaylor */ @Tag public enum EightBall { YES, NO, MAYBE; @TagKey public static final String KEY = "magic-eight-ball"; } @Test public void testAnnotationExists() { final TestTaggable testing = new TestTaggable(EightBall.KEY, "maYbE"); final Optional<EightBall> found = Validators.fromAnnotation(EightBall.class, testing); Assert.assertTrue(found.isPresent()); Assert.assertEquals(EightBall.MAYBE, found.get()); } @Test public void testAnnotationIllegalValue() { final TestTaggable testing = new TestTaggable(EightBall.KEY, "Nope"); final Optional<EightBall> found = Validators.fromAnnotation(EightBall.class, testing); Assert.assertFalse(found.isPresent()); } @Test public void testAnnotationMissingValue() { final TestTaggable testing = new TestTaggable(BuildingTag.KEY, "Nope"); final Optional<EightBall> found = Validators.fromAnnotation(EightBall.class, testing); Assert.assertFalse(found.isPresent()); } @Test public void testExists() { final TestTaggable testing = new TestTaggable(EightBall.KEY, "maYbE"); final Optional<EightBall> found = Validators.from(EightBall.class, testing); Assert.assertTrue(found.isPresent()); Assert.assertEquals(EightBall.MAYBE, found.get()); } @Test public void testIllegalValue() { final TestTaggable testing = new TestTaggable(EightBall.KEY, "Nope"); final Optional<EightBall> found = Validators.from(EightBall.class, testing); Assert.assertFalse(found.isPresent()); } @Test public void testMissingValue() { final TestTaggable testing = new TestTaggable(BuildingTag.KEY, "Nope"); final Optional<EightBall> found = Validators.from(EightBall.class, testing); Assert.assertFalse(found.isPresent()); } @Test public void testWith() { final TestTaggable testing = new TestTaggable(DisusedEightBall.KEY, "maYbE"); final Optional<EightBall> found = Validators.from(DisusedEightBall.class, EightBall.class, testing); Assert.assertTrue(found.isPresent()); Assert.assertEquals(EightBall.MAYBE, found.get()); } }