hexsha
stringlengths
40
40
size
int64
140
1.03M
ext
stringclasses
94 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
663
max_stars_repo_name
stringlengths
4
120
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
663
max_issues_repo_name
stringlengths
4
120
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
663
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
140
1.03M
avg_line_length
float64
2.32
23.1k
max_line_length
int64
11
938k
alphanum_fraction
float64
0.01
1
score
float32
3
4.25
c1f556a18605748a3f80a9c31970172181d081b0
1,335
rs
Rust
shared/rust/src/domain/jig/module/body/legacy/design.rs
mastapegs/ji-cloud
b572289c5987f5e937f5e030fbd2712229ea1204
[ "Apache-2.0", "MIT" ]
null
null
null
shared/rust/src/domain/jig/module/body/legacy/design.rs
mastapegs/ji-cloud
b572289c5987f5e937f5e030fbd2712229ea1204
[ "Apache-2.0", "MIT" ]
null
null
null
shared/rust/src/domain/jig/module/body/legacy/design.rs
mastapegs/ji-cloud
b572289c5987f5e937f5e030fbd2712229ea1204
[ "Apache-2.0", "MIT" ]
null
null
null
pub use super::*; use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct Design { /// Background layer pub bgs: Vec<String>, /// Stickers layer pub stickers: Vec<Sticker>, } #[skip_serializing_none] #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Sticker { pub filename: String, pub transform_matrix: [f64; 16], /// hide and hide_toggle are mapped from the top sections /// in "Houdini": HideOnTap, ShowOnTap, and ToggleOnTap /// start out hidden pub hide: bool, /// toggle hidden state pub hide_toggle: Option<HideToggle>, /// animation options are mapped from the bottom animation section pub animation: Option<Animation>, // associated audio pub audio_filename: Option<String>, /// override the size pub override_size: Option<(f64, f64)>, } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum HideToggle { /// only let the toggle fire once Once, /// let the toggle fire indefinitely Always, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Animation { /// do not let the animation loop pub once: bool, /// wait for tap before playing pub tap: bool, }
26.176471
70
0.681648
3.015625
4e3ca40eda2ff5f21b292bb82181a35834676cc0
1,511
lua
Lua
Data/Script/zone/zone_30/init.lua
audinowho/DumpAsset
2303e1d0e516386545bbbdf8103e8a1fc00e4f92
[ "MS-PL", "Zlib", "MIT" ]
1
2022-02-26T15:41:19.000Z
2022-02-26T15:41:19.000Z
Data/Script/zone/zone_30/init.lua
audinowho/DumpAsset
2303e1d0e516386545bbbdf8103e8a1fc00e4f92
[ "MS-PL", "Zlib", "MIT" ]
null
null
null
Data/Script/zone/zone_30/init.lua
audinowho/DumpAsset
2303e1d0e516386545bbbdf8103e8a1fc00e4f92
[ "MS-PL", "Zlib", "MIT" ]
null
null
null
require 'common' local zone_30 = {} -------------------------------------------------- -- Map Callbacks -------------------------------------------------- function zone_30.Init(zone) DEBUG.EnableDbgCoro() --Enable debugging this coroutine PrintInfo("=>> Init_zone_30") end function zone_30.Rescued(zone, name, mail) COMMON.Rescued(zone, name, mail) end function zone_30.EnterSegment(zone, rescuing, segmentID, mapID) if rescuing ~= true then COMMON.BeginDungeon(zone.ID, segmentID, mapID) end end function zone_30.ExitSegment(zone, result, rescue, segmentID, mapID) DEBUG.EnableDbgCoro() --Enable debugging this coroutine PrintInfo("=>> ExitSegment_zone_30 result "..tostring(result).." segment "..tostring(segmentID)) --first check for rescue flag; if we're in rescue mode then take a different path COMMON.ExitDungeonMissionCheck(zone.ID, segmentID) if rescue == true then COMMON.EndRescue(zone, result, segmentID) elseif result ~= RogueEssence.Data.GameProgress.ResultType.Cleared then COMMON.EndDungeonDay(result, SV.checkpoint.Zone, SV.checkpoint.Segment, SV.checkpoint.Map, SV.checkpoint.Entry) else if segmentID == 0 then if GAME:InRogueMode() then COMMON.EndDungeonDay(result, 1,-1,1,0) else GAME:EnterZone(30, -1, 0, 0) end else PrintInfo("No exit procedure found!") COMMON.EndDungeonDay(result, SV.checkpoint.Zone, SV.checkpoint.Segment, SV.checkpoint.Map, SV.checkpoint.Entry) end end end return zone_30
30.22
115
0.683653
3.109375
571bb698b611a128529c8d8d902ecca028f3404f
1,227
c
C
private/sdktools/vctools/rc/rc.c
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/sdktools/vctools/rc/rc.c
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/sdktools/vctools/rc/rc.c
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
#include "rc.h" int CALLBACK RC(HWND hWnd, int fStatus, RC_MESSAGE_CALLBACK lpfnMsg, RC_PARSE_CALLBACK lpfnParse, int argc, PCHAR *argv); extern BOOL WINAPI Handler(DWORD fdwCtrlType); int CALLBACK UpdateRCStatus(ULONG u, ULONG dw, PCHAR p) { int i = strlen(p); PCHAR ppercent = strchr(p, '%'); if (i >= 2 && ((p[i - 1] == '\n' && p[i - 2] == '\r') || (p[i - 1] == '\r' && p[i - 2] == '\n'))) p[i-2] = '\0'; if (*p) { if (ppercent) { for (ppercent=p,i=0 ; *ppercent ; ppercent++) if (*ppercent == '%') i++; ppercent = malloc(strlen(p) + 1 + i); if (ppercent) { PCHAR pT = ppercent; while (*p) { if (*p == '%') *pT++ = '%'; *pT++ = *p++; } *pT++ = '\0'; printf(ppercent); } else { while (strchr(p, '%')) *strchr(p, '%') = ' '; printf(p); } } else { printf(p); } } printf("\n"); return(0); } int __cdecl main(int nArgC, char** pArgV) { int rc; SetConsoleCtrlHandler(Handler, TRUE); rc = RC(NULL, 0, UpdateRCStatus, NULL, nArgC, (PCHAR*)pArgV); SetConsoleCtrlHandler(Handler, FALSE); exit(rc); return 0; }
20.114754
66
0.481663
3.453125
c352d7c8868f1e7929a1337b54df4602bab8572b
1,359
rs
Rust
src/process/pid.rs
llenotre/maestro
ecc8d905ae5df69c5167e095583d87642871d55b
[ "MIT" ]
45
2020-11-29T19:40:44.000Z
2022-03-04T15:29:05.000Z
src/process/pid.rs
llenotre/maestro
ecc8d905ae5df69c5167e095583d87642871d55b
[ "MIT" ]
null
null
null
src/process/pid.rs
llenotre/maestro
ecc8d905ae5df69c5167e095583d87642871d55b
[ "MIT" ]
null
null
null
//! This module handles process PIDs. //! Each process must have an unique PID, thus they have to be allocated. The kernel uses a //! bitfield to store the used PIDs. use crate::errno::Errno; use crate::util::container::id_allocator::IDAllocator; /// Type representing a Process ID. This ID is unique for every running processes. pub type Pid = u16; /// The maximum possible PID. const MAX_PID: Pid = 32768; /// The PID of the init process. pub const INIT_PID: Pid = 1; /// A structure handling PID allocations. pub struct PIDManager { /// The PID allocator. allocator: IDAllocator, } impl PIDManager { /// Creates a new instance. pub fn new() -> Result<Self, Errno> { let mut s = Self { allocator: IDAllocator::new(MAX_PID as _)?, }; s.allocator.set_used((INIT_PID - 1) as _); Ok(s) } /// Returns a unused PID and marks it as used. pub fn get_unique_pid(&mut self) -> Result<Pid, Errno> { match self.allocator.alloc(None) { Ok(i) => { debug_assert!(i <= MAX_PID as _); Ok((i + 1) as _) }, Err(e) => { Err(e) } } } /// Releases the given PID `pid` to make it available for other processes. /// If the PID wasn't allocated, the function does nothing. pub fn release_pid(&mut self, pid: Pid) { debug_assert!(pid >= 1); debug_assert!(pid <= MAX_PID as _); self.allocator.free((pid - 1) as _) } }
24.709091
91
0.661516
3.296875
2fc17c905f62c443bf30c1624a686d49a974a892
878
rs
Rust
rust--learnings/03/control_flow/src/main.rs
jekhokie/scriptbox
93c03d8ab9b7e7cd9c5c6a65b444392ffe92fd70
[ "MIT" ]
11
2020-03-29T09:12:25.000Z
2022-03-24T01:01:50.000Z
rust--learnings/03/control_flow/src/main.rs
jekhokie/scriptbox
93c03d8ab9b7e7cd9c5c6a65b444392ffe92fd70
[ "MIT" ]
5
2021-06-02T03:41:51.000Z
2022-02-26T03:48:50.000Z
rust--learnings/03/control_flow/src/main.rs
jekhokie/scriptbox
93c03d8ab9b7e7cd9c5c6a65b444392ffe92fd70
[ "MIT" ]
8
2019-02-01T13:33:14.000Z
2021-12-14T20:16:03.000Z
fn main() { let x = 3; // simple less/greater if x < 5 { println!("condition was true - x was less than 5"); } else { println!("condition was false - x was greater than 5"); } // equality if x != 3 { println!("x is not equal to 3"); } else { println!("x is equal to 3"); } // multiple checks - mod operation // likely better to use a `match` here for performance/quality let y = 6; if y % 4 == 0 { println!("y is divisible by 4"); } else if y % 3 == 0 { println!("y is divisible by 3"); } else if y % 2 == 0 { println!("y is divisible by 2"); } else { println!("y is not divisible by 4, 3, or 2"); } // using `if` with `let` let condition = true; let z = if condition { 5 } else { 6 }; println!("The value of z is: {}", z); }
24.388889
66
0.501139
3.140625
86b777d46ee92d3a4b5aae9c2284a98846aad18b
2,543
rs
Rust
src/files.rs
koba-e964/efmt
f52e22b2ef94c56546ec3db6522c3423353fa4c4
[ "Apache-2.0", "MIT" ]
null
null
null
src/files.rs
koba-e964/efmt
f52e22b2ef94c56546ec3db6522c3423353fa4c4
[ "Apache-2.0", "MIT" ]
null
null
null
src/files.rs
koba-e964/efmt
f52e22b2ef94c56546ec3db6522c3423353fa4c4
[ "Apache-2.0", "MIT" ]
null
null
null
use std::path::{Path, PathBuf}; use std::process::Command; pub fn collect_default_target_files() -> anyhow::Result<Vec<PathBuf>> { let current_dir = std::env::current_dir()?; if is_git_repository(&current_dir) { collect_files_with_git(is_format_target) } else { collect_files_without_git(current_dir, is_format_target) } } fn collect_files_with_git<F>(is_target: F) -> anyhow::Result<Vec<PathBuf>> where F: Fn(&Path) -> bool, { let mut files = Vec::new(); let args_list = [ &["ls-files"][..], &["ls-files", "--others", "--exclude-standard"][..], ]; for args in args_list { let output = Command::new("git").args(args).output()?; anyhow::ensure!( output.status.success(), "Failed to execute `$ git {}` command.\n{}", Vec::from(args).join(" "), String::from_utf8_lossy(&output.stderr) ); for file in String::from_utf8(output.stdout)?.split('\n') { if file.is_empty() { continue; } let path = PathBuf::from(file); if !is_target(&path) { continue; } files.push(path); } } Ok(files) } fn collect_files_without_git<P: AsRef<Path>, F>( root_dir: P, is_target: F, ) -> anyhow::Result<Vec<PathBuf>> where F: Fn(&Path) -> bool, { let mut files = Vec::new(); let mut stack = vec![root_dir.as_ref().to_path_buf()]; while let Some(dir) = stack.pop() { for entry in std::fs::read_dir(dir)? { let entry = entry?; if entry.file_type()?.is_dir() { stack.push(entry.path()); } else if entry.file_type()?.is_file() { let path = entry.path(); if is_target(&path) { files.push(path); } } } } Ok(files) } fn is_format_target(path: &Path) -> bool { path.file_name() .and_then(|n| n.to_str()) .map_or(false, |n| { n == "rebar.config" || n.ends_with(".erl") || n.ends_with(".hrl") || n.ends_with(".app.src") }) } fn is_git_repository<P: AsRef<Path>>(dir: P) -> bool { let mut dir = dir.as_ref(); while !dir.join(".git/").exists() { if let Some(parent) = dir.parent() { dir = parent; } else { return false; } } log::debug!("Found `.git` in {:?}", dir); true }
27.344086
74
0.503736
3.140625
49c3d627c2380e673bc43dc77b6b3173c905fba6
3,806
lua
Lua
unity3d-roll-a-ball-master/Atari2/rollaball.lua
DanielTea/Unity_AI
7169daa7dbae8e54d8d5042b20cd04e8c1006de7
[ "MIT" ]
1
2016-12-24T18:33:03.000Z
2016-12-24T18:33:03.000Z
unity3d-roll-a-ball-master/Atari2/rollaball.lua
DanielTea/Unity_AI
7169daa7dbae8e54d8d5042b20cd04e8c1006de7
[ "MIT" ]
null
null
null
unity3d-roll-a-ball-master/Atari2/rollaball.lua
DanielTea/Unity_AI
7169daa7dbae8e54d8d5042b20cd04e8c1006de7
[ "MIT" ]
null
null
null
local classic = require 'classic' require 'image' local Catch, super = classic.class('Catch', Env) -- Constructor function Catch:_init(opts) opts = opts or {} self.level = opts.level or 2 -- Width and height self.size = opts.size or 20 self.screen = torch.FloatTensor(3, self.size, self.size):zero() self.blank = torch.FloatTensor(3, self.size, self.size):zero() end -- 1 state returned, of type 'int', of dimensionality 1 x self.size x self.size, between 0 and 1 function Catch:getStateSpec() return {'int', {3, self.size, self.size}, {0, 1}} end -- 1 action required, of type 'int', of dimensionality 1, between 0 and 2 function Catch:getActionSpec() return {'int', 1, {1, 5}} end -- RGB screen of size self.size x self.size function Catch:getDisplaySpec() return {'real', {3, self.size, self.size}, {0, 1}} end -- Min and max reward function Catch:getRewardSpec() return 0, 12 end function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end -- Redraws screen based on state function Catch:redraw() -- Reset screen self.screen:zero() while file_exists('/media/daniel/BigNeuronalNetwo/NewTests/unity3d-roll-a-ball-master/sem1.txt') == true do --local fin = torch.DiskFile('/home/daniel/unity3d-roll-a-ball-master/SavedScreen.jpg', 'r') --fin:binary() --fin:seekEnd() --local file_size_bytes = fin:position() - 1 --fin:seek(1) --local img_binary = torch.ByteTensor(file_size_bytes) --fin:readByte(img_binary:storage()) --fin:close() -- Then when you're ready to decompress the ByteTensor: --img = image.decompressJPG(img_binary) end --open semaphore file = io.open('/media/daniel/BigNeuronalNetwo/NewTests/unity3d-roll-a-ball-master/sem2.txt','w') file:close() img = image.load('/media/daniel/BigNeuronalNetwo/NewTests/unity3d-roll-a-ball-master/SavedScreen.jpg',3,'float') os.remove('/media/daniel/BigNeuronalNetwo/NewTests/unity3d-roll-a-ball-master/sem2.txt') --img = image.load('/home/daniel/unity3d-roll-a-ball-master/SavedScreen.jpg',3,'float') --log.info(img) --image.display(img) self.screen =img end -- Starts new game function Catch:start() stepnumber = 0 scorefile = io.open("/media/daniel/BigNeuronalNetwo/NewTests/unity3d-roll-a-ball-master/score.txt", "w") scorefile:write(0) scorefile:close() -- Redraw screen self:redraw() --log.info('test') -- Return observation return self.screen end -- Steps in a game function Catch:step(action) local reward = 0 stepnumber = stepnumber +1 while file_exists('/media/daniel/BigNeuronalNetwo/NewTests/unity3d-roll-a-ball-master/unitySWSem.txt') == true do end file = io.open('/media/daniel/BigNeuronalNetwo/NewTests/unity3d-roll-a-ball-master/networkSWSem.txt','w') file:close() -- Reward is 0 by default file = io.open("action.txt", "w") file:write(action) file:close() scorefile = io.open("/media/daniel/BigNeuronalNetwo/NewTests/unity3d-roll-a-ball-master/score.txt", "r") scorefromfile = scorefile:read() scorefile:close() file = io.open("stepnumber.txt", "w") file:write(stepnumber) file:close() scoreint = tonumber(scorefromfile) --log.info(scoreint) --reward = 10000 - stepnumber --log.info(scoreint) os.remove('/media/daniel/BigNeuronalNetwo/NewTests/unity3d-roll-a-ball-master/networkSWSem.txt') -- Check terminal condition --reward = scoreint --log.info(reward) local terminal = false if scoreint == 12 then reward = 12 terminal = true end if stepnumber == 10000 then reward = scoreint --slog.info(reward) terminal = true end --log.info(reward) -- Redraw screen self:redraw() local screen = self.screen return reward, screen, terminal end -- Returns (RGB) display of screen function Catch:getDisplay() return torch.repeatTensor(self.screen, 1, 1, 1) end return Catch
23.639752
113
0.721755
3.328125
2d81870a4b85d1b7aa92c64f0a45dc74291f26f5
1,308
rs
Rust
src/private.rs
avitex/rust-zc
1ab65d0a4fb90326956228ee86563689eafeab31
[ "MIT" ]
41
2020-12-08T12:31:48.000Z
2022-03-15T20:35:07.000Z
src/private.rs
avitex/rust-zc
1ab65d0a4fb90326956228ee86563689eafeab31
[ "MIT" ]
4
2020-12-08T09:48:13.000Z
2021-01-20T00:56:17.000Z
src/private.rs
avitex/rust-zc
1ab65d0a4fb90326956228ee86563689eafeab31
[ "MIT" ]
1
2020-12-09T01:01:13.000Z
2020-12-09T01:01:13.000Z
use core::{mem, ptr}; use crate::Dependant; unsafe fn erase_lifetime<'o, D: Dependant<'o>>(dependant: D) -> D::Static { let self_ptr: *const D = &dependant; let erased = ptr::read(self_ptr.cast::<D::Static>()); mem::forget(dependant); erased } pub unsafe trait Construct<'o, O>: Sized where O: ?Sized, { type Dependant: Dependant<'static>; unsafe fn construct(self, owned: &'o O) -> Self::Dependant; } unsafe impl<'o, O, D, F> Construct<'o, O> for F where O: ?Sized + 'o, D: Dependant<'o>, F: FnOnce(&'o O) -> D + 'static, { type Dependant = D::Static; unsafe fn construct(self, owned: &'o O) -> Self::Dependant { erase_lifetime((self)(owned)) } } pub unsafe trait TryConstruct<'o, O>: Sized where O: ?Sized, { type Error: 'static; type Dependant: Dependant<'static>; unsafe fn try_construct(self, owned: &'o O) -> Result<Self::Dependant, Self::Error>; } unsafe impl<'o, O, D, E, F> TryConstruct<'o, O> for F where E: 'static, O: ?Sized + 'o, D: Dependant<'o>, F: FnOnce(&'o O) -> Result<D, E> + 'static, { type Error = E; type Dependant = D::Static; unsafe fn try_construct(self, owned: &'o O) -> Result<Self::Dependant, Self::Error> { (self)(owned).map(|d| erase_lifetime(d)) } }
22.551724
89
0.595566
3.046875
cbc3029ea79880b0a00f9b2bb81840fa64fd0fa4
4,598
swift
Swift
AWSenseConnect/AWSenseConnectPhone/SessionManager.swift
MiezelKat/AWSense
ad09b0326f69ca4aefb9ea586f943400a2e1432f
[ "MIT" ]
12
2017-04-19T17:10:34.000Z
2021-07-21T12:05:13.000Z
AWSenseConnect/AWSenseConnectPhone/SessionManager.swift
MiezelKat/AWSense
ad09b0326f69ca4aefb9ea586f943400a2e1432f
[ "MIT" ]
1
2020-11-02T14:44:23.000Z
2020-11-02T14:44:23.000Z
AWSenseConnect/AWSenseConnectPhone/SessionManager.swift
MiezelKat/AWSense
ad09b0326f69ca4aefb9ea586f943400a2e1432f
[ "MIT" ]
6
2018-07-21T05:43:30.000Z
2021-10-17T14:09:19.000Z
// // SessionManager.swift // AWSenseConnect // // Created by Katrin Haensel on 03/03/2017. // Copyright © 2017 Katrin Haensel. All rights reserved. // import Foundation import AWSenseShared public class SessionManager : MessageEventHandler{ // MARK: - singleton public static let instance : SessionManager = SessionManager() private init() { CommunicationManager.instance.subscribe(handler: self) } // MARK: - properties public private(set) var currentSession : RemoteSensingSession? private let remoteSensingEvent : RemoteSensingEvent = RemoteSensingEvent() private let sensingBuffer = RemoteSensingDataBuffer.instance // MARK: - MessageEventHandler interface internal func handle(message : Message){ if(currentSession == nil){ return } switch message.type { case .startedSensing: assert(currentSession!.state == .prepareRunning) currentSession!.state = .running remoteSensingEvent.raiseEvent(withType: .sessionStateChanged, forSession: currentSession!) case .stoppedSensing: assert(currentSession!.state == .prepareStopping) currentSession!.state = .stopped remoteSensingEvent.raiseEvent(withType: .sessionStateChanged, forSession: currentSession!) sensingBuffer.serialiseAll() case .sensingData: let pm = message as! SensingDataMessage let data = pm.sensingData let t = pm.sensingDataType remoteSensingEvent.raiseEvent(withType: .remoteSessionDataReceived, forSession: currentSession!, withData: data) sensingBuffer.append(sensingData: data, forType: t) default: break // todo error handling } } // MARK: - methods public func startSensingSession(withName name: String? = nil, configuration: [AWSSensorType], sensorSettings settings: [SensorSettings]? = nil, transmissionIntervall intervall: DataTransmissionInterval = DataTransmissionInterval.standard) throws{ if(currentSession != nil && currentSession!.state != .stopped) { throw RemoteSensingSessionError.invalidSessionState(reason: "Session cannot be started, it is already running, terminated or archived") } currentSession = RemoteSensingSession(withName: name, enabledSensors: configuration, sensorSettings: settings, transmissionIntervall: intervall) remoteSensingEvent.raiseEvent(withType: .sessionCreated, forSession: currentSession!) sensingBuffer.initialise(withSession: currentSession!) if(currentSession != nil && currentSession!.state == .created){ currentSession!.state = .prepareRunning let message = StartSensingMessage(withConfiguration: currentSession!.sensorConfig, transmisssionIntervall: intervall) CommunicationManager.instance.send(message: message) remoteSensingEvent.raiseEvent(withType: .sessionStateChanged, forSession: currentSession!) } } public func stopSensing() throws{ if(currentSession != nil && (currentSession!.state == .running || currentSession!.state == .prepareRunning)){ currentSession!.state = .prepareStopping let message = StopSensingMessage() CommunicationManager.instance.send(message: message) remoteSensingEvent.raiseEvent(withType: .sessionStateChanged, forSession: currentSession!) }else if(currentSession == nil){ throw RemoteSensingSessionError.invalidSessionState(reason: "Session cannot be stopped, create a session first") } else { throw RemoteSensingSessionError.invalidSessionState(reason: "Session cannot be stopped, it is not running at the moment") } } public func getSessionStatus() -> RemoteSensingSessionState?{ if(currentSession == nil){ return .undefined }else{ return currentSession!.state } } public func isWatchReachable() -> Bool{ return CommunicationManager.instance.isReachable() } public func subscribe(handler: RemoteSensingEventHandler){ remoteSensingEvent.add(handler: handler) } public func unsubscribe(handler: RemoteSensingEventHandler){ remoteSensingEvent.remove(handler: handler) } }
37.382114
250
0.657025
3.046875
7fe28a232361fc918112c6827e669517117a6846
2,661
rs
Rust
src/living_entities.rs
LittleB0xes/dailyrium
b6e4818e6ef3cf4067f0ea5f4dc04cd2c3e2ddc1
[ "MIT" ]
null
null
null
src/living_entities.rs
LittleB0xes/dailyrium
b6e4818e6ef3cf4067f0ea5f4dc04cd2c3e2ddc1
[ "MIT" ]
null
null
null
src/living_entities.rs
LittleB0xes/dailyrium
b6e4818e6ef3cf4067f0ea5f4dc04cd2c3e2ddc1
[ "MIT" ]
null
null
null
use tetra::graphics::Color; use crate::dailyrium::{Sprite, Action}; use crate::engine::give_id; use crate::elements::items::{Item, ItemType}; #[derive(Copy, Clone, Eq, PartialEq)] pub enum EntityType { Hero, Zombie, } #[derive(Copy, Clone)] pub enum Behavior { Drunk, Sleep, PlayerControl } #[derive(Clone)] pub struct LivingEntity { pub id: u32, pub x: i32, pub y: i32, pub sprite: Sprite, pub nature: EntityType, pub inventory: Vec<Item>, pub behavior: Behavior, pub action: Action, // Entity stat pub stealth: u8, pub view_range: u8, pub seen: bool, } impl LivingEntity { pub fn new(x: i32, y: i32, t: EntityType) -> LivingEntity { let sprite = Sprite{ glyph: '@' as u16, fg_color: Color::rgba8(255,255,255,255), bg_color: Color::rgba8(0,0,0,255), fade: 0.0 }; let mut entity = LivingEntity { id: give_id(), x, y, sprite, behavior: Behavior::Sleep, action: Action::Waiting, nature: EntityType::Hero, inventory: Vec::new(), stealth: 6, view_range: 6, seen: false, }; match t { EntityType::Hero => entity.breed_a_hero(), EntityType::Zombie => entity.breed_a_zombie(), } entity } fn breed_a_hero(&mut self) { self.sprite.glyph = '@' as u16; self.nature = EntityType::Hero; self.behavior = Behavior::PlayerControl; self.view_range = 8; } fn breed_a_zombie(&mut self) { self.sprite.glyph = 'Z' as u16; self.sprite.fg_color = Color::rgba8(0,0,255, 255); self.sprite.bg_color = Color::rgba8(0,0,0, 255); self.nature = EntityType::Zombie; } pub fn move_entity(&mut self, dx: i32, dy: i32) { self.x += dx; self.y += dy; } pub fn add_to_inventory(&mut self, item: Item) -> bool { match item.nature { ItemType::Gold => { let gold_pos = self.inventory.iter().position(|it| it.nature == ItemType::Gold); match gold_pos { Some(pos) => { let old_gold: u64 = self.inventory[pos].data; let new_gold: u64 = item.data; self.inventory[pos].data = old_gold + new_gold; }, None => { self.inventory.push(item); } } }, } true } }
24.412844
96
0.499436
3.03125
a1a9ab3f44225dcf7d59c4b9e5188a29f1d08523
4,220
go
Go
post.go
rangilin/glowing-dangerzone
1903158243032565f60f41d748782dee9f5f3673
[ "MIT" ]
1
2015-02-04T15:44:18.000Z
2015-02-04T15:44:18.000Z
post.go
rangilin/glowing-dangerzone
1903158243032565f60f41d748782dee9f5f3673
[ "MIT" ]
null
null
null
post.go
rangilin/glowing-dangerzone
1903158243032565f60f41d748782dee9f5f3673
[ "MIT" ]
null
null
null
package main import ( "bufio" "bytes" "encoding/xml" "fmt" "html/template" "os" "path/filepath" "regexp" "strings" "time" ) // Create a PostCreator that operate in specified directory func NewPostCreator(dir string) PostCreator { return PostCreator{dir} } // A PostCreator create folder and files for a new post type PostCreator struct { // directory to create post dir string } // Create a post with specified title func (pc PostCreator) Create(title string) error { date := time.Now().Format(ISO8601Date) postDir := filepath.Join(pc.dir, Prettify(title)) if err := os.Mkdir(postDir, os.ModePerm); err != nil { return fmt.Errorf("Unable to create folder %s due to %v", postDir, err) } file, err := os.Create(filepath.Join(postDir, "post.md")) if err != nil { return fmt.Errorf("Unable to create post.md due to %v", err) } content := fmt.Sprintf(`--- date: %s title: %s --- `, date, title) file.WriteString(content) return nil } // PostParser parse file into Post type PostParser struct { converter MarkdownConverter conf Configuration } func NewPostParser(conf Configuration) PostParser { return PostParser{NewGithubMarkdownConverter(conf), conf} } // Parse will parse Post from specified post folder func (pp PostParser) Parse(dir string) Post { post := NewPost() post.dir = dir post.key = filepath.Base(dir) post.variables, post.content = pp.parsePostFile(dir) post.htmlContent, _ = pp.converter.Convert(post.content) post.url = pp.conf.BaseUrl + filepath.Base(dir) + "/" return *post } func (pp PostParser) parsePostFile(dir string) (map[string]string, string) { f, _ := os.Open(filepath.Join(dir, PostFileName)) defer f.Close() variables := make(map[string]string) content := "" isInVariablesBlock := false scanner := bufio.NewScanner(f) for scanner.Scan() { line := scanner.Text() if !isInVariablesBlock && line == "---" { isInVariablesBlock = true continue } else if isInVariablesBlock && line == "---" { isInVariablesBlock = false continue } if isInVariablesBlock { if key, value, err := pp.parseVariable(line); err == nil { variables[key] = value } } else { content += (line + "\n") } } return variables, content } func (pp PostParser) parseVariable(line string) (key string, value string, err error) { pair := strings.SplitN(line, ":", 2) if len(pair) == 2 { key = strings.TrimSpace(pair[0]) value = strings.TrimSpace(pair[1]) } else { err = fmt.Errorf("Invalid post variable format : %s", line) } return } func NewPost() *Post { p := new(Post) return p } // Post represented a post in blog type Post struct { // post folder name as the post identifier key string // variables in post file variables map[string]string // path of original post folder dir string // url of the post url string // content in Markdown content string // content in HTML converted from Markdown htmlContent string } func (p Post) Title() string { return p.variables["title"] } func (p Post) Date() string { return p.variables["date"] } func (p Post) RSSDate() string { return p.Time().Format(time.RFC1123) } func (p Post) Time() time.Time { t, err := time.Parse("2006-01-02", p.Date()) if err != nil { panic(fmt.Sprintf("Post %s has an invalid date", p.Title())) } return t } func (p Post) Content() string { return p.content } func (p Post) Excerpt() string { r := regexp.MustCompile("<p>(.+?)</p>") result := r.FindStringSubmatch(p.htmlContent) if len(result) > 1 { buf := new(bytes.Buffer) xml.EscapeText(buf, []byte(result[1])) return buf.String() + " ..." } return "" } func (p Post) HTMLContent() template.HTML { return template.HTML(p.htmlContent) } func (p Post) Key() string { return p.key } func (p Post) Dir() string { return p.dir } func (p Post) Url() string { return p.url } func (p Post) Variable(key string) string { return p.variables[key] } // Posts represented an array of Post type Posts []Post func (p Posts) Len() int { return len(p) } func (p Posts) Swap(i, j int) { p[i], p[j] = p[j], p[i] } type PostsByDateDesc struct { Posts } func (s PostsByDateDesc) Less(i, j int) bool { return !s.Posts[i].Time().Before(s.Posts[j].Time()) }
20.485437
87
0.674408
3.125
0ca4dce21686a03b945a69ccbec119c4e788576f
2,373
py
Python
scripts/republish_s3_products.py
hysds/grq2
c86704a4e46f106ab00dcdfc9a658a97097e9289
[ "Apache-2.0" ]
1
2019-10-18T21:27:56.000Z
2019-10-18T21:27:56.000Z
scripts/republish_s3_products.py
hysds/grq2
c86704a4e46f106ab00dcdfc9a658a97097e9289
[ "Apache-2.0" ]
5
2019-10-17T15:46:23.000Z
2021-06-04T22:18:36.000Z
scripts/republish_s3_products.py
hysds/grq2
c86704a4e46f106ab00dcdfc9a658a97097e9289
[ "Apache-2.0" ]
3
2018-04-08T12:53:24.000Z
2020-05-05T01:10:32.000Z
#!/usr/bin/env python from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import json import requests import sys import os from boto.s3.connection import S3Connection from boto.s3.key import Key from hysds.orchestrator import submit_job from grq2 import app from grq2.lib.utils import parse_config # get source and destination index src = "grq_v02_wvcc_merged_data" # bucket bucket_name = "wvcc-dataset-bucket" # region region = "us-east-1" # get s3 connection s3_conn = S3Connection() bucket = s3_conn.get_bucket(bucket_name) # get connection and create destination index es_url = app.config['ES_URL'] # index all docs from source index to destination index query = { "query": { "query_string": { "query": "\"%s\"" % bucket_name } }, "fields": ["_id", "urls"] } r = requests.post('%s/%s/_search?search_type=scan&scroll=60m&size=100' % (es_url, src), data=json.dumps(query)) scan_result = r.json() count = scan_result['hits']['total'] scroll_id = scan_result['_scroll_id'] results = [] while True: r = requests.post('%s/_search/scroll?scroll=60m' % es_url, data=scroll_id) res = r.json() scroll_id = res['_scroll_id'] if len(res['hits']['hits']) == 0: break for hit in res['hits']['hits']: doc = hit['fields'] prefix = "%s/" % doc['urls'][0].replace( 'http://%s.s3-website-%s.amazonaws.com/' % (bucket_name, region), '') print((doc['_id'], prefix)) localize_urls = [] for i in bucket.list(prefix): #localize_urls.append({ 'url': 's3://%s/%s' % (bucket_name, i.name), 'local_path': '%s/' % os.path.basename(prefix[0:-1]) }) localize_urls.append({'url': 'http://%s.s3-website-%s.amazonaws.com/%s' % ( bucket_name, region, i.name), 'local_path': '%s/' % os.path.basename(prefix[0:-1])}) payload = { "job_type": "job:ingest_dataset", "payload": { "dataset": doc['_id'], "dataset_urls": localize_urls } } # print json.dumps(payload, indent=2) submit_job.apply_async((payload,), queue="jobs_processed") # sys.exit()
30.423077
136
0.629583
3.015625
058360f599892d950f1c801924a6052611a13212
4,022
rb
Ruby
lib/transcode.rb
iamsolarpowered/videoclip
649ab065512e38af683a8264f47172010e98a872
[ "MIT" ]
1
2015-11-05T20:47:40.000Z
2015-11-05T20:47:40.000Z
lib/transcode.rb
iamsolarpowered/videoclip
649ab065512e38af683a8264f47172010e98a872
[ "MIT" ]
null
null
null
lib/transcode.rb
iamsolarpowered/videoclip
649ab065512e38af683a8264f47172010e98a872
[ "MIT" ]
null
null
null
module Paperclip class Transcode < Processor def initialize file, options = {}, attachment = nil @file = file @format = options[:format] @options = options @current_format = File.extname(@file.path) @basename = File.basename(@file.path, @current_format) end def make dst = Tempfile.new([@basename, @format].compact.join(".")) dst.binmode begin Paperclip.run 'ffmpeg', cmd(dst) rescue raise PaperclipError, "There was an error transcoding #{@basename} to #{@format}" unless Paperclip.options[:suppress_errors] end dst end def cmd outfile a = [] a << "-i \"#{File.expand_path(@file.path)}\"" a << ffmpeg_options a << "\"#{File.expand_path(outfile.path)}\"" a.join(' ') end def ffmpeg_options a = [] # General options a << "-f #{@options[:force_format]}" if @options[:force_format] a << "-t #{@options[:duration]}" if @options[:duration] a << "-fs #{@options[:file_size]}" if @options[:file_size] a << "-ss #{@options[:time_offset]}" if @options[:time_offset] a << "-title #{@options[:title]}" if @options[:title] a << "-timestamp #{@options[:timestamp]}" if @options[:timestamp] a << "-author #{@options[:author]}" if @options[:author] a << "-copyright #{@options[:copyright]}" if @options[:copyright] a << "-comment #{@options[:comment]}" if @options[:comment] a << "-genre #{@options[:genre]}" if @options[:genre] a << "-album #{@options[:album]}" if @options[:album] a << "-target #{@options[:target]}" if @options[:target] a << "-b #{@options[:bitrate]}" if @options[:bitrate] # Video options a << "-vb #{@options[:video_bitrate]}" if @options[:video_bitrate] a << "-vframes #{@options[:video_frames]}" if @options[:video_frames] a << "-r #{@options[:rate]}" if @options[:rate] a << "-s #{@options[:size]}" if @options[:size] a << "-s #{@options[:geometry]}" if !@options[:size] && @options[:geometry] a << "-aspect #{@options[:aspect]}" if @options[:aspect] a << "-croptop #{@options[:crop_top]}" if @options[:crop_top] a << "-cropbottom #{@options[:crop_bottom]}" if @options[:crop_bottom] a << "-cropleft #{@options[:crop_left]}" if @options[:crop_left] a << "-cropright #{@options[:crop_right]}" if @options[:crop_right] a << "-padtop #{@options[:pad_top]}" if @options[:pad_top] a << "-padbottom #{@options[:pad_bottom]}" if @options[:pad_bottom] a << "-padleft #{@options[:pad_left]}" if @options[:pad_left] a << "-padright #{@options[:pad_right]}" if @options[:pad_right] a << "-padcolor #{@options[:pad_color]}" if @options[:pad_color] a << "-vn" if @options[:disable_video] a << "-vcodec #{@options[:video_codec]}" if @options[:video_codec] a << "-sameq" if @options[:same_quality] # Audio options a << "-ab #{@options[:audio_bitrate]}" if @options[:audio_bitrate] a << "-aframes #{@options[:audio_frames]}" if @options[:audio_frames] a << "-aq #{@options[:audio_quality]}" if @options[:audio_quality] a << "-ar #{@options[:audio_rate]}" if @options[:audio_rate] a << "-ac #{@options[:audio_channels]}" if @options[:audio_channels] a << "-an" if @options[:disable_audio] a << "-acodec #{@options[:audio_codec]}" if @options[:audio_codec] a << "-vol #{@options[:volume]}" if @options[:volume] a << @options[:options] if @options[:options] # additional options a << "-y" # overwrite tmp file a.join(' ') end end end
45.191011
132
0.529587
3.15625
bd2f60a12d630e8dc0cc5bf83be03e456912f05c
1,519
rs
Rust
2020/day-3/src/main.rs
sil-vio/advent-of-code-2021
f9bc9fa550578baf0da5da1143715bf6c94650ee
[ "MIT" ]
1
2021-12-02T16:55:53.000Z
2021-12-02T16:55:53.000Z
2020/day-3/src/main.rs
sil-vio/advent-of-code-2021
f9bc9fa550578baf0da5da1143715bf6c94650ee
[ "MIT" ]
null
null
null
2020/day-3/src/main.rs
sil-vio/advent-of-code-2021
f9bc9fa550578baf0da5da1143715bf6c94650ee
[ "MIT" ]
null
null
null
use std::path::Path; use std::{ fs::File, io::{self, BufRead, BufReader}, }; fn main() { let lines = lines_from_file("input").unwrap(); let mut values =vec![0; 5]; values[0] = check_slope(&lines, 1, 1); values[1] = check_slope(&lines, 3, 1); values[2] = check_slope(&lines, 5, 1); values[3] = check_slope(&lines, 7, 1); values[4] = check_slope(&lines, 1, 2); println!("part 1 : {}", values[1]); println!("part 2 : {}", values.iter().product::<u64>()); } fn check_slope(lines: &Vec<Vec<char>>, dx_slope: usize, down_slope: usize) -> u64 { let mut counter: u64 = 0; for (i, line) in lines.iter().step_by(down_slope).enumerate() { if line[i*dx_slope % lines[0].len()] == '#' { counter += 1; } } counter } fn lines_from_file(filename: impl AsRef<Path>) -> io::Result<Vec<Vec<char>>> { Ok(BufReader::new(File::open(filename)?) .lines() .map(|s| s.unwrap().chars().map(|c| c).collect()) .collect::<Vec<Vec<char>>>()) } #[cfg(test)] mod tests { use super::*; #[test] fn day_3() { let lines = lines_from_file("test_input").unwrap(); assert_eq!(lines.len(), 11); assert_eq!(lines.get(0).unwrap().len(), 11); assert_eq!(check_slope(&lines, 1, 1), 2); assert_eq!(check_slope(&lines, 3, 1), 7); assert_eq!(check_slope(&lines, 5, 1), 3); assert_eq!(check_slope(&lines, 7, 1), 4); assert_eq!(check_slope(&lines, 1, 2), 2); } }
28.12963
83
0.551679
3.265625
031fabfd942c7fb40d6f7d8f3eb85731598ed58b
1,139
lua
Lua
corona/examples/particles/main.lua
blancoberg/timewarp
12b484d304cc6167e50b378ed2fd611a9602e5e6
[ "MIT" ]
null
null
null
corona/examples/particles/main.lua
blancoberg/timewarp
12b484d304cc6167e50b378ed2fd611a9602e5e6
[ "MIT" ]
null
null
null
corona/examples/particles/main.lua
blancoberg/timewarp
12b484d304cc6167e50b378ed2fd611a9602e5e6
[ "MIT" ]
null
null
null
require "blancoberg.timewarp.TimeWarp" local bg = display.newImage("bg.png") bg.width = display.contentWidth bg.height = display.contentHeight bg.x = bg.width/2 bg.y = bg.height/2 local btn = display.newImage("button.png") btn.x = math.round(display.contentWidth/2) btn.y = math.round(display.contentHeight/2) for a=1,70,1 do local testObject = display.newImage("bouncy.png") testObject.x = display.contentWidth * math.random() testObject.y = -testObject.height testObject.xScale = a/70 testObject.yScale = a/70 TimeWarp.to(testObject, { time=1500 + 1000 * (1-testObject.xScale), delay=4000 * math.random(), rotation = 2000 * math.random(), y=display.contentHeight, transition=easing.linear }) end function eventTouch(e) -- warp to slow motion on touch -- if e.phase == "began" then TimeWarp.warpTo(0.07,300,0) TimeWarp.to(btn,{time=200,alpha=0,isPausable=false}) end -- warp to regular speed on release -- if e.phase == "ended" then TimeWarp.warpTo(1,200,200) TimeWarp.to(btn,{time=200,alpha=1,delay=200,isPausable=false}) end end Runtime:addEventListener("touch",eventTouch)
21.490566
64
0.709394
3.0625
39f5446910731a72de8dd5e1121cc653cf980505
1,927
swift
Swift
Sources/Layers/BGRAtoRGBA.swift
silvrwolfboy/Bender
512ea171950d1ab997b05cf469908fbfc48060e6
[ "MIT" ]
1,840
2017-06-02T20:34:35.000Z
2022-03-08T08:43:37.000Z
Sources/Layers/BGRAtoRGBA.swift
silvrwolfboy/Bender
512ea171950d1ab997b05cf469908fbfc48060e6
[ "MIT" ]
56
2017-06-05T16:06:33.000Z
2020-03-17T20:05:58.000Z
Sources/Layers/BGRAtoRGBA.swift
xmartlabs/Bender
512ea171950d1ab997b05cf469908fbfc48060e6
[ "MIT" ]
111
2017-06-05T13:49:05.000Z
2022-02-04T13:35:32.000Z
// // BGRAtoRGBA.swift // Bender // // Created by Mathias Claassen on 5/8/17. // // import MetalPerformanceShaders import MetalPerformanceShadersProxy /// Transforms an image from RGBA to BGRA. (You can use it the other way around too) open class BGRAtoRGBA: NetworkLayer { // Custom kernels let pipelineBGRAtoRGBA: MTLComputePipelineState! public override init(id: String? = nil) { // Load custom metal kernels pipelineBGRAtoRGBA = MetalShaderManager.shared.getFunction(name: "bgra_to_rgba", in: Bundle(for: BGRAtoRGBA.self)) super.init(id: id) } open override func validate() { let incoming = getIncoming() assert(incoming.count == 1, "BGRAtoRGBA supports one input, not \(incoming.count)") } open override func initialize(network: Network, device: MTLDevice, temporaryImage: Bool = true) { super.initialize(network: network, device: device, temporaryImage: temporaryImage) let incoming = getIncoming() outputSize = incoming[0].outputSize createOutputs(size: outputSize, temporary: temporaryImage) } open override func execute(commandBuffer: MTLCommandBuffer, executionIndex index: Int = 0) { let input = getIncoming()[0].getOutput(index: index) let output = getOrCreateOutput(commandBuffer: commandBuffer, index: index) let encoder = commandBuffer.makeComputeCommandEncoder()! encoder.label = "BGRA to RGBA encoder" encoder.setComputePipelineState(pipelineBGRAtoRGBA) encoder.setTexture(input.texture, index: 0) encoder.setTexture(output.texture, index: 1) let threadsPerGroups = MTLSizeMake(32, 8, 1) let threadGroups = output.texture.threadGrid(threadGroup: threadsPerGroups) encoder.dispatchThreadgroups(threadGroups, threadsPerThreadgroup: threadsPerGroups) encoder.endEncoding() input.setRead() } }
36.358491
122
0.702647
3.203125
8562b18fed111962c25c296ba34c97231a83f670
1,437
js
JavaScript
src/Containers/Detail/DetailMainContainer.js
keemtj/airdnd-frontend
a67844d6a7c4de0ca67d9c03134bb2b4ea14792f
[ "MIT" ]
null
null
null
src/Containers/Detail/DetailMainContainer.js
keemtj/airdnd-frontend
a67844d6a7c4de0ca67d9c03134bb2b4ea14792f
[ "MIT" ]
null
null
null
src/Containers/Detail/DetailMainContainer.js
keemtj/airdnd-frontend
a67844d6a7c4de0ca67d9c03134bb2b4ea14792f
[ "MIT" ]
null
null
null
import React, { useEffect } from 'react'; import { useParams } from 'react-router-dom'; import { useSelector, useDispatch } from 'react-redux'; import { throttle } from 'lodash'; import Subject from '../../Components/Detail/Subject'; import HomeInfos from '../../Components/Detail/HomeInfos'; import FullsizeWrapper from '../../Components/Detail/FullsizeWrapper'; import { getHome, onResize } from '../../Modules/home'; const DetailMainContainer = () => { const { isLoading, home, error } = useSelector(state => state.home.homeState); const { isScreenMedium } = useSelector(state => state.home.screenState); const dispatch = useDispatch(); const { id } = useParams(); console.log('params', id); const resize = () => dispatch(onResize()); useEffect(() => { if (home) return; dispatch(getHome(id)); window.addEventListener('resize', throttle(resize, 300)); return () => { window.removeEventListener('resize', resize); }; }, [dispatch]); if (error) return ( <div style={{ padding: '30px 30px 300px' }}> 에러 발생! 잘못된 요청입니다. </div> ); return ( <> <Subject isLoading={isLoading || !home} home={home} /> <HomeInfos isLoading={isLoading || !home} home={home} isScreenMedium={isScreenMedium} /> {!isLoading && home && <FullsizeWrapper home={home} />} </> ); }; export default React.memo(DetailMainContainer);
28.74
80
0.627697
3.171875
475919c4608f27aab075f8ebf41b8322c0141843
4,213
swift
Swift
PKAR_Sample/HomeViewController.swift
Pradeepkn/ARKitSample
a521e4822b8b8515a61231a351fcb7208ca00f8a
[ "MIT" ]
null
null
null
PKAR_Sample/HomeViewController.swift
Pradeepkn/ARKitSample
a521e4822b8b8515a61231a351fcb7208ca00f8a
[ "MIT" ]
null
null
null
PKAR_Sample/HomeViewController.swift
Pradeepkn/ARKitSample
a521e4822b8b8515a61231a351fcb7208ca00f8a
[ "MIT" ]
null
null
null
// // HomeViewController.swift // PKAR_Sample // // Created by Pradeep on 2/13/19. // Copyright © 2019 Tarento Technologies Pvt Ltd. All rights reserved. // import UIKit import Lottie class HomeViewController: BaseViewController { @IBOutlet weak var homeContainerView: UIView! @IBOutlet weak var centerView: UIView! @IBOutlet weak var actionButton: UIButton! @IBOutlet weak var subContainerView: UIView! typealias ResponseCallback = (UIView, Bool) -> () override func viewDidLoad() { super.viewDidLoad() self.actionButton.isHidden = true DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) { self.loadAnimation() } } func loadAnimation() { self.centerView.isHidden = true self.actionButton.isHidden = true var frame = CGRect(x: 0, y: 0, width: Int(self.view.bounds.size.width), height: Int(self.view.bounds.size.height)) self.animate(onView: self.homeContainerView, frame:frame ,animationFile: "summer") { (animatedView: UIView, isFinished : Bool) in animatedView.removeFromSuperview() frame = CGRect(x: 0, y: 0, width: Int(self.view.bounds.size.width), height: Int(self.view.bounds.size.width)) self.animate(onView: self.homeContainerView, frame:frame ,animationFile: "fabulous-onboarding-animation") { (animatedView: UIView, isFinished : Bool) in animatedView.removeFromSuperview() frame = self.homeContainerView.bounds self.centerView.isHidden = false self.actionButton.isHidden = false self.animateProgressive(onView: self.homeContainerView, frame:frame , from: 0.0, to: 0.75, animationFile: "floral-loading-animation") { (animatedView: UIView, isFinished : Bool) in animatedView.removeFromSuperview() self.animate(onView: self.homeContainerView, frame:frame ,animationFile: "dice-animation") { (animatedView: UIView, isFinished : Bool) in } } } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.isNavigationBarHidden = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } func animate(onView:UIView, frame:CGRect, animationFile : String, onCompletion : @escaping ResponseCallback) { let animationView = LOTAnimationView(name: animationFile) animationView.bounds = frame//CGRect(x: Int(onView.bounds.origin.x), y: Int(onView.bounds.origin.y), width: Int(onView.bounds.size.width), height: Int(onView.bounds.size.width)) animationView.center = onView.center animationView.backgroundColor = UIColor.clear self.homeContainerView.addSubview(animationView) animationView.play{ (finished) in onCompletion(animationView, true) } } func animateProgressive(onView:UIView, frame:CGRect, from: CGFloat, to:CGFloat, animationFile : String, onCompletion : @escaping ResponseCallback) { let animationView = LOTAnimationView(name: animationFile) animationView.bounds = frame//CGRect(x: Int(onView.bounds.origin.x), y: Int(onView.bounds.origin.y), width: Int(onView.bounds.size.width), height: Int(onView.bounds.size.width)) animationView.center = onView.center animationView.backgroundColor = UIColor.clear self.homeContainerView.addSubview(animationView) animationView.play(fromProgress: from, toProgress: to) { (finished) in onCompletion(animationView, true) } } @IBAction func tapHereClicked(_ sender: Any) { self.performSegue(withIdentifier: "ARSegueIdentifier", sender: self) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
44.347368
196
0.671018
3
eeb14002322d8a1e96e55a76b4f572924f99479f
2,349
kt
Kotlin
app/src/main/java/space/narrate/waylan/android/ui/search/OrientationPromptModel.kt
narrate-co/waylan_android
c5640fb3bab994fd2c78cabd83fa962fbff75911
[ "Apache-2.0" ]
13
2019-08-12T02:42:41.000Z
2021-02-07T11:26:29.000Z
app/src/main/java/space/narrate/waylan/android/ui/search/OrientationPromptModel.kt
narrate-co/words_android
c5640fb3bab994fd2c78cabd83fa962fbff75911
[ "Apache-2.0" ]
41
2019-09-28T20:53:00.000Z
2021-01-27T15:46:01.000Z
app/src/main/java/space/narrate/waylan/android/ui/search/OrientationPromptModel.kt
narrate-co/waylan_android
c5640fb3bab994fd2c78cabd83fa962fbff75911
[ "Apache-2.0" ]
null
null
null
package space.narrate.waylan.android.ui.search import space.narrate.waylan.android.R import space.narrate.waylan.core.data.prefs.Orientation /** * A sealed class to hold the possible "smart prompts" which can be displayed in the search shelf. * The search shelf is a space just above the search input field which can be expanded to display * contextual prompts. Orientation locking, is one such prompt. * * @property orientationToRequest the [Orientation] which clicking on this prompt should set the * apps orientation [UserPreferenceRepository] * @property message A short message to be displayed in the expanded search shelf area * @property icon An icon to be displayed to the left of [message] in the expanded search shelf area * @property checkedText The textRes to be displayed in the search shelf after the first click on * the prompt, indicating that the prompt has been "checked" or "completed" * @property uncheckedText The textRes to be displayed in the search shelf if the user clicks on * [checkedText], indicating that they want to reverse the "checked" or "completed" prompt. */ sealed class OrientationPromptModel( val orientationToRequest: Orientation, val message: Int, val icon: Int, val checkedText: Int, val uncheckedText: Int ) { class LockToLandscape(orientationToRequest: Orientation) : OrientationPromptModel( orientationToRequest, R.string.orientation_prompt_lock_to_landscape, R.drawable.ic_round_orientation_lock_24px, R.string.orientation_prompt_locked_label, R.string.orientation_prompt_unlocked_label ) class LockToPortrait(orientationToRequest: Orientation) : OrientationPromptModel( orientationToRequest, R.string.orientation_prompt_lock_to_portrait, R.drawable.ic_round_orientation_lock_24px, R.string.orientation_prompt_locked_label, R.string.orientation_prompt_unlocked_label ) class UnlockOrientation(orientationToRequest: Orientation) : OrientationPromptModel( orientationToRequest, R.string.orientation_prompt_unlock_orientation, R.drawable.ic_round_orientation_lock_24px, R.string.orientation_prompt_unlocked_label, R.string.orientation_prompt_locked_label ) }
43.5
100
0.746701
3
517b4139b18b858e4ea3cf610b19f839a6ca789a
4,230
swift
Swift
Sources/CodableCSV/Strategy.swift
lightsprint09/CodableCSV
dd896a5b18f760ef0cdb5c285316d2eb6e2ac223
[ "MIT" ]
null
null
null
Sources/CodableCSV/Strategy.swift
lightsprint09/CodableCSV
dd896a5b18f760ef0cdb5c285316d2eb6e2ac223
[ "MIT" ]
null
null
null
Sources/CodableCSV/Strategy.swift
lightsprint09/CodableCSV
dd896a5b18f760ef0cdb5c285316d2eb6e2ac223
[ "MIT" ]
null
null
null
import Foundation /// The strategies to use when encoding/decoding. public enum Strategy { /// The strategy to use for non-standard floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloat { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Decode the values from the given representation strings. case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String) } } extension Strategy { /// Indication on whether the CSV file contains headers or not. public enum Header: ExpressibleByNilLiteral, ExpressibleByBooleanLiteral { /// The CSV contains no header row. case none /// The CSV contains a single header row. case firstLine /// It is not known whether the CSV contains a header row. Try to infer it! case unknown public init(nilLiteral: ()) { self = .none } public init(booleanLiteral value: BooleanLiteralType) { self = (value) ? .firstLine : .none } } /// Indication on whether some character set should be trimmed or not at the beginning and ending of a CSV field. public enum Trim: ExpressibleByNilLiteral { /// No characters will be trimmed from the input/output. case none /// White spaces before and after delimiters will be trimmed. case whitespaces /// The given set of characters will be trimmed before and after delimiters. case set(CharacterSet) public init(nilLiteral: ()) { self = .none } } /// The strategy to use for decoding `Date` values. public enum DateDecoding { /// Defer to `Date` for decoding. case deferredToDate /// Decode the `Date` as a UNIX timestamp from a number. case secondsSince1970 /// Decode the `Date` as UNIX millisecond timestamp from a number. case millisecondsSince1970 /// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). case iso8601 /// Decode the `Date` as a string parsed by the given formatter. case formatted(DateFormatter) /// Decode the `Date` as a custom value decoded by the given closure. case custom((_ decoder: Decoder) throws -> Foundation.Date) } /// The strategy to use for decoding `Data` values. public enum DataDecoding { /// Defer to `Data` for decoding. case deferredToData /// Decode the `Data` from a Base64-encoded string. case base64 /// Decode the `Data` as a custom value decoded by the given closure. case custom((_ decoder: Decoder) throws -> Foundation.Data) } } extension Strategy { /// The strategy to use for encoding `Date` values. public enum DateEncoding { /// Defer to `Date` for choosing an encoding. case deferredToDate /// Encode the `Date` as a UNIX timestamp (as a number). case secondsSince1970 /// Encode the `Date` as UNIX millisecond timestamp (as a number). case millisecondsSince1970 /// Encode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). case iso8601 /// Encode the `Date` as a string formatted by the given formatter. case formatted(DateFormatter) /// Encode the `Date` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Date, Encoder) throws -> Void) } /// The strategy to use for encoding `Data` values. public enum DataEncoding { /// Defer to `Data` for choosing an encoding. case deferredToData /// Encoded the `Data` as a Base64-encoded string. case base64 /// Encode the `Data` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Data, Encoder) throws -> Void) } }
41.881188
141
0.643026
3.265625
9bca7d46416818ca1bd358b805f267bcddbd6d29
706
kt
Kotlin
src/test/kotlin/dayFolders/day1/RemoveDuplicatesFromArrayKtTest.kt
lilimapradhan9/kotlin-problems
356cef0db9f0ba1106c308d33c13358077aa0674
[ "MIT" ]
1
2020-04-14T10:22:25.000Z
2020-04-14T10:22:25.000Z
src/test/kotlin/dayFolders/day1/RemoveDuplicatesFromArrayKtTest.kt
lilimapradhan9/kotlin-problems
356cef0db9f0ba1106c308d33c13358077aa0674
[ "MIT" ]
null
null
null
src/test/kotlin/dayFolders/day1/RemoveDuplicatesFromArrayKtTest.kt
lilimapradhan9/kotlin-problems
356cef0db9f0ba1106c308d33c13358077aa0674
[ "MIT" ]
null
null
null
package dayFolders.day1 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class RemoveDuplicatesFromArrayKtTest { @Test fun `remove duplicates from array 1,1,2`() { val arrayLength = removeDuplicates(intArrayOf(1, 1, 2)) Assertions.assertEquals(2, arrayLength) } @Test fun `remove duplicates from array 0,0,1,1,1,2,2,3,3,4`() { val arrayLength = removeDuplicates(intArrayOf(0, 0, 1, 1, 1, 2, 2, 3, 3, 4)) Assertions.assertEquals(5, arrayLength) } @Test fun `remove duplicates from empty array`() { val arrayLength = removeDuplicates(intArrayOf()) Assertions.assertEquals(0, arrayLength) } }
25.214286
84
0.66289
3
13af85fbca9608d656a7161325fb42a932bac560
19,344
sql
SQL
src/main/resources/db/migration/oracle/V2.8.0.20190424150601__add-unique-name-constraint-to-entities.sql
patrickfischer1/WebAPI
759334d4161267b1f728a624590b566bb64abaec
[ "Apache-2.0" ]
99
2015-01-06T18:24:25.000Z
2022-03-10T16:34:04.000Z
src/main/resources/db/migration/oracle/V2.8.0.20190424150601__add-unique-name-constraint-to-entities.sql
patrickfischer1/WebAPI
759334d4161267b1f728a624590b566bb64abaec
[ "Apache-2.0" ]
1,261
2015-01-01T17:33:35.000Z
2022-03-28T18:16:27.000Z
src/main/resources/db/migration/oracle/V2.8.0.20190424150601__add-unique-name-constraint-to-entities.sql
patrickfischer1/WebAPI
759334d4161267b1f728a624590b566bb64abaec
[ "Apache-2.0" ]
159
2015-01-12T13:39:42.000Z
2022-03-15T13:39:31.000Z
-- Alter Concept Set table CREATE OR REPLACE PROCEDURE ${ohdsiSchema}.rename_cs_names AS TYPE NumberArray IS TABLE OF NUMBER; TYPE CharArray IS TABLE OF VARCHAR(255); duplicate_names CharArray; name_repeats NumberArray; amount_of_duplicate_names INT; amount_of_constraints INT; constraint_title VARCHAR(255); schema_title VARCHAR(255); all_duplicates INT; BEGIN SELECT COUNT(*) INTO all_duplicates FROM (SELECT concept_set_name FROM ${ohdsiSchema}.concept_set GROUP BY concept_set_name HAVING COUNT(*) > 1); FOR k IN 0 .. coalesce(all_duplicates, 0) LOOP SELECT concept_set_name BULK COLLECT INTO duplicate_names FROM ${ohdsiSchema}.concept_set GROUP BY concept_set_name HAVING COUNT(*) > 1; SELECT COUNT(*) BULK COLLECT INTO name_repeats FROM ${ohdsiSchema}.concept_set GROUP BY concept_set_name HAVING COUNT(*) > 1; amount_of_duplicate_names := duplicate_names.COUNT; FOR i IN 1 .. coalesce(amount_of_duplicate_names, 0) LOOP FOR j IN 1 .. coalesce(name_repeats(i), 0) LOOP UPDATE ${ohdsiSchema}.concept_set SET concept_set_name = concept_set_name || ' (' || j || ')' WHERE concept_set_id = (SELECT concept_set_id FROM ${ohdsiSchema}.concept_set WHERE concept_set_name = duplicate_names(i) AND ROWNUM = 1); END LOOP; END LOOP; duplicate_names.DELETE(); name_repeats.DELETE(); END LOOP; constraint_title := 'uq_cs_name'; schema_title := '${ohdsiSchema}'; SELECT COUNT(*) INTO amount_of_constraints FROM ALL_CONSTRAINTS WHERE OWNER = '${ohdsiSchema}' AND CONSTRAINT_NAME = constraint_title AND TABLE_NAME = 'CONCEPT_SET'; IF amount_of_constraints = 0 THEN EXECUTE IMMEDIATE ('ALTER TABLE ' || schema_title || '.CONCEPT_SET ADD CONSTRAINT ' || constraint_title ||' UNIQUE (concept_set_name)'); END IF; END; / begin rename_cs_names; end; / -- Alter Cohort Definition table CREATE OR REPLACE PROCEDURE ${ohdsiSchema}.rename_cd_names AS TYPE NumberArray IS TABLE OF NUMBER; TYPE CharArray IS TABLE OF VARCHAR(255); duplicate_names CharArray; name_repeats NumberArray; amount_of_duplicate_names INT; amount_of_constraints INT; constraint_title VARCHAR(255); schema_title VARCHAR(255); all_duplicates INT; BEGIN SELECT COUNT(*) INTO all_duplicates FROM (SELECT name FROM ${ohdsiSchema}.cohort_definition GROUP BY name HAVING COUNT(*) > 1); FOR k IN 0 .. coalesce(all_duplicates, 0) LOOP SELECT name BULK COLLECT INTO duplicate_names FROM ${ohdsiSchema}.cohort_definition GROUP BY name HAVING COUNT(*) > 1; SELECT COUNT(*) BULK COLLECT INTO name_repeats FROM ${ohdsiSchema}.cohort_definition GROUP BY name HAVING COUNT(*) > 1; amount_of_duplicate_names := duplicate_names.COUNT; FOR i IN 1 .. coalesce(amount_of_duplicate_names, 0) LOOP FOR j IN 1 .. coalesce(name_repeats(i), 0) LOOP UPDATE ${ohdsiSchema}.cohort_definition SET name = name || ' (' || j || ')' WHERE id = (SELECT id FROM ${ohdsiSchema}.cohort_definition WHERE name = duplicate_names(i) AND ROWNUM = 1); END LOOP; END LOOP; duplicate_names.DELETE(); name_repeats.DELETE(); END LOOP; constraint_title := 'uq_cd_name'; schema_title := '${ohdsiSchema}'; SELECT COUNT(*) INTO amount_of_constraints FROM ALL_CONSTRAINTS WHERE OWNER = '${ohdsiSchema}' AND CONSTRAINT_NAME = constraint_title AND TABLE_NAME = 'COHORT_DEFINITION'; IF amount_of_constraints = 0 THEN EXECUTE IMMEDIATE ('ALTER TABLE ' || schema_title || '.COHORT_DEFINITION ADD CONSTRAINT ' || constraint_title ||' UNIQUE (name)'); END IF; END; / begin rename_cd_names; end; / -- Alter Cohort Characterization table CREATE OR REPLACE PROCEDURE ${ohdsiSchema}.rename_cc_names AS TYPE NumberArray IS TABLE OF NUMBER; TYPE CharArray IS TABLE OF VARCHAR(255); duplicate_names CharArray; name_repeats NumberArray; amount_of_duplicate_names INT; amount_of_constraints INT; constraint_title VARCHAR(255); schema_title VARCHAR(255); all_duplicates INT; BEGIN SELECT COUNT(*) INTO all_duplicates FROM (SELECT name FROM ${ohdsiSchema}.cohort_characterization GROUP BY name HAVING COUNT(*) > 1); FOR k IN 0 .. coalesce(all_duplicates, 0) LOOP SELECT name BULK COLLECT INTO duplicate_names FROM ${ohdsiSchema}.cohort_characterization GROUP BY name HAVING COUNT(*) > 1; SELECT COUNT(*) BULK COLLECT INTO name_repeats FROM ${ohdsiSchema}.cohort_characterization GROUP BY name HAVING COUNT(*) > 1; amount_of_duplicate_names := duplicate_names.COUNT; FOR i IN 1 .. coalesce(amount_of_duplicate_names, 0) LOOP FOR j IN 1 .. coalesce(name_repeats(i), 0) LOOP UPDATE ${ohdsiSchema}.cohort_characterization SET name = name || ' (' || j || ')' WHERE id = (SELECT id FROM ${ohdsiSchema}.cohort_characterization WHERE name = duplicate_names(i) AND ROWNUM = 1); END LOOP; END LOOP; duplicate_names.DELETE(); name_repeats.DELETE(); END LOOP; constraint_title := 'uq_cc_name'; schema_title := '${ohdsiSchema}'; SELECT COUNT(*) INTO amount_of_constraints FROM ALL_CONSTRAINTS WHERE OWNER = '${ohdsiSchema}' AND CONSTRAINT_NAME = constraint_title AND TABLE_NAME = 'COHORT_CHARACTERIZATION'; IF amount_of_constraints = 0 THEN EXECUTE IMMEDIATE ('ALTER TABLE ' || schema_title || '.COHORT_CHARACTERIZATION ADD CONSTRAINT ' || constraint_title ||' UNIQUE (name)'); END IF; END; / begin rename_cc_names; end; / -- Alter FeAnalysis table CREATE OR REPLACE PROCEDURE ${ohdsiSchema}.rename_fe_names AS TYPE NumberArray IS TABLE OF NUMBER; TYPE CharArray IS TABLE OF VARCHAR(255); duplicate_names CharArray; name_repeats NumberArray; amount_of_duplicate_names INT; amount_of_constraints INT; constraint_title VARCHAR(255); schema_title VARCHAR(255); all_duplicates INT; BEGIN SELECT COUNT(*) INTO all_duplicates FROM (SELECT name FROM ${ohdsiSchema}.fe_analysis GROUP BY name HAVING COUNT(*) > 1); FOR k IN 0 .. coalesce(all_duplicates, 0) LOOP SELECT name BULK COLLECT INTO duplicate_names FROM ${ohdsiSchema}.fe_analysis GROUP BY name HAVING COUNT(*) > 1; SELECT COUNT(*) BULK COLLECT INTO name_repeats FROM ${ohdsiSchema}.fe_analysis GROUP BY name HAVING COUNT(*) > 1; amount_of_duplicate_names := duplicate_names.COUNT; FOR i IN 1 .. coalesce(amount_of_duplicate_names, 0) LOOP FOR j IN 1 .. coalesce(name_repeats(i), 0) LOOP UPDATE ${ohdsiSchema}.fe_analysis SET name = name || ' (' || j || ')' WHERE id = (SELECT id FROM ${ohdsiSchema}.fe_analysis WHERE name = duplicate_names(i) AND ROWNUM = 1); END LOOP; END LOOP; duplicate_names.DELETE(); name_repeats.DELETE(); END LOOP; constraint_title := 'uq_fe_name'; schema_title := '${ohdsiSchema}'; SELECT COUNT(*) INTO amount_of_constraints FROM ALL_CONSTRAINTS WHERE OWNER = '${ohdsiSchema}' AND CONSTRAINT_NAME = constraint_title AND TABLE_NAME = 'FE_ANALYSIS'; IF amount_of_constraints = 0 THEN EXECUTE IMMEDIATE ('ALTER TABLE ' || schema_title || '.FE_ANALYSIS ADD CONSTRAINT ' || constraint_title ||' UNIQUE (name)'); END IF; END; / begin rename_fe_names; end; / -- Alter Pathway Analysis table CREATE OR REPLACE PROCEDURE ${ohdsiSchema}.rename_pathway_names AS TYPE NumberArray IS TABLE OF NUMBER; TYPE CharArray IS TABLE OF VARCHAR(255); duplicate_names CharArray; name_repeats NumberArray; amount_of_duplicate_names INT; amount_of_constraints INT; constraint_title VARCHAR(255); schema_title VARCHAR(255); all_duplicates INT; BEGIN SELECT COUNT(*) INTO all_duplicates FROM (SELECT name FROM ${ohdsiSchema}.pathway_analysis GROUP BY name HAVING COUNT(*) > 1); FOR k IN 0 .. coalesce(all_duplicates, 0) LOOP SELECT name BULK COLLECT INTO duplicate_names FROM ${ohdsiSchema}.pathway_analysis GROUP BY name HAVING COUNT(*) > 1; SELECT COUNT(*) BULK COLLECT INTO name_repeats FROM ${ohdsiSchema}.pathway_analysis GROUP BY name HAVING COUNT(*) > 1; amount_of_duplicate_names := duplicate_names.COUNT; FOR i IN 1 .. coalesce(amount_of_duplicate_names, 0) LOOP FOR j IN 1 .. coalesce(name_repeats(i), 0) LOOP UPDATE ${ohdsiSchema}.pathway_analysis SET name = name || ' (' || j || ')' WHERE id = (SELECT id FROM ${ohdsiSchema}.pathway_analysis WHERE name = duplicate_names(i) AND ROWNUM = 1); END LOOP; END LOOP; duplicate_names.DELETE(); name_repeats.DELETE(); END LOOP; constraint_title := 'uq_pw_name'; schema_title := '${ohdsiSchema}'; SELECT COUNT(*) INTO amount_of_constraints FROM ALL_CONSTRAINTS WHERE OWNER = '${ohdsiSchema}' AND CONSTRAINT_NAME = constraint_title AND TABLE_NAME = 'PATHWAY_ANALYSIS'; IF amount_of_constraints = 0 THEN EXECUTE IMMEDIATE ('ALTER TABLE ' || schema_title || '.PATHWAY_ANALYSIS ADD CONSTRAINT ' || constraint_title ||' UNIQUE (name)'); END IF; END; / begin rename_pathway_names; end; / -- Alter IR Analysis table CREATE OR REPLACE PROCEDURE ${ohdsiSchema}.rename_ir_names AS TYPE NumberArray IS TABLE OF NUMBER; TYPE CharArray IS TABLE OF VARCHAR(255); duplicate_names CharArray; name_repeats NumberArray; amount_of_duplicate_names INT; amount_of_constraints INT; constraint_title VARCHAR(255); schema_title VARCHAR(255); all_duplicates INT; BEGIN SELECT COUNT(*) INTO all_duplicates FROM (SELECT name FROM ${ohdsiSchema}.ir_analysis GROUP BY name HAVING COUNT(*) > 1); FOR k IN 0 .. coalesce(all_duplicates, 0) LOOP SELECT name BULK COLLECT INTO duplicate_names FROM ${ohdsiSchema}.ir_analysis GROUP BY name HAVING COUNT(*) > 1; SELECT COUNT(*) BULK COLLECT INTO name_repeats FROM ${ohdsiSchema}.ir_analysis GROUP BY name HAVING COUNT(*) > 1; amount_of_duplicate_names := duplicate_names.COUNT; FOR i IN 1 .. coalesce(amount_of_duplicate_names, 0) LOOP FOR j IN 1 .. coalesce(name_repeats(i), 0) LOOP UPDATE ${ohdsiSchema}.ir_analysis SET name = name || ' (' || j || ')' WHERE id = (SELECT id FROM ${ohdsiSchema}.ir_analysis WHERE name = duplicate_names(i) AND ROWNUM = 1); END LOOP; END LOOP; duplicate_names.DELETE(); name_repeats.DELETE(); END LOOP; constraint_title := 'uq_ir_name'; schema_title := '${ohdsiSchema}'; SELECT COUNT(*) INTO amount_of_constraints FROM ALL_CONSTRAINTS WHERE OWNER = '${ohdsiSchema}' AND CONSTRAINT_NAME = constraint_title AND TABLE_NAME = 'IR_ANALYSIS'; IF amount_of_constraints = 0 THEN EXECUTE IMMEDIATE ('ALTER TABLE ' || schema_title || '.IR_ANALYSIS ADD CONSTRAINT ' || constraint_title ||' UNIQUE (name)'); END IF; END; / begin rename_ir_names; end; / -- Alter Estimation table CREATE OR REPLACE PROCEDURE ${ohdsiSchema}.rename_estimation_names AS TYPE NumberArray IS TABLE OF NUMBER; TYPE CharArray IS TABLE OF VARCHAR(255); duplicate_names CharArray; name_repeats NumberArray; amount_of_duplicate_names INT; amount_of_constraints INT; constraint_title VARCHAR(255); schema_title VARCHAR(255); all_duplicates INT; BEGIN SELECT COUNT(*) INTO all_duplicates FROM (SELECT name FROM ${ohdsiSchema}.estimation GROUP BY name HAVING COUNT(*) > 1); FOR k IN 0 .. coalesce(all_duplicates, 0) LOOP SELECT name BULK COLLECT INTO duplicate_names FROM ${ohdsiSchema}.estimation GROUP BY name HAVING COUNT(*) > 1; SELECT COUNT(*) BULK COLLECT INTO name_repeats FROM ${ohdsiSchema}.estimation GROUP BY name HAVING COUNT(*) > 1; amount_of_duplicate_names := duplicate_names.COUNT; FOR i IN 1 .. coalesce(amount_of_duplicate_names, 0) LOOP FOR j IN 1 .. coalesce(name_repeats(i), 0) LOOP UPDATE ${ohdsiSchema}.estimation SET name = name || ' (' || j || ')' WHERE estimation_id = (SELECT estimation_id FROM ${ohdsiSchema}.estimation WHERE name = duplicate_names(i) AND ROWNUM = 1); END LOOP; END LOOP; duplicate_names.DELETE(); name_repeats.DELETE(); END LOOP; constraint_title := 'uq_es_name'; schema_title := '${ohdsiSchema}'; SELECT COUNT(*) INTO amount_of_constraints FROM ALL_CONSTRAINTS WHERE OWNER = '${ohdsiSchema}' AND CONSTRAINT_NAME = constraint_title AND TABLE_NAME = 'ESTIMATION'; IF amount_of_constraints = 0 THEN EXECUTE IMMEDIATE ('ALTER TABLE ' || schema_title || '.ESTIMATION ADD CONSTRAINT ' || constraint_title ||' UNIQUE (name)'); END IF; END; / begin rename_estimation_names; end; / -- Alter Prediction table CREATE OR REPLACE PROCEDURE ${ohdsiSchema}.rename_prediction_names AS TYPE NumberArray IS TABLE OF NUMBER; TYPE CharArray IS TABLE OF VARCHAR(255); duplicate_names CharArray; name_repeats NumberArray; amount_of_duplicate_names INT; amount_of_constraints INT; constraint_title VARCHAR(255); schema_title VARCHAR(255); all_duplicates INT; BEGIN SELECT COUNT(*) INTO all_duplicates FROM (SELECT name FROM ${ohdsiSchema}.prediction GROUP BY name HAVING COUNT(*) > 1); FOR k IN 0 .. coalesce(all_duplicates, 0) LOOP SELECT name BULK COLLECT INTO duplicate_names FROM ${ohdsiSchema}.prediction GROUP BY name HAVING COUNT(*) > 1; SELECT COUNT(*) BULK COLLECT INTO name_repeats FROM ${ohdsiSchema}.prediction GROUP BY name HAVING COUNT(*) > 1; amount_of_duplicate_names := duplicate_names.COUNT; FOR i IN 1 .. coalesce(amount_of_duplicate_names, 0) LOOP FOR j IN 1 .. coalesce(name_repeats(i), 0) LOOP UPDATE ${ohdsiSchema}.prediction SET name = name || ' (' || j || ')' WHERE prediction_id = (SELECT prediction_id FROM ${ohdsiSchema}.prediction WHERE name = duplicate_names(i) AND ROWNUM = 1); END LOOP; END LOOP; duplicate_names.DELETE(); name_repeats.DELETE(); END LOOP; constraint_title := 'uq_pd_name'; schema_title := '${ohdsiSchema}'; SELECT COUNT(*) INTO amount_of_constraints FROM ALL_CONSTRAINTS WHERE OWNER = '${ohdsiSchema}' AND CONSTRAINT_NAME = constraint_title AND TABLE_NAME = 'PREDICTION'; IF amount_of_constraints = 0 THEN EXECUTE IMMEDIATE ('ALTER TABLE ' || schema_title || '.PREDICTION ADD CONSTRAINT ' || constraint_title ||' UNIQUE (name)'); END IF; END; / begin rename_prediction_names; end; / DROP PROCEDURE ${ohdsiSchema}.rename_cs_names; DROP PROCEDURE ${ohdsiSchema}.rename_cd_names; DROP PROCEDURE ${ohdsiSchema}.rename_cc_names; DROP PROCEDURE ${ohdsiSchema}.rename_fe_names; DROP PROCEDURE ${ohdsiSchema}.rename_pathway_names; DROP PROCEDURE ${ohdsiSchema}.rename_ir_names; DROP PROCEDURE ${ohdsiSchema}.rename_estimation_names; DROP PROCEDURE ${ohdsiSchema}.rename_prediction_names;
34.854054
144
0.547612
3.015625
27f31dd33e6070665eb93ee202323cc1fbd679f7
5,156
kt
Kotlin
app/src/main/java/com/test/videotoimages/VideoToImages.kt
kenmasumitsu/VideoToImages
70888cf0971f439ccba27dcf5fe10a80cef8f49a
[ "Apache-2.0" ]
1
2022-03-14T16:43:27.000Z
2022-03-14T16:43:27.000Z
app/src/main/java/com/test/videotoimages/VideoToImages.kt
kenmasumitsu/VideoToImages
70888cf0971f439ccba27dcf5fe10a80cef8f49a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/test/videotoimages/VideoToImages.kt
kenmasumitsu/VideoToImages
70888cf0971f439ccba27dcf5fe10a80cef8f49a
[ "Apache-2.0" ]
1
2021-09-05T20:07:15.000Z
2021-09-05T20:07:15.000Z
package com.test.videotoimages import android.content.Context import android.content.res.AssetFileDescriptor import android.graphics.Bitmap import android.media.MediaCodec import android.media.MediaCodecInfo.CodecCapabilities import android.media.MediaExtractor import android.media.MediaFormat import android.util.Log class VideoToImages(context: Context) { companion object { val TAG = "VideoToImages" val TIMEOUT_US = 10000L } private val yuvToRgbConverter = YuvToRgbConverter(context) private var thread: Thread = Thread() // It is called a frame is decoded during decoding. var onDecodeFrame: ((bitmap: Bitmap, frameNo: Int) -> Unit)? = null fun isRunning(): Boolean { return thread.isAlive } // This sample takes AssetFileDescriptor object for a video file in assets. // You can easily modify to take a video file in File or URL. fun run(videoAsset: AssetFileDescriptor) { if (isRunning()) { Log.d(TAG, "Failed. already running") return } thread = Thread { var decoder: MediaCodec? = null val extractor = MediaExtractor() extractor.setDataSource(videoAsset) for (i in 0..extractor.trackCount) { val format = extractor.getTrackFormat(i) val mime = format.getString(MediaFormat.KEY_MIME) if (mime!=null && mime.startsWith("video/")) { extractor.selectTrack(i) decoder = MediaCodec.createDecoderByType(mime) format.setInteger( MediaFormat.KEY_COLOR_FORMAT, CodecCapabilities.COLOR_FormatYUV420Flexible ) decoder.configure(format, null, null, 0) break } } if (decoder == null) { Log.e(TAG, "Failed to open the video file") return@Thread } decoder.start() val info = MediaCodec.BufferInfo() var isEOS = false var frameNo = 0 while (!Thread.interrupted()) { if (!isEOS) { val inIndex = decoder.dequeueInputBuffer(TIMEOUT_US) if (inIndex >= 0) { val buffer = decoder.getInputBuffer(inIndex) val sampleSize = extractor.readSampleData(buffer!!, 0) if (sampleSize < 0) { // We shouldn't stop the playback at this point, just pass the EOS // flag to decoder, we will get it again from the // dequeueOutputBuffer Log.d(TAG, "InputBuffer BUFFER_FLAG_END_OF_STREAM") decoder.queueInputBuffer( inIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM ) isEOS = true } else { decoder.queueInputBuffer( inIndex, 0, sampleSize, extractor.sampleTime, 0 ) extractor.advance() } } } val outIndex = decoder.dequeueOutputBuffer(info, TIMEOUT_US) when (outIndex) { MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> { val format = decoder.getOutputFormat() Log.d("DecodeActivity", "New format " + format); } MediaCodec.INFO_TRY_AGAIN_LATER -> { Log.d("DecodeActivity", "dequeueOutputBuffer timed out!"); } else -> { val image = decoder.getOutputImage(outIndex) if (image != null) { val bmp = Bitmap.createBitmap(image.width, image.height, Bitmap.Config.ARGB_8888) yuvToRgbConverter.yuvToRgb(image, bmp) onDecodeFrame?.let { it(bmp, frameNo) } } decoder.releaseOutputBuffer(outIndex, false) frameNo ++ } } // All decoded frames have been rendered, we can stop playing now if ((info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { Log.d(TAG, "OutputBuffer BUFFER_FLAG_END_OF_STREAM") break } } decoder.stop() decoder.release() extractor.release() } thread.start() } }
37.635036
109
0.47052
3.421875
4f0d077c3c7e66027c7d784871fcb079d722f24a
1,673
lua
Lua
code/utilities.lua
gabri-16/RobotExploration
1eebf7cb489ec019421206130d327accac241aad
[ "MIT" ]
null
null
null
code/utilities.lua
gabri-16/RobotExploration
1eebf7cb489ec019421206130d327accac241aad
[ "MIT" ]
null
null
null
code/utilities.lua
gabri-16/RobotExploration
1eebf7cb489ec019421206130d327accac241aad
[ "MIT" ]
null
null
null
---- Utilities ---- ---- Sensors preprocessing ---- OBSTACLE_THRESHOLD = 0.8 -- [0,1], 0 -> no obstacle, increasing exponentially -- Count the number of stopped robots sensed close to the items sensed on a given channel function count_RAB(channel, sensing_range) number_robot_sensed = 0 for i = 1, #robot.range_and_bearing do -- for each robot seen, check they it is close enough if robot.range_and_bearing[i].range < sensing_range and robot.range_and_bearing[i].data[channel] == 1 then number_robot_sensed = number_robot_sensed + 1 end end return number_robot_sensed end -- Check if a robot is in the base function is_in_base() max = 0 for i = 1, #robot.motor_ground do v = robot.motor_ground[i].value if (v > max) then max = v end end return max <= WHITE_GROUND_THRESHOLD end function is_near_obstacle() local obstacle = 0 -- Usage og 0-1 values since true-false create issues... for i=1, #robot.proximity do if robot.proximity[i].value > OBSTACLE_THRESHOLD then obstacle = 1 end end return obstacle end ---- Actuators postprocessing ---- -- Bring velocity back to range [MIN_VELOCITY, MAX_VELOCITY] function restrain_velocity(velocity) local restrained_v = velocity restrained_v.left = math.max(restrained_v.left, MIN_VELOCITY) restrained_v.left = math.min(restrained_v.left, MAX_VELOCITY) restrained_v.right = math.max(restrained_v.right, MIN_VELOCITY) restrained_v.right = math.min(restrained_v.right, MAX_VELOCITY) return restrained_v end ---- Miscellaneous ---- -- Ternary operator like function ternary(cond, T, F) if cond then return T else return F end end
27.42623
110
0.722654
3.46875
f033f0846a998f9a5ac92cbb40712c19a572ab8c
623
py
Python
extra_tests/ctypes_tests/test_unions.py
nanjekyejoannah/pypy
e80079fe13c29eda7b2a6b4cd4557051f975a2d9
[ "Apache-2.0", "OpenSSL" ]
333
2015-08-08T18:03:38.000Z
2022-03-22T18:13:12.000Z
extra_tests/ctypes_tests/test_unions.py
nanjekyejoannah/pypy
e80079fe13c29eda7b2a6b4cd4557051f975a2d9
[ "Apache-2.0", "OpenSSL" ]
7
2020-02-16T16:49:05.000Z
2021-11-26T09:00:56.000Z
extra_tests/ctypes_tests/test_unions.py
nanjekyejoannah/pypy
e80079fe13c29eda7b2a6b4cd4557051f975a2d9
[ "Apache-2.0", "OpenSSL" ]
55
2015-08-16T02:41:30.000Z
2022-03-20T20:33:35.000Z
import sys from ctypes import * def test_getattr(): class Stuff(Union): _fields_ = [('x', c_char), ('y', c_int)] stuff = Stuff() stuff.y = ord('x') | (ord('z') << 24) if sys.byteorder == 'little': assert stuff.x == b'x' else: assert stuff.x == b'z' def test_union_of_structures(): class Stuff(Structure): _fields_ = [('x', c_int)] class Stuff2(Structure): _fields_ = [('x', c_int)] class UnionofStuff(Union): _fields_ = [('one', Stuff), ('two', Stuff2)] u = UnionofStuff() u.one.x = 3 assert u.two.x == 3
21.482759
48
0.523274
3.03125
16536b01e0038960c930d82f66a3b4035488d695
2,438
tsx
TypeScript
web/src/components/Login.tsx
lunush/posty
b0ea2c342e5a80e72ebc6bbb786720b9994e2b89
[ "MIT" ]
null
null
null
web/src/components/Login.tsx
lunush/posty
b0ea2c342e5a80e72ebc6bbb786720b9994e2b89
[ "MIT" ]
null
null
null
web/src/components/Login.tsx
lunush/posty
b0ea2c342e5a80e72ebc6bbb786720b9994e2b89
[ "MIT" ]
null
null
null
import { useMutation } from '@apollo/client' import { useContext, useState } from 'react' import { ActivityIndicator, NativeSyntheticEvent, StyleSheet, Text, View } from 'react-native' import { LOGIN } from 'src/requests' import { Link, useHistory } from 'react-router-dom' import { AuthContext } from 'src/utils/auth' import StandardTextInput from './common/StandardTextInput' import StandardButton from './common/StandardButton' import { color, globalStyles } from 'src/globalStyles' const Login: React.FC = () => { const context = useContext(AuthContext) const history = useHistory() const [state, setState] = useState({ Username: '', Password: '' }) if (context.token) history.push('/') const [login, { error, loading }] = useMutation(LOGIN, { variables: { username: state.Username, password: state.Password }, update(_, { data: { login: token } }) { if (token) { context.login(token) history.push('/') } } }) const handleChange = (e: NativeSyntheticEvent<any>) => { setState({ ...state, [e.nativeEvent.srcElement.placeholder]: e.nativeEvent.text }) } const handleSubmit = () => { if (state.Password.trim() !== '' && state.Username.trim() !== '') login() } return ( <View style={[globalStyles.fullSpace, globalStyles.centeredContainer]}> <Text style={styles.title}>Login</Text> <StandardTextInput value={state.Username} onChange={handleChange} title="Username" /> <StandardTextInput value={state.Password} onChange={handleChange} title="Password" secureTextEntry /> {loading ? ( <ActivityIndicator style={styles.activityIndicator} /> ) : ( <StandardButton title="Login" onPress={handleSubmit} /> )} <Text style={globalStyles.smallText}> Don't have an account yet? Click <Link to="/register" style={{ color: color.link, textDecoration: 'none' }} > {' '} here{' '} </Link> to get one! </Text> {error && <Text style={globalStyles.mediumText}>{error.message}</Text>} </View> ) } const styles = StyleSheet.create({ activityIndicator: { padding: 14, marginVertical: 10 }, title: { color: color.primary, fontSize: 32, height: 40 } }) export default Login
24.626263
77
0.602543
3.203125
02c003beced941ad4c3809c4ef2cbd2d75f2f555
987
sql
SQL
src/tests/perftest/Scripts/Car01.sql
cameronfletcher/dddlib
55e5cc71f8242a813fb67a460147660f9f9fba17
[ "MIT" ]
19
2015-06-21T12:16:05.000Z
2020-04-25T20:01:52.000Z
src/tests/perftest/Scripts/Car01.sql
cameronfletcher/dddlib
55e5cc71f8242a813fb67a460147660f9f9fba17
[ "MIT" ]
84
2015-03-01T13:25:31.000Z
2017-09-13T16:28:33.000Z
src/tests/perftest/Scripts/Car01.sql
cameronfletcher/dddlib
55e5cc71f8242a813fb67a460147660f9f9fba17
[ "MIT" ]
12
2015-03-01T12:51:36.000Z
2021-08-31T01:55:43.000Z
CREATE TABLE [dbo].[Cars] ( [Registration] VARCHAR(10) NOT NULL PRIMARY KEY, [TotalDistanceDriven] INT NOT NULL ); GO CREATE PROCEDURE [dbo].[LoadCar] @Registration VARCHAR(10) AS SELECT [Registration], [TotalDistanceDriven] FROM [dbo].[Cars] WHERE [Registration] = @Registration; GO CREATE PROCEDURE [dbo].[SaveCar] @Registration VARCHAR(10), @TotalDistanceDriven INT, @IsDestroyed BIT AS MERGE INTO [dbo].[Cars] AS [Target] USING (SELECT @Registration AS [Registration], @TotalDistanceDriven AS [TotalDistanceDriven], @IsDestroyed AS [IsDestroyed]) AS [Source] ON [Target].[Registration] = [Source].[Registration] WHEN MATCHED AND [Source].[IsDestroyed] = 1 THEN DELETE WHEN MATCHED THEN UPDATE SET [Target].[TotalDistanceDriven] = [Source].[TotalDistanceDriven] WHEN NOT MATCHED THEN INSERT ([Registration], [TotalDistanceDriven]) VALUES ([Source].[Registration], [Source].[TotalDistanceDriven]); GO
28.2
137
0.700101
3.078125
ee4afd5d9d74f8137ecdf8b0f70696aef8a8459c
5,544
lua
Lua
mods/deathmatch/resource-cache/http-client-files-no-client-cache/minimap/extend.lua
yourpalemir/ww3-altyapi
81754e2c952e0c168ebf41d1bd9bdd9ffb325678
[ "MIT" ]
null
null
null
mods/deathmatch/resource-cache/http-client-files-no-client-cache/minimap/extend.lua
yourpalemir/ww3-altyapi
81754e2c952e0c168ebf41d1bd9bdd9ffb325678
[ "MIT" ]
null
null
null
mods/deathmatch/resource-cache/http-client-files-no-client-cache/minimap/extend.lua
yourpalemir/ww3-altyapi
81754e2c952e0c168ebf41d1bd9bdd9ffb325678
[ "MIT" ]
null
null
null
Extend = { screen = Vector2(guiGetScreenSize()), show = false, size = {}, scale = {}, _define = function(self) self = Extend; self.size.wh = Vector2(self.screen.x - 50,self.screen.y - 50) self.size.blip = 20 self.scale.map = 1 self.scale.arrow = 0.8 self.scale.distance = Vector2(2.05,0.5) self.pos = Vector2(25,25) self.key = 'F11' self.x = 0 self.y = 0 self.texture = DxTexture("components/radar.png", "dxt5", true, "clamp", "3d") self.size.texture = Vector2(self.texture:getSize()) return true end, _key = function(key,press) self = Extend; if key == self.key and press and localPlayer:getData('loggedin') == 1 then self.show = not self.show if not self.show then removeEventHandler('onClientRender',root,self._render) else addEventHandler('onClientRender',root,self._render) end end if key == 'mouse_wheel_up' and self.show then if press then if tonumber(self.scale.map) < 1.50 then self.scale.map = self.scale.map + 0.025 if self.scale.arrow ~= 0.8 then self.scale.arrow = self.scale.arrow - 0.025 end end end end if key == 'mouse_wheel_down' and self.show then if press then if tonumber(self.scale.map) > 0.50 then self.scale.map = self.scale.map - 0.025 if self.scale.arrow < 1 then self.scale.arrow = self.scale.arrow + 0.025 end end end end end, _render = function() self = Extend; if localPlayer.dimension == 0 then local sectionx = localPlayer.position.x / ( 6000 / self.size.texture.x ) + ( self.size.texture.y / 2 ) - ( self.size.wh.x / self.scale.map / 2 ) + 5 local sectiony = localPlayer.position.y / (-6000 / self.size.texture.y ) + (self.size.texture.y / 2) - (self.size.wh.y / self.scale.map / 2 ) + 5 local iunit = 3072 / 6000 * self.scale.map dxDrawRectangle(self.pos.x, self.pos.y, self.size.wh.x, self.size.wh.y, tocolor(0, 0, 0, 255*0.7)) dxDrawImageSection(self.pos.x + 13 / 2 + 1, self.pos.y + 13 / 2, (self.size.wh.x - 13), (self.size.wh.y - 13), sectionx + self.x, sectiony + self.y, (self.size.wh.x - 13) / self.scale.map, (self.size.wh.y - 13) / self.scale.map, self.texture, 0, 0, 0, tocolor( 255, 255, 255, 255 ), false) for i, v in ipairs(getElementsByType("blip")) do if v:getData("blip:maxVisible") then north = {} if (self.pos.y + 13 / 2 + (self.size.wh.y - 13)/2 + (localPlayer.position.y - v.position.y) * iunit) <= self.pos.y + 13/2 then north.y = self.pos.y + 13/2 elseif (self.pos.y + 13/2 + (self.size.wh.y - 13)/2 + (localPlayer.position.y - v.position.y) * iunit) >= self.pos.y + 13/2 + (self.size.wh.y - 13 - 20) then north.y = self.pos.y + 13/2 + (self.size.wh.y - 13 - 20) else north.y = self.pos.y + 13/2 + (self.size.wh.y - 13)/2 + (localPlayer.position.y - v.position.y) * iunit - self.size.blip / 2 end if ((self.pos.x + 13/2 + (self.size.wh.x - 13)/2 + (v.position.x - localPlayer.position.x) * iunit) <= self.pos.x + 13 / 2) then north.x = self.pos.x + 13/2 elseif ((self.pos.x + 13/2 + (self.size.wh.x - 13)/2 + (v.position.x - localPlayer.position.x) * iunit) >= self.pos.x + 13 / 2 + (self.size.wh.x - 13 - 20)) then north.x = self.pos.x + 13/2 + (self.size.wh.x - 13 - 20) else north.x = (self.pos.x + 13/2 + (self.size.wh.x - 13)/2 + (v.position.x - localPlayer.position.x) * iunit) - self.size.blip / 2 end dxDrawImage(north.x, north.y, 16, 16, "components/blips/" .. v.icon .. ".png", 0, 0, 0, tocolor(255, 255, 255, 255), false) else distance = { min = {}, max = {}, } distance.min.h = (self.pos.y + 13 / 2 + (self.size.wh.y - 13) / 2 + (localPlayer.position.y - v.position.y) * iunit) > self.pos.y + 13 / 2 distance.min.w = (self.pos.x + 13 / 2 + (self.size.wh.x - 13) / 2 + (v.position.x - localPlayer.position.x) * iunit) > self.pos.x + 13 / 2 distance.max.h = (self.pos.y + 13 / 2 + (self.size.wh.y - 13) / 2 + (localPlayer.position.y - v.position.y) * iunit) < self.pos.y + 13 / 2 + (self.size.wh.y - 13 - 20) distance.max.w = (self.pos.x + 13 / 2 + (self.size.wh.x - 13) / 2 + (v.position.x - localPlayer.position.x) * iunit) < self.pos.x + 13 / 2 + (self.size.wh.x - 13 - 20) if distance.min.h and distance.min.w and distance.max.h and distance.max.w then dxDrawImage(self.pos.x + 13/2 + (self.size.wh.x - 13)/2 + (v.position.x - localPlayer.position.x) * iunit - v.size / 2, self.pos.y + 13/2 + (self.size.wh.y - 13)/2 + (localPlayer.position.y - v.position.y) * iunit - v.size/2, 20, 20, "components/blips/" .. v.icon .. ".png", 0, 0, 0, tocolor(255, 255, 255, 255), false) end end end dxDrawImage(self.pos.x + self.size.wh.x / 2 + 2 * iunit - (10 / self.scale.arrow) + self.scale.arrow, self.pos.y + self.size.wh.y / 2 + 0 * iunit - (10.5 / self.scale.arrow) + self.scale.arrow, 20, 20, "components/arrow.png", 360 - localPlayer.rotation.z, 0, 0, tocolor(255 ,255 ,255 ,255), false) end end, index = function(self) toggleControl("radar", false) if self:_define() then addEventHandler('onClientKey',root,function(key,press) self._key(key,press) end) north = Blip(733.1318359375, 3700.951171875, -200, 4, 2, 255, 255, 255, 255) north:setOrdering(-2000) north:setData("blip:maxVisible", true) --Blip(1369.87927, -1365.45728, 13.56133, 44) end end, } addEventHandler ("onClientResourceStart", resourceRoot,function() Extend:index() end)
38.5
329
0.607504
3.171875
f0730fe6794bb60447a6e7f8e2d6de7cd6fc45d8
1,220
py
Python
Chapter 3-Regression/2.py
FatiniNadhirah5/Datacamp-Machine-Learning-with-Apache-Spark-2019
a0ef5f34c5a0aea222359a5085386f6a21611e7e
[ "FSFAP" ]
8
2020-05-02T20:24:38.000Z
2021-04-30T21:44:22.000Z
Chapter 3-Regression/2.py
FatiniNadhirah5/Machine-Learning-with-Apache-Spark
a0ef5f34c5a0aea222359a5085386f6a21611e7e
[ "FSFAP" ]
null
null
null
Chapter 3-Regression/2.py
FatiniNadhirah5/Machine-Learning-with-Apache-Spark
a0ef5f34c5a0aea222359a5085386f6a21611e7e
[ "FSFAP" ]
9
2020-05-17T17:44:37.000Z
2022-03-20T12:58:42.000Z
# Flight duration model: Just distance # In this exercise you'll build a regression model to predict flight duration (the duration column). # For the moment you'll keep the model simple, including only the distance of the flight (the km column) as a predictor. # The data are in flights. The first few records are displayed in the terminal. These data have also been split into training and testing sets and are available as flights_train and flights_test. # Instructions # 100 XP # Create a linear regression object. Specify the name of the label column. Fit it to the training data. # Make predictions on the testing data. # Create a regression evaluator object and use it to evaluate RMSE on the testing data. from pyspark.ml.regression import LinearRegression from pyspark.ml.evaluation import RegressionEvaluator # Create a regression object and train on training data regression = LinearRegression(labelCol='duration').fit(flights_train) # Create predictions for the testing data and take a look at the predictions predictions = regression.transform(flights_test) predictions.select('duration', 'prediction').show(5, False) # Calculate the RMSE RegressionEvaluator(labelCol='duration').evaluate(predictions)
48.8
195
0.80082
3.265625
821426ba2216dca4ef3765c8b9929f66e050f1fe
4,930
swift
Swift
QuakeX/QuakeX/Screens/EmergencyContact/EmergencyContactVC.swift
FurkanHanciSecond/QuakeX
c3ae1ddef128e5d50f5c80e0f595bc8987108436
[ "MIT" ]
null
null
null
QuakeX/QuakeX/Screens/EmergencyContact/EmergencyContactVC.swift
FurkanHanciSecond/QuakeX
c3ae1ddef128e5d50f5c80e0f595bc8987108436
[ "MIT" ]
null
null
null
QuakeX/QuakeX/Screens/EmergencyContact/EmergencyContactVC.swift
FurkanHanciSecond/QuakeX
c3ae1ddef128e5d50f5c80e0f595bc8987108436
[ "MIT" ]
null
null
null
// // EmergencyPeopleVC.swift // QuakeX // // Created by Furkan Hanci on 2/13/22. // import UIKit class EmergencyContactVC: UIViewController { private lazy var emergencyTableView : UITableView = { let table = UITableView() return table }() private var contacts : [EmergencyContact]? private let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext override func viewDidLoad() { super.viewDidLoad() setup() refreshTableView() } private func setup() { configureView() setupNavigationBar() configureTableView() fetchContacts() } private func setupNavigationBar() { let addButton = UIBarButtonItem(image: UIImage(systemName: "plus.circle.fill"), style: .done, target: self, action: #selector(handlePlusButton(_:))) navigationItem.rightBarButtonItem = addButton } @objc private func handlePlusButton(_ sender: UIButton) { present(AddNewContactVC(), animated: true, completion: nil) //navigationController?.pushViewController(AddNewContactVC(), animated: true) } private func configureView() { view.backgroundColor = .systemBackground self.title = Constants.Text.Bar.emergencyContacts } private func setTableViewDelegate() { emergencyTableView.delegate = self } private func setTableViewDataSource() { emergencyTableView.dataSource = self } private func configureTableView() { setTableViewDelegate() setTableViewDataSource() view.addSubview(emergencyTableView) emergencyTableView.pinToEdges(of: view) emergencyTableView.removeExcessCells() emergencyTableView.separatorStyle = .none emergencyTableView.register(EmergencyTableViewCell.self, forCellReuseIdentifier: Constants.emergencyCellID) } private func refreshTableView() { self.emergencyTableView.refreshControl = UIRefreshControl() if let refreshControl = emergencyTableView.refreshControl { refreshControl.tintColor = .gray refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .valueChanged) } } @objc private func refresh(_ sender : UIRefreshControl) { self.emergencyTableView.refreshControl?.beginRefreshing() self.emergencyTableView.refreshControl?.endRefreshing() self.emergencyTableView.reloadData() self.fetchContacts() } private func fetchContacts() { do { self.contacts = try context.fetch(EmergencyContact.fetchRequest()) DispatchQueue.main.async { self.emergencyTableView.reloadData() } } catch { AlertManager.showAlert(message: QuakeError.coreDataError.rawValue, viewController: self) } } } extension EmergencyContactVC : UITableViewDelegate { func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let action = UIContextualAction(style: .destructive, title: "Delete Contact") { action, view, handler in let eventRemove = self.contacts?[indexPath.row] self.context.delete(eventRemove ?? eventRemove.unsafelyUnwrapped) do { try self.context.save() } catch { AlertManager.showAlert(title: Constants.Text.Error.oops, message: QuakeError.dataError.rawValue, alertAction: nil, viewController: self) } self.fetchContacts() } return UISwipeActionsConfiguration(actions: [action]) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let contacts = self.contacts?[indexPath.row] guard let contactNumber = contacts?.number else { return } guard let number = URL(string: "tel://" + contactNumber) else { return } UIApplication.shared.open(number) } } extension EmergencyContactVC : UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contacts?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = emergencyTableView.dequeueReusableCell(withIdentifier: Constants.emergencyCellID, for: indexPath) as! EmergencyTableViewCell let emergencyContacts = self.contacts?[indexPath.row] cell.setCell(data: emergencyContacts) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } }
32.649007
156
0.651927
3.015625
dfed76259ffbc89d8cf19650160126c2966cc752
1,788
tsx
TypeScript
webui/src/component/etc/DarkModeSwitch.tsx
Jaeyo/personal-archive
8690d662605f13d070d3f052722017eb56c18a61
[ "MIT" ]
35
2021-02-05T17:16:49.000Z
2021-08-19T03:02:20.000Z
webui/src/component/etc/DarkModeSwitch.tsx
Jaeyo/personal-archive
8690d662605f13d070d3f052722017eb56c18a61
[ "MIT" ]
15
2021-02-09T16:06:56.000Z
2021-08-22T04:21:48.000Z
webui/src/component/etc/DarkModeSwitch.tsx
Jaeyo/personal-archive
8690d662605f13d070d3f052722017eb56c18a61
[ "MIT" ]
8
2021-02-08T05:16:23.000Z
2021-08-18T09:02:57.000Z
import React, { FC, useEffect } from "react" import { disable as disableDarkMode, enable as enableDarkMode, setFetchMethod } from "darkreader" import { useLocalStorage, useSubscribe } from "../../common/Hooks" import Toggle from "react-toggle" import { Moon } from "@kiwicom/orbit-components/icons" import styled from "styled-components" import { IoSunny } from "react-icons/all" import { ToggleDarkMode } from "../../common/EventBus" const DarkModeSwitch: FC = () => { const [isEnabled, setEnabled] = useDarkMode() useSubscribe(ToggleDarkMode, () => setEnabled(!isEnabled)) return ( <Wrapper> <Toggle id="dark-mode-switch" defaultChecked={isEnabled} onChange={() => setEnabled(!isEnabled)} icons={{ checked: <Moon size="small" />, unchecked: <IoSunny />, }} /> </Wrapper> ) } const useDarkMode = (): [ boolean, (isEnabled: boolean) => void, ] => { const [darkMode, setDarkMode] = useLocalStorage('theme.dark_mode', '0') const isEnabled = darkMode === '1' const setEnabled = (isEnabled: boolean) => setDarkMode(isEnabled ? '1' : '0') useEffect(() => { setFetchMethod(window.fetch) }, []) useEffect(() => { setTimeout(() => { if (isEnabled) { enableDarkMode({ scrollbarColor: '#222', }) } else { disableDarkMode() } }, 200) }, [isEnabled]) return [isEnabled, setEnabled] } const Wrapper = styled.div` padding-top: 4px; margin-left: 4px; .react-toggle-track-check { margin-top: 4px; margin-bottom: 0; color: #f0c545; } .react-toggle-track-x { margin-top: 4px; margin-bottom: 0; right: 14px; // color: #eee; color: #f0c545; } ` export default DarkModeSwitch
22.632911
97
0.607383
3.171875
9c2eb40ff3dcb9ba178f4e6ed33f3bbc45067df5
4,195
js
JavaScript
Scripts/tools/jwt.js
JUkhan/jwt_php
f46ccd8c47885ce7057081de0ded882f58fcebd9
[ "Apache-2.0" ]
null
null
null
Scripts/tools/jwt.js
JUkhan/jwt_php
f46ccd8c47885ce7057081de0ded882f58fcebd9
[ "Apache-2.0" ]
null
null
null
Scripts/tools/jwt.js
JUkhan/jwt_php
f46ccd8c47885ce7057081de0ded882f58fcebd9
[ "Apache-2.0" ]
null
null
null
 (function (window) { //extention Methods Function.method = Array.method = String.method = Object.method = function (name, fn) { this.prototype[name] = fn; return this; }; Array .method('each', function (callback) { for (var i = 0, len = this.length; i < len; i++) { callback(this[i], i); } }) .method('remove', function (callback) { var fx = function (arr) { return arr.length; }; for (var i = 0; i < fx(this) ; i++) { if (callback(this[i])) { this.splice(i, 1); i--; } } return this; }) .method('where', function (callback) { var res = []; for (var i = 0, len = this.length; i < len; i++) { if (callback(this[i])) { res.push(this[i]); } } return res; }) .method('select', function (conditionalCallback, selectionCallback) { var res = [], index=0; for (var i = 0, len = this.length; i < len; i++) { if (conditionalCallback(this[i], i)) { res.push(selectionCallback(this[i], index)); index++; } } return res; }) .method('first', function (callback) { for (var i = 0, len = this.length; i < len; i++) { if (callback(this[i])) { return this[i]; } } return null; }) .method('last', function (callback) { var obj = null; for (var i = 0, len = this.length; i < len; i++) { if (callback(this[i])) { obj = this[i]; } } return obj; }) .method('selectWithJoin', function (list1, list1Callback, conditionalCallback, selectionCallback) { var res = [], fx = function (list, pitem, callback) { var temp = []; for (var i = 0, len = list.length; i < len; i++) { if (callback(pitem, list[i])) { temp.push(list[i]); } } return temp; }; this.ForEach(function (item) { fx(list1, item, list1Callback).ForEach(function (join) { if (conditionalCallback(item, join)) { res.push(selectionCallback(item, join)); } }); }); return res; }) .method('groupBy', function (callback) { var res = [], temp = []; this.ForEach(function (item) { var key = callback(item); if (temp[key]) { temp[key].push(item); } else { temp[key] = [item]; } }); for (var i in temp) { if (temp.hasOwnProperty(i)) { res.push({ key: i, items: temp[i] }); } } return res; }) .method('paging', function (pageno, size) { pageno--; return this.slice(pageno * size, (pageno * size) + size); }) .method('insertAt', function (index, item) { return this.splice(index, 0, item); }); String.method('format', function () { var str = this; for (var i = 0; i < arguments.length; i++) { str = str.replace(new RegExp('\\{' + i + '\\}', 'g'), arguments[i]); } return str; }); String.isNullOrWhiteSpace = function (str) { if (str) { return new RegExp("^\\s+$").test(str); } return true; } Function.prototype.bind = Function.prototype.bind || function (b) { if (typeof this !== "function") { throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var a = Array.prototype.slice, f = a.call(arguments, 1), e = this, c = function () { }, d = function () { return e.apply(this instanceof c ? this : b || window, f.concat(a.call(arguments))); }; c.prototype = this.prototype; d.prototype = new c(); return d; }; })(window); if (window.addEventListener) { window.addEventListener("message", listener, false); } else { attachEvent('onMessage', listener); } function sendMessage(name, ctype) { if (name) { var data = { id: 'jwt', comName: name, comType: ctype }; window.parent.postMessage(data, '*'); } } function listener(event) { }
33.293651
460
0.500834
3.28125
b71272ea69940df2d8a019668bc0f2be0a799a31
1,822
kt
Kotlin
app/src/androidTest/java/com/sergeyrodin/matchesboxes/history/HighlightedItemsTestUtils.kt
rodins/matches-boxes
719cec50f4e6129d0628598e20e21018b79bb8f6
[ "Apache-2.0" ]
null
null
null
app/src/androidTest/java/com/sergeyrodin/matchesboxes/history/HighlightedItemsTestUtils.kt
rodins/matches-boxes
719cec50f4e6129d0628598e20e21018b79bb8f6
[ "Apache-2.0" ]
null
null
null
app/src/androidTest/java/com/sergeyrodin/matchesboxes/history/HighlightedItemsTestUtils.kt
rodins/matches-boxes
719cec50f4e6129d0628598e20e21018b79bb8f6
[ "Apache-2.0" ]
null
null
null
package com.sergeyrodin.matchesboxes.history import android.graphics.drawable.ColorDrawable import android.view.View import android.widget.TextView import androidx.core.content.ContextCompat import androidx.test.internal.util.Checks import com.sergeyrodin.matchesboxes.R import org.hamcrest.Description import org.hamcrest.Matcher import org.hamcrest.TypeSafeMatcher fun hasBackgroundColor(colorRes: Int): Matcher<View> { Checks.checkNotNull(colorRes) return object: TypeSafeMatcher<View>() { override fun describeTo(description: Description?) { description?.appendText("background color: $colorRes") } override fun matchesSafely(item: View?): Boolean { if(item?.background == null) { return false } val actualColor = (item.background as ColorDrawable).color val expectedColor = ColorDrawable(ContextCompat.getColor(item.context, colorRes)).color return actualColor == expectedColor } } } fun hasBackgroundColorAndText(colorRes: Int, text: String): Matcher<View> { return object: TypeSafeMatcher<View>() { override fun describeTo(description: Description?) { description?.appendText("text: $text, background color: $colorRes") } override fun matchesSafely(item: View?): Boolean { if(item?.background == null) return false val actualColor = (item.background as ColorDrawable).color val expectedColor = ColorDrawable(ContextCompat.getColor(item.context, colorRes)).color val nameTextView = item.findViewById<TextView>(R.id.name_text) val actualText = nameTextView.text.toString() return actualColor == expectedColor && text == actualText } } }
35.72549
99
0.680571
3.15625
6d11dea1d5162455d00c3985bf642e2417a977cb
3,213
lua
Lua
server/server.lua
JokeDevil/JD_Prison
abfb08810abe9fa1599eb8abb9a86c2e495b08f9
[ "Apache-2.0" ]
null
null
null
server/server.lua
JokeDevil/JD_Prison
abfb08810abe9fa1599eb8abb9a86c2e495b08f9
[ "Apache-2.0" ]
null
null
null
server/server.lua
JokeDevil/JD_Prison
abfb08810abe9fa1599eb8abb9a86c2e495b08f9
[ "Apache-2.0" ]
2
2021-05-12T06:38:49.000Z
2021-09-15T22:09:21.000Z
RegisterCommand("jail", function(source, args, rawCommand) if tablelength(args) > 0 then local tPID = tonumber(args[1]) local jT = Config.defaultsecs if tablelength(args) > 1 then if (args[2] ~= nil) then jT = tonumber(args[2]) end end if jT > Config.maxsecs then jT = Config.maxsecs end if GetPlayerName(tPID) ~= nil then TriggerClientEvent("sendToJail", tPID, jT, source, 1) end end exports.JD_logs:discord('**'.. GetPlayerName(source) .. '**: ``/' .. rawCommand .. '``', source, 0 , '10592673', 'jail') end) RegisterCommand("unjail", function(source, args, rawCommand) CancelEvent() if IsPlayerAceAllowed(source, Config.staffAcePerm) then local tPID = tonumber(args[1]) if GetPlayerName(tPID) ~= nil then --print("Unjailing ".. GetPlayerName(tPID).. " - cm entered by ".. GetPlayerName(source)) TriggerClientEvent("unJail", tPID, GetPlayerName(source)) end exports.JD_logs:discord('**'.. GetPlayerName(source) .. '**: ``/' .. rawCommand .. '``', source, 0 , '10592673', 'jail') else TriggerClientEvent('sendChatMessage', -1, "You don't have permissions to do this") end end) RegisterCommand("jailme", function(source, args, rawCommand) CancelEvent() local jT = Config.defaultsecs if args[1] ~= nil then jT = tonumber(args[1]) end if jT > Config.maxsecs then jT = Config.maxsecs end TriggerClientEvent("sendMeToJail", source, jT, source) exports.JD_logs:discord('**'.. GetPlayerName(source) .. '**: ``/' .. rawCommand .. '``', source, 0 , '10592673', 'jail') end) RegisterCommand("staffjail", function(source, args, rawCommand) CancelEvent() if IsPlayerAceAllowed(source, Config.staffAcePerm) then local jT = Config.defaultsecs if args[1] ~= nil then pP = tonumber(args[1]) jT = tonumber(args[2]) end if tonumber(args[2]) ~= nil then if jT > Config.maxsecs then jT = Config.maxsecs end TriggerClientEvent("staffMeToJail", pP, jT, source) exports.JD_logs:discord('**'.. GetPlayerName(source) .. '**: ``/' .. rawCommand .. '``', source, 0 , '10592673', 'jail') else TriggerClientEvent('sendChatMessage', -1, "^*^1Use /staffjail [id] [time]^0^r") end end end) RegisterNetEvent('getChatMessage') AddEventHandler('getChatMessage', function(id, message) local _id = id local _message = message TriggerClientEvent('sendChatMessage', _id, _message) end) RegisterNetEvent('getGlobalChatMessage') AddEventHandler('getGlobalChatMessage', function(message) local _message = message TriggerClientEvent('sendChatMessage', -1, _message) end) RegisterNetEvent('getGlobalChatMessageStaff') AddEventHandler('getGlobalChatMessageStaff', function(message) local _message = message TriggerEvent('chat:addMessage', {color = { 230, 77, 67}, args = {"[Staff Jail]",message}}) end) RegisterNetEvent('serverSendToJail') AddEventHandler('serverSendToJail', function(id) local _id = id TriggerClientEvent('sendToJail', _id) end) RegisterNetEvent('ServerESCORT') AddEventHandler('ServerESCORT', function(id) local _id = id TriggerClientEvent('EscortOut', _id) end) function tablelength(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end
30.6
123
0.696234
3.015625
d1f540a77a35b5de031397c6955eb6be547b4274
1,353
kt
Kotlin
domic/api/src/main/kotlin/com/lyft/domic/api/rendering/Renderer.kt
lyft/domic
e18c3b6030efae23009c74fd88b762f63ecf8d3a
[ "Apache-2.0" ]
482
2018-05-08T06:07:51.000Z
2021-08-19T06:54:43.000Z
domic/api/src/main/kotlin/com/lyft/domic/api/rendering/Renderer.kt
lyft/domic
e18c3b6030efae23009c74fd88b762f63ecf8d3a
[ "Apache-2.0" ]
25
2018-05-08T08:38:02.000Z
2021-10-08T22:12:50.000Z
domic/api/src/main/kotlin/com/lyft/domic/api/rendering/Renderer.kt
lyft/domic
e18c3b6030efae23009c74fd88b762f63ecf8d3a
[ "Apache-2.0" ]
24
2018-05-09T10:43:03.000Z
2021-08-19T06:54:46.000Z
package com.lyft.domic.api.rendering import io.reactivex.Observable import io.reactivex.disposables.Disposable interface Renderer { /** * "Renders" stream of changes. * * Implementation can be opinionated on grouping, and/or ordering of execution. * * [Renderer] might use [Change.equals] and [Change.hashCode] to compare [Change]s and optimize * rendering pipeline based on that, for example render latest equal [Change] arrived * within same buffering window. * * Each [Change]'s [Change.perform] will be called once on proper thread (Main Thread by default). * * @return [Disposable] that allows to stop observing the [Observable]. [Renderer] should try * to remove observed but not yet rendered actions from current buffer. */ fun render(changes: Observable<out Change>): Disposable /** * "Renders" what is in the buffer at the moment, blocking the caller thread. * * Main purpose of this API is to add a way of solving ["First Frame Problem"](https://github.com/lyft/domic/issues/14). * * Implementation can be opinionated on threading and throw an exception if called on wrong thread. */ fun renderCurrentBuffer() /** * Shuts down the [Renderer]. [Renderer] can not be reused after shut down. */ fun shutdown() }
35.605263
124
0.683666
3
faa4fa5ded5b37db7d4499ba81ec77a273bf1415
2,087
swift
Swift
Playground/Array_Playground.playground/Contents.swift
nchkdxlq/SwiftDemo
e73dd09d1f73526e77cd3315e2cc0e4447ca2ca5
[ "MIT" ]
null
null
null
Playground/Array_Playground.playground/Contents.swift
nchkdxlq/SwiftDemo
e73dd09d1f73526e77cd3315e2cc0e4447ca2ca5
[ "MIT" ]
null
null
null
Playground/Array_Playground.playground/Contents.swift
nchkdxlq/SwiftDemo
e73dd09d1f73526e77cd3315e2cc0e4447ca2ca5
[ "MIT" ]
null
null
null
//: Playground - noun: a place where people can play import UIKit /********************* Arrar的基本操作 ***********************/ /****** 初始化数组 ******/ var arr = [3, 6, 9] arr[0] = 1 var doubleArr: Array<Double> = [] var doubleArr1: [Double] = [] var doubleArr2 = [Double]() var strArr: [String] = ["luoquan", "cookie", "iOS"] var intArr = Array(repeating: 6, count: 2) // init an empty array, /* 初始化数组是一定要指定数组的类型,也就是指定数组元素的类型 */ var emptyArr: [String] = Array() var emptyArr1 = [String]() if emptyArr.isEmpty { print("is Empty") } /***** 数组追加 ******/ // append var nameArr = [String]() nameArr.append("luoquan") nameArr.append("小明") // 运算符 + var boys = ["Kang", "David"] var girls = ["ilas", "rose"] var boysGirls = boys + girls // 预运算符 += nameArr += boys nameArr += girls // insert // 插入单个元素 girls.insert("小芳", at: 0) // 插入一个数组 boys.insert(contentsOf: ["小三", "李四"], at: 0) /******** 删除数组 (返回删除的元素)*********/ nameArr nameArr.removeLast() nameArr.removeFirst() nameArr.remove(at: 0) //nameArr.removeLast(<#T##n: Int##Int#>) //nameArr.removeLast(<#T##n: Int##Int#>) nameArr nameArr.popLast() nameArr.removeSubrange(0..<2) //nameArr.removeAll() nameArr.removeAll(keepingCapacity: true) /******* 修改数组 *******/ girls girls[0] = "美眉" girls.replaceSubrange(1..<3, with: ["女神", "妹纸"]) /******** 遍历数组 ********/ nameArr += boys nameArr += girls for name in nameArr { print(name) } for (index, name) in nameArr.enumerated() { print("第 \(index) 位同学的名字是:\(name)") } nameArr.forEach { (name) in print("name = \(name)") } nameArr // 什么东西 不懂 ??????? var gene = nameArr.makeIterator() gene.next() var enume = nameArr.enumerated() var enumeGene = enume.makeIterator() enumeGene.next() /******* 数组的高阶函数 *********/ var upStr = nameArr.map { (name) -> String in name.uppercased() } var countArr = nameArr.map { $0.characters.count } print(countArr) var countGrate2 = countArr.filter { (num) -> Bool in return num > 2 } print(countGrate2) countGrate2 = countArr.filter {$0 > 2} print(countGrate2) let range = 0..<4 let range1 = 0...4
15.123188
58
0.603258
3.171875
e8f70cb35f8f35780ab43f567c03a983bf3f8b23
5,512
py
Python
othello.py
edjacob25/Intelligent-Systems
ae24c7e1039c98cd2940a5a813aae27fabadb99f
[ "MIT" ]
null
null
null
othello.py
edjacob25/Intelligent-Systems
ae24c7e1039c98cd2940a5a813aae27fabadb99f
[ "MIT" ]
null
null
null
othello.py
edjacob25/Intelligent-Systems
ae24c7e1039c98cd2940a5a813aae27fabadb99f
[ "MIT" ]
null
null
null
from games import (GameState, Game, query_player, random_player, alphabeta_player, play_game, minimax_decision, alphabeta_full_search, alphabeta_search) class Othello(Game): """Juega Othello en un tablero 8 x 8, con Max (primer jugador) jugando con las fichas negras. Un estado tiene el jugador al que le toca jugar, una utilidad en caché, una lista de movimientos en la forma de una lista de posiciones (x, y), y un tablero, en la forma de un diccionario de entradas {(x, y): Jugador}, donde Jugador es 'B' para las fichas blancas y 'N' para las fichas negras.""" def __init__(self): moves = [(x, y) for x in range(1, 9) for y in range(1, 9)] moves.remove((4, 4)) moves.remove((4, 5)) moves.remove((5, 4)) moves.remove((5, 5)) # siempre inicia 'N' self.initial = GameState(to_move='N', utility=0, board={(4, 4):'B',(4, 5):'N', (5, 4):'N',(5, 5):'B'}, moves=moves) def actions(self, state): """Los movimientos legales son las posiciones que se alinean con otra pieza del mismo color del jugador que mueve formando una segmento de línea recta que contenga al menos una pieza del contrincante.""" return self.legal_moves(state.moves, state.board, state.to_move) def legal_moves(self, smoves, board, player): """Determina los movimientos legales de un jugador sobre un tablero""" moves = [] for (x, y) in smoves: if self.change_dir(x, y, -1, -1, board, player) \ or self.change_dir(x, y, -1, 0, board, player) \ or self.change_dir(x, y, -1, 1, board, player) \ or self.change_dir(x, y, 0, -1, board, player) \ or self.change_dir(x, y, 0, 1, board, player) \ or self.change_dir(x, y, 1, -1, board, player) \ or self.change_dir(x, y, 1, 0, board, player) \ or self.change_dir(x, y, 1, 1, board, player): moves.append((x, y)) return moves def change_dir(self, x, y, xd, yd, board, player): """Determina una dirección que cambiará el color de al menos una pieza del contrincante""" def find_player(x, y): """Determina si se encuentra otra pieza del jugador en una dirección""" x += xd y += yd while (x, y) in board: if board[(x, y)] == player: return True else: x += xd y += yd return False x1 = x + xd y1 = y + yd if (x1, y1) in board and player != board[(x1, y1)]: return find_player(x1, y1) else: return False def result(self, state, move): def change_player(xd, yd): """Cambia las piezas al color del jugador en una dirección""" x, y = move if self.change_dir(x, y, xd, yd, board, player): x += xd y += yd while (x, y) in board: if board[(x, y)] == player: return else: board[(x, y)] = player x += xd y += yd board = state.board.copy() moves = list(state.moves) player = state.to_move if move in self.actions(state): board[move] = player change_player(-1, -1) change_player(-1, 0) change_player(-1, 1) change_player(0, -1) change_player(0, 1) change_player(1, -1) change_player(1, 0) change_player(1, 1) moves.remove(move) return GameState(to_move=('B' if player == 'N' else 'N'), utility=self.compute_utility(board, move, player), board=board, moves=moves) else: return GameState(to_move=('B' if player == 'N' else 'N'), utility=self.compute_utility(board, move, player), board=board, moves=moves) def utility(self, state, player): "Return the value to player; 1 for win, -1 for loss, 0 otherwise." return state.utility if player == 'N' else -state.utility def terminal_test(self, state): "Un estado es terminal si ninguno de los jugadores tiene acciones" laN = len(self.legal_moves(state.moves, state.board, 'N')) laB = len(self.legal_moves(state.moves, state.board, 'B')) return (laN + laB) == 0 def display(self, state): """despliega el estado del tablero de juego""" board = state.board print(' ', end=' ') for y in range(1, 9): print(y, end=' ') print() for x in range(1, 9): print(x, end=' ') for y in range(1, 9): print(board.get((x, y), '.'), end=' ') print() def compute_utility(self, board, move, player): """Regresa la diferencia entre el número de piezas de 'N' y el número de piezas de 'B'""" pieces = list(board.values()) return pieces.count('N') - pieces.count('B')
40.529412
80
0.502903
3.234375
58ce5b1be799a8d0ea40cee7f7eb2c202fcb8516
10,844
rs
Rust
polars/tests/it/core/rolling_window.rs
alexander-beedie/polars
06ba4f3796a1f4aaa39a04d5454a48009568e290
[ "MIT" ]
null
null
null
polars/tests/it/core/rolling_window.rs
alexander-beedie/polars
06ba4f3796a1f4aaa39a04d5454a48009568e290
[ "MIT" ]
null
null
null
polars/tests/it/core/rolling_window.rs
alexander-beedie/polars
06ba4f3796a1f4aaa39a04d5454a48009568e290
[ "MIT" ]
null
null
null
use super::*; #[test] fn test_rolling() { let s = Int32Chunked::new("foo", &[1, 2, 3, 2, 1]).into_series(); let a = s .rolling_sum(RollingOptionsImpl { window_size: Duration::new(2), min_periods: 1, ..Default::default() }) .unwrap(); let a = a.i32().unwrap(); assert_eq!( Vec::from(a), [1, 3, 5, 5, 3] .iter() .copied() .map(Some) .collect::<Vec<_>>() ); let a = s .rolling_min(RollingOptionsImpl { window_size: Duration::new(2), min_periods: 1, ..Default::default() }) .unwrap(); let a = a.i32().unwrap(); assert_eq!( Vec::from(a), [1, 1, 2, 2, 1] .iter() .copied() .map(Some) .collect::<Vec<_>>() ); let a = s .rolling_max(RollingOptionsImpl { window_size: Duration::new(2), weights: Some(vec![1., 1.]), min_periods: 1, ..Default::default() }) .unwrap(); let a = a.f64().unwrap(); assert_eq!( Vec::from(a), [1., 2., 3., 3., 2.] .iter() .copied() .map(Some) .collect::<Vec<_>>() ); } #[test] fn test_rolling_min_periods() { let s = Int32Chunked::new("foo", &[1, 2, 3, 2, 1]).into_series(); let a = s .rolling_max(RollingOptionsImpl { window_size: Duration::new(2), min_periods: 2, ..Default::default() }) .unwrap(); let a = a.i32().unwrap(); assert_eq!(Vec::from(a), &[None, Some(2), Some(3), Some(3), Some(2)]); } #[test] fn test_rolling_mean() { let s = Float64Chunked::new( "foo", &[ Some(0.0), Some(1.0), Some(2.0), None, None, Some(5.0), Some(6.0), ], ) .into_series(); // check err on wrong input assert!(s .rolling_mean(RollingOptionsImpl { window_size: Duration::new(1), min_periods: 2, ..Default::default() }) .is_err()); // validate that we divide by the proper window length. (same as pandas) let a = s .rolling_mean(RollingOptionsImpl { window_size: Duration::new(3), min_periods: 1, center: false, ..Default::default() }) .unwrap(); let a = a.f64().unwrap(); assert_eq!( Vec::from(a), &[ Some(0.0), Some(0.5), Some(1.0), Some(1.5), Some(2.0), Some(5.0), Some(5.5) ] ); // check centered rolling window let a = s .rolling_mean(RollingOptionsImpl { window_size: Duration::new(3), min_periods: 1, center: true, ..Default::default() }) .unwrap(); let a = a.f64().unwrap(); assert_eq!( Vec::from(a), &[ Some(0.5), Some(1.0), Some(1.5), Some(2.0), Some(5.0), Some(5.5), Some(5.5) ] ); // integers let ca = Int32Chunked::from_slice("", &[1, 8, 6, 2, 16, 10]); let out = ca .into_series() .rolling_mean(RollingOptionsImpl { window_size: Duration::new(2), weights: None, min_periods: 2, center: false, ..Default::default() }) .unwrap(); let out = out.f64().unwrap(); assert_eq!( Vec::from(out), &[None, Some(4.5), Some(7.0), Some(4.0), Some(9.0), Some(13.0),] ); } #[test] fn test_rolling_apply() { let ca = Float64Chunked::new( "foo", &[ Some(0.0), Some(1.0), Some(2.0), None, None, Some(5.0), Some(6.0), ], ); let out = ca .rolling_apply( &|s| s.sum_as_series(), RollingOptionsFixedWindow { window_size: 3, min_periods: 3, ..Default::default() }, ) .unwrap(); let out = out.f64().unwrap(); assert_eq!( Vec::from(out), &[ None, None, Some(3.0), Some(3.0), Some(2.0), Some(5.0), Some(11.0) ] ); } #[test] fn test_rolling_var() { let s = Float64Chunked::new( "foo", &[ Some(0.0), Some(1.0), Some(2.0), None, None, Some(5.0), Some(6.0), ], ) .into_series(); // window larger than array assert_eq!( s.rolling_var(RollingOptionsImpl { window_size: Duration::new(10), min_periods: 10, ..Default::default() }) .unwrap() .null_count(), s.len() ); let options = RollingOptionsImpl { window_size: Duration::new(3), min_periods: 3, ..Default::default() }; let out = s .rolling_var(options.clone()) .unwrap() .cast(&DataType::Int32) .unwrap(); let out = out.i32().unwrap(); assert_eq!( Vec::from(out), &[None, None, Some(1), None, None, None, None,] ); let s = Float64Chunked::from_slice("", &[0.0, 2.0, 8.0, 3.0, 12.0, 1.0]).into_series(); let out = s .rolling_var(options) .unwrap() .cast(&DataType::Int32) .unwrap(); let out = out.i32().unwrap(); assert_eq!( Vec::from(out), &[None, None, Some(17), Some(10), Some(20), Some(34),] ); // check centered rolling window let out = s .rolling_var(RollingOptionsImpl { window_size: Duration::new(4), min_periods: 3, center: true, ..Default::default() }) .unwrap(); let out = out.f64().unwrap(); assert_eq!( Vec::from(out), &[ None, Some(17.333333333333332), Some(11.583333333333334), Some(21.583333333333332), Some(24.666666666666668), Some(34.33333333333334) ] ); } #[test] fn test_median_quantile_types() { let s = Int32Chunked::new("foo", &[1, 2, 3, 2, 1]).into_series(); let rol_med = s .rolling_median(RollingOptionsImpl { window_size: Duration::new(2), min_periods: 1, ..Default::default() }) .unwrap(); let rol_med_weighted = s .rolling_median(RollingOptionsImpl { window_size: Duration::new(2), min_periods: 1, weights: Some(vec![1.0, 2.0]), ..Default::default() }) .unwrap(); let rol_quantile = s .rolling_quantile( 0.3, QuantileInterpolOptions::Linear, RollingOptionsImpl { window_size: Duration::new(2), min_periods: 1, ..Default::default() }, ) .unwrap(); let rol_quantile_weighted = s .rolling_quantile( 0.3, QuantileInterpolOptions::Linear, RollingOptionsImpl { window_size: Duration::new(2), min_periods: 1, weights: Some(vec![1.0, 2.0]), ..Default::default() }, ) .unwrap(); assert_eq!(*rol_med.dtype(), DataType::Float64); assert_eq!(*rol_med_weighted.dtype(), DataType::Float64); assert_eq!(*rol_quantile.dtype(), DataType::Float64); assert_eq!(*rol_quantile_weighted.dtype(), DataType::Float64); let s = Float32Chunked::new("foo", &[1.0, 2.0, 3.0, 2.0, 1.0]).into_series(); let rol_med = s .rolling_median(RollingOptionsImpl { window_size: Duration::new(2), min_periods: 1, ..Default::default() }) .unwrap(); let rol_med_weighted = s .rolling_median(RollingOptionsImpl { window_size: Duration::new(2), min_periods: 1, weights: Some(vec![1.0, 2.0]), ..Default::default() }) .unwrap(); let rol_quantile = s .rolling_quantile( 0.3, QuantileInterpolOptions::Linear, RollingOptionsImpl { window_size: Duration::new(2), min_periods: 1, ..Default::default() }, ) .unwrap(); let rol_quantile_weighted = s .rolling_quantile( 0.3, QuantileInterpolOptions::Linear, RollingOptionsImpl { window_size: Duration::new(2), min_periods: 1, weights: Some(vec![1.0, 2.0]), ..Default::default() }, ) .unwrap(); assert_eq!(*rol_med.dtype(), DataType::Float32); assert_eq!(*rol_med_weighted.dtype(), DataType::Float32); assert_eq!(*rol_quantile.dtype(), DataType::Float32); assert_eq!(*rol_quantile_weighted.dtype(), DataType::Float32); let s1 = Float64Chunked::new("foo", &[1.0, 2.0, 3.0, 2.0, 1.0]).into_series(); let rol_med = s1 .rolling_median(RollingOptionsImpl { window_size: Duration::new(2), min_periods: 1, ..Default::default() }) .unwrap(); let rol_med_weighted = s1 .rolling_median(RollingOptionsImpl { window_size: Duration::new(2), min_periods: 1, weights: Some(vec![1.0, 2.0]), ..Default::default() }) .unwrap(); let rol_quantile = s1 .rolling_quantile( 0.3, QuantileInterpolOptions::Linear, RollingOptionsImpl { window_size: Duration::new(2), min_periods: 1, ..Default::default() }, ) .unwrap(); let rol_quantile_weighted = s1 .rolling_quantile( 0.3, QuantileInterpolOptions::Linear, RollingOptionsImpl { window_size: Duration::new(2), min_periods: 1, weights: Some(vec![1.0, 2.0]), ..Default::default() }, ) .unwrap(); assert_eq!(*rol_med.dtype(), DataType::Float64); assert_eq!(*rol_med_weighted.dtype(), DataType::Float64); assert_eq!(*rol_quantile.dtype(), DataType::Float64); assert_eq!(*rol_quantile_weighted.dtype(), DataType::Float64); }
25.160093
91
0.462744
3.34375
c09e563829075cdc057912981a834e22d997d400
33,066
swift
Swift
Tests/Sequencer/Sequence/ShuffleSequenceIterationTests.swift
kartik-venugopal/aural-player
73e1e2768563094da63a73bddb4e22b3469ebf3a
[ "MIT" ]
21
2022-02-07T23:42:43.000Z
2022-03-17T12:07:28.000Z
Tests/Sequencer/Sequence/ShuffleSequenceIterationTests.swift
kartik-venugopal/aural-player
73e1e2768563094da63a73bddb4e22b3469ebf3a
[ "MIT" ]
2
2022-03-01T20:20:27.000Z
2022-03-07T14:23:04.000Z
Tests/Sequencer/Sequence/ShuffleSequenceIterationTests.swift
kartik-venugopal/aural-player
73e1e2768563094da63a73bddb4e22b3469ebf3a
[ "MIT" ]
3
2022-02-10T16:42:31.000Z
2022-03-18T11:11:48.000Z
// // ShuffleSequenceIterationTests.swift // Aural // // Copyright © 2021 Kartik Venugopal. All rights reserved. // // This software is licensed under the MIT software license. // See the file "LICENSE" in the project root directory for license terms. // import XCTest class ShuffleSequenceIterationTests: AuralTestCase { private var sequence: ShuffleSequence = ShuffleSequence() private var sequenceArray: [Int] { return sequence.sequence } private var sequenceArrayCount: Int { return sequenceArray.count } override func setUp() { // Start with a fresh object before each test sequence = ShuffleSequence() } func testPrevious_noSequence() { // Ensure that the sequence is not pointing to any element. XCTAssertNil(sequence.currentValue) // previous() should produce nil when there is no sequence. // Calling previous() multiple times here should always produce the same result. for _ in 1...5 { XCTAssertNil(sequence.previous()) // Ensure that the sequence is still not pointing to any element (i.e. no iteration). XCTAssertNil(sequence.currentValue) } } func testPrevious_sequenceNotStarted() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 10) // Ensure that the sequence is not pointing to any element. XCTAssertNil(sequence.currentValue) // Calling previous() multiple times here should always produce the same result. for _ in 1...5 { // No previous element available when sequence has not started. XCTAssertNil(sequence.previous()) // Also verify that no iteration was performed (i.e. still not pointing to any element). XCTAssertNil(sequence.currentValue) } } func testPrevious_atFirstElement() { // Create and start the sequence. sequence.resizeAndReshuffle(size: 10, startWith: 5) // Ensure that the sequence points to the first element). XCTAssertEqual(sequenceArray.first, sequence.currentValue) // Calling previous() multiple times here should always produce the same result. for _ in 1...5 { XCTAssertNil(sequence.previous()) // Ensure that the calls to previous() did not result in any iteration (i.e. it still points to the first element). XCTAssertEqual(sequenceArray.first, sequence.currentValue) } } func testPrevious_atSecondElement() { sequence.resizeAndReshuffle(size: 10) // Iterate to the 2nd element. XCTAssertEqual(sequence.next(repeatMode: .off), sequenceArray[0]) XCTAssertEqual(sequence.next(repeatMode: .off), sequenceArray[1]) // Ensure sequence is pointing to the second element. XCTAssertEqual(sequenceArray[1], sequence.currentValue) // Perform the test. let previous = sequence.previous() XCTAssertNotNil(previous) // Previous value should equal the first element. XCTAssertEqual(previous, sequenceArray.first) // Ensure that the call to previous() resulted in iteration to the first element. XCTAssertEqual(sequenceArray.first, sequence.currentValue) // Any further calls should result in nil for _ in 1...5 { XCTAssertNil(sequence.previous()) // Ensure sequence is still pointing to the first element (i.e. no iteration). XCTAssertEqual(sequenceArray.first, sequence.currentValue) } } func testPrevious_iterateBackwardsFromTheEnd() { sequence.resizeAndReshuffle(size: 1000) // Iterate to the last element. for _ in 0..<sequenceArray.count { _ = sequence.next(repeatMode: .off) } // Ensure sequence is pointing to the last element. XCTAssertEqual(sequenceArray.last, sequence.currentValue) // Iterate backwards, invoking previous() var cursor: Int = sequenceArray.count - 1 while cursor > 0 { let previous = sequence.previous() XCTAssertNotNil(previous) XCTAssertEqual(previous, sequenceArray[cursor - 1]) // Ensure sequence is now pointing to the element at index = cursor - 1 (i.e. iteration). XCTAssertEqual(sequenceArray[cursor - 1], sequence.currentValue) cursor.decrement() } } // MARK: next() tests ---------------------------------------------------------------------------------------------------- func testNext_noSequence() { for repeatMode in RepeatMode.allCases { sequence.clear() // next() should produce nil, regardless of repeat mode. XCTAssertNil(sequence.next(repeatMode: repeatMode)) } } func testNext_sequenceNotStarted() { for repeatMode in RepeatMode.allCases { sequence.clear() // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 10) // Ensure sequence is not pointing to any element (i.e. no iteration), because it has not been started. XCTAssertNil(sequence.currentValue) // next() should produce the first element, regardless of repeat mode. XCTAssertEqual(sequenceArray.first, sequence.next(repeatMode: repeatMode)) // Ensure sequence is now pointing to the first element (i.e. iteration). XCTAssertEqual(sequenceArray.first, sequence.currentValue) } } func testNext_atFirstElement() { for repeatMode in RepeatMode.allCases { sequence.clear() // Create and start the sequence. sequence.resizeAndReshuffle(size: 10, startWith: 5) // Ensure sequence is now pointing to the first element. XCTAssertEqual(sequenceArray.first, sequence.currentValue) // next() should produce the second element, regardless of repeat mode. XCTAssertEqual(sequenceArray[1], sequence.next(repeatMode: repeatMode)) // Ensure sequence is now pointing to the second element (i.e. iteration). XCTAssertEqual(sequenceArray[1], sequence.currentValue) } } func testNext_atSecondLastElement() { for repeatMode in RepeatMode.allCases { sequence.clear() // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 1000) // Ensure sequence is not pointing to any element (i.e. no iteration). XCTAssertNil(sequence.currentValue) // Iterate to the second-last element. for index in 0..<(sequenceArrayCount - 1) { XCTAssertEqual(sequence.next(repeatMode: repeatMode), sequenceArray[index]) } // Ensure sequence is now pointing to the second-last element (i.e. iteration). XCTAssertEqual(sequenceArray[sequenceArrayCount - 2], sequence.currentValue) // next() should produce the last element, regardless of repeat mode. XCTAssertEqual(sequenceArray.last, sequence.next(repeatMode: repeatMode)) // Ensure sequence is now pointing to the last element (i.e. iteration). XCTAssertEqual(sequenceArray.last, sequence.currentValue) } } func testNext_atLastElement_repeatOff() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 1000) // Iterate to the last element. for index in 0..<sequenceArrayCount { XCTAssertEqual(sequence.next(repeatMode: .off), sequenceArray[index]) } // Ensure sequence is now pointing to the last element (i.e. iteration). XCTAssertEqual(sequenceArray.last, sequence.currentValue) // next() should produce nil when not repeating the sequence. XCTAssertNil(sequence.next(repeatMode: .off)) // Ensure sequence is still pointing to the last element (i.e. no iteration). XCTAssertEqual(sequenceArray.last, sequence.currentValue) } func testNext_atLastElement_repeatOne() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 1000) // Iterate to the last element. for index in 0..<sequenceArrayCount { XCTAssertEqual(sequence.next(repeatMode: .one), sequenceArray[index]) } // Ensure sequence is now pointing to the last element (i.e. iteration). XCTAssertEqual(sequenceArray.last, sequence.currentValue) // next() should produce nil when not repeating the sequence. XCTAssertNil(sequence.next(repeatMode: .one)) // Ensure sequence is still pointing to the last element (i.e. iteration). XCTAssertEqual(sequenceArray.last, sequence.currentValue) } func testNext_atLastElement_repeatAll() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 1000) let seqArrayBeforeReshuffle: [Int] = Array(sequenceArray) // Iterate to the last element. for index in 0..<sequenceArrayCount { XCTAssertEqual(sequence.next(repeatMode: .all), sequenceArray[index]) } // Ensure sequence is now pointing to the last element (i.e. iteration). XCTAssertEqual(sequenceArray.last, sequence.currentValue) let lastElementBeforeReshuffle = sequenceArray.last! // next() should cause the sequence to be reshuffled, and a value to be produced, so the value should be non-nil. let next = sequence.next(repeatMode: .all) XCTAssertNotNil(next) let seqArrayAfterReshuffle: [Int] = Array(sequenceArray) let firstElementAfterReshuffle = seqArrayAfterReshuffle.first! // Check that next() produced the first element in the new sequence XCTAssertEqual(next, firstElementAfterReshuffle) // Ensure the order of the sequence elements changed (i.e. new sequence), and that the last element // in the old sequence is not equal the first element in the new sequence. // (so that no track plays twice in a row) XCTAssertFalse(seqArrayBeforeReshuffle.elementsEqual(seqArrayAfterReshuffle)) XCTAssertNotEqual(lastElementBeforeReshuffle, firstElementAfterReshuffle) // Ensure sequence is now pointing to the first element of the new sequence (i.e. iteration). XCTAssertEqual(sequenceArray.first, sequence.currentValue) } // MARK: peekPrevious() tests --------------------------------------------------------------------------------------- func testPeekPrevious_noSequence() { // Ensure that the sequence is not pointing to any element. XCTAssertNil(sequence.currentValue) // peekPrevious() should produce nil when there is no sequence. // Calling peekPrevious() multiple times here should always produce the same result. for _ in 1...5 { XCTAssertNil(sequence.peekPrevious()) // Ensure that the sequence is still not pointing to any element (i.e. no iteration). XCTAssertNil(sequence.currentValue) } } func testPeekPrevious_sequenceNotStarted() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 10) // Ensure that the sequence is not pointing to any element. XCTAssertNil(sequence.currentValue) // Calling peekPrevious() multiple times here should always produce the same result. for _ in 1...5 { XCTAssertNil(sequence.peekPrevious()) // Also verify that no iteration was performed (i.e. still not pointing to any element). XCTAssertNil(sequence.currentValue) } } func testPeekPrevious_atFirstElement() { // Create and start the sequence. sequence.resizeAndReshuffle(size: 10, startWith: 5) // Ensure that the sequence points to the first element). XCTAssertEqual(sequenceArray.first, sequence.currentValue) // Calling peekPrevious() multiple times here should always produce the same result. for _ in 1...5 { // When pointing to the first element, the previous element should be nil. XCTAssertNil(sequence.peekPrevious()) // Ensure that the calls to peekPrevious() did not result in any iteration (i.e. it still points to the first element). XCTAssertEqual(sequenceArray.first, sequence.currentValue) } } func testPeekPrevious_atSecondElement() { sequence.resizeAndReshuffle(size: 10) // Iterate to the 2nd element. XCTAssertEqual(sequence.next(repeatMode: .off), sequenceArray[0]) XCTAssertEqual(sequence.next(repeatMode: .off), sequenceArray[1]) // Ensure sequence is pointing to the second element. XCTAssertEqual(sequenceArray[1], sequence.currentValue) // Perform the test. let previous = sequence.peekPrevious() XCTAssertNotNil(previous) // Previous value should equal the first element. XCTAssertEqual(previous, sequenceArray.first) // Ensure that the call to peekPrevious() resulted in no iteration (i.e. still pointing to the 2nd element) XCTAssertEqual(sequenceArray[1], sequence.currentValue) // Any further calls should result in the same value being produced (i.e. first element). for _ in 1...5 { XCTAssertEqual(previous, sequenceArray.first) // Ensure sequence is still pointing to the second element (i.e. no iteration). XCTAssertEqual(sequenceArray[1], sequence.currentValue) } } func testPeekPrevious_iterateBackwardsFromTheEnd() { sequence.resizeAndReshuffle(size: 1000) // Iterate to the last element. for _ in 0..<sequenceArray.count { _ = sequence.next(repeatMode: .off) } // Ensure sequence is pointing to the last element. XCTAssertEqual(sequenceArray.last, sequence.currentValue) // Iterate backwards var cursor: Int = sequenceArray.count - 1 while cursor > 0 { // Ensure sequence is pointing to the element at index = cursor. XCTAssertEqual(sequenceArray[cursor], sequence.currentValue) // Then test peekPrevious(). let previous = sequence.peekPrevious() XCTAssertNotNil(previous) XCTAssertEqual(previous, sequenceArray[cursor - 1]) // Call previous() to actually iterate one element back. _ = sequence.previous() cursor.decrement() } } // MARK: peekNext() tests --------------------------------------------------------------------------------------- func testPeekNext_noSequence() { // Ensure sequence is not pointing to any element. XCTAssertNil(sequence.currentValue) // peekNext() should produce nil, even with repeated calls // No iteration should take place. for _ in 1...5 { XCTAssertNil(sequence.peekNext()) XCTAssertNil(sequence.currentValue) } } func testPeekNext_sequenceNotStarted() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 10) // Ensure sequence is not pointing to any element (i.e. no iteration), because it has not been started. XCTAssertNil(sequence.currentValue) // peekNext() should produce the first element, even with repeated calls. for _ in 1...5 { XCTAssertEqual(sequenceArray.first, sequence.peekNext()) // Ensure sequence is still not pointing to any element (i.e. no iteration). XCTAssertNil(sequence.currentValue) } } func testPeekNext_atFirstElement() { // Create and start the sequence. sequence.resizeAndReshuffle(size: 10, startWith: 5) // Ensure sequence is now pointing to the first element. XCTAssertEqual(sequenceArray.first, sequence.currentValue) for _ in 1...5 { // peekNext() should produce the second element, even with repeated calls. XCTAssertEqual(sequenceArray[1], sequence.peekNext()) // Ensure sequence is still pointing to the first element (i.e. no iteration). XCTAssertEqual(sequenceArray.first, sequence.currentValue) } } func testPeekNext_atSecondLastElement() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 1000) // Ensure sequence is not pointing to any element (i.e. no iteration). XCTAssertNil(sequence.currentValue) // Iterate to the second-last element. for index in 0..<(sequenceArrayCount - 1) { XCTAssertEqual(sequence.next(repeatMode: .off), sequenceArray[index]) } // Ensure sequence is now pointing to the second-last element (i.e. iteration). XCTAssertEqual(sequenceArray[sequenceArrayCount - 2], sequence.currentValue) // peekNext() should produce the last element, even with repeated calls. for _ in 1...5 { XCTAssertEqual(sequenceArray.last, sequence.peekNext()) // Ensure sequence is still pointing to the second-last element (i.e. no iteration). XCTAssertEqual(sequenceArray[sequenceArrayCount - 2], sequence.currentValue) } } func testPeekNext_atLastElement() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 1000) // Iterate to the last element. for index in 0..<sequenceArrayCount { XCTAssertEqual(sequence.next(repeatMode: .off), sequenceArray[index]) } // Ensure sequence is now pointing to the last element (i.e. iteration). XCTAssertEqual(sequenceArray.last, sequence.currentValue) // peekNext() should always produce nil, even with repeated calls. for _ in 1...5 { XCTAssertNil(sequence.peekNext()) // Ensure sequence is still pointing to the last element (i.e. no iteration). XCTAssertEqual(sequenceArray.last, sequence.currentValue) } } // MARK: hasPrevious tests --------------------------------------------------------------------------------------- func testHasPrevious_noSequence() { // Ensure that the sequence is not pointing to any element. XCTAssertNil(sequence.currentValue) // hasPrevious should produce false when there is no sequence. // Calling hasPrevious multiple times here should always produce the same result. for _ in 1...5 { XCTAssertFalse(sequence.hasPrevious) // Ensure that the sequence is still not pointing to any element (i.e. no iteration). XCTAssertNil(sequence.currentValue) } } func testHasPrevious_sequenceNotStarted() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 10) // Ensure that the sequence is not pointing to any element. XCTAssertNil(sequence.currentValue) // Calling hasPrevious multiple times here should always produce the same result. for _ in 1...5 { // No previous element available when sequence has not started. XCTAssertFalse(sequence.hasPrevious) // Also verify that no iteration was performed (i.e. still not pointing to any element). XCTAssertNil(sequence.currentValue) } } func testHasPrevious_atFirstElement() { // Create and start the sequence. sequence.resizeAndReshuffle(size: 10, startWith: 5) // Ensure that the sequence points to the first element). XCTAssertEqual(sequenceArray.first, sequence.currentValue) // Calling hasPrevious multiple times here should always produce the same result. for _ in 1...5 { // When pointing to the first element, there should be no previous element. XCTAssertFalse(sequence.hasPrevious) // Ensure that the calls to hasPrevious did not result in any iteration (i.e. it still points to the first element). XCTAssertEqual(sequenceArray.first, sequence.currentValue) } } func testHasPrevious_atSecondElement() { sequence.resizeAndReshuffle(size: 10) // Iterate to the 2nd element. XCTAssertEqual(sequence.next(repeatMode: .off), sequenceArray[0]) XCTAssertEqual(sequence.next(repeatMode: .off), sequenceArray[1]) // Ensure sequence is pointing to the second element. XCTAssertEqual(sequenceArray[1], sequence.currentValue) // Any further calls should result in the same value being produced (i.e. true). for _ in 1...5 { XCTAssertTrue(sequence.hasPrevious) // Ensure sequence is still pointing to the second element (i.e. no iteration). XCTAssertEqual(sequenceArray[1], sequence.currentValue) } } func testHasPrevious_iterateBackwardsFromTheEnd() { sequence.resizeAndReshuffle(size: 1000) // Iterate to the last element. for _ in 0..<sequenceArray.count { _ = sequence.next(repeatMode: .off) } // Ensure sequence is pointing to the last element. XCTAssertEqual(sequenceArray.last, sequence.currentValue) // Iterate backwards var cursor: Int = sequenceArray.count - 1 while cursor > 0 { // Ensure sequence is pointing to the element at index = cursor. XCTAssertEqual(sequenceArray[cursor], sequence.currentValue) // Then test hasPrevious. XCTAssertTrue(sequence.hasPrevious) // Call previous() to actually iterate one element back. _ = sequence.previous() cursor.decrement() } } // MARK: hasNext tests --------------------------------------------------------------------------------------- func testHasNext_noSequence() { // Ensure sequence is not pointing to any element. XCTAssertNil(sequence.currentValue) // hasNext should produce false, even with repeated calls // No iteration should take place. for _ in 1...5 { XCTAssertFalse(sequence.hasNext) XCTAssertNil(sequence.currentValue) } } func testHasNext_sequenceNotStarted() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 10) // Ensure sequence is not pointing to any element (i.e. no iteration), because it has not been started. XCTAssertNil(sequence.currentValue) // hasNext should return true when sequence has not started, even with repeated calls. for _ in 1...5 { XCTAssertTrue(sequence.hasNext) // Ensure sequence is still not pointing to any element (i.e. no iteration). XCTAssertNil(sequence.currentValue) } } func testHasNext_atFirstElement() { // Create and start the sequence. sequence.resizeAndReshuffle(size: 10, startWith: 5) // Ensure sequence is now pointing to the first element. XCTAssertEqual(sequenceArray.first, sequence.currentValue) for _ in 1...5 { // hasNext should produce true, even with repeated calls. XCTAssertTrue(sequence.hasNext) // Ensure sequence is still pointing to the first element (i.e. no iteration). XCTAssertEqual(sequenceArray.first, sequence.currentValue) } } func testHasNext_atSecondLastElement() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 1000) // Ensure sequence is not pointing to any element (i.e. no iteration). XCTAssertNil(sequence.currentValue) // Iterate to the second-last element. for index in 0..<(sequenceArrayCount - 1) { XCTAssertEqual(sequence.next(repeatMode: .off), sequenceArray[index]) } // Ensure sequence is now pointing to the second-last element (i.e. iteration). XCTAssertEqual(sequenceArray[sequenceArrayCount - 2], sequence.currentValue) // hasNext should produce true, even with repeated calls. for _ in 1...5 { XCTAssertTrue(sequence.hasNext) // Ensure sequence is still pointing to the second-last element (i.e. no iteration). XCTAssertEqual(sequenceArray[sequenceArrayCount - 2], sequence.currentValue) } } func testHasNext_atLastElement() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 1000) // Iterate to the last element. for index in 0..<sequenceArrayCount { XCTAssertEqual(sequence.next(repeatMode: .off), sequenceArray[index]) } // Ensure sequence is now pointing to the last element (i.e. iteration). XCTAssertEqual(sequenceArray.last, sequence.currentValue) // hasNext should always produce false, even with repeated calls. for _ in 1...5 { XCTAssertFalse(sequence.hasNext) // Ensure sequence is still pointing to the last element (i.e. no iteration). XCTAssertEqual(sequenceArray.last, sequence.currentValue) } } // MARK: hasEnded tests --------------------------------------------------------------------------------------- func testHasEnded_noSequence() { // An empty sequence is never considered to have started or ended. XCTAssertFalse(sequence.hasEnded) } func testHasEnded_sequenceNotStarted() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 10) // Ensure sequence is not pointing to any element (i.e. no iteration), because it has not been started. XCTAssertNil(sequence.currentValue) // hasEnded should return false when sequence has not started, even with repeated calls. for _ in 1...5 { XCTAssertFalse(sequence.hasEnded) // Ensure sequence is still not pointing to any element (i.e. no iteration). XCTAssertNil(sequence.currentValue) } } func testHasEnded_atFirstElement() { // Create and start the sequence. sequence.resizeAndReshuffle(size: 10, startWith: 5) // Ensure sequence is now pointing to the first element. XCTAssertEqual(sequenceArray.first, sequence.currentValue) for _ in 1...5 { // hasEnded should produce false, even with repeated calls. XCTAssertFalse(sequence.hasEnded) // Ensure sequence is still pointing to the first element (i.e. no iteration). XCTAssertEqual(sequenceArray.first, sequence.currentValue) } } func testHasEnded_atSecondLastElement() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 1000) // Ensure sequence is not pointing to any element (i.e. no iteration). XCTAssertNil(sequence.currentValue) // Iterate to the second-last element. for index in 0..<(sequenceArrayCount - 1) { XCTAssertEqual(sequence.next(repeatMode: .off), sequenceArray[index]) // hasEnded should produce false, throughout the loop. XCTAssertFalse(sequence.hasEnded) } // Ensure sequence is now pointing to the second-last element (i.e. iteration). XCTAssertEqual(sequenceArray[sequenceArrayCount - 2], sequence.currentValue) // hasEnded should still produce false, even with repeated calls. for _ in 1...5 { XCTAssertFalse(sequence.hasEnded) // Ensure sequence is still pointing to the second-last element (i.e. no iteration). XCTAssertEqual(sequenceArray[sequenceArrayCount - 2], sequence.currentValue) } } func testHasEnded_atLastElement() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 1000) // Iterate to the last element. for index in 0..<sequenceArrayCount { // hasEnded should produce false, throughout the loop. XCTAssertFalse(sequence.hasEnded) XCTAssertEqual(sequence.next(repeatMode: .off), sequenceArray[index]) } // Ensure sequence is now pointing to the last element (i.e. iteration). XCTAssertEqual(sequenceArray.last, sequence.currentValue) // hasEnded should now produce true, even with repeated calls, because sequence is now pointing to the last element. for _ in 1...5 { XCTAssertTrue(sequence.hasEnded) // Ensure sequence is still pointing to the last element (i.e. no iteration). XCTAssertEqual(sequenceArray.last, sequence.currentValue) } } func testHasEnded_atLastElement_afterReshuffle() { // Create but don't start the sequence. sequence.resizeAndReshuffle(size: 1000) // Iterate to the last element. for index in 0..<sequenceArrayCount { // hasEnded should produce false, throughout the loop. XCTAssertFalse(sequence.hasEnded) XCTAssertEqual(sequence.next(repeatMode: .off), sequenceArray[index]) } // Ensure sequence is now pointing to the last element (i.e. iteration). XCTAssertEqual(sequenceArray.last, sequence.currentValue) // hasEnded should now produce true, even with repeated calls, because sequence is now pointing to the last element. for _ in 1...5 { XCTAssertTrue(sequence.hasEnded) // Ensure sequence is still pointing to the last element (i.e. no iteration). XCTAssertEqual(sequenceArray.last, sequence.currentValue) } // Trigger a sequence reshuffle by calling next() with repeatMode = .all (this will cause the creation of a new sequence) XCTAssertNotNil(sequence.next(repeatMode: .all)) // Ensure sequence is pointing to the first element of the new sequence (i.e. iteration). XCTAssertEqual(sequenceArray.first, sequence.currentValue) // Now, hasEnded should produce false, as a new sequence has been created. for _ in 1...5 { XCTAssertFalse(sequence.hasEnded) // Ensure sequence is still pointing to the first element of the new sequence (i.e. no iteration). XCTAssertEqual(sequenceArray.first, sequence.currentValue) } } }
38.22659
131
0.595748
3.109375
56c84693fb28b4b4835199d7d553f8f34180d36b
1,436
ts
TypeScript
src/app/workplans/workplans-list/workplans-list.component.ts
FlorinMC/form-builder
40f0dabc2b7f2e58e53f739e09f002e3749fbac3
[ "MIT" ]
null
null
null
src/app/workplans/workplans-list/workplans-list.component.ts
FlorinMC/form-builder
40f0dabc2b7f2e58e53f739e09f002e3749fbac3
[ "MIT" ]
null
null
null
src/app/workplans/workplans-list/workplans-list.component.ts
FlorinMC/form-builder
40f0dabc2b7f2e58e53f739e09f002e3749fbac3
[ "MIT" ]
null
null
null
import { HttpResponse } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import { WebApiService } from '../../shared/services/web-api.service'; import { Workplan } from '../workplan/workplan.model'; import { WorkplansListService } from './workplans-list.service'; @Component({ selector: 'app-workplans-list', templateUrl: 'workplans-list.component.html', styleUrls: ['./workplans-list.component.scss'], }) export class WorkplansListComponent implements OnInit { public workplansList: Workplan[]; public workplans: Observable<HttpResponse<Workplan[]>> = null; constructor( private workplansListService: WorkplansListService, private webApiService: WebApiService, ) { } public ngOnInit(): void { this.getWorkplansListItems(); } private getWorkplansListItems(): void { this.workplans = Observable.fromPromise(this.workplansListService.getWorkplansList()); this.workplans.subscribe(async (resp: HttpResponse<Workplan[]>) => { const response: HttpResponse<Workplan[]> = await resp; if (response) { const workplansList: Workplan[] = response && response.body; this.workplansList = workplansList.map((workplan: Workplan): Workplan => { return workplan; }); } }, (err: Error) => { this.webApiService.checkErrorFault(err); }); } }
33.395349
90
0.69429
3.0625
d43dffe27f7d2c7666c92eed22de74cbf6273890
1,106
rs
Rust
src/basics/src/main.rs
jrbeverly/rust-lang-checks
1ded16c64147834f350dd0c9da4b06d8b5a77df6
[ "MIT" ]
null
null
null
src/basics/src/main.rs
jrbeverly/rust-lang-checks
1ded16c64147834f350dd0c9da4b06d8b5a77df6
[ "MIT" ]
null
null
null
src/basics/src/main.rs
jrbeverly/rust-lang-checks
1ded16c64147834f350dd0c9da4b06d8b5a77df6
[ "MIT" ]
null
null
null
fn main() { println!("Hello, world!"); println!("The first letter of the English alphabet is {} and the last letter is {}.", 'A', 'Z'); let mut a_number : u32; let a_word = "Ten"; a_number = 10; println!("The number is {}.", a_number); println!("The word is {}.", a_word); a_number = 15; println!("The number is {}.", a_number); print_byrange(500, 0, 512); let simple_struct = generate_struct(); print_struct(simple_struct); } struct DataOf { name: String, scale: u8 } fn generate_struct() -> DataOf { let result = DataOf { name: String::from("ABC"), scale: 5 }; return result; } fn print_struct(st : DataOf) { println!("The name is {}.", st.name); println!("The scale is {}.", st.scale); } fn print_byrange(num: i32, min : i32, max: i32) { let out_of_range: bool; if num < min { out_of_range = true; } else if num == min { out_of_range = true; } else if num > max { out_of_range = true; } else { out_of_range = false; } println!("The number is {}.", out_of_range); }
24.577778
100
0.576854
3.203125
39d0b9db90b1a5bea3e64a9aa2c3c4e47927c178
6,155
swift
Swift
Pod/Classes/Container/Container.swift
mikenolimits/Oatmeal
e4d2c41d4dbbe27426080b7fcf783fc8a650fb63
[ "MIT" ]
1
2016-01-11T03:30:30.000Z
2016-01-11T03:30:30.000Z
Pod/Classes/Container/Container.swift
mikenolimits/Oatmeal
e4d2c41d4dbbe27426080b7fcf783fc8a650fb63
[ "MIT" ]
null
null
null
Pod/Classes/Container/Container.swift
mikenolimits/Oatmeal
e4d2c41d4dbbe27426080b7fcf783fc8a650fb63
[ "MIT" ]
null
null
null
import Foundation public class Container : Oatmeal { public static var entityName : String? = "Container" /* The singleton reference to the container itself */ static public let App = Container() /* Singletons bound to the app always need a reference */ public var singletons : [Resolveable] = [ Events(),Reflections() ] /* Lazy members bound to the app do not need a reference, and will be deinitlized whenever they are no longer needed. */ private var members: [String:Resolveable.Type] = [String: Resolveable.Type]() { didSet { #if debug print(members, terminator: "\n") #endif } } public required init() { } public func didResolve(member : Any) { if let proactiveMember = member as? ProactiveResolveable { proactiveMember.didResolve() } //We're going to ensure that all events are registered as soon as the class is resolved. if let eventUser = member as? UsesEvents { eventUser.setEvents() } if let autoresolver = member as? Autoresolves { injectDependencies(autoresolver) } } /* First we will check if the user provided an entityName, if they did, we will use it. Otherwise we will get the name of the class instead. If the object autoresolves, then we will check if a custom entityName is provided as autoresolves do not have a static one, and they might be stored as singletons later with custom keys. */ public func get<O : Resolveable>() -> O? { guard let name = O.entityName else { let name = getDynamicName(String(O)) return self.get(name) as? O } if let auto = O() as? Autoresolveable where auto.customEntityName != "" { return self.get(auto.customEntityName) as? O } return self.get(name) as? O } /* First we will check for a framework bound members because it will be most common Second we we will check singletons */ public func get(key:String)->Resolveable? { if let member = members[key] { let entity = member.init() //The instance method for didResolve will only work with an itialized object self.didResolve(entity) return entity } if let member = singletons.find({$0.dynamicType.entityName == key}) { //Singletons are always initialized self.didResolve(member) return member } else { return nil } } public func has(key:String)-> Bool { return get(key) != nil } public func has(key:Resolveable.Type)-> Bool { if let entityName = key.entityName { return (get(entityName) != nil) } let dynamicName = getDynamicName(String(key.init().dynamicType)) return (get(dynamicName) != nil) } /* This is the "safe" bind method. If the developer makes their class Resolveable, and it has a custom entity name, it would be unlikely for a name collision to occur and for the class not to resolve later on. */ public func bind(key: String,member: Resolveable.Type) { self.members[key] = member if let proactiveMember = member as? ProactiveResolveable { proactiveMember.didBind() } } public func bind(member: Resolveable) { //Now that we have both the type and a reference to the class, //We can initialize it whenever its needed. let entity = member.dynamicType guard let name = member.dynamicType.entityName else { let dynamicName = getDynamicName(String(entity)) self.members[dynamicName] = entity return } self.members[name] = entity //In case the developer wants to listen for the binding of their class if let proactiveMember = member as? ProactiveResolveable { proactiveMember.didBind() } } public func bindSingleton(singleton : Resolveable) { self.singletons.append(singleton) } public func bindIf(condition : () -> Bool, withMember : Resolveable.Type,completion : () -> ()) { if(condition()) { let entity = withMember.init() bind(entity) completion() } } public func register(providers : [ServiceProvider]) { for i in providers { register(i) } } public func getDynamicName(name:String) -> String { return name.capitalizedString.replace(".Type",withString: "") } public func register(provider: ServiceProvider) { for i in provider.provides { if let entityName = i.entityName { members[entityName] = i } else { let name = getDynamicName(String(i.dynamicType)) members[name] = i } } } public func injectDependencies(obj: Autoresolves) { for (key,prop) in obj.dependencies() { if let autoresolvable = obj as? Autoresolveable, resolved = ~key as? NSObject { autoresolvable.setValue(resolved, forKey: prop.label) } } } public func open(any: Any?) -> Any.Type { let mi = Mirror(reflecting: any) if let children = AnyRandomAccessCollection(mi.children) { if mi.children.count == 0 { return NullElement.self } for (_, value) in children { return value.dynamicType } } return mi.subjectType } }
26.76087
214
0.547847
3.046875
ae0ccb9c2a224c5db88bcb48d684384633c2a54e
9,346
rs
Rust
src/clock/traceconfig/mod.rs
braun-embedded/nrf52
c52a2915bfcf57f27a7cf650b77a79bd418679cb
[ "Apache-2.0", "MIT" ]
1
2021-07-06T15:09:06.000Z
2021-07-06T15:09:06.000Z
src/clock/traceconfig/mod.rs
braun-embedded/nrf52
c52a2915bfcf57f27a7cf650b77a79bd418679cb
[ "Apache-2.0", "MIT" ]
null
null
null
src/clock/traceconfig/mod.rs
braun-embedded/nrf52
c52a2915bfcf57f27a7cf650b77a79bd418679cb
[ "Apache-2.0", "MIT" ]
null
null
null
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::TRACECONFIG { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = "Possible values of the field `TRACEPORTSPEED`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TRACEPORTSPEEDR { #[doc = "32 MHz Trace Port clock (TRACECLK = 16 MHz)"] _32MHZ, #[doc = "16 MHz Trace Port clock (TRACECLK = 8 MHz)"] _16MHZ, #[doc = "8 MHz Trace Port clock (TRACECLK = 4 MHz)"] _8MHZ, #[doc = "4 MHz Trace Port clock (TRACECLK = 2 MHz)"] _4MHZ, } impl TRACEPORTSPEEDR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { TRACEPORTSPEEDR::_32MHZ => 0, TRACEPORTSPEEDR::_16MHZ => 1, TRACEPORTSPEEDR::_8MHZ => 2, TRACEPORTSPEEDR::_4MHZ => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> TRACEPORTSPEEDR { match value { 0 => TRACEPORTSPEEDR::_32MHZ, 1 => TRACEPORTSPEEDR::_16MHZ, 2 => TRACEPORTSPEEDR::_8MHZ, 3 => TRACEPORTSPEEDR::_4MHZ, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `_32MHZ`"] #[inline] pub fn is_32mhz(&self) -> bool { *self == TRACEPORTSPEEDR::_32MHZ } #[doc = "Checks if the value of the field is `_16MHZ`"] #[inline] pub fn is_16mhz(&self) -> bool { *self == TRACEPORTSPEEDR::_16MHZ } #[doc = "Checks if the value of the field is `_8MHZ`"] #[inline] pub fn is_8mhz(&self) -> bool { *self == TRACEPORTSPEEDR::_8MHZ } #[doc = "Checks if the value of the field is `_4MHZ`"] #[inline] pub fn is_4mhz(&self) -> bool { *self == TRACEPORTSPEEDR::_4MHZ } } #[doc = "Possible values of the field `TRACEMUX`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TRACEMUXR { #[doc = "GPIOs multiplexed onto all trace-pins"] GPIO, #[doc = "SWO multiplexed onto P0.18, GPIO multiplexed onto other trace pins"] SERIAL, #[doc = "TRACECLK and TRACEDATA multiplexed onto P0.20, P0.18, P0.16, P0.15 and P0.14."] PARALLEL, #[doc = r" Reserved"] _Reserved(u8), } impl TRACEMUXR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { TRACEMUXR::GPIO => 0, TRACEMUXR::SERIAL => 1, TRACEMUXR::PARALLEL => 2, TRACEMUXR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> TRACEMUXR { match value { 0 => TRACEMUXR::GPIO, 1 => TRACEMUXR::SERIAL, 2 => TRACEMUXR::PARALLEL, i => TRACEMUXR::_Reserved(i), } } #[doc = "Checks if the value of the field is `GPIO`"] #[inline] pub fn is_gpio(&self) -> bool { *self == TRACEMUXR::GPIO } #[doc = "Checks if the value of the field is `SERIAL`"] #[inline] pub fn is_serial(&self) -> bool { *self == TRACEMUXR::SERIAL } #[doc = "Checks if the value of the field is `PARALLEL`"] #[inline] pub fn is_parallel(&self) -> bool { *self == TRACEMUXR::PARALLEL } } #[doc = "Values that can be written to the field `TRACEPORTSPEED`"] pub enum TRACEPORTSPEEDW { #[doc = "32 MHz Trace Port clock (TRACECLK = 16 MHz)"] _32MHZ, #[doc = "16 MHz Trace Port clock (TRACECLK = 8 MHz)"] _16MHZ, #[doc = "8 MHz Trace Port clock (TRACECLK = 4 MHz)"] _8MHZ, #[doc = "4 MHz Trace Port clock (TRACECLK = 2 MHz)"] _4MHZ, } impl TRACEPORTSPEEDW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { TRACEPORTSPEEDW::_32MHZ => 0, TRACEPORTSPEEDW::_16MHZ => 1, TRACEPORTSPEEDW::_8MHZ => 2, TRACEPORTSPEEDW::_4MHZ => 3, } } } #[doc = r" Proxy"] pub struct _TRACEPORTSPEEDW<'a> { w: &'a mut W, } impl<'a> _TRACEPORTSPEEDW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TRACEPORTSPEEDW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "32 MHz Trace Port clock (TRACECLK = 16 MHz)"] #[inline] pub fn _32mhz(self) -> &'a mut W { self.variant(TRACEPORTSPEEDW::_32MHZ) } #[doc = "16 MHz Trace Port clock (TRACECLK = 8 MHz)"] #[inline] pub fn _16mhz(self) -> &'a mut W { self.variant(TRACEPORTSPEEDW::_16MHZ) } #[doc = "8 MHz Trace Port clock (TRACECLK = 4 MHz)"] #[inline] pub fn _8mhz(self) -> &'a mut W { self.variant(TRACEPORTSPEEDW::_8MHZ) } #[doc = "4 MHz Trace Port clock (TRACECLK = 2 MHz)"] #[inline] pub fn _4mhz(self) -> &'a mut W { self.variant(TRACEPORTSPEEDW::_4MHZ) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `TRACEMUX`"] pub enum TRACEMUXW { #[doc = "GPIOs multiplexed onto all trace-pins"] GPIO, #[doc = "SWO multiplexed onto P0.18, GPIO multiplexed onto other trace pins"] SERIAL, #[doc = "TRACECLK and TRACEDATA multiplexed onto P0.20, P0.18, P0.16, P0.15 and P0.14."] PARALLEL, } impl TRACEMUXW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { TRACEMUXW::GPIO => 0, TRACEMUXW::SERIAL => 1, TRACEMUXW::PARALLEL => 2, } } } #[doc = r" Proxy"] pub struct _TRACEMUXW<'a> { w: &'a mut W, } impl<'a> _TRACEMUXW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TRACEMUXW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "GPIOs multiplexed onto all trace-pins"] #[inline] pub fn gpio(self) -> &'a mut W { self.variant(TRACEMUXW::GPIO) } #[doc = "SWO multiplexed onto P0.18, GPIO multiplexed onto other trace pins"] #[inline] pub fn serial(self) -> &'a mut W { self.variant(TRACEMUXW::SERIAL) } #[doc = "TRACECLK and TRACEDATA multiplexed onto P0.20, P0.18, P0.16, P0.15 and P0.14."] #[inline] pub fn parallel(self) -> &'a mut W { self.variant(TRACEMUXW::PARALLEL) } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:1 - Speed of Trace Port clock. Note that the TRACECLK pin will output this clock divided by two."] #[inline] pub fn traceportspeed(&self) -> TRACEPORTSPEEDR { TRACEPORTSPEEDR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bits 16:17 - Pin multiplexing of trace signals."] #[inline] pub fn tracemux(&self) -> TRACEMUXR { TRACEMUXR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:1 - Speed of Trace Port clock. Note that the TRACECLK pin will output this clock divided by two."] #[inline] pub fn traceportspeed(&mut self) -> _TRACEPORTSPEEDW { _TRACEPORTSPEEDW { w: self } } #[doc = "Bits 16:17 - Pin multiplexing of trace signals."] #[inline] pub fn tracemux(&mut self) -> _TRACEMUXW { _TRACEMUXW { w: self } } }
29.115265
118
0.542906
3.1875
854717e96a040bdd7f43187d24ad3e371377cac0
4,175
rs
Rust
benches/benchmark.rs
coder543/zapper
d790e21a1fa5fa2c9346edcff0cef450c7cc5ebe
[ "MIT" ]
116
2018-06-26T11:29:13.000Z
2022-01-07T07:53:26.000Z
benches/benchmark.rs
coder543/zap
d790e21a1fa5fa2c9346edcff0cef450c7cc5ebe
[ "MIT" ]
2
2018-06-28T05:28:58.000Z
2018-07-13T07:21:28.000Z
benches/benchmark.rs
coder543/zap
d790e21a1fa5fa2c9346edcff0cef450c7cc5ebe
[ "MIT" ]
2
2018-12-18T11:41:33.000Z
2019-01-30T21:53:19.000Z
extern crate handlebars; #[macro_use] extern crate zapper; #[macro_use] extern crate criterion; use criterion::Criterion; #[macro_use] extern crate serde_derive; extern crate serde_json; use handlebars::{to_json, Handlebars}; use zapper::compile; #[derive(Clone, ZapperRunner, Serialize)] #[filter = "sqrt/0n"] #[filter = "round/1n"] #[filter = "toupper/0s"] struct Person { id: u64, name: String, age: u32, weight: f64, } #[derive(ZapperEnv)] #[runner = "Person"] struct Provider { provider: String, provider_code: u32, } fn sqrt(_data: &Person, _args: &[f64], input: f64) -> f64 { input.sqrt() } fn round(_data: &Person, args: &[f64], input: f64) -> f64 { let digits = args[0]; let factor = 10u32.pow(digits as u32) as f64; let value = (input * factor).round() as f64; value / factor } fn toupper(_data: &Person, _args: &[f64], input: &str, buffer: &mut String) { for c in input.as_bytes() { buffer.push(c.to_ascii_uppercase() as char) } } fn bench_zapper(c: &mut Criterion) { let template = "{{provider}} {{provider_code}} {{id}} {{name}} {{age}} {{weight}}kg\n"; let env = Provider { provider: "apns".to_string(), provider_code: 31, }; let mut bytecode = match compile(template, &env) { Ok(bc) => bc, Err(err) => { eprintln!("error compiling template: {}", err); return; } }; // build up a group of 1000 (similar) people let mut group = vec![]; for i in 0..1000 { group.push(Person { id: 12 + i, name: "Bob".to_string(), age: 49, weight: 170.3 + i as f64, }); } c.bench_function("zapper", move |b| { b.iter(|| { let mut output = Vec::new(); for person in &group { bytecode.render(person, &mut output).unwrap(); } output }) }); } fn bench_zapper_par(c: &mut Criterion) { let template = "{{provider}} {{provider_code}} {{id}} {{name}} {{age}} {{weight}}kg\n"; let env = Provider { provider: "apns".to_string(), provider_code: 31, }; let bytecode = match compile(template, &env) { Ok(bc) => bc, Err(err) => { eprintln!("error compiling template: {}", err); return; } }; // build up a group of 1000 (similar) people let mut group = vec![]; for i in 0..1000 { group.push(Person { id: 12 + i, name: "Bob".to_string(), age: 49, weight: 170.3 + i as f64, }); } c.bench_function("zapper_par", move |b| { b.iter(|| { let mut output = Vec::new(); bytecode.par_render(&group, &mut output, 50).unwrap(); output }) }); } fn bench_hbs(c: &mut Criterion) { use serde_json::value::Map; let template = "{{#each group as |p| ~}}{{provider}} {{provider_code}} {{p.id}} {{p.name}} {{p.age}} {{p.weight}}kg\n{{/each~}}"; let mut handlebars = Handlebars::new(); handlebars .register_template_string("table", template) .unwrap(); let mut group = vec![]; for i in 0..1000 { group.push(Person { id: 12 + i, name: "Bob".to_string(), age: 49, weight: 170.3 + i as f64, }); } let mut data = Map::new(); data.insert("provider".to_string(), to_json(&"apns".to_string())); data.insert("provider_code".to_string(), to_json(&"35".to_string())); c.bench_function("hbs", move |b| { b.iter(|| { let mut data = data.clone(); data.insert("group".to_string(), to_json(&group)); handlebars.render("table", &data).unwrap() }) }); } pub fn benches() { use std::time::Duration; let mut criterion: Criterion = Criterion::default() .configure_from_args() .sample_size(200) .measurement_time(Duration::from_secs(40)); bench_zapper(&mut criterion); bench_zapper_par(&mut criterion); bench_hbs(&mut criterion); } criterion_main!(benches);
25.30303
133
0.540359
3.15625
43c08c473c97d781b926aeca628fbb0ec1d3b504
1,928
go
Go
examples/templates/main.go
robvanbentem/sendinblue
317844f502f77c0822f3fa64b4ab17e9aaba86fc
[ "Apache-2.0" ]
null
null
null
examples/templates/main.go
robvanbentem/sendinblue
317844f502f77c0822f3fa64b4ab17e9aaba86fc
[ "Apache-2.0" ]
null
null
null
examples/templates/main.go
robvanbentem/sendinblue
317844f502f77c0822f3fa64b4ab17e9aaba86fc
[ "Apache-2.0" ]
null
null
null
package main import ( "log" "os" "github.com/JKhawaja/sendinblue" ) func main() { // recommendation: set API key as system environment variable apiKey := os.Getenv("SIB_KEY") // Create SendInBlue Client sibClient, err := sib.NewClient(apiKey) if err != nil { log.Println("Client creation error: ") log.Println(err) os.Exit(1) } /* Create Template */ myTemplate := &sib.Template{ Template_name: "Test Template", Html_content: "Hello World.", Subject: "Test Template Email", From_email: "[email protected]", // SENDER EMAIL HERE Status: 1, // activate template } createResponse, err := sibClient.CreateTemplate(myTemplate) if err != nil { log.Println("Create template error: ") log.Println(err) os.Exit(1) } log.Println(createResponse.Code) log.Println(createResponse.Message) /* Send Template Email */ templateID := createResponse.Data.ID userList := []string{"[email protected]", "[email protected]", "[email protected]"} // RECEIVER EMAILS HERE sendResponse, err := sibClient.SendTemplateEmail(templateID, userList, nil) if err != nil { log.Println("Send template email error: ") log.Println(err) os.Exit(1) } log.Println(sendResponse.Code) log.Println(sendResponse.Message) /* Update Template */ udpateTemplate := &sib.Template{ Template_name: "Test Template", Html_content: "Hello World. UPDATED!", Subject: "Test Template Email", From_email: "[email protected]", // SENDER EMAIL HERE Status: 1, } err = sibClient.UpdateTemplate(templateID, udpateTemplate) if err != nil { log.Println("Update template error: ") log.Println(err) os.Exit(1) } log.Println("Update Template: successful") /* Get Template */ getResponse, err := sibClient.GetTemplate(templateID) if err != nil { log.Println("Get template error: ") log.Println(err) os.Exit(1) } log.Println(getResponse) }
22.952381
108
0.679461
3.21875
0b8210f4f1d6486c1ca027ea81ba3795882b8a8f
3,433
py
Python
tests/python/benchmarks/two_neighborhood_bench.py
sid17/weaver
f9074397ca854a777a873eaf409621de679f9749
[ "BSD-3-Clause" ]
163
2015-01-02T03:51:38.000Z
2022-03-21T23:06:39.000Z
tests/python/benchmarks/two_neighborhood_bench.py
sid17/weaver
f9074397ca854a777a873eaf409621de679f9749
[ "BSD-3-Clause" ]
1
2015-04-08T23:17:06.000Z
2015-04-24T15:25:26.000Z
tests/python/benchmarks/two_neighborhood_bench.py
sid17/weaver
f9074397ca854a777a873eaf409621de679f9749
[ "BSD-3-Clause" ]
20
2015-02-17T19:24:05.000Z
2020-10-29T01:59:18.000Z
#! /usr/bin/env python # # =============================================================== # Description: Two neighborhood benchmark # # Created: 2014-03-21 13:39:06 # # Author: Ayush Dubey, [email protected] # # Copyright (C) 2013-2014, Cornell University, see the LICENSE # file for licensing agreement # =============================================================== # import random import sys import time import threading import weaver.client as client import simple_client random.seed(42) num_edges = 1768149 edge_sources = [None] * num_edges def choose_random_pair(): global edge_sources return (edge_sources[random.randint(0, num_edges-1)], edge_sources[random.randint(0, num_edges-1)]) if (len(sys.argv) != 2): print "want single extra arg for file to open" assert(False) f = open(sys.argv[1]) i = 0 for line in f: if (line[0] is '#'): continue edge_sources[i] = int(line.split(" ")[0]) i += 1 print "done loading file" num_started = 0 num_finished = 0 cv = threading.Condition() num_nodes = 81306 # snap twitter-combined read_percent = 95 # node handles are range(0, num_nodes) num_vts = 1 num_clients = 100 requests_per_client = 200 def add_labels(c, idx): global num_nodes tx_id = c.begin_tx() for i in range(num_nodes): if i % num_clients is idx: c.set_node_property(tx_id, i, 'name', str(i)) assert(c.end_tx(tx_id)) print "writing labels finished for client " + str(idx) def exec_reads(reqs, sc, c, exec_time, idx): global num_started global cv global num_clients global num_finished with cv: while num_started < num_clients: cv.wait() start = time.time() cnt = 0 for pair in reqs: cnt += 1 if (random.randint(1,100) > read_percent) : tx_id = c.begin_tx() c.create_edge(tx_id, pair[0], pair[1]) assert(c.end_tx(tx_id)) else: two_neighborhood = sc.two_neighborhood(pair[0], "name", caching = True) end = time.time() with cv: num_finished += 1 cv.notify_all() exec_time[idx] = end - start clients = [] simple_clients = [] for i in range(num_clients): clients.append(client.Client(client._CLIENT_ID + i, i % num_vts)) simple_clients.append(simple_client.simple_client(clients[i])) reqs = [] for i in range(num_clients): cl_reqs = [] for _ in range(requests_per_client): cl_reqs.append(choose_random_pair()) reqs.append(cl_reqs) exec_time = [0] * num_clients threads = [] print "starting writes" for i in range(num_clients): thr = threading.Thread(target=add_labels, args=(clients[i], i)) thr.start() threads.append(thr) for thr in threads: thr.join() print "starting requests" for i in range(num_clients): thr = threading.Thread(target=exec_reads, args=(reqs[i], simple_clients[i], clients[i], exec_time, i)) thr.start() threads.append(thr) start_time = time.time() with cv: num_started = num_clients cv.notify_all() while num_finished < num_clients: cv.wait() end_time = time.time() total_time = end_time-start_time for thr in threads: thr.join() print 'Total time for ' + str(num_clients * requests_per_client) + 'requests = ' + str(total_time) throughput = (num_clients * requests_per_client) / total_time print 'Throughput = ' + str(throughput)
26.206107
106
0.633265
3.359375
b53930e00b8e30d1a30458d8ec17684e16e3dbf7
1,507
rs
Rust
cross-checks/rust-checks/backends/fakechecks-zstd/src/bin/printer.rs
sjvs/c2rust
0eb7359b35f9159c446074748d9dbd09fb212ce9
[ "BSD-3-Clause" ]
null
null
null
cross-checks/rust-checks/backends/fakechecks-zstd/src/bin/printer.rs
sjvs/c2rust
0eb7359b35f9159c446074748d9dbd09fb212ce9
[ "BSD-3-Clause" ]
null
null
null
cross-checks/rust-checks/backends/fakechecks-zstd/src/bin/printer.rs
sjvs/c2rust
0eb7359b35f9159c446074748d9dbd09fb212ce9
[ "BSD-3-Clause" ]
null
null
null
#![feature(int_to_from_bytes)] extern crate zstd; use std::fmt; use std::fs::File; use std::io; use std::io::{Read, Write}; use std::env; const BUF_SIZE: usize = 4 * 1024 * 1024; // 4MB buffer const MAX_XCHECK_LEN: usize = 52; pub fn main() -> Result<(), std::io::Error> { let mut out = String::with_capacity(BUF_SIZE); for arg in env::args() { let file = File::open(arg)?; let mut reader = zstd::stream::Decoder::new(file)?; loop { let mut buf = [0u8; 9]; if reader.read_exact(&mut buf).is_err() { break; } let mut val_buf = [0u8; 8]; val_buf.copy_from_slice(&buf[1..]); let val = u64::from_le(u64::from_bytes(val_buf)); if out.len() >= BUF_SIZE - MAX_XCHECK_LEN { io::stdout().write_all(out.as_bytes())?; out.clear(); } let old_len = out.len(); let tag_name = match buf[0] { 0 => "Unk", 1 => "Ent", 2 => "Exi", 3 => "Arg", 4 => "Ret", _ => panic!("Unknown cross-check tag: {}", buf[0]) }; fmt::write(&mut out, format_args!("XCHECK({0}):{1:}/0x{1:08x}\n", tag_name, val)) .expect("Error formatting xcheck"); assert!(out.len() <= old_len + MAX_XCHECK_LEN); } } // Flush the buffer io::stdout().write_all(out.as_bytes())?; Ok(()) }
30.755102
93
0.480425
3.09375
7702543adac5ec672ebee6edafcfa2a0bad395e9
2,991
rs
Rust
src/day_04_password.rs
lucis-fluxum/advent-of-code
9b69119ae875525423076369ae8b4b8a578ef43e
[ "MIT" ]
null
null
null
src/day_04_password.rs
lucis-fluxum/advent-of-code
9b69119ae875525423076369ae8b4b8a578ef43e
[ "MIT" ]
null
null
null
src/day_04_password.rs
lucis-fluxum/advent-of-code
9b69119ae875525423076369ae8b4b8a578ef43e
[ "MIT" ]
null
null
null
use std::fs::read_to_string; use itertools::Itertools; use rayon::prelude::*; fn get_input() -> Vec<u32> { let contents = read_to_string("src/day_04_password/input.txt").unwrap(); let bounds: Vec<&str> = contents.trim().split('-').collect(); let lower_bound = bounds[0].parse::<u32>().unwrap(); let upper_bound = bounds[1].parse::<u32>().unwrap(); (lower_bound..upper_bound).collect() } fn get_digits(num: u32) -> Vec<u32> { num.to_string() .chars() .map(|c| c.to_digit(10).unwrap()) .collect() } fn is_possible_password(candidate: u32) -> bool { let mut adjacent_digit_condition = false; let mut non_decreasing_condition = true; for (a, b) in get_digits(candidate).into_iter().tuple_windows() { if a == b { adjacent_digit_condition = true; } else if a > b { non_decreasing_condition = false; break; } } adjacent_digit_condition && non_decreasing_condition } fn is_possible_password_no_triples(candidate: u32) -> bool { let mut valid_pair_exists = false; let mut iterator = get_digits(candidate).into_iter(); // Have to find at least one isolated pair let mut current_num = iterator.next().unwrap(); let mut current_freq = 1; for n in iterator { if n == current_num { current_freq += 1; } else if current_freq == 2 { // We have an isolated pair! valid_pair_exists = true; break; } else { current_num = n; current_freq = 1; } } // Check if the last two elements formed a pair if current_freq == 2 { valid_pair_exists = true; } is_possible_password(candidate) && valid_pair_exists } pub fn find_num_possible_passwords() -> usize { let candidates: Vec<u32> = get_input() .into_par_iter() .filter(|&p| is_possible_password(p)) .collect(); candidates.len() } pub fn find_num_possible_passwords_no_triples() -> usize { let candidates: Vec<u32> = get_input() .into_par_iter() .filter(|&p| is_possible_password_no_triples(p)) .collect(); candidates.len() } #[cfg(test)] mod tests { use crate::day_04_password::{ find_num_possible_passwords, find_num_possible_passwords_no_triples, is_possible_password, is_possible_password_no_triples, }; #[test] fn example_passwords() { assert!(is_possible_password(111111)); assert!(!is_possible_password(223450)); assert!(!is_possible_password(123789)); assert!(is_possible_password_no_triples(112233)); assert!(!is_possible_password_no_triples(123444)); assert!(is_possible_password_no_triples(111122)); } #[test] fn part_1_valid() { assert_eq!(find_num_possible_passwords(), 921); } #[test] fn part_2_valid() { assert_eq!(find_num_possible_passwords_no_triples(), 603); } }
28.216981
98
0.626881
3.34375
d9296165627e20e922d4f63833ab99afa8f2dc0e
13,635
rs
Rust
tests/guard.rs
TotalKrill/rocket_cors
bf4f91abec0e3fb38b78cf57b93c657071384135
[ "Apache-2.0", "MIT" ]
null
null
null
tests/guard.rs
TotalKrill/rocket_cors
bf4f91abec0e3fb38b78cf57b93c657071384135
[ "Apache-2.0", "MIT" ]
null
null
null
tests/guard.rs
TotalKrill/rocket_cors
bf4f91abec0e3fb38b78cf57b93c657071384135
[ "Apache-2.0", "MIT" ]
1
2020-08-29T14:47:53.000Z
2020-08-29T14:47:53.000Z
//! This crate tests using `rocket_cors` using the per-route handling with request guard #![feature(proc_macro_hygiene, decl_macro)] use hyper; use rocket_cors as cors; use std::str::FromStr; use rocket::http::Method; use rocket::http::{Header, Status}; use rocket::local::Client; use rocket::response::Body; use rocket::{get, options, routes}; use rocket::{Response, State}; #[get("/")] fn cors(cors: cors::Guard<'_>) -> cors::Responder<'_, &str> { cors.responder("Hello CORS") } #[get("/panic")] fn panicking_route(_cors: cors::Guard<'_>) { panic!("This route will panic"); } /// Manually specify our own OPTIONS route #[options("/manual")] fn cors_manual_options(cors: cors::Guard<'_>) -> cors::Responder<'_, &str> { cors.responder("Manual CORS Preflight") } /// Manually specify our own OPTIONS route #[get("/manual")] fn cors_manual(cors: cors::Guard<'_>) -> cors::Responder<'_, &str> { cors.responder("Hello CORS") } /// Using a `Response` instead of a `Responder` #[get("/response")] fn response(cors: cors::Guard<'_>) -> Response<'_> { cors.response(Response::new()) } /// `Responder` with String #[get("/responder/string")] fn responder_string(cors: cors::Guard<'_>) -> cors::Responder<'_, String> { cors.responder("Hello CORS".to_string()) } /// `Responder` with 'static () #[get("/responder/unit")] fn responder_unit(cors: cors::Guard<'_>) -> cors::Responder<'_, ()> { cors.responder(()) } struct SomeState; /// Borrow `SomeState` from Rocket #[get("/state")] fn state<'r>(cors: cors::Guard<'r>, _state: State<'r, SomeState>) -> cors::Responder<'r, &'r str> { cors.responder("hmm") } fn make_cors() -> cors::Cors { let allowed_origins = cors::AllowedOrigins::some_exact(&["https://www.acme.com"]); cors::CorsOptions { allowed_origins, allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(), allowed_headers: cors::AllowedHeaders::some(&["Authorization", "Accept"]), allow_credentials: true, ..Default::default() } .to_cors() .expect("To not fail") } fn make_rocket() -> rocket::Rocket { rocket::ignite() .mount("/", routes![cors, panicking_route]) .mount( "/", routes![response, responder_string, responder_unit, state], ) .mount("/", cors::catch_all_options_routes()) // mount the catch all routes .mount("/", routes![cors_manual, cors_manual_options]) // manual OPTIOONS routes .manage(make_cors()) .manage(SomeState) } #[test] fn smoke_test() { let rocket = make_rocket(); let client = Client::new(rocket).unwrap(); // `Options` pre-flight checks let origin_header = Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap()); let method_header = Header::from(hyper::header::AccessControlRequestMethod( hyper::method::Method::Get, )); let request_headers = hyper::header::AccessControlRequestHeaders(vec![ FromStr::from_str("Authorization").unwrap() ]); let request_headers = Header::from(request_headers); let req = client .options("/") .header(origin_header) .header(method_header) .header(request_headers); let response = req.dispatch(); assert!(response.status().class().is_success()); // "Actual" request let origin_header = Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap()); let authorization = Header::new("Authorization", "let me in"); let req = client.get("/").header(origin_header).header(authorization); let mut response = req.dispatch(); assert!(response.status().class().is_success()); let body_str = response.body().and_then(Body::into_string); assert_eq!(body_str, Some("Hello CORS".to_string())); let origin_header = response .headers() .get_one("Access-Control-Allow-Origin") .expect("to exist"); assert_eq!("https://www.acme.com", origin_header); } /// Check the "catch all" OPTIONS route works for `/` #[test] fn cors_options_catch_all_check() { let rocket = make_rocket(); let client = Client::new(rocket).unwrap(); let origin_header = Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap()); let method_header = Header::from(hyper::header::AccessControlRequestMethod( hyper::method::Method::Get, )); let request_headers = hyper::header::AccessControlRequestHeaders(vec![ FromStr::from_str("Authorization").unwrap() ]); let request_headers = Header::from(request_headers); let req = client .options("/") .header(origin_header) .header(method_header) .header(request_headers); let response = req.dispatch(); assert!(response.status().class().is_success()); let origin_header = response .headers() .get_one("Access-Control-Allow-Origin") .expect("to exist"); assert_eq!("https://www.acme.com", origin_header); } /// Check the "catch all" OPTIONS route works for other routes #[test] fn cors_options_catch_all_check_other_routes() { let rocket = make_rocket(); let client = Client::new(rocket).unwrap(); let origin_header = Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap()); let method_header = Header::from(hyper::header::AccessControlRequestMethod( hyper::method::Method::Get, )); let request_headers = hyper::header::AccessControlRequestHeaders(vec![ FromStr::from_str("Authorization").unwrap() ]); let request_headers = Header::from(request_headers); let req = client .options("/response/unit") .header(origin_header) .header(method_header) .header(request_headers); let response = req.dispatch(); assert!(response.status().class().is_success()); let origin_header = response .headers() .get_one("Access-Control-Allow-Origin") .expect("to exist"); assert_eq!("https://www.acme.com", origin_header); } #[test] fn cors_get_check() { let rocket = make_rocket(); let client = Client::new(rocket).unwrap(); let origin_header = Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap()); let authorization = Header::new("Authorization", "let me in"); let req = client.get("/").header(origin_header).header(authorization); let mut response = req.dispatch(); assert!(response.status().class().is_success()); let body_str = response.body().and_then(Body::into_string); assert_eq!(body_str, Some("Hello CORS".to_string())); let origin_header = response .headers() .get_one("Access-Control-Allow-Origin") .expect("to exist"); assert_eq!("https://www.acme.com", origin_header); } /// This test is to check that non CORS compliant requests to GET should still work. (i.e. curl) #[test] fn cors_get_no_origin() { let rocket = make_rocket(); let client = Client::new(rocket).unwrap(); let authorization = Header::new("Authorization", "let me in"); let req = client.get("/").header(authorization); let mut response = req.dispatch(); assert!(response.status().class().is_success()); let body_str = response.body().and_then(Body::into_string); assert_eq!(body_str, Some("Hello CORS".to_string())); assert!(response .headers() .get_one("Access-Control-Allow-Origin") .is_none()); } #[test] fn cors_options_bad_origin() { let rocket = make_rocket(); let client = Client::new(rocket).unwrap(); let origin_header = Header::from(hyper::header::Origin::from_str("https://www.bad-origin.com").unwrap()); let method_header = Header::from(hyper::header::AccessControlRequestMethod( hyper::method::Method::Get, )); let request_headers = hyper::header::AccessControlRequestHeaders(vec![ FromStr::from_str("Authorization").unwrap() ]); let request_headers = Header::from(request_headers); let req = client .options("/") .header(origin_header) .header(method_header) .header(request_headers); let response = req.dispatch(); assert_eq!(response.status(), Status::Forbidden); assert!(response .headers() .get_one("Access-Control-Allow-Origin") .is_none()); } #[test] fn cors_options_missing_origin() { let rocket = make_rocket(); let client = Client::new(rocket).unwrap(); let method_header = Header::from(hyper::header::AccessControlRequestMethod( hyper::method::Method::Get, )); let request_headers = hyper::header::AccessControlRequestHeaders(vec![ FromStr::from_str("Authorization").unwrap() ]); let request_headers = Header::from(request_headers); let req = client .options("/") .header(method_header) .header(request_headers); let response = req.dispatch(); assert!(response.status().class().is_success()); assert!(response .headers() .get_one("Access-Control-Allow-Origin") .is_none()); } #[test] fn cors_options_bad_request_method() { let rocket = make_rocket(); let client = Client::new(rocket).unwrap(); let origin_header = Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap()); let method_header = Header::from(hyper::header::AccessControlRequestMethod( hyper::method::Method::Post, )); let request_headers = hyper::header::AccessControlRequestHeaders(vec![ FromStr::from_str("Authorization").unwrap() ]); let request_headers = Header::from(request_headers); let req = client .options("/") .header(origin_header) .header(method_header) .header(request_headers); let response = req.dispatch(); assert_eq!(response.status(), Status::Forbidden); assert!(response .headers() .get_one("Access-Control-Allow-Origin") .is_none()); } #[test] fn cors_options_bad_request_header() { let rocket = make_rocket(); let client = Client::new(rocket).unwrap(); let origin_header = Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap()); let method_header = Header::from(hyper::header::AccessControlRequestMethod( hyper::method::Method::Get, )); let request_headers = hyper::header::AccessControlRequestHeaders(vec![FromStr::from_str("Foobar").unwrap()]); let request_headers = Header::from(request_headers); let req = client .options("/") .header(origin_header) .header(method_header) .header(request_headers); let response = req.dispatch(); assert_eq!(response.status(), Status::Forbidden); assert!(response .headers() .get_one("Access-Control-Allow-Origin") .is_none()); } #[test] fn cors_get_bad_origin() { let rocket = make_rocket(); let client = Client::new(rocket).unwrap(); let origin_header = Header::from(hyper::header::Origin::from_str("https://www.bad-origin.com").unwrap()); let authorization = Header::new("Authorization", "let me in"); let req = client.get("/").header(origin_header).header(authorization); let response = req.dispatch(); assert_eq!(response.status(), Status::Forbidden); assert!(response .headers() .get_one("Access-Control-Allow-Origin") .is_none()); } /// This test ensures that on a failing CORS request, the route (along with its side effects) /// should never be executed. /// The route used will panic if executed #[test] fn routes_failing_checks_are_not_executed() { let rocket = make_rocket(); let client = Client::new(rocket).unwrap(); let origin_header = Header::from(hyper::header::Origin::from_str("https://www.bad-origin.com").unwrap()); let authorization = Header::new("Authorization", "let me in"); let req = client.get("/").header(origin_header).header(authorization); let response = req.dispatch(); assert_eq!(response.status(), Status::Forbidden); assert!(response .headers() .get_one("Access-Control-Allow-Origin") .is_none()); } /// This test ensures that manually mounted CORS OPTIONS routes are used even in the presence of /// a "catch all" route. #[test] fn overridden_options_routes_are_used() { let rocket = make_rocket(); let client = Client::new(rocket).unwrap(); let origin_header = Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap()); let method_header = Header::from(hyper::header::AccessControlRequestMethod( hyper::method::Method::Get, )); let request_headers = hyper::header::AccessControlRequestHeaders(vec![ FromStr::from_str("Authorization").unwrap() ]); let request_headers = Header::from(request_headers); let req = client .options("/manual") .header(origin_header) .header(method_header) .header(request_headers); let mut response = req.dispatch(); let body_str = response.body().and_then(Body::into_string); assert!(response.status().class().is_success()); assert_eq!(body_str, Some("Manual CORS Preflight".to_string())); let origin_header = response .headers() .get_one("Access-Control-Allow-Origin") .expect("to exist"); assert_eq!("https://www.acme.com", origin_header); }
32.387173
99
0.641878
3.03125
afeb0c820e9ecdade109cddffa659a1c404e6e73
5,010
rb
Ruby
examples/rlgl_compute_shader.rb
vaiorabbit/raylib-bindings
36396b932e3444ab03f242e400ed77cc2c4dfcd4
[ "Zlib" ]
1
2022-01-16T07:16:16.000Z
2022-01-16T07:16:16.000Z
examples/rlgl_compute_shader.rb
vaiorabbit/raylib-bindings
36396b932e3444ab03f242e400ed77cc2c4dfcd4
[ "Zlib" ]
2
2022-01-14T07:48:18.000Z
2022-01-20T21:08:33.000Z
examples/rlgl_compute_shader.rb
vaiorabbit/raylib-bindings
36396b932e3444ab03f242e400ed77cc2c4dfcd4
[ "Zlib" ]
null
null
null
require_relative 'util/setup_dll' require_relative 'util/resource_path' # [NOTE] This sample requires: # - Windows OS # - OpenGL 4.3 capable GPU # - libraylib.dll built with 'GRAPHICS=GRAPHICS_API_OPENGL_43' if __FILE__ == $PROGRAM_NAME # IMPORTANT: This must match gol*.glsl GOL_WIDTH constant. # This must be a multiple of 16 (check golLogic compute dispatch). GOL_WIDTH = 768 # Maximum amount of queued draw commands (squares draw from mouse down events). MAX_BUFFERED_TRANSFERTS = 48 # Game Of Life Update Command class GolUpdateCmd < FFI::Struct layout( :x, :uint, # x coordinate of the gol command :y, :uint, # y coordinate of the gol command :w, :uint, # width of the filled zone :enabled, :uint, # whether to enable or disable zone ) end # Game Of Life Update Commands SSBO class GolUpdateSSBO < FFI::Struct layout( :count, :uint, :commands, [GolUpdateCmd, MAX_BUFFERED_TRANSFERTS], ) end InitWindow(GOL_WIDTH, GOL_WIDTH, "Yet Another Ruby-raylib bindings - compute shader - game of life") resolution = Vector2.create(GOL_WIDTH, GOL_WIDTH) brushSize = 8 # Game of Life logic compute shader golLogicCode = LoadFileText(RAYLIB_OTHERS_PATH + "resources/shaders/glsl430/gol.glsl") golLogicShader = rlCompileShader(golLogicCode, RL_COMPUTE_SHADER) golLogicProgram = rlLoadComputeShaderProgram(golLogicShader) UnloadFileText(golLogicCode) # Game of Life logic compute shader golRenderShader = LoadShader(nil, RAYLIB_OTHERS_PATH + "resources/shaders/glsl430/gol_render.glsl") resUniformLoc = GetShaderLocation(golRenderShader, "resolution") # Game of Life transfert shader golTransfertCode = LoadFileText( RAYLIB_OTHERS_PATH + "resources/shaders/glsl430/gol_transfert.glsl") golTransfertShader = rlCompileShader(golTransfertCode, RL_COMPUTE_SHADER) golTransfertProgram = rlLoadComputeShaderProgram(golTransfertShader) UnloadFileText(golTransfertCode) # SSBOs ssboA = rlLoadShaderBuffer(GOL_WIDTH*GOL_WIDTH*FFI::type_size(:uint), nil, RL_DYNAMIC_COPY) ssboB = rlLoadShaderBuffer(GOL_WIDTH*GOL_WIDTH*FFI::type_size(:uint), nil, RL_DYNAMIC_COPY) transfertBuffer = GolUpdateSSBO.new transfertBuffer[:count] = 0 transfertSSBO = rlLoadShaderBuffer(GolUpdateSSBO.size, nil, RL_DYNAMIC_COPY) # Create a white texture of the size of the window to update # each pixel of the window using the fragment shader whiteImage = GenImageColor(GOL_WIDTH, GOL_WIDTH, WHITE) whiteTex = LoadTextureFromImage(whiteImage) UnloadImage(whiteImage) until WindowShouldClose() brushSize += GetMouseWheelMove().to_f if (IsMouseButtonDown(MOUSE_BUTTON_LEFT) || IsMouseButtonDown(MOUSE_BUTTON_RIGHT)) && (transfertBuffer[:count] < MAX_BUFFERED_TRANSFERTS) # Buffer a new command transfertBuffer[:commands][transfertBuffer[:count]][:x] = GetMouseX() - brushSize/2 transfertBuffer[:commands][transfertBuffer[:count]][:y] = GetMouseY() - brushSize/2 transfertBuffer[:commands][transfertBuffer[:count]][:w] = brushSize transfertBuffer[:commands][transfertBuffer[:count]][:enabled] = IsMouseButtonDown(MOUSE_BUTTON_LEFT) ? 1 : 0 transfertBuffer[:count] += 1 elsif transfertBuffer[:count] > 0 # Process transfert buffer # Send SSBO buffer to GPU rlUpdateShaderBufferElements(transfertSSBO, transfertBuffer, GolUpdateSSBO.size, 0) # Process ssbo command rlEnableShader(golTransfertProgram) rlBindShaderBuffer(ssboA, 1) rlBindShaderBuffer(transfertSSBO, 3) rlComputeShaderDispatch(transfertBuffer[:count], 1, 1) # each GPU unit will process a command rlDisableShader() transfertBuffer[:count] = 0 else # elsif IsKeyDown(KEY_SPACE) # Process game of life logic rlEnableShader(golLogicProgram) rlBindShaderBuffer(ssboA, 1) rlBindShaderBuffer(ssboB, 2) rlComputeShaderDispatch(GOL_WIDTH/16, GOL_WIDTH/16, 1) rlDisableShader() # ssboA <-> ssboB ssboA, ssboB = ssboB, ssboA end rlBindShaderBuffer(ssboA, 1) SetShaderValue(golRenderShader, resUniformLoc, resolution, SHADER_UNIFORM_VEC2) BeginDrawing() ClearBackground(BLANK) BeginShaderMode(golRenderShader) DrawTexture(whiteTex, 0, 0, WHITE) EndShaderMode() DrawRectangleLines(GetMouseX() - brushSize/2, GetMouseY() - brushSize/2, brushSize, brushSize, RED) DrawText("Use Mouse wheel to increase/decrease brush size", 10, 10, 20, WHITE) DrawFPS(GetScreenWidth() - 100, 10) EndDrawing() end # Unload shader buffers objects. rlUnloadShaderBuffer(ssboA) rlUnloadShaderBuffer(ssboB) rlUnloadShaderBuffer(transfertSSBO) # Unload compute shader programs rlUnloadShaderProgram(golTransfertProgram) rlUnloadShaderProgram(golLogicProgram) UnloadTexture(whiteTex) # Unload white texture UnloadShader(golRenderShader) # Unload rendering fragment shader CloseWindow() end
35.034965
141
0.737126
3.234375
c3629ad070876a3613e0f791655cf8212e27f6ce
1,508
go
Go
tracker.go
die-net/dhtproxy
0e13123cfdd963f0e6121401d1d00de24efbdaed
[ "Apache-2.0" ]
14
2016-06-01T03:08:00.000Z
2021-03-16T06:46:48.000Z
tracker.go
die-net/dhtproxy
0e13123cfdd963f0e6121401d1d00de24efbdaed
[ "Apache-2.0" ]
3
2016-11-17T13:28:13.000Z
2021-09-07T16:35:53.000Z
tracker.go
die-net/dhtproxy
0e13123cfdd963f0e6121401d1d00de24efbdaed
[ "Apache-2.0" ]
6
2017-02-13T20:21:22.000Z
2021-09-20T06:36:37.000Z
package main import ( "net/http" "strings" "time" bencode "github.com/jackpal/bencode-go" "github.com/nictuku/dht" ) type TrackerResponse struct { Interval int64 "interval" //nolint:govet // Bencode-go uses non-comformant struct tags MinInterval int64 "min interval" //nolint:govet // Bencode-go uses non-comformant struct tags Complete int "complete" //nolint:govet // Bencode-go uses non-comformant struct tags Incomplete int "incomplete" //nolint:govet // Bencode-go uses non-comformant struct tags Peers string "peers" //nolint:govet // Bencode-go uses non-comformant struct tags } func trackerHandler(w http.ResponseWriter, r *http.Request) { if r.FormValue("compact") != "1" { http.Error(w, "Only compact protocol supported.", 400) return } infoHash := dht.InfoHash(r.FormValue("info_hash")) if len(infoHash) != 20 { http.Error(w, "Bad info_hash.", 400) return } response := TrackerResponse{ Interval: 300, MinInterval: 60, } peers, ok := peerCache.Get(string(infoHash)) dhtNode.Find(infoHash) if !ok || len(peers) == 0 { response.Interval = 30 response.MinInterval = 10 time.Sleep(5 * time.Second) peers, ok = peerCache.Get(string(infoHash)) } if ok && len(peers) > 0 { response.Incomplete = len(peers) response.Peers = strings.Join(peers, "") } w.Header().Set("Content-Type", "application/octet-stream") if err := bencode.Marshal(w, response); err != nil { http.Error(w, err.Error(), 500) } }
24.721311
95
0.677719
3.078125
b99351bfeeb42e8d1436c3da5d04cfcea700438c
3,216
h
C
ivan_original/include/find_oc_adapt.h
stevenglasford/Seminar_NDSU_2020
3bc778185ac40a92913c091e2e717434cbf17b31
[ "Apache-2.0" ]
null
null
null
ivan_original/include/find_oc_adapt.h
stevenglasford/Seminar_NDSU_2020
3bc778185ac40a92913c091e2e717434cbf17b31
[ "Apache-2.0" ]
null
null
null
ivan_original/include/find_oc_adapt.h
stevenglasford/Seminar_NDSU_2020
3bc778185ac40a92913c091e2e717434cbf17b31
[ "Apache-2.0" ]
null
null
null
/* * Fichier utilisateur associe a la fonction de calcul de la trajectoire optimale avec un pas adaptatif * * Ce fichier contient deux fonctions : * -une implementation de la fontion de recherche de contrôle optimal, find_optimal_control_adapt() * -une adaptation de l'integrateur de Heun pour plusieurs pas */ /*! * * \brief fonction de recherche du controle optimal * * @param[in] y : l'état en cours * @param[in] h : pas de progression unitaire * @param[in] t : temps en cours * @param[out] val: la valeur optimale trouvée * @param[in] nbSteps : nombre de pas unitaires utilisé pour l'intégration à partir de y avec un contrôle donné * @param[in] vtab : la fonction valeur utilisée pour le calcul de la valeur optimale * @return le numéro du contrôle optimal trouvé */ int HJB::find_optimal_control_adapt(const double* y, double h, double t, double& val, int nbSteps, double *vtab) { double val_star,vect[ncall]; bool inTheBounds; int c; int u_star; double rc; double dvect[dim]; double currentVal; //int dimc=u->dimC; val_star=INF; u_star=-1; for(c=0;c<ncall;c++) { /* * pour tous les controles possibles * calcul de la positions suivante correspondante avec RK2 */ heunIntegrator(y, nbSteps, c, t, h, dvect, &inTheBounds); rc = (!inTheBounds) ? INF : (*this.*interpolation)(dvect,topt); if(rc<=2.0*T) vect[c]=rc; else vect[c]=INF; } for(c=0;c<ncall;c++) { if(vect[c]<INF) { currentVal=vect[c]; if(currentVal<val_star) { val_star=currentVal; u_star=c; } } } val=val_star; return(u_star); } /*! * * \brief Cette fonction réalise le calcul d'une intégration de numérique de Heune sur un nombre donné de pas * * @param[in] yInit : l'état de début * @param[in] h : pas de progression unitaire * @param[in] tau : temps initial * @param[out] inTheBounds: indicateur booléen de non dépassement des limites du domaine de calcul * @param[in] nbSteps : nombre de pas unitaires utilisé pour l'intégration à partir de yInit avec un contrôle donné * @param[in] c : le numéro du contrôle à appliquer le long de tout le chemin * @param[out] res: l'état final (successeur de yInit pour le contrôle c ) * */ void HJB::heunIntegrator(const double* yInit,int nbSteps, int c, double tau, double h, double *res, bool *inTheBounds) { double ff2[dim], ff[dim],y[dim]; // tableaux pour le stockage temporaire des images intermediaires calculees // pour le schema de Heun int d; double tt=tau; // temps en cours pour le chemin a calculer int k=0; *inTheBounds=true; for(d=0;d<dim;d++) y[d]=yInit[d]; while ((k<nbSteps )& (*inTheBounds)) { (*dynamics)(y,(*u)[c],tt,ff2); for(d=0;d<dim;d++) res[d]=y[d]+h*ff2[d]; (*dynamics)(res,(*u)[c],tt+h,ff); for(d=0;d<dim;d++) { res[d]=y[d]+0.5*h*(ff[d]+ff2[d]); y[d]=res[d]; } if(periodic_mesh) periodizePoint(res); for(d=0; d<dim; d++) { if(res[d]< mesh->lowBounds[d] || res[d]>mesh->highBounds[d]) { (*inTheBounds)=false; break; } } k++; tt+=h; } }
24.363636
118
0.631219
3.140625
7c943ad6482de1cb87596eab0a46b4b0d669bea5
3,738
rs
Rust
src/main.rs
RottenFishbone/wpm
8f5668fef0bff4be15ad19606ce68b728823dbaa
[ "MIT" ]
null
null
null
src/main.rs
RottenFishbone/wpm
8f5668fef0bff4be15ad19606ce68b728823dbaa
[ "MIT" ]
2
2022-01-18T23:57:03.000Z
2022-03-02T02:21:41.000Z
src/main.rs
RottenFishbone/wpm
8f5668fef0bff4be15ad19606ce68b728823dbaa
[ "MIT" ]
null
null
null
#![allow(dead_code)] #![allow(unused_imports)] mod app; use app::{UIEvent, Controller}; use std::{ error::Error, io::{ Write, stdout }, panic::{self, PanicInfo}, sync::mpsc::Sender, thread, time:: { Duration, SystemTime }, }; use crossterm::{ event::{ self, DisableMouseCapture, KeyModifiers, EnableMouseCapture, Event, KeyCode }, terminal::{ EnterAlternateScreen, LeaveAlternateScreen, enable_raw_mode, disable_raw_mode}, execute, }; use tui::{Terminal, backend::CrosstermBackend}; type Result<T> = std::result::Result<T, UIError>; type CrossTerminal = Terminal<CrosstermBackend<std::io::Stdout>>; #[derive(Debug)] enum UIError {} fn main() { panic::set_hook(Box::new(|info|{ panic_hook(info); })); enable_raw_mode().unwrap(); let mut stdout = stdout(); execute!(stdout, EnterAlternateScreen, EnableMouseCapture).unwrap(); let backend = CrosstermBackend::new(stdout); let mut terminal = Terminal::new(backend).unwrap(); // Spawn a thread to handle UI events let (event_tx, event_rx) = std::sync::mpsc::channel::<UIEvent>(); spawn_event_loop(event_tx, 250).unwrap(); // Main loop let (mut controller, exit_rx) = Controller::new(); loop { terminal.draw(|f| app::view::render(f, &controller.model)).unwrap(); // Blocking read on events, this causes a redraw on new UIEvents ONLY if let UIEvent::Input(key_ev) = event_rx.recv().unwrap() { // Handle <Ctrl+C> if let KeyModifiers::CONTROL = key_ev.modifiers { if key_ev.code == KeyCode::Char('c') { break; } } controller.handle_key_event(key_ev); } else { controller.update(); } // Non-blocking read on exit signals match exit_rx.try_recv() { Ok(_) | Err(std::sync::mpsc::TryRecvError::Disconnected) => { break; }, _=> {} } } kill_terminal(); } /// Spawn a thread that hooks into user events as well as emits a tick event /// at a given interval. In the event that the Reciever is dropped, the thread /// will close itself, effectively acting as a kill command. fn spawn_event_loop(event_tx: Sender<UIEvent>, tick_rate: u64) -> Result<()> { thread::spawn(move || { // Declare tick_rate as a Duration let mut last_tick = SystemTime::now(); let tick_rate = Duration::from_millis(tick_rate); loop { let elapsed = last_tick.elapsed().unwrap(); // Poll for new events if event::poll(tick_rate).unwrap() { // Check for key events if let Event::Key(key) = event::read().unwrap() { // Send the key event through the channel, closing // the thread on error if let Err(_) = event_tx.send(UIEvent::Input(key)) { break; } } } if elapsed >= tick_rate { // Send the tick event, closing thread on error if let Err(_) = event_tx.send(UIEvent::Tick) { break; } last_tick = SystemTime::now(); } } }); Ok(()) } /// Revert the terminal session to a normal, usable, state. fn kill_terminal(){ execute!(stdout(), LeaveAlternateScreen, DisableMouseCapture).unwrap(); disable_raw_mode().unwrap(); } /// Provides a hook that allows the program to return the terminal /// to a usable state before exiting. fn panic_hook(info: &PanicInfo<'_>) { kill_terminal(); eprintln!("Caught panic hook: {:?}", info); }
30.145161
78
0.578384
3.09375
fb1a4d5a61ceafa023bda39460f9836b2c1ca179
1,761
go
Go
util/config_dump/port_forwarder.go
mlbiam/kiali
75723d5d1b6fc0b65c47d48f5ee7f552e3ea76eb
[ "Apache-2.0" ]
7
2021-10-31T09:29:45.000Z
2022-02-21T18:52:17.000Z
util/config_dump/port_forwarder.go
mlbiam/kiali
75723d5d1b6fc0b65c47d48f5ee7f552e3ea76eb
[ "Apache-2.0" ]
2
2020-08-11T20:00:58.000Z
2022-03-06T20:52:09.000Z
util/config_dump/port_forwarder.go
mlbiam/kiali
75723d5d1b6fc0b65c47d48f5ee7f552e3ea76eb
[ "Apache-2.0" ]
1
2021-08-24T09:16:54.000Z
2021-08-24T09:16:54.000Z
package config_dump import ( "io" "net/http" "os" "k8s.io/client-go/rest" "k8s.io/client-go/tools/portforward" "k8s.io/client-go/transport/spdy" "github.com/kiali/kiali/log" ) type PortForwarder interface { Start() error Stop() } type forwarder struct { forwarder *portforward.PortForwarder ReadyCh chan struct{} StopCh chan struct{} } func (f forwarder) Start() error { // It starts the port-forward errCh := make(chan error, 1) go func() { errCh <- f.forwarder.ForwardPorts() }() // Waiting until the ReadyChan has a value select { case err := <-errCh: log.Errorf("Failing starting the port forwarding") return err case <-f.ReadyCh: // Ready to forward requests return nil } } func (f forwarder) Stop() { // Closing the StopCh channel is closing the forwarding close(f.StopCh) } func NewPortForwarder(client rest.Interface, clientConfig *rest.Config, namespace, pod, address, portMap string, writer io.Writer) (forwarder, error) { stopCh := make(chan struct{}) readyCh := make(chan struct{}) forwarderUrl := client.Post(). Namespace(namespace). Resource("pods"). Name(pod). SubResource("portforward").URL() transport, upgrader, err := spdy.RoundTripperFor(clientConfig) if err != nil { log.Errorf("Error creating a RoundTripper: %v", err) return forwarder{}, err } dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, http.MethodPost, forwarderUrl) fwer, err := portforward.NewOnAddresses(dialer, []string{address}, []string{portMap}, stopCh, readyCh, writer, os.Stderr) if err != nil { log.Errorf("Error creating the port-forwarder: %v", err) return forwarder{}, err } return forwarder{ forwarder: fwer, ReadyCh: readyCh, StopCh: stopCh, }, nil }
22.0125
151
0.698467
3.078125
e9bedf6379a6acaa0d2717c221dde3c3cce763ee
3,282
rs
Rust
src/parse.rs
ironthree/fedora-update-feedback
9352fa50bb03926e74d4ab316f306172f14d5414
[ "Apache-2.0", "MIT" ]
2
2020-03-12T10:41:00.000Z
2020-03-29T11:09:36.000Z
src/parse.rs
ironthree/fedora-update-feedback
9352fa50bb03926e74d4ab316f306172f14d5414
[ "Apache-2.0", "MIT" ]
5
2020-01-26T22:04:10.000Z
2021-10-11T11:19:36.000Z
src/parse.rs
ironthree/fedora-update-feedback
9352fa50bb03926e74d4ab316f306172f14d5414
[ "Apache-2.0", "MIT" ]
null
null
null
/// This helper function parses a NEVRA string into its components. #[allow(clippy::many_single_char_names)] pub fn parse_nevra(nevra: &str) -> Result<(&str, &str, &str, &str, &str), String> { let mut nevr_a: Vec<&str> = nevra.rsplitn(2, '.').collect(); if nevr_a.len() != 2 { return Err(format!("Unexpected error when parsing NEVRAs: {}", nevra)); }; // rsplitn returns things in reverse order let a = nevr_a.remove(0); let nevr = nevr_a.remove(0); let mut n_ev_r: Vec<&str> = nevr.rsplitn(3, '-').collect(); if n_ev_r.len() != 3 { return Err(format!("Unexpected error when parsing NEVRAs: {}", nevr)); }; // rsplitn returns things in reverse order let r = n_ev_r.remove(0); let ev = n_ev_r.remove(0); let n = n_ev_r.remove(0); let (e, v) = if ev.contains(':') { let mut e_v: Vec<&str> = ev.split(':').collect(); let e = e_v.remove(0); let v = e_v.remove(0); (e, v) } else { ("0", ev) }; Ok((n, e, v, r, a)) } /// This helper function parses a NEVRA.rpm string into its components. #[allow(clippy::many_single_char_names)] pub fn parse_filename(nevrax: &str) -> Result<(&str, &str, &str, &str, &str), String> { let mut nevra_x: Vec<&str> = nevrax.rsplitn(2, '.').collect(); if nevra_x.len() != 2 { return Err(format!("Unexpected error when parsing dnf output: {}", nevrax)); }; // rsplitn returns things in reverse order let _x = nevra_x.remove(0); let nevra = nevra_x.remove(0); let (n, e, v, r, a) = parse_nevra(nevra)?; Ok((n, e, v, r, a)) } /// This helper function parses an NVR string into its components. #[allow(clippy::many_single_char_names)] pub fn parse_nvr(nvr: &str) -> Result<(&str, &str, &str), String> { let mut n_v_r: Vec<&str> = nvr.rsplitn(3, '-').collect(); if n_v_r.len() != 3 { return Err(format!("Unexpected error when parsing NEVRAs: {}", nvr)); }; // rsplitn returns things in reverse order let r = n_v_r.remove(0); let v = n_v_r.remove(0); let n = n_v_r.remove(0); Ok((n, v, r)) } #[cfg(test)] mod tests { use super::*; #[test] fn nevra() { let string = "maven-1:3.6.1-5.fc32.noarch"; let value = ("maven", "1", "3.6.1", "5.fc32", "noarch"); assert_eq!(parse_nevra(string).unwrap(), value); let string = "dnf-4.2.18-2.fc32.noarch"; let value = ("dnf", "0", "4.2.18", "2.fc32", "noarch"); assert_eq!(parse_nevra(string).unwrap(), value); } #[test] fn filename() { let string = "maven-1:3.6.1-5.fc32.noarch.rpm"; let value = ("maven", "1", "3.6.1", "5.fc32", "noarch"); assert_eq!(parse_filename(string).unwrap(), value); let string = "dnf-4.2.18-2.fc32.src.rpm"; let value = ("dnf", "0", "4.2.18", "2.fc32", "src"); assert_eq!(parse_filename(string).unwrap(), value); } #[test] fn nvr() { let string = "maven-3.6.1-5.fc32"; let value = ("maven", "3.6.1", "5.fc32"); assert_eq!(parse_nvr(string).unwrap(), value); let string = "dnf-4.2.18-2.fc32"; let value = ("dnf", "4.2.18", "2.fc32"); assert_eq!(parse_nvr(string).unwrap(), value); } }
28.789474
87
0.560938
3.109375
71f6bb2feb581ec1b3bbd8af89935dbe07be970e
4,741
ts
TypeScript
src/entities/Job/manager.ts
ncomerci/decentraland-gatsby
0d07cd1b1894f7777067f94c6140292d9546fc0d
[ "Apache-2.0" ]
8
2021-04-08T15:08:28.000Z
2022-02-24T10:34:46.000Z
src/entities/Job/manager.ts
ncomerci/decentraland-gatsby
0d07cd1b1894f7777067f94c6140292d9546fc0d
[ "Apache-2.0" ]
171
2020-03-12T18:58:01.000Z
2022-03-31T17:41:16.000Z
src/entities/Job/manager.ts
ncomerci/decentraland-gatsby
0d07cd1b1894f7777067f94c6140292d9546fc0d
[ "Apache-2.0" ]
10
2020-10-21T11:50:44.000Z
2022-03-29T07:46:54.000Z
import { CronJob } from 'cron' import { v4 as uuid } from 'uuid' import { JobSettings, TimePresets, CronTime } from './types' import JobContext from './context' import { createVoidPool, Pool } from '../Pool/utils' import MemoryModel from './model/memory' import DatabaseModel from './model/model' import { job_manager_duration_seconds, job_manager_pool_size } from './metrics' import logger from '../Development/logger' import type { Job } from './job' export default class JobManager { memory: boolean = false runningJobs = new Set<string>() jobs: Map<string, Job<any>> = new Map() crons: CronJob[] = [] pool: Pool<any> interval: NodeJS.Timeout initialInterval: NodeJS.Timeout queue: Job[] running: boolean = false constructor(settings: JobSettings) { const max = settings.concurrency || Infinity this.pool = createVoidPool({ min: 0, max }) this.memory = !!settings.memory this.cron(this.time(settings.cron || '@minutely'), () => this.check()) } time(cronTime: CronTime): string | Date { if (typeof cronTime === 'string' && TimePresets[cronTime]) { return TimePresets[cronTime] } return cronTime } getModel() { if (this.memory) { return MemoryModel } return DatabaseModel } stats() { return { size: this.pool.size, available: this.pool.available, running: this.pool.borrowed, pending: this.pool.pending, ids: Array.from(this.runningJobs.values()), } } define(handler: string, job: Job<any>) { return this.use(job, { handler }) } cron(cron: CronTime, job: Job<any>) { return this.use(job, { cron }) } use( job: Job<any>, options: Partial<{ handler: string; cron: CronTime }> = {} ) { const handler = options.handler || job.jobName || job.name if (this.jobs.has(handler)) { logger.warning(`replacing job "${handler}"`, { handler, type: 'job' }) } this.jobs.set(handler, job) if (options.cron) { this.crons.push( new CronJob(this.time(options.cron), () => { this.runJobs(uuid(), handler, {}, job) }) ) } return this } start() { this.crons.forEach((cron) => cron.start()) this.running = true } stop() { this.crons.forEach((cron) => cron.stop()) this.running = false } async check() { if (!this.running) { return } const jobs = await this.getModel().getPending() const pendingJobs = jobs.filter((job) => !this.runningJobs.has(job.id)) if (pendingJobs.length) { Promise.all( pendingJobs.map((job) => this.run(job.id, job.name, job.payload)) ) } } updatePayload = async (id: string, payload: object = {}) => { await this.getModel().updatePayload(id, payload) } schedule = async ( handler: string | Job<any>, date: Date, payload: object = {} ) => { const name = typeof handler === 'string' ? handler : handler.jobName || handler.name const job = await this.getModel().schedule(uuid(), name, date, payload) if (this.running && job.run_at.getTime() < Date.now()) { this.run(job.id, job.name, job.payload) } } async run(id: string, handler: string, payload: any): Promise<void> { const context = { type: 'job', id, name: handler, payload } if (!this.jobs.has(handler)) { logger.error(`Missing job: ${handler} (id: "${id}")`, context) return } if (this.runningJobs.has(id)) { logger.log(`Job ${handler} (id: "${id}") is already running`, context) return } await this.runJobs(id, handler, payload, this.jobs.get(handler)!) } async runJobs( id: string, handler: string, payload: any, job: Job<any> ): Promise<void> { if (!this.running) { return } const context = new JobContext( id, handler || job.name, payload || {}, this.schedule, this.updatePayload ) if (id) { this.runningJobs.add(id) } let error = 0 const labels = { job: handler || 'uknown' } job_manager_pool_size.inc(labels) const completeJob = job_manager_duration_seconds.startTimer(labels) const resource = await this.pool.acquire() try { await job(context) if (id) { await this.getModel().complete(id) } } catch (err) { logger.error(`Error running job "${handler}"`, { type: 'cron', id, handler, payload, message: err.message, stack: err.stack, ...err, }) error = 1 } await this.pool.release(resource) completeJob({ error }) job_manager_pool_size.dec(labels) if (id) { this.runningJobs.delete(id) } } }
23.705
79
0.596288
3.171875
746cbece16520bddb049eb23d8fa6f7f432ae0dd
2,693
h
C
compiler/semantic/sym_tbl.h
Engineev/mocker
9d3006419ea04683d0b2e6f5ccd21d464e6704e3
[ "MIT" ]
14
2019-02-18T01:41:50.000Z
2021-08-11T00:27:51.000Z
compiler/semantic/sym_tbl.h
Engineev/mocker
9d3006419ea04683d0b2e6f5ccd21d464e6704e3
[ "MIT" ]
null
null
null
compiler/semantic/sym_tbl.h
Engineev/mocker
9d3006419ea04683d0b2e6f5ccd21d464e6704e3
[ "MIT" ]
1
2021-08-11T00:28:39.000Z
2021-08-11T00:28:39.000Z
#ifndef MOCKER_SYM_TBL_H #define MOCKER_SYM_TBL_H #include <memory> #include <stdexcept> #include <string> #include <unordered_map> #include <vector> #include "ast/ast_node.h" #include "ast/visitor.h" namespace mocker { class ScopeID { public: ScopeID() = default; ScopeID(const ScopeID &) = default; ScopeID(ScopeID &&) noexcept = default; ScopeID &operator=(const ScopeID &) = default; ScopeID &operator=(ScopeID &&) noexcept = default; ~ScopeID() = default; bool operator==(const ScopeID &rhs) const { if (rhs.ids.size() != ids.size()) return false; for (std::size_t i = 0; i < ids.size(); ++i) if (ids[i] != rhs.ids[i]) return false; return true; } bool operator!=(const ScopeID &rhs) const { return !(*this == rhs); } std::string fmt() const { std::string res; for (std::size_t id : ids) res += std::to_string(id) + "-"; res.pop_back(); return res; } private: friend class SymTbl; ScopeID(std::vector<std::size_t> ids) : ids(std::move(ids)) {} std::vector<std::size_t> ids; }; class SymTbl { public: SymTbl(); SymTbl(const SymTbl &) = delete; SymTbl(SymTbl &&) noexcept = default; SymTbl &operator=(const SymTbl &) = delete; SymTbl &operator=(SymTbl &&) noexcept = default; ~SymTbl() = default; // return the scope ID of the global scope ScopeID global() const; // Create a subscope in the scope provided and return the ID of the new scope. // If the scope provided does not exists, throw std::out_of_range ScopeID createSubscope(const ScopeID &pntID); // Try to find the given symbol in the given scope AND it parent scopes. // If the symbol does not exist, then the returned shared_ptr is empty. std::shared_ptr<ast::Declaration> lookUp(const ScopeID &scopeID, const std::string &identifier) const; // If the identifier has already exists in the CURRENT scope, no addition will // be perform and the return value is false. Otherwise add the symbol into the // current scope, symbols from outer scopes may be covered, and return true. bool addSymbol(const ScopeID &scopeID, const std::string &identifier, std::shared_ptr<ast::Declaration> decl); private: struct Scope { explicit Scope(const std::shared_ptr<Scope> &pnt); std::unordered_map<std::string, std::shared_ptr<ast::Declaration>> syms; std::vector<std::shared_ptr<Scope>> subscopes; std::weak_ptr<Scope> pnt; }; // Just a helper function. Some asserts are performed. std::shared_ptr<Scope> getScope(const ScopeID &id) const; std::shared_ptr<Scope> root; }; } // namespace mocker #endif // MOCKER_SYM_TBL_H
28.648936
80
0.6684
3.015625
700a38ec5004584048d3a76fc4b2e846a71398bc
1,762
lua
Lua
oop/image.lua
warcraft-iii/lib-stdlib
4d98971a2755ba72dd855cf070068f85a0c56e55
[ "MIT" ]
3
2019-12-14T00:23:13.000Z
2021-07-06T08:55:07.000Z
oop/image.lua
warcraft-iii/lib-stdlib
4d98971a2755ba72dd855cf070068f85a0c56e55
[ "MIT" ]
null
null
null
oop/image.lua
warcraft-iii/lib-stdlib
4d98971a2755ba72dd855cf070068f85a0c56e55
[ "MIT" ]
null
null
null
---@type Image local Image = require('lib.stdlib.oop._generated._image') ---<static> create ---@overload fun(file: string, size: Vector3, pos: Vector3, origin: Vector3, imageType: integer): Image ---@param file string ---@param sizeX float ---@param sizeY float ---@param sizeZ float ---@param posX float ---@param posY float ---@param posZ float ---@param originX float ---@param originY float ---@param originZ float ---@param imageType integer ---@return Image function Image:create(file, sizeX, sizeY, sizeZ, posX, posY, posZ, originX, originY, originZ, imageType) if type(sizeX) == 'table' and type(sizeY) == 'table' and type(sizeZ) == 'table' then imageType = posX originX, originY, originZ = table.unpack(sizeZ) posX, posY, posZ = table.unpack(sizeY) sizeX, sizeY, sizeZ = table.unpack(sizeZ) end -- @debug@ checkclass(self, Image, 'create', 'self') checktype(file, 'string', 'create', 1) checktype(sizeX, 'float', 'create', 2) checktype(sizeY, 'float', 'create', 3) checktype(sizeZ, 'float', 'create', 4) checktype(posX, 'float', 'create', 5) checktype(posY, 'float', 'create', 6) checktype(posZ, 'float', 'create', 7) checktype(originX, 'float', 'create', 8) checktype(originY, 'float', 'create', 9) checktype(originZ, 'float', 'create', 10) checktype(imageType, 'integer', 'create', 11) -- @end-debug@ return Image:fromUd(Native.CreateImage(file, sizeX, sizeY, sizeZ, posX, posY, posZ, originX, originY, originZ, imageType)) end ---show ---@return void function Image:show() return self:setShown(true) end ---hide ---@return void function Image:hide() return self:setShown(false) end return Image
31.464286
114
0.643587
3.015625
5f1410e66518e2b1c00aee6be11eb38dfdacf80f
8,408
ts
TypeScript
panel/models/tabs.ts
sthagen/holoviz-panel
9abae5ac78e55857ed209de06feae3439f2f533b
[ "BSD-3-Clause" ]
601
2018-08-25T20:01:22.000Z
2019-11-19T19:37:08.000Z
panel/models/tabs.ts
sthagen/holoviz-panel
9abae5ac78e55857ed209de06feae3439f2f533b
[ "BSD-3-Clause" ]
626
2018-08-27T16:30:33.000Z
2019-11-20T17:02:00.000Z
panel/models/tabs.ts
sthagen/holoviz-panel
9abae5ac78e55857ed209de06feae3439f2f533b
[ "BSD-3-Clause" ]
73
2018-09-28T07:46:05.000Z
2019-11-18T22:45:36.000Z
import {Grid, ContentBox, Sizeable} from "@bokehjs/core/layout" import {div, size, children, display, undisplay, position, scroll_size} from "@bokehjs/core/dom" import {sum, remove_at} from "@bokehjs/core/util/array" import * as p from "@bokehjs/core/properties" import {Tabs as BkTabs, TabsView as BkTabsView} from "@bokehjs/models/layouts/tabs" import {LayoutDOMView} from "@bokehjs/models/layouts/layout_dom" import * as tabs from "@bokehjs/styles/tabs.css" import * as buttons from "@bokehjs/styles/buttons.css" import * as menus from "@bokehjs/styles/menus.css" function show(element: HTMLElement): void { element.style.visibility = "" element.style.opacity = "" } function hide(element: HTMLElement): void { element.style.visibility = "hidden" element.style.opacity = "0" } export class TabsView extends BkTabsView { model: Tabs connect_signals(): void { super.connect_signals() let view: any = this while (view != null) { if (view.model.type.endsWith('Tabs')) { view.connect(view.model.properties.active.change, () => this.update_zindex()) } view = view.parent || view._parent // Handle ReactiveHTML } } get is_visible(): boolean { let parent: any = this.parent let current_view: any = this while (parent != null) { if (parent.model.type.endsWith('Tabs')) { if (parent.child_views.indexOf(current_view) !== parent.model.active) { return false } } current_view = parent parent = parent.parent || parent._parent // Handle ReactiveHTML } return true } override _update_layout(): void { const loc = this.model.tabs_location const vertical = loc == "above" || loc == "below" // XXX: this is a hack, this should be handled by "fit" policy in grid layout const {scroll_el, headers_el} = this this.header = new class extends ContentBox { protected override _measure(viewport: Sizeable) { const min_headers = 3 const scroll = size(scroll_el) const headers = children(headers_el).slice(0, min_headers).map((el) => size(el)) const {width, height} = super._measure(viewport) if (vertical) { const min_width = scroll.width + sum(headers.map((size) => size.width)) return {width: viewport.width != Infinity ? viewport.width : min_width, height} } else { const min_height = scroll.height + sum(headers.map((size) => size.height)) return {width, height: viewport.height != Infinity ? viewport.height : min_height} } } }(this.header_el) let {width_policy, height_policy} = this.model if (width_policy == "auto") width_policy = this._width_policy() if (height_policy == "auto") height_policy = this._height_policy() const {sizing_mode} = this.model if (sizing_mode != null) { if (sizing_mode == "fixed") width_policy = height_policy = "fixed" else if (sizing_mode == "stretch_both") width_policy = height_policy = "max" else if (sizing_mode == "stretch_width") width_policy = "max" else if (sizing_mode == "stretch_height") height_policy = "max" } if (vertical) this.header.set_sizing({width_policy: width_policy, height_policy: "fixed"}) else this.header.set_sizing({width_policy: "fixed", height_policy: height_policy}) let row = 1 let col = 1 switch (loc) { case "above": row -= 1; break case "below": row += 1; break case "left": col -= 1; break case "right": col += 1; break } const header = {layout: this.header, row, col} const panels = this.child_views.map((child_view) => { return {layout: child_view.layout, row: 1, col: 1} }) this.layout = new Grid([header, ...panels]) this.layout.set_sizing(this.box_sizing()) } update_zindex(): void { const {child_views} = this for (const child_view of child_views) { if (child_view != null && child_view.el != null) child_view.el.style.zIndex = "" } if (this.is_visible) { const active = child_views[this.model.active] if (active != null && active.el != null) active.el.style.zIndex = "1" } } override update_position(): void { super.update_position() this.header_el.style.position = "absolute" // XXX: do it in position() position(this.header_el, this.header.bbox) const loc = this.model.tabs_location const vertical = loc == "above" || loc == "below" const scroll_el_size = size(this.scroll_el) const headers_el_size = scroll_size(this.headers_el) if (vertical) { const {width} = this.header.bbox if (headers_el_size.width > width) { this.wrapper_el.style.maxWidth = `${width - scroll_el_size.width}px` display(this.scroll_el) this.do_scroll(this.model.active) } else { this.headers_el.style.left = '0px' this.wrapper_el.style.maxWidth = "" undisplay(this.scroll_el) } } else { const {height} = this.header.bbox if (headers_el_size.height > height) { this.wrapper_el.style.maxHeight = `${height - scroll_el_size.height}px` display(this.scroll_el) this.do_scroll(this.model.active) } else { this.headers_el.style.top = '0px' this.wrapper_el.style.maxHeight = "" undisplay(this.scroll_el) } } const {child_views} = this for (const child_view of child_views) { hide(child_view.el) child_view.el.style.removeProperty('zIndex'); } const tab = child_views[this.model.active] if (tab != null) show(tab.el) } override render(): void { LayoutDOMView.prototype.render.call(this) let {active} = this.model const headers = this.model.tabs.map((tab, i) => { const el = div({class: [tabs.tab, i == active ? tabs.active : null]}, tab.title) el.addEventListener("click", (event) => { if (this.model.disabled) return if (event.target == event.currentTarget) this.change_active(i) }) if (tab.closable) { const close_el = div({class: tabs.close}) close_el.addEventListener("click", (event) => { if (event.target == event.currentTarget) { this.model.tabs = remove_at(this.model.tabs, i) const ntabs = this.model.tabs.length if (this.model.active > ntabs - 1) this.model.active = ntabs - 1 } }) el.appendChild(close_el) } if (this.model.disabled || tab.disabled) { el.classList.add(tabs.disabled) } return el }) this.headers_el = div({class: [tabs.headers]}, headers) this.wrapper_el = div({class: tabs.headers_wrapper}, this.headers_el) this.left_el = div({class: [buttons.btn, buttons.btn_default], disabled: ""}, div({class: [menus.caret, tabs.left]})) this.right_el = div({class: [buttons.btn, buttons.btn_default]}, div({class: [menus.caret, tabs.right]})) this.left_el.addEventListener("click", () => this.do_scroll("left")) this.right_el.addEventListener("click", () => this.do_scroll("right")) this.scroll_el = div({class: buttons.btn_group}, this.left_el, this.right_el) const loc = this.model.tabs_location this.header_el = div({class: [tabs.tabs_header, tabs[loc]]}, this.scroll_el, this.wrapper_el) this.el.appendChild(this.header_el) this.update_zindex() if (active === -1 && this.model.tabs.length) this.model.active = 0 } on_active_change(): void { const i = this.model.active const headers = children(this.headers_el) for (const el of headers) el.classList.remove(tabs.active) headers[i].classList.add(tabs.active) const {child_views} = this for (const child_view of child_views) { hide(child_view.el) } show(child_views[i].el) } } export namespace Tabs { export type Attrs = p.AttrsOf<Props> export type Props = BkTabs.Props & { } } export interface Tabs extends BkTabs.Attrs {} export class Tabs extends BkTabs { properties: Tabs.Props constructor(attrs?: Partial<Tabs.Attrs>) { super(attrs) } static __module__ = "panel.models.tabs" static init_Tabs(): void { this.prototype.default_view = TabsView this.define<Tabs.Props>(({}) => ({ })) } }
30.911765
121
0.633206
3.09375
fe2be417f7d927bfb1deca81f53dd1df8d2dd802
413
c
C
examples/arguments.c
mogenson/async.h
41d45217019c4e1d12c986c36240d733c0d52a0c
[ "MIT" ]
4
2021-02-07T15:20:36.000Z
2022-02-20T01:43:31.000Z
examples/arguments.c
mogenson/async.h
41d45217019c4e1d12c986c36240d733c0d52a0c
[ "MIT" ]
null
null
null
examples/arguments.c
mogenson/async.h
41d45217019c4e1d12c986c36240d733c0d52a0c
[ "MIT" ]
null
null
null
#include "../async.h" #include <stdio.h> /* define an async task named print that takes two arguments */ ASYNC(print, char c, int i) { BEGIN(); while (1) { printf("c is '%c' and i is %d\n", c, i); // print arguments YIELD(); } END(); } int main() { char c = 'a'; int i = 0; while (i < 10) { AWAIT(print, c, i); // run print task with arguments c++; i++; } return 0; }
14.241379
63
0.527845
3.15625
164a33323bc9be004418d76fc1a037fdd75e8f69
1,761
h
C
SEGANKU/eagle.h
mangostaniko/cg15-seganku
83d603f52e072cf12f08908b94dae3a86577ef84
[ "Apache-2.0" ]
null
null
null
SEGANKU/eagle.h
mangostaniko/cg15-seganku
83d603f52e072cf12f08908b94dae3a86577ef84
[ "Apache-2.0" ]
null
null
null
SEGANKU/eagle.h
mangostaniko/cg15-seganku
83d603f52e072cf12f08908b94dae3a86577ef84
[ "Apache-2.0" ]
null
null
null
#ifndef EAGLE_H #define EAGLE_H #define GLM_SWIZZLE #define GLM_FORCE_RADIANS #include <btBulletDynamicsCommon.h> #include <glm/gtx/vector_angle.hpp> #include "geometry.h" enum EagleState { CIRCLING = 0, ATTACKING = 1, RETREATING = 2 }; class Eagle : public Geometry { // PHYSICS btCollisionShape *playerShape; btRigidBody *playerBody; btDefaultMotionState *motionState; // GAMEPLAY // all durations given in seconds const float EAT_RADIUS = 1.0f; const float TARGET_DEFENSE_REACH_RADIUS = 13.0f; const float ATTACK_WAIT_TIME_MIN = 15.0f; // min time after which eagle will attempt to attack player const float ATTACK_WAIT_TIME_MAX = 25.0f; // max time after which eagle will attempt to attack player glm::mat4 eagleInitTransform; EagleState state = CIRCLING; float totalTimePassed = 0; float timeSinceLastAttack = 0; float timeIntervalToNextAttack = ATTACK_WAIT_TIME_MIN; glm::vec3 targetPos; bool targetHidden = false; bool targetDefenseActive = false; public: Eagle(const glm::mat4 &matrix, const std::string &filePath); ~Eagle(); virtual void update(float timeDelta, const glm::vec3 &targetPos_, bool targetHidden_, bool targetDefenseActive_); /** * @brief return the current state of behaviour of the eagle * @return the current state of behaviour of the eagle */ EagleState getState(); /** * @brief check whether the target is in TARGET_DEFENSE_REACH_RADIUS of the eagle * @return whether the target is in TARGET_DEFENSE_REACH_RADIUS of the eagle */ bool isInTargetDefenseReach(); /** * @brief check whether the target is in EAT_RADIUS of the eagle * @return whether the target is in EAT_RADIUS of the eagle */ bool isTargetEaten(); void resetEagle(); private: }; #endif // EAGLE_H
23.48
114
0.750142
3.015625
71440ba287886ee3ce18f41bbf99c45c782c5023
2,188
ts
TypeScript
src/state/reducers/imgLibrary/imgLibraryReducer.ts
janisdd/basic-board-game-editor
c53f6149b6d74d66c0ce542c01418df1f96bce98
[ "MIT" ]
null
null
null
src/state/reducers/imgLibrary/imgLibraryReducer.ts
janisdd/basic-board-game-editor
c53f6149b6d74d66c0ce542c01418df1f96bce98
[ "MIT" ]
4
2018-07-02T12:20:11.000Z
2021-03-08T23:54:02.000Z
src/state/reducers/imgLibrary/imgLibraryReducer.ts
janisdd/basic-board-game-editor
c53f6149b6d74d66c0ce542c01418df1f96bce98
[ "MIT" ]
null
null
null
import {Action} from "redux"; import { ImgStorage} from "../../../externalStorage/imgStorage"; import {notExhaustive} from "../_notExhausiveHelper"; import {replaceProperty, replacePropertyByGuid} from "../../../helpers/functionHelpers"; import {ImageAssetSurrogate} from "../../../types/world"; export type State = ReadonlyArray<ImageAssetSurrogate> //the real imgs are stored in src/externalStorage/imgStorage.ts export const initial: State = [] export interface ActionBase extends Action { readonly type: ActionType } export enum ActionType { ADD_img = 'imgLibraryReducer_ADD_img', REMOVE_img = 'imgLibraryReducer_REMOVE_img', SET_imgDisplayIndex = 'imgLibraryReducer_SET_imgDisplayIndex', RESET = 'imgLibraryReducer_RESET', } export interface ADD_imgAction extends ActionBase { readonly type: ActionType.ADD_img readonly imgSurrogate: ImageAssetSurrogate } export interface REMOVE_imgAction extends ActionBase { readonly type: ActionType.REMOVE_img readonly imgSurrogateGuid: string } export interface SET_imgDisplayIndexAction extends ActionBase { readonly type: ActionType.SET_imgDisplayIndex readonly imgSurrogateGuid: string readonly imgDisplayIndex: number } export interface ResetAction extends ActionBase { readonly type: ActionType.RESET } export type AllActions = ResetAction | ADD_imgAction | REMOVE_imgAction | SET_imgDisplayIndexAction export function reducer(state: State = initial, action: AllActions): State { switch (action.type) { case ActionType.REMOVE_img: //remove real img & surrogate ImgStorage.removeImg(action.imgSurrogateGuid) return state.filter(p => p.guid !== action.imgSurrogateGuid) case ActionType.ADD_img: { //the img itself should be added already to the img storage return state.concat(action.imgSurrogate) } case ActionType.SET_imgDisplayIndex: return replacePropertyByGuid(state, action.imgSurrogateGuid, (el => { return { ...el, displayIndex: action.imgDisplayIndex } })) case ActionType.RESET: return initial default: notExhaustive(action) return state } }
23.276596
88
0.738117
3.140625
8754099e672e8330e96d277abd7c1de56127c476
3,434
swift
Swift
Marvel/Sources/Presentation/CharacterDetail/ViewModels/ComicsViewModel.swift
drogel/Marvel
d97db33dda9bbc119bd7243415cadf7570e29ad0
[ "Unlicense" ]
null
null
null
Marvel/Sources/Presentation/CharacterDetail/ViewModels/ComicsViewModel.swift
drogel/Marvel
d97db33dda9bbc119bd7243415cadf7570e29ad0
[ "Unlicense" ]
null
null
null
Marvel/Sources/Presentation/CharacterDetail/ViewModels/ComicsViewModel.swift
drogel/Marvel
d97db33dda9bbc119bd7243415cadf7570e29ad0
[ "Unlicense" ]
1
2022-02-11T11:40:16.000Z
2022-02-11T11:40:16.000Z
// // ComicsViewModel.swift // Marvel // // Created by Diego Rogel on 5/2/22. // import Combine import Foundation protocol ComicsViewModelProtocol: ViewModel { var comicCellModelsPublisher: AnyPublisher<[ComicCellModel], Never> { get } func willDisplayComicCell(at indexPath: IndexPath) async } class ComicsViewModel: ComicsViewModelProtocol { var comicCellModelsPublisher: AnyPublisher<[ComicCellModel], Never> { $publishedComicCellModels.eraseToAnyPublisher() } @Published private var publishedComicCellModels: [ComicCellModel] private let comicsFetcher: FetchComicsUseCase private let characterID: Int private let imageURLBuilder: ImageURLBuilder private let pager: Pager init(comicsFetcher: FetchComicsUseCase, characterID: Int, imageURLBuilder: ImageURLBuilder, pager: Pager) { self.comicsFetcher = comicsFetcher self.characterID = characterID self.imageURLBuilder = imageURLBuilder self.pager = pager publishedComicCellModels = [] } func start() async { await loadComics(with: startingQuery) } func willDisplayComicCell(at indexPath: IndexPath) async { guard shouldLoadMore(at: indexPath) else { return } await loadMore() } } private extension ComicsViewModel { var startingQuery: FetchComicsQuery { query(atOffset: 0) } func shouldLoadMore(at indexPath: IndexPath) -> Bool { pager.isAtEndOfCurrentPageWithMoreContent(indexPath.row) } func query(atOffset offset: Int) -> FetchComicsQuery { FetchComicsQuery(characterID: characterID, offset: offset) } func loadMore() async { await loadComics(with: query(atOffset: publishedComicCellModels.count)) } func loadComics(with query: FetchComicsQuery) async { do { let contentPage = try await comicsFetcher.fetch(query: query) handleSuccess(with: contentPage) } catch { return } } func handleSuccess(with contentPage: ContentPage<Comic>) { guard let comicsCellData = mapToCells(comics: contentPage.contents) else { return } pager.update(currentPage: contentPage) publishedComicCellModels += comicsCellData } func mapToCells(comics: [Comic]) -> [ComicCellModel]? { comics.compactMap(comicCell) } func comicCell(from comic: Comic) -> ComicCellModel? { let imageURL = buildImageURL(from: comic) let title = buildTitle(from: comic.title) let issueNumber = buildIssueNumber(from: comic.issueNumber) let identifier = String(comic.identifier) return ComicCellModel(identifier: identifier, title: title, issueNumber: issueNumber, imageURL: imageURL) } func buildTitle(from title: String) -> String { removeIssueNumber(from: title) } func buildIssueNumber(from issueNumber: Int) -> String { let issueNumberString = String(issueNumber) return String(format: "issue_number %@".localized, issueNumberString) } func buildImageURL(from comic: Comic) -> URL? { imageURLBuilder.buildURL(from: comic.image, variant: .portraitLarge) } func removeIssueNumber(from comicTitle: String) -> String { comicTitle .replacingOccurrences(of: #"\s#\d*"#, with: "", options: .regularExpression) .trimmingCharacters(in: .whitespaces) } }
31.796296
113
0.685498
3
861c857b461954ab8c61f5194c4a45405941d4ae
2,528
rs
Rust
rust-by-example/18-error_handling/src/bin/18_5_0_iterate.rs
tetsuyainfra/playground-rust
62adbeb32bba9a05a684b08ef4f422f36e9010c4
[ "MIT" ]
null
null
null
rust-by-example/18-error_handling/src/bin/18_5_0_iterate.rs
tetsuyainfra/playground-rust
62adbeb32bba9a05a684b08ef4f422f36e9010c4
[ "MIT" ]
null
null
null
rust-by-example/18-error_handling/src/bin/18_5_0_iterate.rs
tetsuyainfra/playground-rust
62adbeb32bba9a05a684b08ef4f422f36e9010c4
[ "MIT" ]
null
null
null
// filter_map() : 関数を呼んでフィルタを適用した結果がNoneなら取り除く // collect() : イテレーションを途中で終了して、Resutl<Vec<T>, E>にして返す // (ので、Errは一つだし、イテレーションが途中で終わる) // partition() : 実行結果を成功と失敗に分けて返す // Iterating over Results // An Iter::map operation might fail, for example: fn main1() { let strings = vec!["tofu", "93", "18"]; let numbers: Vec<_> = strings.into_iter().map(|s| s.parse::<i32>()).collect(); println!("Results1: {:?}", numbers); } // Let's step through strategies for handling this. // Ignore the failed items with filter_map() // filter_map calls a function and filters out the results that are None. fn main2() { let strings = vec!["tofu", "93", "18"]; // [93, 18] let numbers: Vec<_> = strings .into_iter() .map(|s| s.parse::<i32>()) .filter_map(Result::ok) .collect(); println!("Results2: {:?}", numbers); } // Fail the entire operation with collect() // Result implements FromIter so that a vector of results (Vec<Result<T, E>>) can be turned into a result with a vector (Result<Vec<T>, E>). Once an Result::Err is found, the iteration will terminate. fn main3() { let strings = vec!["tofu", "93", "18"]; // -> Result::Errが帰ってくる let numbers: Result<Vec<_>, _> = strings.into_iter().map(|s| s.parse::<i32>()).collect(); println!("Results3: {:?}", numbers); } fn main3_2() { let strings = vec!["93", "tofu", "93", "18"]; // -> Result::Errが帰ってくる let numbers: Result<Vec<_>, _> = strings.into_iter().map(|s| s.parse::<i32>()).collect(); println!("Results3_2: {:?}", numbers); } // Collect all valid values and failures with partition() fn main4() { let strings = vec!["tofu", "93", "18"]; // (Err, Vec<i32>)になる let (numbers, errors): (Vec<_>, Vec<_>) = strings .into_iter() .map(|s| s.parse::<i32>()) .partition(Result::is_ok); println!("Numbers4: {:?}", numbers); println!("Errors4: {:?}", errors); } // When you look at the results, // you'll note that everything is still wrapped in Result. // A little more boilerplate is needed for this. fn main4_2() { let strings = vec!["tofu", "93", "18"]; let (numbers, errors): (Vec<_>, Vec<_>) = strings .into_iter() .map(|s| s.parse::<i32>()) .partition(Result::is_ok); let numbers: Vec<_> = numbers.into_iter().map(Result::unwrap).collect(); let errors: Vec<_> = errors.into_iter().map(Result::unwrap_err).collect(); println!("Numbers42: {:?}", numbers); println!("Errors42: {:?}", errors); } fn main() { main1(); main2(); main3(); main3_2(); // add main4(); main4_2(); }
32.831169
200
0.620253
3.5625
b33a04bca6e6604ce7056e32268b1bdde2e7c7ac
1,678
swift
Swift
MemeMe/MemeController.swift
BoostCamp/MemeMe_Henry
0a5891d273f6c71b0fb3b6b9b448d627dd7a89a7
[ "MIT" ]
null
null
null
MemeMe/MemeController.swift
BoostCamp/MemeMe_Henry
0a5891d273f6c71b0fb3b6b9b448d627dd7a89a7
[ "MIT" ]
null
null
null
MemeMe/MemeController.swift
BoostCamp/MemeMe_Henry
0a5891d273f6c71b0fb3b6b9b448d627dd7a89a7
[ "MIT" ]
null
null
null
// // MemeController.swift // MemeMe // // Created by JUNYEONG.YOO on 1/25/17. // Copyright © 2017 Boostcamp. All rights reserved. // import Foundation import UIKit struct MemeController { private static var appDelegate: AppDelegate { return UIApplication.shared.delegate as! AppDelegate } // Returns number of memed images static func count() -> Int { return appDelegate.memes.count } // Add a new memed image to the array static func insert(_ meme: Meme) { appDelegate.memes.append(meme) RealmController.insert(meme) } // Get a memed image from the array static func select(at index: Int) -> Meme { return appDelegate.memes[index] } // Update a memed image static func update(at index: Int, _ updatedMeme: Meme) { let oldMeme = appDelegate.memes[index] appDelegate.memes[index] = updatedMeme RealmController.update(old: oldMeme, updated: updatedMeme) } // Delete a memed image static func delete(at index: Int) { let deletedMeme: Meme = appDelegate.memes.remove(at: index) // Delete images from document directory let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String let documentURL = URL(fileURLWithPath: documentDirectory) let originalImageURL = documentURL.appendingPathComponent(deletedMeme.originalImageName) let memedImageURL = documentURL.appendingPathComponent(deletedMeme.memedImageName) do { try FileManager.default.removeItem(at: originalImageURL) try FileManager.default.removeItem(at: memedImageURL) } catch { print("Could not delete image from document directory") } RealmController.delete(deletedMeme) } }
27.064516
117
0.747318
3.046875
b1df3e19c459a39b4bccbc7bcf194776c3d6f984
1,135
c
C
oven/UI.c
Mr-Bossman/oven
3b1829fb05c69d219692128413d0311c6d33f9ab
[ "MIT" ]
null
null
null
oven/UI.c
Mr-Bossman/oven
3b1829fb05c69d219692128413d0311c6d33f9ab
[ "MIT" ]
null
null
null
oven/UI.c
Mr-Bossman/oven
3b1829fb05c69d219692128413d0311c6d33f9ab
[ "MIT" ]
null
null
null
#include "UI.h" #include "common.h" #include "menus.h" #include "temp_control.h" static bool C = true; static uint16_t getTemp(){ if(C) return menu2("Enter Temp *C:",475,100); else return ((menu2("Enter Temp *F:",885,215)-32)*5)/9; } static int16_t getTempRise(){ if(C) return menu3("Enter *C/S:",500,-500,2); else return ((menu3("Enter *F/S:",900,-900,2))*5)/9; } static uint16_t getTime(){ return menu2("Enter Time S:",240,10); } void Options(struct tempC * data){ for(uint8_t i = 0; i < 6;i++){ uint8_t option = menu1("Select an option:\n>Set target temp...\n Set rise time...\n Set temp...\n C or F...\n Start...",5); switch (option){ case 0:{ data[i].stableTemp = false; data[i].temp = getTemp(); data[i].rise = getTempRise(); continue; } case 1:{ data[i].stableTemp = false; data[i].times = getTime(); data[i].rise = getTempRise(); continue; } case 2:{ data[i].stableTemp = true; data[i].times = getTime(); data[i].temp = getTemp(); continue; } case 3:{ C ^= true; continue; } case 4:{ break; } } break; } }
19.912281
125
0.577974
3
0edc5c372d4510af2ff58bb3607a8527a05c242e
1,520
ts
TypeScript
src/commons/ArrayCollection.ts
prishedko/algorithms-ts
a4355a3c4f74cb188488bae34827316c3c581f8e
[ "MIT" ]
5
2017-11-02T09:25:07.000Z
2020-08-30T15:57:32.000Z
src/commons/ArrayCollection.ts
prishedko/algorithms-ts
a4355a3c4f74cb188488bae34827316c3c581f8e
[ "MIT" ]
null
null
null
src/commons/ArrayCollection.ts
prishedko/algorithms-ts
a4355a3c4f74cb188488bae34827316c3c581f8e
[ "MIT" ]
null
null
null
import { CommonsAPI } from './api' import { ArrayIterator } from './ArrayIterator' import Collection = CommonsAPI.Collection import CollectionIterator = CommonsAPI.CollectionIterator /** * Implementation of <tt>Collection</tt> that uses an array to store elements. Can either copy given array or reuse it - * this behavior is defined by <tt>copyArray</tt> parameter of the constructor. */ export class ArrayCollection<E> implements Collection<E> { private array: E[] constructor(from: E[] = [], copyArray: boolean = true) { if (copyArray) { this.array = [...from] } else { this.array = from } } map<T>(f: (e: E) => T): Collection<T> { return new ArrayCollection(this.array.map(f), false) } filter(p: (e: E) => boolean): Collection<E> { return new ArrayCollection(this.array.filter(p), false) } forEach(f: (e: E) => void): void { this.array.forEach(f) } reduce<A>(r: (accumulator: A, currentElement: E) => A, initialValue: A): A { return this.array.reduce(r, initialValue) } size(): number { return this.array.length } find(p: (e: E) => boolean): E | undefined { return this.array.find(p) } every(p: (e: E) => boolean): boolean { return this.array.every(p) } some(p: (e: E) => boolean): boolean { return this.array.some(p) } iterator(): CollectionIterator<E> { return new ArrayIterator(this.array) } }
26.206897
120
0.596711
3.296875
3cece4175c5a0536a09ba5585d3b03e185b907d5
3,869
lua
Lua
6_setup/additional_files/zh/mm8/zh_update/Scripts/Core/dump.lua
might-and-magic/mm678_i18n
ddc37c743ac37169908641dcd5328a7ccae5138f
[ "MIT" ]
17
2020-02-25T14:37:23.000Z
2022-02-21T15:33:09.000Z
6_setup/additional_files/zh/mm8/zh_update/Scripts/Core/dump.lua
might-and-magic/mm678_i18n
ddc37c743ac37169908641dcd5328a7ccae5138f
[ "MIT" ]
1
2022-01-09T02:14:56.000Z
2022-02-13T10:08:11.000Z
6_setup/additional_files/zh/mm8/zh_update/Scripts/Core/dump.lua
might-and-magic/mm678_i18n
ddc37c743ac37169908641dcd5328a7ccae5138f
[ "MIT" ]
3
2020-10-06T20:38:13.000Z
2021-02-17T02:11:17.000Z
DumpLimit = 10000 local _KNOWNGLOBALS = dump, structs local Keywords = {} do local t = {"and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while", "goto"} for k, v in pairs(t) do Keywords[v] = k end end -- Mostly for debugging and expirimenting. Shows 't', expanding all tables in it up to the 'depth' level. function dump(t, depth, exact) local buf = {} local bufn = 0 local ShowN local tables = {} local ptrs = {} local ShowTable depth = depth and depth * 2 or math.huge local function Write(str) bufn = bufn + 1 buf[bufn] = str end local function mystring(v) if type(v) == "number" then if v ~= v then return "0/0" elseif v == 1/0 then return "1/0" elseif v == -1/0 then return "-1/0" end end return tostring(v) end local function Key(v) if type(v) == "string" then if not v:match("^[%a_][%w_]*$") or exact and Keywords[v] then v = ("[%q]"):format(v) end return v..' = ' elseif v == nil then return "" elseif type(v) == "table" then tables[v] = tables[v] or false -- when shown needs address added end return '['..mystring(v)..'] = ' end local function Val(v) if type(v) == "string" then if exact then return ("%q"):format(v) end return '"'..v..'"' else return mystring(v) end end local function FindSameStruct(v) local ptr = v["?ptr"] local class = structs.class(v) local same = ptrs[ptr] while same and class ~= structs.class(same) do same = ptrs[same] end return same end local function ShowVal(k, v, space) if bufn ~= ShowN then buf[bufn] = buf[bufn]..',' end if type(v) == "table" then local n = tables[v] local SameStruct = not n and structs and FindSameStruct(v) if SameStruct then n = tables[SameStruct] if n then v = SameStruct end end if not n then -- not already shown if #space < depth then Write(("%s%s{"):format(space, Key(k))) if n == false then -- needs address added tables[v] = 0 buf[bufn] = buf[bufn].." -- "..Val(v) else tables[v] = bufn end if structs then local ptr = v["?ptr"] if ptr then ptrs[v] = ptrs[ptr] ptrs[ptr] = v end end ShowTable(v, space) return Write(space.."}") else tables[v] = false -- when shown needs address added end elseif n ~= 0 then -- address not already added tables[v] = 0 buf[n] = buf[n].." -- "..Val(v) end if SameStruct then return Write(("%s%sclone %s"):format(space, Key(k), Val(v))) end end Write(("%s%s%s"):format(space, Key(k), Val(v))) end local function ShowArray(t, space) -- local i = 1 for k, v in t do ShowVal(nil, v, space) -- if k == i then -- ShowVal(nil, v, space) -- i = i + 1 -- else -- ShowVal(k, v, space) -- end end end local function ShowStruct(t, space) for k, v in structs.enum(t) do ShowVal(k, v, space) end end function ShowTable(t, space) if bufn > DumpLimit then return Write(space.." ...") end ShowN = bufn space = space.." " if not structs or not pcall(ShowStruct, t, space) and not pcall(ShowArray, t, space) then -- !!! local i = 1 for k, v in sortpairs(t) do if k == i then i, k = i + 1, nil elseif k == i + 1 then ShowVal(nil, nil, space) i, k = i + 2, nil elseif k == i + 2 then ShowVal(nil, nil, space) ShowVal(nil, nil, space) i, k = i + 3, nil end ShowVal(k, v, space) end end end if type(t) == "table" and depth ~= 0 then Write("{") tables[t] = bufn local ptr = t["?ptr"] if ptr then ptrs[ptr] = t end ShowTable(t, "") Write("}") else Write(Val(t)) end return table.concat(buf, "\n") end
21.494444
189
0.571207
3.375
dd6a29cf085de89a1078d72a130fc8ff97ceb89d
1,883
go
Go
src/assorted/interface_value_type.go
devak23/go
19023b6a412c97824362e8a600062f7869f32fb5
[ "MIT" ]
null
null
null
src/assorted/interface_value_type.go
devak23/go
19023b6a412c97824362e8a600062f7869f32fb5
[ "MIT" ]
null
null
null
src/assorted/interface_value_type.go
devak23/go
19023b6a412c97824362e8a600062f7869f32fb5
[ "MIT" ]
null
null
null
// How do we know what specific object is being held by the interface pointer? package assorted import ( "fmt" "strconv" ) // define an object type Human struct { name string age int } // define an empty interface (which is implemented by everyone!) type Element interface{} // define a custom type called List which is nothing but an array of // objects that implement the Element interface type List []Element // define a toString() sorta method for the object func (h Human) String() string { return "(name: " + h.name + "- age: " + strconv.Itoa(h.age) + " years)" } // the main function func InterfaceValueTypeMain() { list := make(List, 3) list[0] = 1 // an int list[1] = "Hello" // a string list[2] = Human{"Dennis", 37} determineTypeUsingIf(list) determineTypeUsingSwitch(list) } func determineTypeUsingIf(list List) { fmt.Println("---------------USING IF-------------") for index, element := range list { if value, ok := element.(int); ok { fmt.Printf("list[%d] is an int and it's value is %d\n", index, value) } else if value, ok := element.(string); ok { fmt.Printf("list[%d] is a string and it's value is %s\n", index, value) } else if value, ok := element.(Human); ok { fmt.Printf("list[%d] is a Human object and it's value is %s\n", index, value) } else { fmt.Printf("list[%d] is a weird one!", index) } } } func determineTypeUsingSwitch(list List) { fmt.Println("---------------USING SWITCH-------------") for index, element := range list { switch value := element.(type) { case int: fmt.Printf("list[%d] is an int and it's value is %d\n", index, value) case string: fmt.Printf("list[%d] is a string and it's value is %s\n", index, value) case Human: fmt.Printf("list[%d] is a Human object and it's value is %s\n", index, value) default: fmt.Printf("list[%d] is a weird one!", index) } } }
27.691176
80
0.640998
3.34375
df9839c88c981c0aa33b8780d0bc86452bd5f103
2,589
swift
Swift
Tests/CryptoTests/BCryptTests.swift
mcdappdev/crypto
fb45f5b0654b5af81943a2b3b2a31f76fdba8fa6
[ "MIT" ]
null
null
null
Tests/CryptoTests/BCryptTests.swift
mcdappdev/crypto
fb45f5b0654b5af81943a2b3b2a31f76fdba8fa6
[ "MIT" ]
null
null
null
Tests/CryptoTests/BCryptTests.swift
mcdappdev/crypto
fb45f5b0654b5af81943a2b3b2a31f76fdba8fa6
[ "MIT" ]
null
null
null
import XCTest @testable import Crypto class BCryptTests: XCTestCase { static let allTests = [ ("testVersion", testVersion), ("testFail", testFail), ("testInvalidSalt", testInvalidSalt), ("testVerify", testVerify), ("testNotVerify", testNotVerify), ("testInvalidCost", testInvalidCost) ] func testVersion() throws { let digest = try BCrypt.hash("foo", cost: 6) XCTAssert(digest.hasPrefix("$2b$06$")) } func testFail() throws { let digest = try BCrypt.hash("foo", cost: 6) let res = try BCrypt.verify("bar", created: digest) XCTAssertEqual(res, false) } func testInvalidCost() throws { XCTAssertThrowsError(try BCrypt.hash("foo", cost: 2)) } func testInvalidSalt() throws { do { _ = try BCrypt.verify("", created: "foo") XCTFail("Should have failed") } catch let error as CryptoError { print(error) } } func testVerify() throws { for (desired, message) in tests { let result = try BCrypt.verify(message, created: desired) XCTAssert(result, "\(message): did not match \(desired)") } } func testNotVerify() throws { let testCase = tests.first! let message = "vapor_" + testCase.value let shouldNotMatch = testCase.key let result = try BCrypt.verify(message, created: shouldNotMatch) XCTAssertFalse(result, "\(shouldNotMatch): matched \(message)") } } let tests = [ "$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW" : "U*U", "$2a$05$CCCCCCCCCCCCCCCCCCCCC.VGOzA784oUp/Z0DY336zx7pLYAy0lwK" : "U*U*", "$2a$05$XXXXXXXXXXXXXXXXXXXXXOAcXxm9kjPGEMsLznoKqmqw7tc8WCx4a" : "U*U*U", "$2a$05$abcdefghijklmnopqrstuu5s2v8.iXieOjg/.AySBTTZIIVFJeBui" : "0123456789abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + "chars after 72 are ignored", "$2a$04$TI13sbmh3IHnmRepeEFoJOkVZWsn5S1O8QOwm8ZU5gNIpJog9pXZm" : "vapor", "$2y$11$kHM/VXmCVsGXDGIVu9mD8eY/uEYI.Nva9sHgrLYuLzr0il28DDOGO" : "Vapor3", "$2a$06$DCq7YPn5Rq63x1Lad4cll.TV4S6ytwfsfvkgY8jIucDrjc8deX1s." : "", "$2a$06$m0CrhHm10qJ3lXRY.5zDGO3rS2KdeeWLuGmsfGlMfOxih58VYVfxe" : "a", "$2a$06$If6bvum7DFjUnE9p2uDeDu0YHzrHM6tf.iqN8.yx.jNN1ILEf7h0i" : "abc", "$2a$06$.rCVZVOThsIa97pEDOxvGuRRgzG64bvtJ0938xuqzv18d3ZpQhstC" : "abcdefghijklmnopqrstuvwxyz", "$2a$06$fPIsBO8qRqkjj273rfaOI.HtSV9jLDpTbZn782DC6/t7qT67P6FfO" : "~!@#$%^&*() ~!@#$%^&*()PNBFRD", ]
36.985714
106
0.648127
3
650bd2653086235614c46bb1b73a337dfc0ba477
6,046
py
Python
vintage_commands.py
ktuan89/Vintage
81f178043d1dad4ec9bd50ad4db2df9ef994f098
[ "MIT", "Unlicense" ]
null
null
null
vintage_commands.py
ktuan89/Vintage
81f178043d1dad4ec9bd50ad4db2df9ef994f098
[ "MIT", "Unlicense" ]
null
null
null
vintage_commands.py
ktuan89/Vintage
81f178043d1dad4ec9bd50ad4db2df9ef994f098
[ "MIT", "Unlicense" ]
null
null
null
import sublime, sublime_plugin import os #import subprocess def is_legal_path_char(c): # XXX make this platform-specific? return c not in " \n\"|*<>{}[]()" def move_while_path_character(view, start, is_at_boundary, increment=1): while True: if not is_legal_path_char(view.substr(start)): break start = start + increment if is_at_boundary(start): break return start class ViOpenFileUnderSelectionCommand(sublime_plugin.TextCommand): def run(self, edit): #sel = self.view.sel()[0] region = self.view.sel()[0] """if not sel.empty(): file_name = self.view.substr(sel) else: caret_pos = self.view.sel()[0].begin() current_line = self.view.line(caret_pos) left = move_while_path_character( self.view, caret_pos, lambda x: x < current_line.begin(), increment=-1) right = move_while_path_character( self.view, caret_pos, lambda x: x > current_line.end(), increment=1) file_name = self.view.substr(sublime.Region(left + 1, right))""" if region.empty(): line = self.view.line(region) file_name = self.view.substr(line) else: file_name = self.view.substr(region) """file_name = os.path.join(os.path.dirname(self.view.file_name()), file_name)""" if file_name.endswith(":"): file_name = file_name[0:-1] if os.path.exists(file_name): self.view.window().open_file(file_name) class CopyCurrentWord(sublime_plugin.TextCommand): def run(self, edit): for region in self.view.sel(): if region.empty(): sublime.set_clipboard(self.view.substr(self.view.word(region.begin()))) class OpenFileInXcode(sublime_plugin.TextCommand): def run(self, edit): if self.view.file_name() is not None: #print self.view.file_name() #subprocess.call(["open", "-a", "/Applications/Xcode.app", self.view.file_name()]) os.system("open -a /Applications/Xcode.app '" + self.view.file_name() + "'") class ViSaveAndExit(sublime_plugin.WindowCommand): def run(self): self.window.run_command('save') self.window.run_command('close') if len(self.window.views()) == 0: self.window.run_command('close') #class MoveFocusedViewToBeginning(sublime_plugin.EventListener): # def on_activated(self, view): # view.window().set_view_index(view, 0, 0) class ExtendedSwitcherHaha(sublime_plugin.WindowCommand): # declarations open_files = [] open_views = [] window = [] settings = [] # lets go def run(self, list_mode): print "Here here here" # self.view.insert(edit, 0, "Hello, World!") self.open_files = [] self.open_views = [] self.window = sublime.active_window() self.settings = sublime.load_settings('ExtendedSwitcher.sublime-settings') for f in self.getViews(list_mode): # if skip the current active is enabled do not add the current file it for selection if self.settings.get('skip_current_file') == True: if f.id() == self.window.active_view().id(): continue self.open_views.append(f) # add the view object file_name = f.file_name() # get the full path if file_name: if f.is_dirty(): file_name += self.settings.get('mark_dirty_file_char') # if there are any unsaved changes to the file if self.settings.get('show_full_file_path') == True: self.open_files.append(os.path.basename(file_name) + ' - ' + os.path.dirname(file_name)) else: self.open_files.append(os.path.basename(file_name)) else: self.open_files.append("Untitled") if self.check_for_sorting() == True: self.sort_files() self.window.show_quick_panel(self.open_files, self.tab_selected) # show the file list # display the selected open file def tab_selected(self, selected): if selected > -1: self.window.focus_view(self.open_views[selected]) return selected # sort the files for display in alphabetical order def sort_files(self): open_files = self.open_files open_views = [] open_files.sort() for f in open_files: for fv in self.open_views: if fv.file_name(): f = f.replace(" - " + os.path.dirname(fv.file_name()),'') if (f == os.path.basename(fv.file_name())) or (f == os.path.basename(fv.file_name())+self.settings.get('mark_dirty_file_char')): open_views.append(fv) self.open_views.remove(fv) if f == "Untitled" and not fv.file_name(): open_views.append(fv) self.open_views.remove(fv) self.open_views = open_views # flags for sorting def check_for_sorting(self): if self.settings.has("sort"): return self.settings.get("sort", False) def getViews(self, list_mode): views = [] # get only the open files for the active_group if list_mode == "active_group": views = self.window.views_in_group(self.window.active_group()) # get all open view if list_mode is window or active_group doesnt not have any files open if (list_mode == "window") or (len(views) < 1): views = self.window.views() return views
35.775148
148
0.561528
3.234375
dde98c3f791acaa29fe35bbe74233526f80de09f
11,917
lua
Lua
script/gui_settings_window.lua
eduran84/Train_Alerts
0b25aaf0a645055f1d7c809e89d245fc0f1dfd2b
[ "MIT" ]
null
null
null
script/gui_settings_window.lua
eduran84/Train_Alerts
0b25aaf0a645055f1d7c809e89d245fc0f1dfd2b
[ "MIT" ]
1
2019-05-08T10:24:36.000Z
2019-05-09T10:05:55.000Z
script/gui_settings_window.lua
eduran84/Train_Alerts
0b25aaf0a645055f1d7c809e89d245fc0f1dfd2b
[ "MIT" ]
null
null
null
-- load modules local EGM_Frame = require(defs.pathes.modules.EGM_Frame) --localize functions and variables local pairs, tonumber, floor, log2 = pairs, tonumber, math.floor, log2 local register_ui, unregister_ui = util.register_ui, util.unregister_ui local raise_private_event = raise_private_event local names = defs.names local styles = names.styles local element_names = names.gui.elements local offset = defs.constants.timeout_offset local col2state = { -1, defines.train_state.wait_signal, defines.train_state.wait_station, defines.train_state.no_path, defines.train_state.manual_control, defines.train_state.no_schedule, } -- localize access to relevant global variables local tsm local data = { frames = {}, tables = {}, table_rows = {}, ui_elements = {}, } -- UI functions -- local function build_frame(pind) if debug_mode then log2("Creating settings window for player", game.players[pind].name) end local frame = EGM_Frame.build( game.players[pind].gui.center, { name = element_names.setting_frame, caption = {"tral.setting-frame-caption"}, direction = "vertical", style = styles.alert_window_frame } ) frame.style.maximal_height = defs.constants.setting_frame_max_height register_ui( data.ui_elements, EGM_Frame.add_button(frame, { type = "sprite-button", style = styles.title_button, sprite = "utility/close_white", }), {name = "close_window"} ) frame.visible = false local flow = EGM_Frame.get_flow(frame) -- content flow of this frame flow.add{ type = "label", caption = {"tral.ignore-explainer-1"}, style = styles.helper_label, } flow.add{ type = "label", caption = {"tral.ignore-explainer-2"}, style = styles.helper_label, } local header_frame = flow.add{ type = "frame", style = styles.table_header_frame, } local spritelist = { [2] = "item/rail-signal", [3] = "item/train-stop", [4] = names.sprites.no_path, [5] = "utility/show_player_names_in_map_view", [6] = names.sprites.no_schedule, } header_frame.add{ type = "label", style = "caption_label", caption = {"tral.settings-col-header-1"} }.style.width = defs.constants.id_label_width header_frame.style.vertical_align = "center" for i = 2, 6 do local icon = header_frame.add{type = "flow", style = styles.image_flow}.add{ type = "sprite", sprite = spritelist[i], tooltip = {"tral.settings-col-header-tt-"..i} } end local table = flow.add{ type = "frame", style = styles.table_body_frame, }.add{ type = "scroll-pane", style = styles.table_pane, vertical_scroll_policy = "auto-and-reserve-space", horizontal_scroll_policy = "never", } return frame, table end local add_train_to_list -- defined later local function reset(pind) if debug_mode then log2("Resetting settings window for player #", pind, "\n", debug.traceback()) else log2("Resetting settings window for player #", pind) end local frame = data.frames[pind] if frame and frame.valid then unregister_ui(data.ui_elements, frame) frame.destroy() end frame = game.players[pind].gui.center[element_names.setting_frame] if frame and frame.valid then unregister_ui(data.ui_elements, frame) frame.destroy() end data.ui_elements[pind] = nil for _, table_row in pairs(data.table_rows) do table_row[pind] = nil end data.frames[pind], data.tables[pind] = build_frame(pind) for train_id, train_data in pairs(tsm.ignored_trains) do add_train_to_list({train_id = train_id}, pind) end end local function get_frame(pind) local frame = data.frames[pind] if frame and frame.valid then return frame end reset(pind) return data.frames[pind] end local function get_table(pind) local table = data.tables[pind] if table and table.valid then return table end reset(pind) return data.tables[pind] end local function open(pind) local frame = get_frame(pind) frame.visible = true game.players[pind].opened = frame end do local label_def = {type = "label", style = styles.id_label, caption = ""} local textbox_def = {} for i = 2, 6 do textbox_def[i] = {type = "text-box", style = styles.textbox_valid, text = ""} end add_train_to_list = function(event, pind) local train_id = event.train_id if train_id and (pind or not(data.table_rows[train_id])) then data.table_rows[train_id] = data.table_rows[train_id] or {} local label_action = {name = "train_label_clicked", train_id = train_id} label_def.caption = train_id local timeout_values = tsm.ignored_trains[train_id].timeout_values or shared.train_state_monitor.timeout_values local players if pind then players = {[pind] = true} else players = game.players end for i = 2, 6 do local timeout = timeout_values[col2state[i]] textbox_def[i].text = timeout >= 0 and (timeout - offset) / 60 or -1 end local textbox_action = {name = "timeout_text_changed", train_id = train_id} for pind in pairs(players) do local flow = get_table(pind).add{ type = "flow", direction = "horizontal", style = styles.table_row_flow } data.table_rows[train_id][pind] = {flow = flow, invalid_count = 0, was_valid = {}} local flow_add = flow.add register_ui(data.ui_elements, flow_add(label_def), label_action) for _, tb in pairs(textbox_def) do local box = flow_add(tb) register_ui(data.ui_elements, box, textbox_action) data.table_rows[train_id][pind].was_valid[box.index] = true end register_ui( data.ui_elements, flow_add{ type = "sprite-button", sprite = "utility/confirm_slot", style = "slot_button", tooltip = {"tral.settings-apply-tt"}, }, {name = "confirm_timeouts", train_id = train_id} ) register_ui( data.ui_elements, flow_add{ type = "sprite-button", sprite = "utility/set_bar_slot", style = "slot_button", tooltip = {"tral.settings-reset-tt"}, }, {name = "reset_timeouts", train_id = train_id} ) end end if not pind and event.player_index then open(event.player_index) end end end local function remove_train_from_list(event) local train_id = event.train_id local train = tsm.ignored_trains[train_id].train tsm.ignored_trains[train_id] = nil if data.table_rows[train_id] then for pind in pairs(game.players) do local row = data.table_rows[train_id][pind].flow unregister_ui(data.ui_elements, row) if row and row.valid then row.destroy() end end data.table_rows[train_id] = nil if train and train.valid then raise_private_event(defs.events.on_timeouts_modified, {train = train, force = true}) end end end -- event handlers -- local gui_actions = {} function gui_actions.close_window(event, action) get_frame(event.player_index).visible = false end function gui_actions.train_label_clicked(event, action) local train_id = action.train_id if event.button == 2 and tsm.ignored_trains[train_id] then --LMB util.train.open_train_gui(event.player_index, tsm.ignored_trains[train_id].train) local frame = get_frame(event.player_index) frame.visible = true else event.train_id = train_id remove_train_from_list(event) end end function gui_actions.timeout_text_changed(event, action) local box = event.element local num = tonumber(box.text) local player_data = data.table_rows[action.train_id][event.player_index] local was_valid = player_data.was_valid[box.index] local is_valid = num and num == floor(num) and num >= -1 if is_valid and not was_valid then -- turned valid box.style = styles.textbox_valid player_data.invalid_count = player_data.invalid_count - 1 player_data.was_valid[box.index] = is_valid if player_data.invalid_count == 0 then box.parent.children[7].enabled = true -- children[7] is the checkmark button end elseif not is_valid and was_valid then -- turned invalid box.style = styles.textbox_invalid player_data.invalid_count = player_data.invalid_count + 1 box.parent.children[7].enabled = false player_data.was_valid[box.index] = is_valid end end function gui_actions.confirm_timeouts(event, action) local train_id = action.train_id local flow = event.element.parent tsm.ignored_trains[train_id].timeout_values = {} for i = 2, 6 do local timeout = tonumber(flow.children[i].text) if timeout >= 0 then timeout = timeout * 60 + offset end tsm.ignored_trains[train_id].timeout_values[col2state[i]] = timeout end if debug_mode then log2("New timeouts:", tsm.ignored_trains[train_id].timeout_values) end raise_private_event(defs.events.on_timeouts_modified, {train = tsm.ignored_trains[train_id].train, force = true}) for pind, player in pairs(game.players) do if pind ~= event.player_index then gui_actions.reset_timeouts({player_index = pind, element = event.element}, {train_id = train_id}) end end end gui_actions.reset_timeouts = function(event, action) local timeout_values = tsm.ignored_trains[action.train_id].timeout_values or shared.train_state_monitor.timeout_values local flow = event.element.parent local player_data = data.table_rows[action.train_id][event.player_index] for i = 2, 6 do local timeout = timeout_values[col2state[i]] local box = flow.children[i] box.text = timeout >=0 and (timeout - offset) / 60 or -1 box.style = styles.textbox_valid player_data.invalid_count = player_data.invalid_count - 1 player_data.was_valid[box.index] = true end end local on_gui_input = function(event) local element = event.element if not (element and element.valid) then return end local player_data = data.ui_elements[event.player_index] if not player_data then return end local action = player_data[element.index] if action then if debug_mode then log2("event:", event, "\nplayer data:", player_data, "action:", action) end gui_actions[action.name](event, action) return true end end local function on_gui_closed(event) if event.element and event.element.name == element_names.setting_frame then get_frame(event.player_index).visible = false elseif event.entity and event.entity.type == "locomotive" then local frame = get_frame(event.player_index) if frame.visible then game.players[event.player_index].opened = frame end end end local function on_player_created(event) reset(event.player_index) end -- public module API -- local events = { [defines.events.on_gui_click] = on_gui_input, [defines.events.on_gui_text_changed] = on_gui_input, [defines.events.on_player_created] = on_player_created, [defines.events.on_gui_closed] = on_gui_closed, } local private_events = { [defs.events.on_train_ignored] = add_train_to_list, [defs.events.on_train_does_not_exist] = remove_train_from_list, } local gui_settings_window = {} function gui_settings_window.on_init() global.gui_settings_window = global.gui_settings_window or data tsm = global.train_state_monitor for pind in pairs(game.players) do on_player_created({player_index = pind}) end end function gui_settings_window.on_load() data = global.gui_settings_window tsm = global.train_state_monitor end function gui_settings_window.get_events() return events end function gui_settings_window.get_private_events() return private_events end function gui_settings_window.on_configuration_changed(data) if data.mod_changes[defs.names.mod_name] then for pind in pairs(game.players) do reset(pind) end end end return gui_settings_window
31.278215
117
0.703113
3.046875
fd8226b2b9f7673d4e5338d36ff98453e9d99c5e
3,938
swift
Swift
Tests/OperationsTests/OperationsTests.swift
dreymonde/Operations
d069c90f405898b5ad3ee3250597065522ebf2f2
[ "MIT" ]
1
2018-03-06T12:32:44.000Z
2018-03-06T12:32:44.000Z
Tests/OperationsTests/OperationsTests.swift
dreymonde/Operations
d069c90f405898b5ad3ee3250597065522ebf2f2
[ "MIT" ]
null
null
null
Tests/OperationsTests/OperationsTests.swift
dreymonde/Operations
d069c90f405898b5ad3ee3250597065522ebf2f2
[ "MIT" ]
null
null
null
// // OperationsTests.swift // Operations // // Created by Oleg Dreyman on 3/6/18. // Copyright © 2018 Operations. All rights reserved. // import Foundation import XCTest import Operations class AsyncPutOperation : AsyncOperation { let number: Int let put: (Int) -> () init(number: Int, put: @escaping (Int) -> ()) { self.number = number self.put = put super.init() self.name = "put-\(number)" } deinit { print("Deinit", name ?? "UNK") } override func execute() { print(number, "Running") DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 0.5) { guard !self.isCancelled else { self.finish() return } self.put(self.number) self.finish() } } override func willFinish() { print(number, "Finishing...") } override func didFinish() { print(number, "Finished") } } class OperationsTests: XCTestCase { func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. //// XCTAssertEqual(Operations().text, "Hello, World!") } func testArray() { var ar: [Int] = [] let queue = CustomOperationQueue() .logging() queue.name = "test-array" let put1 = AsyncPutOperation(number: 1, put: { ar.append($0) }) put1.completionBlock = { print("Block 1") } let put2 = AsyncPutOperation(number: 2, put: { ar.append($0) }) let obsF = put1.observe(\.isFinished, options: [.old, .new]) { (_, change) in print("OP1", "isFinished", change.oldValue!, change.newValue!) } let obsE = put1.observe(\.isExecuting, options: [.old, .new]) { (_, change) in print("OP1", "isExecuting", change.oldValue!, change.newValue!) } let obsC = put1.observe(\.isCancelled, options: [.old, .new]) { (_, change) in print("OP1", "isCancelled", change.oldValue!, change.newValue!) } put2.addDependency(put1) let obsR = put2.observe(\.isReady, options: [.old, .new]) { (_, change) in print("OP2", "isReady", change.oldValue!, change.newValue!) } unwarn(obsF, obsE, obsC, obsR) let expectation = self.expectation(description: "waiting on put2") put2.completionBlock = { print(ar) expectation.fulfill() } queue.addOperation(put1) queue.addOperation(put2) waitForExpectations(timeout: 5.0) XCTAssertEqual(ar, [1, 2]) } func testAsyncBlock() { let queue = CustomOperationQueue() .logging() queue.name = "test-async-block" var str: String? let block = AsyncBlockOperation { finish in DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 0.2, execute: { str = "Hey" finish() }) } let expectation = self.expectation(description: "block") block.completionBlock = { expectation.fulfill() } queue.addOperation(block) waitForExpectations(timeout: 5.0) XCTAssertEqual(str, "Hey") } func testCancel() { let queue = OperationQueue(name: "test-cancel") let op = BlockOperation { print("so-so") } op.cancel() let expectation = self.expectation(description: "on cancelled") op.completionBlock = { expectation.fulfill() } queue.addOperation(op) waitForExpectations(timeout: 5.0) } static var allTests = [ ("testExample", testExample), ] } func unwarn(_ obj: Any...) { return }
28.955882
96
0.548502
3.15625
bcaa88ec1d5cfba9123381cd5c24f3224e6e9979
1,204
js
JavaScript
devsrc/src/js/actions/heights.js
jios325/lan-smart-cancun
4572f2524f4f54a532da9acc6c7e233a54410744
[ "MIT" ]
null
null
null
devsrc/src/js/actions/heights.js
jios325/lan-smart-cancun
4572f2524f4f54a532da9acc6c7e233a54410744
[ "MIT" ]
null
null
null
devsrc/src/js/actions/heights.js
jios325/lan-smart-cancun
4572f2524f4f54a532da9acc6c7e233a54410744
[ "MIT" ]
null
null
null
$(document).ready(function () { //llama funciones de alturas en primer load if ($(window).width() >= 1024) { //desktop removeHeightHomeHeader() } else{ heightHomeHeader() } //llama funciones de alturas en resize de ventana $(window).resize(function () { if ($(window).width() >= 1024) { // de escritorio a mobile removeHeightHomeHeader() } else { // pasa de mobile a escritorio heightHomeHeader() } }).resize() //fix de chrome function calcVH($class) { var vH = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); document.getElementById($class).setAttribute("style", "height:" + vH + "px;"); } function removeH($class){ document.getElementById($class).removeAttribute("style"); } function heightHomeHeader(){ if($('#main-section-home').length){ calcVH('main-section-home'); window.addEventListener('onorientationchange', calcVH, true); } } function removeHeightHomeHeader(){ if($('#main-section-home').length){ removeH('main-section-home'); } } })
30.1
88
0.580565
3.03125
296bfafad9ff8c7a18b0d6faac1d434f8d555762
11,080
asm
Assembly
2.asm
AsadKhalil/Assembly_x86
48aa2a0ab93fd359f5f20369bb9064052c2f2884
[ "MIT" ]
null
null
null
2.asm
AsadKhalil/Assembly_x86
48aa2a0ab93fd359f5f20369bb9064052c2f2884
[ "MIT" ]
null
null
null
2.asm
AsadKhalil/Assembly_x86
48aa2a0ab93fd359f5f20369bb9064052c2f2884
[ "MIT" ]
null
null
null
[org 0x0100] jmp start ;each queue has a size of 32 words = 64 bytes = 512 bits Queue: times 512 dw 0 flag: dw 0 ;each bit of the flag is used to represent the state ;of the corresponding flag ;========================================= ;qcreate function returns the queue number ;if it finds a free queue or -1 if it ;failed. found: push word 1 jmp endqfunc notfound: push word -1 jmp endqfunc qcreate: push bp ;saving the value of bp mov bp, sp ;moving the value of sp into bp for having a reference in stack push ax ;saving thr value of ax push bx ;saving the value of bx push cx ;saving the value of cx mov bx, -64 ;initializing bx with -64 mov ax, 0 ;initializing ax with 0 mov cx, 0 ;initializing cx with 0 loop1: add bx, 64 mov ax, [Queue + bx + 62];rear cmp ax, 30 jnz skipqc mov ax, 1 jmp compare skipqc: inc ax compare: cmp ax, [Queue + bx] jnz found inc cx cmp cx, 15 jz notfound jmp loop1 endqfunc: pop cx pop bx pop ax pop bp ret ;========================================= ;========================================= ;qdestroy marks the queue as free. ;It is assumed that by marking the queue ;free means that queue is reset to empty queue ;and the its corresponding value in flag variable ;is updated. It also takes Queue number as parameter. qdestroy: push bp ;saving the value of bp mov bp, sp ;moving the value of sp into bp for having a reference in stack push ax ;saving thr value of ax push bx ;saving the value of bx push cx ;saving the value of cx push dx ;saving the value of dx ;initializing registers mov ax, 64 mov bx, 0 mov cx, 0 mov dx, 0 ;moving the parameter in bx register mov bx, [bp + 4] mul bx mov bx, ax l1: mov word [Queue + bx], 0 add bx, 2 inc cx cmp cx, 32 jnz l1 ;updating the value of this queue in the flag variable mov ax, [flag] mov bx, [bp + 4] ;moving Queue number in bx mov cx, 1 ;reseting cx register cmp cx, bx l2: rol ax, 1 inc cx cmp cx, bx jb l2 skip1: sub dx, dx ;generating zero in the carry flag rcr ax, 1 mov cx, 1 cmp cx, bx ja skip2 l3: ror ax, 1 inc cx cmp cx, bx jbe l3 skip2: mov word [flag], ax ;ending function pop dx pop cx pop bx pop ax pop bp ret 2 ;========================================= ;========================================= ;This function sets the specified bit of ;flag variable to 0. setzero: push bp mov bp, sp push ax push bx push cx push dx mov ax, [flag] mov bx, [bp + 4] mov cx, 1 ;reseting cx register cmp cx, bx ;ja skip1b l2c: rol ax, 1 inc cx cmp cx, bx jb l2c skip1b: mov dx, 5 sub dx, dx rcr ax, 1 mov cx, 1 cmp cx, bx ja skip2c l3c: ror ax, 1 inc cx cmp cx, bx jbe l3c skip2c: mov word [flag], ax ;ending function pop dx pop cx pop bx pop ax pop bp ret 2 ;========================================= ;This function sets the specified bit of ;flag variable to 1. setbit: push bp mov bp, sp push ax push bx push cx push dx mov ax, [flag] mov bx, [bp + 4] mov cx, 1 ;reseting cx register cmp cx, bx ja skip1a l2b: rol ax, 1 inc cx cmp cx, bx jbe l2b skip1a: mov dl, 5 mov dh, 10 sub dl, dh rcr ax, 1 mov cx, 1 cmp cx, bx ja skip2b l3b: ror ax, 1 inc cx cmp cx, bx jbe l3b skip2b: mov word [flag], ax ;ending function pop dx pop cx pop bx pop ax pop bp ret 2 ;========================================= ;This function returns 1 if insertion is ;possible other wise -1. checkinpos: push bp mov bp, sp push ax mov ax, 0 mov ax, [bp + 4] ;moving rear cmp ax, 30 jz skipc inc ax jmp rempart skipc: mov ax, 1 rempart: cmp ax, [bp + 6] ;comparing it with front jz notpossible mov word [bp + 8], 1 jmp endc notpossible: mov word [bp + 8], -1 endc: pop ax pop bp ret 4 ;========================================= ;========================================= ;This function checks if qremove is possible checkrempos: push bp mov bp, sp push ax mov ax, 0 mov ax, [bp + 6] ;moving front cmp ax, 30 jz skipd inc ax jmp rempart2 skipd: mov ax, 1 rempart2: cmp ax, [bp + 4] ja notpossible2 mov word [bp + 8], 1 jmp endd notpossible2: mov word [bp + 8], -1 endd: pop ax pop bp ret 4 ;========================================= ;========================================= ;This function is used to remove items from ;the circular queue. qremove: push bp ;saving the value of bp mov bp, sp ;moving the value of sp into bp for having a reference in stack push ax ;saving thr value of ax push bx ;saving the value of bx push cx ;saving the value of cx push dx ;saving the value of dx push si ;saving the value of si ;initializing registers mov ax, 64 mov bx, 0 mov cx, 0 mov dx, 0 mov si, 0 ;moving queue number in bx register mov bx, [bp + 4] mul bx mov bx, ax checkqr: sub sp, 2 mov ax, [Queue + bx] ;Queue front push ax mov cx, ax mov ax, [Queue + bx + 62] ;Queue rear push ax call checkrempos pop dx cmp dx, 1 jnz notapplicable2 jmp applicable2 notapplicable2: mov word [bp + 6], 0 jmp endrem applicable2: mov word [bp + 6], 1 mov ax, [Queue + bx] mov si, 2 mul si mov si, ax mov word [Queue + bx + si], 0 mov word ax, [Queue + bx] cmp ax, 30 jnz skipq mov ax, 1 jmp placefront skipq: inc ax placefront: mov [Queue + bx], ax checkifreset: cmp cx, [Queue + bx + 62] jnz endrem mov word[Queue + bx], 0 mov word[Queue + bx + 62], 0 push word [bp + 4] call setzero endrem: pop si pop dx pop cx pop bx pop ax pop bp ret 2 ;========================================= ;========================================= ;This function is used to add items in the ;circular queue. A real circular queue is ;dynamic but according to this question ;the circular queue is static. qadd: push bp ;saving the value of bp mov bp, sp ;moving the value of sp into bp for having a reference in stack push ax ;saving thr value of ax push bx ;saving the value of bx push cx ;saving the value of cx push dx ;saving the value of dx push si ;saving the value of si ;initializing registers mov ax, 64 mov bx, 0 mov cx, 0 mov dx, 0 mov si, 0 ;moving queue number in bx register mov bx, [bp + 4] mul bx mov bx, ax check1: sub sp, 2 mov ax, [Queue + bx] push ax mov ax, [Queue + bx + 62] push ax call checkinpos pop dx cmp dx, 1 jz applicable notapplicable: mov word [bp + 8], 0 jmp endaddfunc skipb: mov ax, 1 jmp skipad applicable: cmp word [Queue + bx + 62], 1 jnz skip4d cmp word [Queue + bx], 1 jnz skip4d push word [bp + 4] call setbit skip4d: mov ax, [Queue + bx + 62] cmp ax, 30 jz skipb inc ax skipad: mov word [Queue + bx + 62], ax mov si, 2 mul si mov si, ax mov ax, [bp + 6] ;moving data parameter in ax mov word [Queue + bx + si], ax mov word [bp + 8], 1 mov ax, [Queue + bx] cmp ax, 0 jnz endaddfunc inc ax mov [Queue + bx], ax endaddfunc: pop si pop dx pop cx pop bx pop ax pop bp ret 4 ;========================================= start: sub sp, 2 call qcreate pop dx mov ax, 2 push ax call qdestroy sub sp, 2 mov ax, 0xA ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xB ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xC ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xD ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xE ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xF ;item to add push ax mov ax, 0 ;queue number push ax call qadd sub sp, 2 call qcreate pop dx mov ax, 0xAA ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xAB ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xAC ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xAD ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xAE ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xAF ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xBA ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xBB ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xBC ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xBD ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xBE ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xBF ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xCA ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xCB ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xCC ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xCD ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xCE ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xCF ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xDA ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xDB ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xDC ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xDD ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xDE ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xDF ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0xEA ;item to add push ax mov ax, 0 ;queue number push ax sub sp, 2 call qcreate pop dx call qadd push word 0 call qremove push word 0 call qremove push word 0 call qremove mov ax, 0x11 ;item to add push ax mov ax, 0 ;queue number push ax call qadd mov ax, 0x33 ;item to add push ax mov ax, 0 ;queue number push ax call qadd finish: mov ax, 0x04c00 int 21h
13.628536
76
0.562906
3.453125
357e2075c1ba2bc376295cdd8f8bff7b151585d1
1,391
lua
Lua
modules/Mutex/Mutex.lua
Anaminus/roblox-library
64fb523224fd72fefadd572d252b867254b1872a
[ "Unlicense" ]
31
2020-03-30T05:44:17.000Z
2022-02-07T06:57:16.000Z
modules/Mutex/Mutex.lua
Anaminus/roblox-library
64fb523224fd72fefadd572d252b867254b1872a
[ "Unlicense" ]
2
2020-08-17T11:29:11.000Z
2021-12-13T18:04:13.000Z
modules/Mutex/Mutex.lua
Anaminus/roblox-library
64fb523224fd72fefadd572d252b867254b1872a
[ "Unlicense" ]
6
2020-07-29T21:04:01.000Z
2021-09-09T03:01:40.000Z
--@sec: Mutex --@def: function Mutex(): Mutex --@doc: Mutex is a mutual exclusion lock. local Mutex = {__index={}} --@sec: Mutex.Lock --@def: function Mutex:Lock() --@doc: Lock locks the mutex. If the lock is already in use, then the calling -- thread is blocked until the lock is available. function Mutex.__index:Lock() table.insert(self.threads, coroutine.running()) if #self.threads > 1 then coroutine.yield() end end --@sec: Mutex.Unlock --@def: function Mutex:Unlock() --@doc: Unlock unlocks the mutex. If threads are blocked by the mutex, then the -- next blocked thread will be resumed. function Mutex.__index:Unlock() local thread = table.remove(self.threads, 1) if not thread then error("attempt to unlock non-locked mutex", 2) end if #self.threads == 0 then return end thread = self.threads[1] task.defer(thread) end --@sec: Mutex.Wrap --@def: function Mutex:Wrap(func: (...any)->(...any)): (...any)->(...any) --@doc: Wrap returns a function that, when called, locks the mutex before *func* -- is called, and unlocks it after *func* returns. The new function receives and -- returns the same parameters as *func*. function Mutex.__index:Wrap(func) return function(...) self:Lock() local results = table.pack(func(...)) self:Unlock() return table.unpack(results, 1, results.n) end end return function() return setmetatable({threads = {}}, Mutex) end
27.82
80
0.700935
3.28125
cbbc09eb52ee7284bfb474e794a9731810c0db62
1,211
go
Go
device/edison_posix.go
xshellinc/iotit
42f4cdaafd3fdc378c6e4461889ae1cf2575f57e
[ "Apache-2.0" ]
33
2017-03-04T05:15:20.000Z
2022-03-26T06:20:58.000Z
device/edison_posix.go
xshellinc/iotit
42f4cdaafd3fdc378c6e4461889ae1cf2575f57e
[ "Apache-2.0" ]
88
2017-02-07T05:57:42.000Z
2021-07-26T22:59:42.000Z
device/edison_posix.go
xshellinc/iotit
42f4cdaafd3fdc378c6e4461889ae1cf2575f57e
[ "Apache-2.0" ]
1
2017-10-17T06:57:28.000Z
2017-10-17T06:57:28.000Z
// +build !windows package device import ( "fmt" "os" "time" log "github.com/sirupsen/logrus" "github.com/xshellinc/iotit/device/config" "github.com/xshellinc/iotit/vbox" "github.com/xshellinc/tools/dialogs" "github.com/xshellinc/tools/lib/help" ) func (d *edison) Prepare() error { if err := d.flasher.Prepare(); err != nil { return err } for !dialogs.YesNoDialog("Please unplug your Edison board. Type yes once unpluged.") { } return nil } func (d *edison) Write() error { for { script := "flashall.sh" args := []string{ fmt.Sprintf("%s@%s", vbox.VBoxUser, vbox.VBoxIP), "-p", vbox.VBoxSSHPort, config.TmpDir + script, } if err := help.ExecStandardStd("ssh", args...); err != nil { fmt.Println("[-] Can't find Intel Edison board, please try to re-connect it") if !dialogs.YesNoDialog("Type yes once connected.") { fmt.Println("Exiting with exit status 2 ...") os.Exit(2) } continue } break } if err := d.conf.Stop(d.Quiet); err != nil { log.Error(err) } job := help.NewBackgroundJob() go func() { defer job.Close() time.Sleep(120 * time.Second) }() help.WaitJobAndSpin("Your Edison board is restarting...", job) return nil }
19.852459
87
0.646573
3.203125
4154c1d7849b2da752e89f5b237532935106fdc4
1,849
c
C
DSA/revAsingleLL.c
atig05/HACKTOBERFEST-2021
a13b4a72c3c13760643f0f2aa4d5dcd8bf2c79dc
[ "MIT" ]
2
2021-10-02T16:48:56.000Z
2021-10-02T17:14:26.000Z
DSA/revAsingleLL.c
atig05/HACKTOBERFEST-2021
a13b4a72c3c13760643f0f2aa4d5dcd8bf2c79dc
[ "MIT" ]
3
2021-10-30T17:35:27.000Z
2021-10-31T13:43:04.000Z
DSA/revAsingleLL.c
atig05/HACKTOBERFEST-2021
a13b4a72c3c13760643f0f2aa4d5dcd8bf2c79dc
[ "MIT" ]
4
2021-10-30T08:55:42.000Z
2021-11-10T04:37:51.000Z
#include<stdio.h> #include<stdlib.h> struct Node { char data; struct Node * link; }; struct Node * head = NULL; void Create() { int n; struct Node *ptr, *Cptr; printf("Enter the number of nodes: "); scanf("%d",&n); if(n == 0) return; ptr = (struct Node *)calloc(1,sizeof(struct Node)); printf("Enter data: "); scanf("%d",&ptr->data); head = ptr; for(int i = 2; i <= n; i++) { Cptr = (struct Node *)calloc(1,sizeof(struct Node)); printf("Enter data: "); scanf("%d",&Cptr->data); ptr->link = Cptr; ptr = Cptr; } ptr->link = NULL; } //loop takes n iterations so has O(n) time. void Display() { struct Node * ptr; ptr = head; while(ptr->link != NULL) { printf("%d->",ptr->data); ptr = ptr->link; } printf("%d",ptr->data); printf("\n\n"); } //recursion also takes O(n) time as well as space complexity. //As recursion takes place in system stack it takes more space than looping void recursive_display(struct Node *ptr) { if(ptr != NULL) { printf("%d ",ptr->data); recursive_display(ptr->link); } } void recursive_rev_display(struct Node *ptr) { if(ptr != NULL) { recursive_rev_display(ptr->link); printf("%d ",ptr->data); } } void reverse() { struct Node *current, *next, *prev; current = head; prev = NULL; while(current != NULL) { next = current->link; current->link = prev; prev = current; current = next; } head = prev; } int main() { Create(); printf("The main list: "); Display(); recursive_display(head); printf("\n"); recursive_rev_display(head); printf("\n"); reverse(); printf("The reversed list: "); Display(); return 0; }
19.061856
75
0.541374
3.109375
8cb5ca9673700d888be3756b535271891c2f8b92
1,471
sql
SQL
SQL/Lab1.sql
andrei-micuda/teme-fmi
d31c032c45e0e910d75fc05faab3681d421aac7c
[ "MIT" ]
1
2020-06-07T09:45:17.000Z
2020-06-07T09:45:17.000Z
SQL/Lab1.sql
micu01/teme-fmi
d31c032c45e0e910d75fc05faab3681d421aac7c
[ "MIT" ]
null
null
null
SQL/Lab1.sql
micu01/teme-fmi
d31c032c45e0e910d75fc05faab3681d421aac7c
[ "MIT" ]
2
2020-04-09T19:27:36.000Z
2020-06-28T17:45:14.000Z
--LAB 1 --a DESCRIBE EMPLOYEES; --c SELECT * FROM EMPLOYEES; --e SELECT EMPLOYEE_ID, FIRST_NAME || ' ' || LAST_NAME AS NAME, JOB_ID, HIRE_DATE FROM EMPLOYEES; --f SELECT LAST_NAME || ', ' || JOB_ID AS "Angajat si titlu" FROM EMPLOYEES; --g SELECT EMPLOYEE_ID || ',' || FIRST_NAME || ',' || LAST_NAME || ',' || EMAIL || ',' || PHONE_NUMBER || ',' || HIRE_DATE || ',' || JOB_ID || ',' || SALARY || ',' || COMMISSION_PCT || ',' || MANAGER_ID || ',' || DEPARTMENT_ID AS "Informatii complete" FROM EMPLOYEES; --h SELECT TO_CHAR(SYSDATE, 'DD/MM/YYYY HH24:MI') FROM DUAL; --j SELECT EMPLOYEE_ID, LAST_NAME, TO_CHAR(HIRE_DATE, 'DAY') AS "DAY HIRED" FROM EMPLOYEES; --k SELECT * FROM EMPLOYEES ORDER BY TO_CHAR(HIRE_DATE, 'YYYY'), TO_CHAR(HIRE_DATE, 'DDD'); --l SELECT LAST_NAME, SALARY FROM EMPLOYEES WHERE SALARY > 2850 ORDER BY SALARY; --m SELECT LAST_NAME, JOB_ID, HIRE_DATE FROM EMPLOYEES WHERE HIRE_DATE > TO_DATE('20-FEB-87') AND HIRE_DATE < TO_DATE('01-MAY-89'); --n SELECT FIRST_NAME || ' ' || LAST_NAME AS NAME, DEPARTMENT_ID FROM EMPLOYEES WHERE DEPARTMENT_ID IN (10, 30, 50) ORDER BY LAST_NAME; --o SELECT LAST_NAME, JOB_ID, SALARY FROM EMPLOYEES WHERE ( JOB_ID LIKE '%CLERK%' OR JOB_ID LIKE '%REP%' ) AND SALARY NOT IN (1000, 2000, 3000); --p SELECT LAST_NAME, JOB_ID FROM EMPLOYEES WHERE MANAGER_ID IS NULL; --q SELECT LAST_NAME, SALARY, COMMISSION_PCT FROM EMPLOYEES WHERE SALARY > (SALARY * COMMISSION_PCT) * 5;
20.71831
247
0.670972
3.03125
5b4b54def1a93b161d88ba6d6ba2a33176a89f7c
3,100
c
C
CryptoPkg/Library/BaseCryptLibNull/Pk/CryptRsaBasicNull.c
KaoTuz/edk2-stable202108
49d9306e7bf64b2f07d8473be1f2faea49d0a012
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
9
2021-07-26T17:02:51.000Z
2021-12-30T10:49:46.000Z
CryptoPkg/Library/BaseCryptLibNull/Pk/CryptRsaBasicNull.c
ESdove/edk2_exploring
34ff32b45f43d233d9696e7c8e3de68ea3000a7b
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
null
null
null
CryptoPkg/Library/BaseCryptLibNull/Pk/CryptRsaBasicNull.c
ESdove/edk2_exploring
34ff32b45f43d233d9696e7c8e3de68ea3000a7b
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
null
null
null
/** @file RSA Asymmetric Cipher Wrapper Null Implementation. This file implements following APIs which provide basic capabilities for RSA: 1) RsaNew 2) RsaFree 3) RsaSetKey 4) RsaPkcs1Verify Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "InternalCryptLib.h" /** Allocates and initializes one RSA context for subsequent use. @return Pointer to the RSA context that has been initialized. If the allocations fails, RsaNew() returns NULL. **/ VOID * EFIAPI RsaNew ( VOID ) { // // Allocates & Initializes RSA Context // ASSERT (FALSE); return NULL; } /** Release the specified RSA context. @param[in] RsaContext Pointer to the RSA context to be released. **/ VOID EFIAPI RsaFree ( IN VOID *RsaContext ) { // // Free RSA Context // ASSERT (FALSE); } /** Sets the tag-designated key component into the established RSA context. This function sets the tag-designated RSA key component into the established RSA context from the user-specified non-negative integer (octet string format represented in RSA PKCS#1). If BigNumber is NULL, then the specified key component in RSA context is cleared. If RsaContext is NULL, then return FALSE. @param[in, out] RsaContext Pointer to RSA context being set. @param[in] KeyTag Tag of RSA key component being set. @param[in] BigNumber Pointer to octet integer buffer. If NULL, then the specified key component in RSA context is cleared. @param[in] BnSize Size of big number buffer in bytes. If BigNumber is NULL, then it is ignored. @retval TRUE RSA key component was set successfully. @retval FALSE Invalid RSA key component tag. **/ BOOLEAN EFIAPI RsaSetKey ( IN OUT VOID *RsaContext, IN RSA_KEY_TAG KeyTag, IN CONST UINT8 *BigNumber, IN UINTN BnSize ) { ASSERT (FALSE); return FALSE; } /** Verifies the RSA-SSA signature with EMSA-PKCS1-v1_5 encoding scheme defined in RSA PKCS#1. If RsaContext is NULL, then return FALSE. If MessageHash is NULL, then return FALSE. If Signature is NULL, then return FALSE. If HashSize is not equal to the size of MD5, SHA-1 or SHA-256 digest, then return FALSE. @param[in] RsaContext Pointer to RSA context for signature verification. @param[in] MessageHash Pointer to octet message hash to be checked. @param[in] HashSize Size of the message hash in bytes. @param[in] Signature Pointer to RSA PKCS1-v1_5 signature to be verified. @param[in] SigSize Size of signature in bytes. @retval TRUE Valid signature encoded in PKCS1-v1_5. @retval FALSE Invalid signature or invalid RSA context. **/ BOOLEAN EFIAPI RsaPkcs1Verify ( IN VOID *RsaContext, IN CONST UINT8 *MessageHash, IN UINTN HashSize, IN CONST UINT8 *Signature, IN UINTN SigSize ) { ASSERT (FALSE); return FALSE; }
25.409836
90
0.676452
3.15625
ea311e4bd0560e4ffa887219be017d381094ad20
1,041
swift
Swift
SwiftLog/Closure/main.swift
BigRhino/MyRhino
661043d07226f7ede716c7983ad99daec1dd246c
[ "MIT" ]
null
null
null
SwiftLog/Closure/main.swift
BigRhino/MyRhino
661043d07226f7ede716c7983ad99daec1dd246c
[ "MIT" ]
null
null
null
SwiftLog/Closure/main.swift
BigRhino/MyRhino
661043d07226f7ede716c7983ad99daec1dd246c
[ "MIT" ]
1
2018-12-18T06:46:31.000Z
2018-12-18T06:46:31.000Z
// // main.swift // Closure // // Created by iMac on 2017/11/8. // Copyright © 2017年 iMac. All rights reserved. // import Foundation let volunteerCounts = [1,340,32,2,53,77,14] func sortAsending(_ i:Int,_ j:Int) -> Bool{ return i < j } //print(volunteerCounts.sorted(by: sortAsending)) print(volunteerCounts.sorted(by: { (a, b) -> Bool in return a > b })) print(volunteerCounts.sorted(by: { i,j in i > j })) print(volunteerCounts.sorted(by: {$0 < $1})) print(volunteerCounts.map({ (number) -> Int in return number * 10 }) ) func makeTownGrand() -> (Int,Int) ->Int{ func buildRoads(byAddingLights lights:Int, toExistingLights existingLights:Int)->Int{ return lights + existingLights } return buildRoads } var stoplights = 4 let townPlanByAddingLightsToExistingLights = makeTownGrand() stoplights = townPlanByAddingLightsToExistingLights(4, stoplights) print("Knowhere has \(stoplights) stoplights.") //逃匿闭包 //当一个闭包作为函数的参数,这个闭包在函数执行返回之后,才执行,就叫做逃匿闭包
16.265625
66
0.669549
3.046875
7423d521e2d2e8b66d7c3008d28851b19586f543
1,222
rs
Rust
examples/traverse_comment_tree.rs
Hyde46/reddit_api_rs
036010d95123a804a6f8100ced2d37b29c3260ec
[ "MIT" ]
4
2020-07-24T10:59:17.000Z
2021-08-31T15:27:42.000Z
src/bin.rs
Hyde46/reddit_api_rs
036010d95123a804a6f8100ced2d37b29c3260ec
[ "MIT" ]
null
null
null
src/bin.rs
Hyde46/reddit_api_rs
036010d95123a804a6f8100ced2d37b29c3260ec
[ "MIT" ]
null
null
null
extern crate rsreddit; use rsreddit::client::Reddit; use rsreddit::model::listing::Listing; use rsreddit::model::listing::ListingCollection; fn main() { // Get Comment Tree for a thread by its permalink let reddit = Reddit::default().build(); let tree = reddit .thread_by_permalink("/r/rust/comments/hwuvmf/swc_now_works_with_stable_rustc/") .unwrap(); print_comment_tree(&tree); } fn print_comment_tree(tree: &ListingCollection) { //print Thread Title println!( "Title: {}", tree.listings[0].data.children[0] .data .title .as_ref() .unwrap() ); //Print comments recursivley travers_comment_tree(&tree.listings[1], 0); } fn travers_comment_tree(comment: &Listing, tab_count: usize) { comment.data.children.iter().for_each(|c| { //Generate right amount if identation let tabs = std::iter::repeat(" ").take(tab_count).collect::<String>(); //Print comment println!("{}>{}", tabs, c.data.body.as_ref().unwrap()); //Go a level deeper if let Some(replies) = &c.data.replies { travers_comment_tree(replies, tab_count + 1); } }); }
29.095238
88
0.61293
3.140625
2da1c0ec779633142c70b9d9c5abc3faaa7a078a
4,868
lua
Lua
authentication/players.lua
violencedev/cegui-authentication
c14f3db9aee44a8dd8dcb23070ae61055779637f
[ "MIT" ]
5
2021-12-19T19:36:43.000Z
2022-02-14T18:24:32.000Z
authentication/players.lua
violencedev/cegui-authentication
c14f3db9aee44a8dd8dcb23070ae61055779637f
[ "MIT" ]
null
null
null
authentication/players.lua
violencedev/cegui-authentication
c14f3db9aee44a8dd8dcb23070ae61055779637f
[ "MIT" ]
1
2021-12-29T23:36:00.000Z
2021-12-29T23:36:00.000Z
local db = exports["database"]:getConnection() addEventHandler('onPlayerJoin', root, function() outputChatBox('#0000FF[!] #FFFFFFSunucuya hoş geldiniz!', source, 0, 255, 0, true) spawnPlayer(source, 0, 5, 0) fadeCamera(source, true, 12) triggerClientEvent(source, 'logIn:interface', source) setCameraMatrix(source, 1468.8785400391, -919.25317382813, 100.153465271, 1468.388671875, -918.42474365234, 99.881813049316) setPlayerHudComponentVisible(source, "radar", false) end) addEventHandler('onResourceStart', resourceRoot, function() outputDebugString('[authentication] kullanici hesaplari yukleniyor...') dbQuery(function(qH) local results = dbPoll(qH, 0) local i = 0 for _,v in pairs(results) do i = i + 1 table.insert(accounts, {id=v.id, username=v.username, password=v.password, email=v.email, serial=v.serial, ip=v.ip}) end setElementData(root, 'toplam:ac:loaded', i) end, db, 'SELECT * FROM accounts') outputDebugString('[authentication] toplam ' .. (tostring(getElementData(root, 'toplam:ac:loaded')) or "0") .. ' hesap basariyla yuklendi.') setElementData(root, 'toplam:ac:loaded', nil) if getElementData(root, 'toplam:ac:loaded') == 0 or getElementData(root, 'toplam:ac:loaded') == false then restartResource(getThisResource()) end end) addEvent('join:to:server', true) addEventHandler('join:to:server', root, function() setCameraTarget(client, client) fadeCamera(client, true, 3) outputChatBox('#0000FF[!] #FFFFFF' .. getElementData(client, 'account:username') .. ' isimli hesaba başarıyla giriş yaptınız.', client, 0, 255, 0, true) end) addEvent('kickHimup', true) addEventHandler('kickHimup', root, function(player) kickPlayer(player, player, 'Hesabiniza baska bir yerden erisim saglandi.') end) function register_attempt(kullaniciadi, sifre) if not isUSExists(kullaniciadi) == true then if string.len(sifre) > 4 then local serial, ip = getPlayerSerial(client), getPlayerIP(client) dbExec(db, 'INSERT INTO accounts(username, password, email, serial, ip) VALUES(?, ?, ?, ?, ?)', kullaniciadi, tostring(sifre), "", getPlayerSerial(client), getPlayerIP(client)) dbQuery(function(qH) local results = dbPoll(qH, 0) local id = results[1].id outputChatBox(id) table.insert(accounts, {id=id, username=kullaniciadi, password=sifre, email="", serial=serial, ip=ip}) end, db, "SELECT * FROM accounts ORDER BY id DESC LIMIT 1") redirect_to_sw(kullaniciadi, sifre, client) end end end addEvent('register:attempt', true) addEventHandler('register:attempt', root, register_attempt) function redirect_to_sw(kullaniciadi, sifre, pl) if isAccountExists(kullaniciadi, sifre) == true then -- giriş yaptır --setElementData(client, 'id', getAccountIDFromInfo(kullaniciadi, sifre)) -- id ayarlandı setElementData(pl, 'account:username', kullaniciadi) dbQuery(function(qH) local results = dbPoll(qH, 0) for k, v in pairs(results) do if v.username == kullaniciadi then setElementData(pl, 'money', (tonumber(v.money) or 0)) end end end, db, 'SELECT * FROM accounts') --setElementData(pl, 'oynadigi:hesap', getAccountObject(kullaniciadi, sifre)) triggerClientEvent(pl, 'recome:player', client) end end addEvent('redirect:player', true) addEventHandler('redirect:player', root, redirect_to_sw) function getAccountObject(username, password) for _,v in pairs(accounts) do if v.username == username and v.password ~= password then return v end end end function getAccountIDFromInfo(username, password) for _,v in pairs(accounts) do if v.username == username then if v.password ~= password then return (v.id) end end end end function anotherOneisPlayingInThatAccount(username, password) for _,v in pairs(getElementsByType('player')) do if getElementData(v, 'id') ~= getAccountIDFromInfo(username, password) then return v end end end function isUSExists(username) for _,v in pairs(accounts) do if v.username == username then return true end end end function isAccountExists(username, password) for _,v in pairs(accounts) do if v.username == username then if tostring(v.password) == tostring(password) then return true end end end end
38.330709
189
0.63106
3.09375
7fd606110f210ac73b79729939de2ecf15ee32b1
2,553
go
Go
torrent/storage.go
danalex97/nfsTorrent
1364d920aca0c1b656cd52ab1107e35801fae83f
[ "MIT" ]
1
2019-03-12T12:34:13.000Z
2019-03-12T12:34:13.000Z
torrent/storage.go
wade-welles/CacheTorrent
1364d920aca0c1b656cd52ab1107e35801fae83f
[ "MIT" ]
38
2018-04-11T08:47:07.000Z
2018-06-20T17:51:11.000Z
torrent/storage.go
wade-welles/CacheTorrent
1364d920aca0c1b656cd52ab1107e35801fae83f
[ "MIT" ]
1
2019-03-12T12:34:10.000Z
2019-03-12T12:34:10.000Z
package torrent import ( "github.com/danalex97/nfsTorrent/config" "github.com/danalex97/nfsTorrent/log" "sync" ) var pieceNumber config.Const = config.NewConst(config.StoragePieces) // Storage is a concurrent-safe piece storage module. The synchronization is // done via a read-write lock and the pieces are stored using a map. When the // download is finished it also notifies the Configuration module. type Storage interface { Have(index int) (PieceMeta, bool) Store(Piece) Pieces() []int } type storage struct { sync.RWMutex id string pieces map[int]PieceMeta // the pieces that I have completed bool // Used for logging time func() int // Used only for monitoring percents []int percentDone []bool } func NewStorage(id string, pieces []PieceMeta, time func() int) Storage { storage := new(storage) storage.id = id storage.completed = false storage.time = time storage.pieces = make(map[int]PieceMeta) for _, p := range pieces { storage.pieces[p.Index] = p } // Used only informatively. storage.percents = []int{2, 20, 50, 70} storage.percentDone = []bool{false, false, false, false} storage.checkCompleted() return storage } // Returns if I have a piece(I have it downloaded and stored). func (s *storage) Have(index int) (PieceMeta, bool) { s.RLock() defer s.RUnlock() p, ok := s.pieces[index] return p, ok } // Store a piece from a `piece` message. func (s *storage) Store(p Piece) { s.Lock() defer s.Unlock() s.pieces[p.Index] = PieceMeta{ p.Index, p.Begin, p.Piece.Size, } s.checkCompleted() } // Return a list of all indexes of the pieces currently stored. func (s *storage) Pieces() []int { s.RLock() defer s.RUnlock() pieces := []int{} for _, piece := range s.pieces { pieces = append(pieces, piece.Index) } return pieces } func (s *storage) checkCompleted() { // Only informative. for i := range s.percents { if s.percentDone[i] == false { if len(s.pieces) > pieceNumber.Int() * s.percents[i] / 100 { s.percentDone[i] = true log.Println(s.id, "Downloaded", s.percents[i], "%") } } } if len(s.pieces) >= pieceNumber.Int() && !s.completed { // Notify logger time := s.time() log.LogCompleted(log.Completed{ Id : s.id, Time : time, }) // Callback used to interact with the simulation config.Config.SharedCallback() // Notify completed log.Println(s.id, "Completed at", time, "ms") s.completed = true } }
21.275
77
0.648257
3.3125
c2b04aae7d92cb3f9d20de7ece645d49b1f99018
1,345
lua
Lua
[core]/dpGarage/client/MusicPlayer.lua
dcr30/drive-crew-mta
1bc6b1bf6520b1818c54b7fb9b75f97f9b290e69
[ "Apache-2.0" ]
16
2017-09-02T20:31:49.000Z
2020-06-07T20:59:55.000Z
[core]/dpGarage/client/MusicPlayer.lua
dcr30/drive-crew-mta
1bc6b1bf6520b1818c54b7fb9b75f97f9b290e69
[ "Apache-2.0" ]
1
2019-05-21T18:35:44.000Z
2019-05-21T18:35:44.000Z
[core]/dpGarage/client/MusicPlayer.lua
JluHeuKa/driftparadise-legacy
570ff6350a1960d531448c62ec10a0708f429c31
[ "Apache-2.0" ]
16
2018-02-18T16:39:35.000Z
2020-05-18T16:15:01.000Z
MusicPlayer = {} local MUSIC_VOLUME = 0.45 local TRACKS_COUNT = 10 local currentTrack = 1 local sound local soundVolume = 0 local soundVolumeSpeed = 5 local function playNextTrack() if not exports.dpConfig:getProperty("game.background_music") then return end currentTrack = currentTrack + 1 if currentTrack > TRACKS_COUNT then currentTrack = 1 end if isElement(sound) then destroyElement(sound) end sound = playSound("assets/music/" .. tostring(currentTrack) .. ".mp3", false) sound:setEffectEnabled("reverb", true) end local function update(dt) dt = dt / 1000 if not isElement(sound) then return end sound.volume = sound.volume + (soundVolume - sound.volume) * dt * soundVolumeSpeed end function MusicPlayer.start() addEventHandler("onClientSoundStopped", resourceRoot, playNextTrack) addEventHandler("onClientPreRender", root, update) currentTrack = math.random(1, TRACKS_COUNT) playNextTrack() if isElement(sound) then sound.volume = 0 sound.playbackPosition = math.random(0, sound.length * 0.7) end soundVolume = MUSIC_VOLUME end function MusicPlayer.fadeOut() soundVolume = 0 end function MusicPlayer.stop() removeEventHandler("onClientSoundStopped", resourceRoot, playNextTrack) removeEventHandler("onClientPreRender", root, update) if isElement(sound) then destroyElement(sound) end end
22.79661
83
0.765799
3.171875
ba2158456b72c1e6ffe0ebb7c0a7e891a9e71553
1,276
lua
Lua
internal/lua/graph.lua
prologic/LadyLua
d63e0310cadf21ad0157680d2d1ae8753a52bfc7
[ "MIT" ]
77
2021-04-08T13:17:05.000Z
2022-03-31T13:06:36.000Z
internal/lua/graph.lua
prologic/LadyLua
d63e0310cadf21ad0157680d2d1ae8753a52bfc7
[ "MIT" ]
2
2021-07-22T10:39:53.000Z
2021-11-01T14:02:13.000Z
internal/lua/graph.lua
prologic/LadyLua
d63e0310cadf21ad0157680d2d1ae8753a52bfc7
[ "MIT" ]
5
2016-04-06T01:30:51.000Z
2017-11-13T20:57:27.000Z
local setmetatable = setmetatable local pairs = pairs local type = type local function visit(k, n, m, s) if m[k] == 0 then return 1 end if m[k] == 1 then return end m[k] = 0 local f = n[k] for i=1, #f do if visit(f[i], n, m, s) then return 1 end end m[k] = 1 s[#s+1] = k end local tsort = {} tsort.__index = tsort function tsort.new() return setmetatable({ n = {} }, tsort) end function tsort:add(...) local p = { ... } local c = #p if c == 0 then return self end if c == 1 then p = p[1] if type(p) == "table" then c = #p else p = { p } end end local n = self.n for i=1, c do local f = p[i] if n[f] == nil then n[f] = {} end end for i=2, c, 1 do local f = p[i] local t = p[i-1] local o = n[f] o[#o+1] = t end return self end function tsort:sort() local n = self.n local s = {} local m = {} for k in pairs(n) do if m[k] == nil then if visit(k, n, m, s) then return nil, "There is a circular dependency in the graph. It is not possible to derive a topological sort." end end end return s end return tsort
22
123
0.492947
3.375
9c4f3aabb2d42e4de2a4d5bd205743baf8be454f
1,522
js
JavaScript
Conta.js
LukasSilva05/my-bank-js
4ca202c5053eb8af09e09e26295953f5f8c21fa4
[ "Apache-2.0" ]
null
null
null
Conta.js
LukasSilva05/my-bank-js
4ca202c5053eb8af09e09e26295953f5f8c21fa4
[ "Apache-2.0" ]
null
null
null
Conta.js
LukasSilva05/my-bank-js
4ca202c5053eb8af09e09e26295953f5f8c21fa4
[ "Apache-2.0" ]
null
null
null
class Conta { agencia; numero; cliente; _saldo = 0.0; get saldo() { return this._saldo; } sacar(valor) { if (this._saldo >= valor) { if (valor > 0) { this._saldo = this._saldo - valor; console.log("\nSaque concluído!") console.log(`\nSaldo atual: R$ ${conta._saldo}`) } else { console.log("\nQuantia inválida!") console.log(`\nSaldo atual: R$ ${conta._saldo}`) } } } depositar(valor) { if (valor <= 0) { console.log("\nQuantia inválida!") console.log(`\nSaldo atual: R$ ${conta._saldo}`) } else { this._saldo = this._saldo + valor; console.log("\nQuantia Depositada!") console.log(`\nSaldo atual: R$ ${conta._saldo}`) } } transferencia(valor) { if (valor > 0) { this._saldo = this._saldo + valor; } } transferir(valor, contaDestino) { if (this._saldo <= valor || valor < 0) { console.log("\nQuantia inválida!") console.log(`\nSaldo atual: R$ ${conta1._saldo}`) } else { this._saldo -= valor; contaDestino.transferencia(valor); console.log("\nTransferência efetuada com sucesso!") console.log(`\nSaldo atual: R$ ${conta1._saldo}`) } } } module.exports = Conta;
28.185185
65
0.471748
3.0625
51b7b819e9efded1a6147adc3c79867006f759e3
10,773
lua
Lua
test/functional/autocmd/cmdline_spec.lua
blueyed/neovim
65578693b28008ca953e446158e31c267e5df7a3
[ "Vim" ]
2
2019-02-21T11:18:42.000Z
2019-02-25T09:31:48.000Z
test/functional/autocmd/cmdline_spec.lua
blueyed/neovim
65578693b28008ca953e446158e31c267e5df7a3
[ "Vim" ]
1
2019-02-08T11:20:39.000Z
2019-02-08T11:20:39.000Z
test/functional/autocmd/cmdline_spec.lua
blueyed/neovim
65578693b28008ca953e446158e31c267e5df7a3
[ "Vim" ]
null
null
null
local helpers = require('test.functional.helpers')(after_each) local Screen = require('test.functional.ui.screen') local clear = helpers.clear local command = helpers.command local eq = helpers.eq local expect = helpers.expect local eval = helpers.eval local next_msg = helpers.next_msg local feed = helpers.feed local meths = helpers.meths describe('cmdline autocommands', function() local channel before_each(function() clear() channel = meths.get_api_info()[1] meths.set_var("channel",channel) command("autocmd CmdlineEnter * call rpcnotify(g:channel, 'CmdlineEnter', v:event)") command("autocmd CmdlineLeave * call rpcnotify(g:channel, 'CmdlineLeave', v:event)") command("autocmd CmdWinEnter * call rpcnotify(g:channel, 'CmdWinEnter', v:event)") command("autocmd CmdWinLeave * call rpcnotify(g:channel, 'CmdWinLeave', v:event)") end) it('works', function() feed(':') eq({'notification', 'CmdlineEnter', {{cmdtype=':', cmdlevel=1}}}, next_msg()) feed('redraw<cr>') eq({'notification', 'CmdlineLeave', {{cmdtype=':', cmdlevel=1, abort=false}}}, next_msg()) feed(':') eq({'notification', 'CmdlineEnter', {{cmdtype=':', cmdlevel=1}}}, next_msg()) -- note: feed('bork<c-c>') might not consume 'bork' -- due to out-of-band interupt handling feed('bork<esc>') eq({'notification', 'CmdlineLeave', {{cmdtype=':', cmdlevel=1, abort=true}}}, next_msg()) end) it('can abort cmdline', function() command("autocmd CmdlineLeave * let v:event.abort= len(getcmdline())>15") feed(":put! ='ok'<cr>") expect([[ ok ]]) feed(":put! ='blah blah'<cr>") expect([[ ok ]]) end) it('handles errors correctly', function() clear() local screen = Screen.new(72, 8) screen:attach() screen:set_default_attr_ids({ [1] = {bold = true, foreground = Screen.colors.Blue1}, [2] = {foreground = Screen.colors.Grey100, background = Screen.colors.Red}, [3] = {bold = true, foreground = Screen.colors.SeaGreen4}, [4] = {bold = true, reverse = true}, }) command("autocmd CmdlineEnter * echoerr 'FAIL'") command("autocmd CmdlineLeave * echoerr 'very error'") feed(':') screen:expect([[ | {1:~ }| {1:~ }| {1:~ }| {4: }| : | {2:E5500: autocmd has thrown an exception: Vim(echoerr):FAIL} | :^ | ]]) feed("put ='lorem ipsum'<cr>") screen:expect([[ | {4: }| : | {2:E5500: autocmd has thrown an exception: Vim(echoerr):FAIL} | :put ='lorem ipsum' | {2:E5500: autocmd has thrown an exception: Vim(echoerr):very error} | | {3:Press ENTER or type command to continue}^ | ]]) -- cmdline was still executed feed('<cr>') screen:expect([[ | ^lorem ipsum | {1:~ }| {1:~ }| {1:~ }| {1:~ }| {1:~ }| | ]]) command("autocmd CmdlineChanged * echoerr 'change erreor'") -- history recall still works feed(":<c-p>") screen:expect([[ | lorem ipsum | {4: }| : | {2:E5500: autocmd has thrown an exception: Vim(echoerr):FAIL} | :put ='lorem ipsum' | {2:E5500: autocmd has thrown an exception: Vim(echoerr):change erreor} | :put ='lorem ipsum'^ | ]]) feed("<left>") screen:expect([[ | lorem ipsum | {4: }| : | {2:E5500: autocmd has thrown an exception: Vim(echoerr):FAIL} | :put ='lorem ipsum' | {2:E5500: autocmd has thrown an exception: Vim(echoerr):change erreor} | :put ='lorem ipsum^' | ]]) -- edit still works feed(".") screen:expect([[ {4: }| : | {2:E5500: autocmd has thrown an exception: Vim(echoerr):FAIL} | :put ='lorem ipsum' | {2:E5500: autocmd has thrown an exception: Vim(echoerr):change erreor} | :put ='lorem ipsum.' | {2:E5500: autocmd has thrown an exception: Vim(echoerr):change erreor} | :put ='lorem ipsum.^' | ]]) feed('<cr>') screen:expect([[ :put ='lorem ipsum' | {2:E5500: autocmd has thrown an exception: Vim(echoerr):change erreor} | :put ='lorem ipsum.' | {2:E5500: autocmd has thrown an exception: Vim(echoerr):change erreor} | :put ='lorem ipsum.' | {2:E5500: autocmd has thrown an exception: Vim(echoerr):very error} | | {3:Press ENTER or type command to continue}^ | ]]) -- cmdline was still executed feed('<cr>') screen:expect([[ | lorem ipsum | ^lorem ipsum. | {1:~ }| {1:~ }| {1:~ }| {1:~ }| | ]]) end) it('works with nested cmdline', function() feed(':') eq({'notification', 'CmdlineEnter', {{cmdtype=':', cmdlevel=1}}}, next_msg()) feed('<c-r>=') eq({'notification', 'CmdlineEnter', {{cmdtype='=', cmdlevel=2}}}, next_msg()) feed('<c-f>') eq({'notification', 'CmdWinEnter', {{}}}, next_msg()) feed(':') eq({'notification', 'CmdlineEnter', {{cmdtype=':', cmdlevel=3}}}, next_msg()) feed('<c-c>') eq({'notification', 'CmdlineLeave', {{cmdtype=':', cmdlevel=3, abort=true}}}, next_msg()) feed('<c-c>') eq({'notification', 'CmdWinLeave', {{}}}, next_msg()) feed('1+2<cr>') eq({'notification', 'CmdlineLeave', {{cmdtype='=', cmdlevel=2, abort=false}}}, next_msg()) end) it('supports CmdlineChanged' ,function() command("autocmd CmdlineChanged * call rpcnotify(g:channel, 'CmdlineChanged', v:event, getcmdline())") feed(':') eq({'notification', 'CmdlineEnter', {{cmdtype=':', cmdlevel=1}}}, next_msg()) feed('l') eq({'notification', 'CmdlineChanged', {{cmdtype=':', cmdlevel=1}, "l"}}, next_msg()) feed('e') eq({'notification', 'CmdlineChanged', {{cmdtype=':', cmdlevel=1}, "le"}}, next_msg()) feed('t') eq({'notification', 'CmdlineChanged', {{cmdtype=':', cmdlevel=1}, "let"}}, next_msg()) feed('<space>') eq({'notification', 'CmdlineChanged', {{cmdtype=':', cmdlevel=1}, "let "}}, next_msg()) feed('x') eq({'notification', 'CmdlineChanged', {{cmdtype=':', cmdlevel=1}, "let x"}}, next_msg()) feed('<space>') eq({'notification', 'CmdlineChanged', {{cmdtype=':', cmdlevel=1}, "let x "}}, next_msg()) feed('=') eq({'notification', 'CmdlineChanged', {{cmdtype=':', cmdlevel=1}, "let x ="}}, next_msg()) feed('<space>') eq({'notification', 'CmdlineChanged', {{cmdtype=':', cmdlevel=1}, "let x = "}}, next_msg()) feed('<c-r>=') eq({'notification', 'CmdlineEnter', {{cmdtype='=', cmdlevel=2}}}, next_msg()) feed('1') eq({'notification', 'CmdlineChanged', {{cmdtype='=', cmdlevel=2}, "1"}}, next_msg()) feed('+') eq({'notification', 'CmdlineChanged', {{cmdtype='=', cmdlevel=2}, "1+"}}, next_msg()) feed('1') eq({'notification', 'CmdlineChanged', {{cmdtype='=', cmdlevel=2}, "1+1"}}, next_msg()) feed('<cr>') eq({'notification', 'CmdlineLeave', {{cmdtype='=', cmdlevel=2, abort=false}}}, next_msg()) eq({'notification', 'CmdlineChanged', {{cmdtype=':', cmdlevel=1}, "let x = "}}, next_msg()) eq({'notification', 'CmdlineChanged', {{cmdtype=':', cmdlevel=1}, "let x = 2"}}, next_msg()) feed('<cr>') eq({'notification', 'CmdlineLeave', {{cmdtype=':', cmdlevel=1, abort=false}}}, next_msg()) eq(2, eval('x')) end) end)
47.88
106
0.392277
3.109375
e517797ce4fd79cc0044e257fb302061185f8065
1,235
ts
TypeScript
src/services-bot/WxWorkMarkdown.ts
willerhe/coa-wx-work
38e852e8cc31a31e2fac57ddd33608f67a2663c6
[ "MIT" ]
null
null
null
src/services-bot/WxWorkMarkdown.ts
willerhe/coa-wx-work
38e852e8cc31a31e2fac57ddd33608f67a2663c6
[ "MIT" ]
null
null
null
src/services-bot/WxWorkMarkdown.ts
willerhe/coa-wx-work
38e852e8cc31a31e2fac57ddd33608f67a2663c6
[ "MIT" ]
null
null
null
export class WxWorkMarkdown { private data = '' text (text: string, color?: 'info' | 'comment' | 'warning') { if (!color) this.data += text else this.data += `<font color="${color}">${text}</font>` return this } header3 (text: string) { return this.text(`### ${text}`) } header4 (text: string) { return this.text(`#### ${text}`) } header5 (text: string) { return this.text(`##### ${text}`) } header6 (text: string) { return this.text(`###### ${text}`) } red (text: string) { return this.text(text, 'warning') } green (text: string) { return this.text(text, 'info') } gray (text: string) { return this.text(text, 'comment') } bold (text: string) { return this.text(`**${text}**`) } link (title: string, url: string) { return this.text(`[${title}](${url})`) } commentText (text: string) { return this.text(text, 'comment') } warningText (text: string) { return this.text(text, 'warning') } infoText (text: string) { return this.text(text, 'info') } br () { this.data += '\n' return this } quote () { this.data += '> ' return this } value () { return this.data } }
16.917808
63
0.536842
3.015625
9b9fc145bc70e814a53c9602ff7c48a2170e6050
5,707
js
JavaScript
bartop-api/test/integration/catalogsEndpointTest.js
bartop-io/bartop
4e6115a1f0a49d292952e5b04e26f6c7f04eb082
[ "MIT" ]
4
2018-11-26T14:41:19.000Z
2019-12-12T05:48:43.000Z
bartop-api/test/integration/catalogsEndpointTest.js
dpopp07/bartop
4e6115a1f0a49d292952e5b04e26f6c7f04eb082
[ "MIT" ]
157
2017-10-25T03:49:46.000Z
2018-07-27T18:44:28.000Z
bartop-api/test/integration/catalogsEndpointTest.js
dpopp07/bartop
4e6115a1f0a49d292952e5b04e26f6c7f04eb082
[ "MIT" ]
1
2017-10-25T04:03:29.000Z
2017-10-25T04:03:29.000Z
const request = require('supertest'); const expect = require('chai').expect; const app = require('../../src/server'); const r = require('../../src/db'); const { users, drinks } = require('../utils/testObjects'); describe('Resource - Catalog', function() { const TOKEN = global.testToken; let userId; let oldFashionedId; before(async function() { // increase hook timeout, tests require extensive environment setup this.timeout(9000); // prime the database with test tables/data const tables = await r.tableList(); if (tables.includes('users')) { await r.tableDrop('users'); } await r.tableCreate('users'); if (tables.includes('drinks')) { await r.tableDrop('drinks'); } await r.tableCreate('drinks'); const response = await r.table('users').insert(users.testUser); userId = response.generated_keys[0]; const dbResponse = await r.table('drinks').insert(drinks.oldFashioned); oldFashionedId = dbResponse.generated_keys[0]; return; }); it('Mutation - add a single drink to a catalog', function(done) { const query = ` mutation { addDrinksToCatalog( input: { userId: "${userId}", drinkIds: ["${oldFashionedId}"] } ) { drinks { name } errors { message } } }`; request(app) .post('/api/graphql') .set('Authorization', `Bearer ${TOKEN}`) .set('Content-Type', 'application/json') .send({ query }) .end((err, res) => { const payload = res.body.data.addDrinksToCatalog; expect(res.statusCode).to.equal(200); expect(payload).to.be.an('object'); expect(payload.drinks).to.be.an('array'); expect(payload.drinks[0].name).to.equal('Old Fashioned'); expect(payload.errors).to.equal(null); done(); }); }); it('Mutation - add a fake drink, should be invalid', function(done) { const badId = 'bestfriend<insertname>'; const query = ` mutation { addDrinksToCatalog( input: { userId: "${userId}", drinkIds: ["${badId}"] } ) { drinks { name } errors { message id } } }`; request(app) .post('/api/graphql') .set('Authorization', `Bearer ${TOKEN}`) .set('Content-Type', 'application/json') .send({ query }) .end((err, res) => { const payload = res.body.data.addDrinksToCatalog; expect(res.statusCode).to.equal(200); expect(payload).to.be.an('object'); expect(payload.drinks).to.equal(null); expect(payload.errors).to.be.an('array'); expect(payload.errors[0].message).to.equal('Drinks Not Found'); expect(payload.errors[0].id[0]).to.equal(badId); done(); }); }); it('Mutation - error on adding a drink for user that doesnt exist', function(done) { const badId = 'bernieEddy'; const query = ` mutation { addDrinksToCatalog( input: { userId: "${badId}", drinkIds: ["${oldFashionedId}"] } ) { drinks { name } errors { message id } } }`; request(app) .post('/api/graphql') .set('Authorization', `Bearer ${TOKEN}`) .set('Content-Type', 'application/json') .send({ query }) .end((err, res) => { const payload = res.body.data.addDrinksToCatalog; expect(res.statusCode).to.equal(200); expect(payload.errors).to.be.an('array'); expect(payload.errors[0].message).to.equal('Resource not found.'); expect(payload.errors[0].id[0]).to.equal(badId); done(); }); }); it('Mutation - remove a single drink from a catalog', function(done) { const query = ` mutation { removeDrinksFromCatalog( input: { userId: "${userId}", drinkIds: "${oldFashionedId}" } ) { drinks { name } errors { message } } }`; request(app) .post('/api/graphql') .set('Authorization', `Bearer ${TOKEN}`) .set('Content-Type', 'application/json') .send({ query }) .end((err, res) => { const payload = res.body.data.removeDrinksFromCatalog; expect(res.statusCode).to.equal(200); expect(payload).to.be.an('object'); expect(payload.drinks).to.be.an('array'); expect(payload.drinks[0].name).to.equal('Old Fashioned'); expect(payload.errors).to.equal(null); done(); }); }); it('Mutation - remove a fake drink, should be invalid', function(done) { const query = ` mutation { removeDrinksFromCatalog( input: { userId: "${userId}", drinkIds: ["proxieseverywhere", "run"] } ) { drinks { name } errors { message id } } }`; request(app) .post('/api/graphql') .set('Authorization', `Bearer ${TOKEN}`) .set('Content-Type', 'application/json') .send({ query }) .end((err, res) => { const payload = res.body.data.removeDrinksFromCatalog; expect(res.statusCode).to.equal(200); expect(payload).to.be.an('object'); expect(payload.drinks).to.equal(null); expect(payload.errors).to.be.an('array'); expect(payload.errors[0].message).to.equal('Drinks Not Found'); expect(payload.errors[0].id).to.deep.equal([ 'proxieseverywhere', 'run' ]); done(); }); }); });
29.266667
86
0.54109
3.203125
697c96734a266e26cbc4e01b254aa319a2d3de80
3,121
lua
Lua
lib/src/Dom/tryToAttributes.lua
LouieK22/anatta
f8762f5dee5bb5b82f0a8646701f35fd66f62da4
[ "MIT" ]
9
2018-10-23T00:32:43.000Z
2020-07-23T17:23:18.000Z
lib/src/Dom/tryToAttributes.lua
LouieK22/anatta
f8762f5dee5bb5b82f0a8646701f35fd66f62da4
[ "MIT" ]
16
2018-10-23T19:30:53.000Z
2019-11-27T09:33:41.000Z
lib/src/Dom/tryToAttributes.lua
LouieK22/anatta
f8762f5dee5bb5b82f0a8646701f35fd66f62da4
[ "MIT" ]
2
2019-04-04T09:43:15.000Z
2019-07-21T11:07:06.000Z
local Constants = require(script.Parent.Parent.Core.Constants) local ENTITY_ATTRIBUTE_NAME = Constants.EntityAttributeName local INSTANCE_REF_FOLDER = Constants.InstanceRefFolder local ErrConversionFailed = "%s (%s) cannot be turned into an attribute" local function instanceConversion(attributeMap, attributeName, value, instance) local refFolder = instance:FindFirstChild(INSTANCE_REF_FOLDER) if not refFolder then refFolder = Instance.new("Folder") refFolder.Name = INSTANCE_REF_FOLDER refFolder.Parent = instance end local objectValue = refFolder:FindFirstChild(attributeName) if not objectValue then objectValue = Instance.new("ObjectValue") objectValue.Name = attributeName objectValue.Parent = refFolder end attributeMap[attributeName] = value objectValue.Value = value end local conversions = { Instance = instanceConversion, instanceOf = instanceConversion, instance = instanceConversion, instanceIsA = instanceConversion, enum = function(attributeMap, attributeName, value) attributeMap[attributeName] = value.Name end, TweenInfo = function(attributeMap, attributeName, value) convert(attributeMap, attributeName, { EasingDirection = "enum", Time = "number", DelayTime = "number", RepeatCount = "number", EasingStyle = "enum", Reverses = "boolean", }, value) end, } function convert(attributeMap, attributeName, concreteType, instance, entity, value) if typeof(concreteType) == "table" then for field, fieldConcreteType in pairs(concreteType) do local fieldAttributeName = ("%s_%s"):format(attributeName, field) convert(attributeMap, fieldAttributeName, fieldConcreteType, instance, entity, value[field]) end elseif conversions[concreteType] then conversions[concreteType](attributeMap, attributeName, value, instance) elseif concreteType ~= nil then attributeMap[attributeName] = value else return false, (ErrConversionFailed:format(attributeName, concreteType)) end return true, attributeMap end return function(instance, entity, definition, component) local typeDefinition = definition.type local componentName = definition.name local checkSuccess, checkResult = typeDefinition.check(component) if not checkSuccess then return false, ("Error converting %s on %s: %s"):format(componentName, instance:GetFullName(), checkResult) end local conversionSuccess, concreteType = typeDefinition:tryGetConcreteType() if not conversionSuccess then return false, ("Error converting %s: %s"):format(componentName, concreteType) end if typeDefinition.typeName == "array" then concreteType = table.create(#component) for _ = 1, #component do local arrayFieldSuccess, fieldConcreteType = typeDefinition.typeParams[1]:tryGetConcreteType() if not arrayFieldSuccess then return false, ("Error converting %s: %s"):format(componentName, fieldConcreteType) end table.insert(concreteType, fieldConcreteType) end end local success, attributeMap = convert({}, componentName, concreteType, instance, entity, component) attributeMap[ENTITY_ATTRIBUTE_NAME] = entity return success, attributeMap end
30.009615
108
0.777956
3.09375
ccacff056d1541f2bb1828f019f45c3e84644f80
2,184
lua
Lua
src/wesenGemaMod/Commands/ResetCommand.lua
wesen1/wesenGemaMod
15a4b44cce7f1e5c18ce6fea9242562f15ecce93
[ "MIT" ]
1
2020-11-05T05:45:36.000Z
2020-11-05T05:45:36.000Z
src/wesenGemaMod/Commands/ResetCommand.lua
wesen1/wesenGemaMod
15a4b44cce7f1e5c18ce6fea9242562f15ecce93
[ "MIT" ]
64
2018-03-24T16:31:56.000Z
2021-12-31T19:18:40.000Z
src/wesenGemaMod/Commands/ResetCommand.lua
wesen1/wesenGemaMod
15a4b44cce7f1e5c18ce6fea9242562f15ecce93
[ "MIT" ]
2
2021-01-05T00:05:46.000Z
2021-06-25T04:39:08.000Z
--- -- @author wesen -- @copyright 2021 wesen <[email protected]> -- @release 0.1 -- @license MIT -- local BaseCommand = require "CommandManager.BaseCommand" local LuaServerApi = require "AC-LuaServer.Core.LuaServerApi" local StaticString = require "Output.StaticString" local TemplateException = require "AC-LuaServer.Core.Util.Exception.TemplateException" --- -- Command !reset. -- Allows a player to instantly respawn while not causing info messages in other players consoles. -- -- @type ResetCommand -- local ResetCommand = BaseCommand:extend() --- -- ResetCommand constructor. -- function ResetCommand:new() self.super.new( self, StaticString("resetCommandName"):getString(), 0, StaticString("resetCommandGroupName"):getString(), {}, StaticString("resetCommandDescription"):getString(), { StaticString("resetCommandAlias1"):getString(), StaticString("resetCommandAlias2"):getString() } ) end -- Public Methods --- -- Instantly respawns a player. -- -- @tparam Player _player The player who executed the command -- @tparam string[] _arguments The list of arguments which were passed by the player -- -- @raise Error when the player is currently in one of the spectate modes -- function ResetCommand:execute(_player, _arguments) local currentTeam = LuaServerApi.getteam(_player:getCn()) if (currentTeam == LuaServerApi.TEAM_CLA_SPECT or currentTeam == LuaServerApi.TEAM_RVSF_SPECT or currentTeam == LuaServerApi.TEAM_SPECT ) then error(TemplateException( "Commands/Reset/Exceptions/PlayerIsSpectator", {} )) end -- Kill the player to make him drop the flag if he currently holds it LuaServerApi:forcedeath(_player:getCn()) -- Set the players primary weapon to his next requested primary weapon LuaServerApi.setprimary(_player:getCn(), LuaServerApi.getnextprimary(_player:getCn())) if (LuaServerApi.callhandler("onPlayerSpawn", _player:getCn()) ~= LuaServerApi.PLUGIN_BLOCK) then -- Respawn the player at a random spawn point LuaServerApi.sendspawn(_player:getCn()) LuaServerApi.callhandler("onPlayerSpawnAfter", _player:getCn()) end end return ResetCommand
26
99
0.735348
3.203125
79b11be15e9fbb348c73de252762157f3ce245ca
770
sql
SQL
tests/input/pandoc-codeblock-include/query1.sql
Kristinn-Stefansson/pandocker
a9e7205a187ad0c3134bfd9c704de58ec89539c5
[ "BSD-3-Clause" ]
128
2017-12-21T13:24:45.000Z
2022-03-30T13:12:53.000Z
tests/input/pandoc-codeblock-include/query1.sql
Kristinn-Stefansson/pandocker
a9e7205a187ad0c3134bfd9c704de58ec89539c5
[ "BSD-3-Clause" ]
141
2017-06-16T10:17:19.000Z
2022-03-25T15:17:21.000Z
tests/input/pandoc-codeblock-include/query1.sql
Kristinn-Stefansson/pandocker
a9e7205a187ad0c3134bfd9c704de58ec89539c5
[ "BSD-3-Clause" ]
27
2017-12-21T13:26:34.000Z
2022-03-05T18:38:21.000Z
WITH RECURSIVE x(i) AS ( VALUES(0) UNION ALL SELECT i + 1 FROM x WHERE i < 101 ), Z(Ix, Iy, Cx, Cy, X, Y, I) AS ( SELECT Ix, Iy, X::FLOAT, Y::FLOAT, X::FLOAT, Y::FLOAT, 0 FROM (SELECT -2.2 + 0.031 * i, i FROM x) AS xgen(x,ix) CROSS JOIN (SELECT -1.5 + 0.031 * i, i FROM x) AS ygen(y,iy) UNION ALL SELECT Ix, Iy, Cx, Cy, X * X - Y * Y + Cx AS X, Y * X * 2 + Cy, I + 1 FROM Z WHERE X * X + Y * Y < 16.0 AND I < 27 ), Zt (Ix, Iy, I) AS ( SELECT Ix, Iy, MAX(I) AS I FROM Z GROUP BY Iy, Ix ORDER BY Iy, Ix ) SELECT array_to_string( array_agg( SUBSTRING( ' .,,,-----++++%%%%@@@@#### ', GREATEST(I,1), 1 ) ),'' ) FROM Zt GROUP BY Iy ORDER BY Iy;
20.263158
73
0.467532
3.4375
7081222c9f84594a4873e05924c35b50ad2a8355
1,506
go
Go
pkg/ml/train/intertitle/train.go
liampulles/cabiria
c651f97c98c87e4bcfbadac07b60e5699093df34
[ "MIT" ]
null
null
null
pkg/ml/train/intertitle/train.go
liampulles/cabiria
c651f97c98c87e4bcfbadac07b60e5699093df34
[ "MIT" ]
null
null
null
pkg/ml/train/intertitle/train.go
liampulles/cabiria
c651f97c98c87e4bcfbadac07b60e5699093df34
[ "MIT" ]
null
null
null
package intertitle import ( "bufio" "encoding/csv" "fmt" "io" "os" "strconv" "github.com/liampulles/cabiria/pkg/ml" ) // Train loads a list of intensity stats pointed to by csvPath, // and trains a predictive intertitle model which is saved to modelPath func Train(csvPath string, modelPath string) error { // Load rawData, err := loadCsv(csvPath) if err != nil { return err } //Initializes a new KNN classifier cls := ml.NewKNNClassifier(1) //Do a training-test split trainData, testData := ml.Split(rawData, 0.66) err = cls.Fit(trainData) if err != nil { return err } // Determine pass-rate passRate, err := ml.Test(cls, testData) if err != nil { return err } fmt.Printf("Pass rate on test data: %f%%\n", passRate*100) // Save model err = cls.Save(modelPath) return err } func loadCsv(path string) ([]ml.Sample, error) { csvFile, err := os.Open(path) if err != nil { return nil, err } reader := csv.NewReader(bufio.NewReader(csvFile)) var samples []ml.Sample for { line, err := reader.Read() if err == io.EOF { break } else if err != nil { return nil, err } sample := ml.Sample{} for i := 0; i < len(line)-1; i++ { f, err := strconv.ParseFloat(line[i], 64) if err != nil { return nil, err } sample.Input = append(sample.Input, f) } f, err := strconv.ParseFloat(line[len(line)-1], 64) if err != nil { return nil, err } sample.Output = []float64{f} samples = append(samples, sample) } return samples, nil }
19.815789
71
0.643426
3.375
8564a3f6afcee2a22f7b9997c082980722644168
1,403
js
JavaScript
lib/commons/preproc.js
RechInformatica/rech-environment-ide
28d84665ca4c57eac1155310630ac964eaca318e
[ "MIT" ]
2
2017-07-08T15:40:29.000Z
2018-06-20T12:45:50.000Z
lib/commons/preproc.js
RechInformatica/rech-environment-ide
28d84665ca4c57eac1155310630ac964eaca318e
[ "MIT" ]
2
2017-10-30T14:31:51.000Z
2020-12-26T07:18:56.000Z
lib/commons/preproc.js
RechInformatica/rech-environment-ide
28d84665ca4c57eac1155310630ac964eaca318e
[ "MIT" ]
3
2017-07-08T18:22:43.000Z
2021-02-21T19:44:43.000Z
'use babel'; import Exec from './exec'; import Path from './path'; import WcVersao from './wc-versao'; export default class Preproc { constructor() { this.options = []; } /** * Cria uma instância do préproc para atualização da base local */ static localDatabaseUpdate() { let newPreproc = new Preproc(); newPreproc.addOptions(["-bd", "-bdl", "-is", "-msi"]); return newPreproc; } /** * Define o caminho a pré-processar */ setPath(path) { if (path instanceof Path) { this.path = path.fullPath(); } else { this.path = path; } return this; } /** * Adiciona opções */ addOptions(options) { this.options = this.options.concat(options); return this; } /** * Retorna os argumentos command-line para pré-processar */ getCmdArgs() { return ['preproc.bat'].concat(this.options).concat([this.path]); } /** * Executa o pré-processador */ exec() { return new Promise((resolve) => { new WcVersao().currentWc().then((wc) => { new Exec().exec(this.getCmdArgs().concat(this.getWcParams(wc)), (process) => { resolve(); }); }); }); } /** * Retorna os parâmetros do WC */ getWcParams(wc) { return ['-dc=f:\\siger\\wc\\des\\'+wc.name+'\\fon\\;f:\\fontes\\']; } }
20.042857
87
0.536707
3.09375
01cdda97f1aae91b48945c3b6878026d7f3a6714
2,575
rs
Rust
rust/src/shell_sort.rs
pop/coding-exercises
9657b3a7d9bef1ae70f801c8a69cfb2c63a4af21
[ "MIT" ]
null
null
null
rust/src/shell_sort.rs
pop/coding-exercises
9657b3a7d9bef1ae70f801c8a69cfb2c63a4af21
[ "MIT" ]
12
2020-12-13T21:40:14.000Z
2020-12-29T23:19:21.000Z
rust/src/shell_sort.rs
pop/coding-exercises
9657b3a7d9bef1ae70f801c8a69cfb2c63a4af21
[ "MIT" ]
null
null
null
/// /// Shell Sort /// /// ``` /// # use exercises::shell_sort; /// /// let mut input = vec![1,3,5,7,9,8,6,4,2]; /// shell_sort::sort(&mut input); /// assert_eq!(vec![1,2,3,4,5,6,7,8,9], input); /// ``` /// /// Note: we sort elements of type u8 as a placeholder. We could just as easily sort elements of /// type T where T implements PartialOrd (or something like that), but for simplicity we're using /// a concrete integer type. /// /// Following thes resources: /// * https://www.tutorialspoint.com/data_structures_algorithms/shell_sort_algorithm.htm /// * https://www.toptal.com/developers/sorting-algorithms/shell-sort /// /// The algorithm goes like this: /// Step 1 − Initialize the value of h /// Step 2 − Divide the list into smaller sub-list of equal interval h /// Step 3 − Sort these sub-lists using insertion sort /// Step 3 − Repeat until complete list is sorted /// /// Wikipedia has a good high-level description: /// /// > The method starts by sorting pairs of elements far apart from each other, then progressively /// > reducing the gap between elements to be compared. By starting with far apart elements, it can /// > move some out-of-place elements into position faster than a simple nearest neighbor exchange. /// pub fn sort(input: &mut Vec<u8>) { // Initialize `gap` to be length of the input array. // This immediately gets cut to ~1/3 for faster comparison. // We cannot initialize it to 1/3 outside of the loop because of the `while` comparison. let mut gap = input.len(); while gap != 1 { // We start with a gap of len/3 + 1 // Tutorials/psuedocode complicate this step... // I'm still not sure why we cannot statically start with this gap. // And that makes me nervous. gap = std::cmp::max(gap/2, 1); for index in gap..input.len() { // `a` is the left-most value in our tuple comparison let a = index-gap; // `b` is our right-most value in our tuple comparison let b = index; // If the left value is bigger, swap them if input[a] > input[b] { input.swap(a, b); } } } crate::insertion_sort::sort(input); } #[test] fn test_shell_sort() { use rand::prelude::*; let mut rng = thread_rng(); let distr = rand::distributions::Uniform::new_inclusive(1, 100); let mut input = (1..10).map(|_| rng.sample(distr)).collect::<Vec<u8>>(); let mut sorted = input.clone(); sorted.sort(); sort(&mut input); assert_eq!(input, sorted); }
33.012821
99
0.631456
3.265625
70be694a78e0db5f13be738b24153354e9512c2f
2,212
go
Go
ai.go
fr3fou/tic-tac-toe-ai
a784c4390a272cb432350ca7608dc2952962e30a
[ "MIT" ]
4
2020-08-02T16:33:17.000Z
2021-05-10T20:28:40.000Z
ai.go
fr3fou/tic-tac-toe-ai
a784c4390a272cb432350ca7608dc2952962e30a
[ "MIT" ]
null
null
null
ai.go
fr3fou/tic-tac-toe-ai
a784c4390a272cb432350ca7608dc2952962e30a
[ "MIT" ]
null
null
null
package main import "math" // value should only be called at leaf / terminal nodes (game MUST be over). func value(b Board, aiWon bool) int { spots := b.EmptySpots() if aiWon { return max(1, spots) } return min(-1, -spots) } func minimax(b Board, ai, current Player, alpha, beta float64) int { other := otherPlayer(current) if b.IsWinner(other) { return value(b, ai == other) } // Draw is 0 if b.EmptySpots() == 0 { return 0 } if current == ai { // Maximizing max := math.Inf(-1) for _, state := range nextBoards(b, current) { value := float64(minimax(state.Board, ai, other, alpha, beta)) max = math.Max(max, value) alpha = math.Max(alpha, value) if alpha >= beta { break } } return int(max) } else { // Minimizing min := math.Inf(+1) for _, state := range nextBoards(b, current) { value := float64(minimax(state.Board, ai, other, alpha, beta)) min = math.Min(min, value) beta = math.Min(beta, value) if alpha >= beta { break } } return int(min) } } func Minimax(ai Player, g *Game) { max := math.Inf(-1) bestState := State{} other := otherPlayer(ai) for _, state := range nextBoards(g.Board, ai) { value := float64(minimax(state.Board, ai, other, math.Inf(-1), math.Inf(1))) if value > max { max = value bestState = state } } g.Place(bestState.X, bestState.Y) } func min(a, b int) int { if a < b { return a } return b } func max(a, b int) int { if a > b { return a } return b } type State struct { X int Y int Board Board } func nextBoards(b Board, player Player) []State { boards := []State{} for i, row := range b { for j, square := range row { if square != None { continue } board := copyBoard(b) board[i][j] = player boards = append(boards, State{ X: i, Y: j, Board: board, }) } } return boards } func copyBoard(src Board) Board { dst := Board{} for i, row := range src { dst = append(dst, []Player{}) for _, square := range row { dst[i] = append(dst[i], square) } } return dst }
17.555556
79
0.559222
3.390625
c105c094ce2467dcfc5a09d4f04c8a6b96ebcf55
12,413
rs
Rust
src/operator_construction/operatorargs.rs
busstoptaktik/geodesy
2718c094001b0a2168deb4fbaaa09c4ab9f78a7c
[ "Apache-2.0", "MIT" ]
9
2021-09-22T21:38:12.000Z
2022-03-21T12:34:52.000Z
src/operator_construction/operatorargs.rs
busstoptaktik/geodesy
2718c094001b0a2168deb4fbaaa09c4ab9f78a7c
[ "Apache-2.0", "MIT" ]
15
2021-07-29T13:31:18.000Z
2022-02-05T23:28:50.000Z
src/operator_construction/operatorargs.rs
busstoptaktik/geodesy
2718c094001b0a2168deb4fbaaa09c4ab9f78a7c
[ "Apache-2.0", "MIT" ]
null
null
null
use std::collections::HashMap; use yaml_rust::{Yaml, YamlEmitter, YamlLoader}; use crate::GeodesyError; #[derive(Debug, Clone, Default, PartialEq)] pub struct OperatorArgs { pub name: String, pub args: HashMap<String, String>, pub used: HashMap<String, String>, pub all_used: HashMap<String, String>, } impl OperatorArgs { #[must_use] pub fn new() -> OperatorArgs { let mut op = OperatorArgs { name: String::new(), args: HashMap::new(), used: HashMap::new(), all_used: HashMap::new(), }; // Global defaults op.insert("ellps", "GRS80"); op } /// Provides an `OperatorArgs` object, populated by the defaults from an existing /// `OperatorArgs`, combined with a new object definition. /// /// This is the mechanism for inheritance of global args in pipelines. #[must_use] pub fn spawn(&self, definition: &str) -> OperatorArgs { let mut oa = OperatorArgs::new(); for (arg, val) in &self.args { if arg.starts_with('_') || (arg == "inv") { continue; } oa.insert(arg, val); } oa.populate(definition, ""); oa } /// /// Insert PROJ style operator definition arguments, converted from a YAML /// setup string. /// /// If `which` is set to the empty string, we first look for a pipeline /// definition. If that is not found, and there is only one list element /// in the setup string, we assert that this is the element to handle. /// /// If `which` is not the empty string, we look for a list element with /// that name, and handle that either as a pipeline definition, or as a /// single operator definition. /// /// # Returns /// /// `true` on success, `false` on sseccus. /// /// # Examples /// /// ```rust /// use geodesy::operator_construction::OperatorArgs; /// /// let mut args = OperatorArgs::new(); /// let txt = std::fs::read_to_string("tests/tests.yml").unwrap_or_default(); /// /// assert!(args.populate(&txt, "a_pipeline_for_testing")); /// assert_eq!(&args.value("_step_0", "")[0..4], "cart"); /// ``` /// /// pub fn populate(&mut self, definition: &str, which: &str) -> bool { // First, we copy the full text in the args, to enable recursive definitions self.insert("_definition", definition); // Read the entire YAML-document and try to locate the `which` document let docs = YamlLoader::load_from_str(definition); if docs.is_err() { return false; } let docs = docs.unwrap(); let mut index = Some(0_usize); if !which.is_empty() { index = docs.iter().position(|doc| !doc[which].is_badvalue()); if index.is_none() { return self.badvalue("Cannot locate definition"); } } let index = index.unwrap(); let main = &docs[index].as_hash(); if main.is_none() { return self.badvalue("Cannot parse definition"); } let main = main.unwrap(); // Is it conforming? let mut main_entry_name = which; if main_entry_name.is_empty() { for (arg, val) in main { if val.is_badvalue() { return self.badvalue("Cannot parse definition"); } let name = &arg.as_str().unwrap(); if name.starts_with('_') { continue; } if !main_entry_name.is_empty() { return self.badvalue("Too many items in definition root"); } main_entry_name = name; } } self.name = main_entry_name.to_string(); // Grab the sub-tree defining the 'main_entry_name' let main_entry = &docs[index][main_entry_name]; if main_entry.is_badvalue() { return self.badvalue("Cannot locate definition"); } // Loop over all globals and create the corresponding OperatorArgs entries if let Some(globals) = main_entry["globals"].as_hash() { for (arg, val) in globals { let thearg = arg.as_str().unwrap(); if thearg != "inv" { let theval = match val { Yaml::Integer(val) => val.to_string(), Yaml::Real(val) => val.as_str().to_string(), Yaml::String(val) => val.to_string(), Yaml::Boolean(val) => val.to_string(), _ => "".to_string(), }; if !theval.is_empty() { self.insert(thearg, &theval); } } } } // Try to locate the step definitions, to determine whether we // are handling a pipeline or a plain operator definition let steps = main_entry["steps"].as_vec(); // Not a pipeline? Just insert the operator args and return if steps.is_none() { let args = main_entry.as_hash(); if args.is_none() { return self.badvalue("Cannot read args"); } let args = args.unwrap(); for (arg, val) in args { let thearg = arg.as_str().unwrap_or(""); if thearg.is_empty() { continue; } let theval = match val { Yaml::Integer(val) => val.to_string(), Yaml::Real(val) => val.as_str().to_string(), Yaml::String(val) => val.to_string(), Yaml::Boolean(val) => val.to_string(), _ => "".to_string(), }; if !theval.is_empty() { self.insert(thearg, &theval); } } return true; } // It's a pipeline - insert the number of steps into the argument list. let steps = steps.unwrap(); self.insert("_nsteps", &steps.len().to_string()); // Insert each step into the argument list, formatted as YAML. for (index, step) in steps.iter().enumerate() { // Write the step definition to a new string let mut step_definition = String::new(); let mut emitter = YamlEmitter::new(&mut step_definition); emitter.dump(step).unwrap(); // Remove the initial doc separator "---\n" let stripped_definition = step_definition.trim_start_matches("---\n"); let step_key = format!("_step_{}", index); self.insert(&step_key, stripped_definition); } true } fn badvalue(&mut self, cause: &str) -> bool { self.name = "badvalue".to_string(); self.insert("cause", cause); false } pub fn name(&mut self, name: &str) { self.name = name.to_string(); } pub fn insert(&mut self, key: &str, value: &str) { // Self-referencing keys (x: ^x), are no-ops. // The syntax "x: ^x" makes sense in a nested command (or a pipeline // step), but the meaning is "use the value already in the hashmap". // Actually inserting it will lead to overwriting of the actual // value-of-interest, and to infinite recursion on lookup. if key != value.trim_start_matches('^') { self.args.insert(key.to_string(), value.to_string()); } } // Recursive workhorse, tracing indirect definitions for ::value fn value_search(&mut self, key: &str, default: &str, recursions: usize) -> String { if recursions > 100 { return default.to_string(); } let arg = self.args.get(key); let arg = match arg { Some(arg) => arg.to_string(), None => return default.to_string(), }; // all_used includes intermediate steps in indirect definitions self.all_used.insert(key.to_string(), arg.to_string()); if let Some(arg) = arg.strip_prefix('^') { // Default if looking for an out-of-scope arg. if self.args.get(arg).is_none() { return default.to_string(); } return self.value_search(arg, default, recursions + 1); } arg } /// Return the arg for a given key; maintain usage info. pub fn value(&mut self, key: &str, default: &str) -> String { let arg = self.value_search(key, default, 0); if arg != default { self.used.insert(key.to_string(), arg.to_string()); } arg } pub fn numeric_value(&mut self, key: &str, default: f64) -> Result<f64, GeodesyError> { let arg = self.value(key, ""); // key not given: return default if arg.is_empty() { return Ok(default); } // key given, value numeric: return value if let Ok(v) = arg.parse::<f64>() { return Ok(v); } // key given, but not numeric: return error string Err(GeodesyError::Syntax(format!( "Numeric value expected for '{}.{}' - got [{}: {}].", self.name, key, key, arg ))) } // If key is given, and value != false: true; else: false pub fn flag(&mut self, key: &str) -> bool { self.value(key, "false") != "false" } } //---------------------------------------------------------------------------------- #[cfg(test)] mod tests { #[test] fn operator_args() { use super::*; let mut args = OperatorArgs::new(); // dx and dy are straightforward args.insert("dx", "11"); args.insert("dy", "22"); // But we hide dz behind two levels of indirection args.insert("dz", "^ddz"); args.insert("ddz", "^dddz"); args.insert("dddz", "33"); assert_eq!("00", args.value("", "00")); assert_eq!("11", args.value("dx", "")); assert_eq!("22", args.value("dy", "")); assert_eq!(args.used.len(), 2); args.insert("dx", "^dx"); assert_eq!("11", args.value("dx", "")); args.insert("dx", "^^^^dx"); assert_eq!("11", args.value("dx", "")); assert_eq!("33", args.value("dz", "")); assert_eq!(33.0, args.numeric_value("dz", 42.0).unwrap()); assert_eq!(42.0, args.numeric_value("bar", 42.0).unwrap()); assert_eq!(args.used.len(), 3); assert_eq!(args.all_used.len(), 5); // println!("used: {:?}", &args.used); // println!("all_used: {:?}", &args.all_used); assert_eq!("", args.value("abcdefg", "")); // Finally one for testing 'err' returned for non-numerics args.insert("ds", "foo"); assert!(args.numeric_value("ds", 0.0).is_err()); // if let Err(msg) = args.numeric_value("bar", "ds", 0.0) { // println!("**** err: {}", msg) // } } #[test] fn preparing_args() { use super::*; let mut args = OperatorArgs::new(); // Explicitly stating the name of the pipeline let txt = std::fs::read_to_string("tests/tests.yml").unwrap_or_default(); assert!(args.populate(&txt, "a_pipeline_for_testing")); assert_eq!(&args.value("_step_0", " ")[0..4], "cart"); // Let populate() figure out what we want let mut args = OperatorArgs::new(); assert!(args.populate(&txt, "")); assert_eq!(&args.value("x", "5"), "3"); // When op is not a pipeline let mut args = OperatorArgs::new(); assert!(args.populate("cart: {ellps: intl}", "")); assert_eq!(args.name, "cart"); assert_eq!(&args.value("ellps", ""), "intl"); // Inheritance let mut moreargs = args.spawn("foo: {bar: baz}"); assert_eq!(&moreargs.name, "foo"); assert_eq!(&moreargs.value("ellps", ""), "intl"); assert_eq!(&moreargs.value("bar", ""), "baz"); } #[test] fn bad_value() { use super::*; let v = Yaml::BadValue; assert!(v.is_badvalue()); let v = Yaml::Null; assert!(v.is_null()); let v = Yaml::Integer(77); assert!(v == Yaml::Integer(77)); } }
34.480556
91
0.520422
3.109375
3572df1f927526b36b840a90dfbe4e17409c32d2
3,155
lua
Lua
resources/[fivem]/money/server.lua
raag2005/development-vrp
1f78f2a10fd0cfdd8b470bb263aee8947763beda
[ "MIT" ]
null
null
null
resources/[fivem]/money/server.lua
raag2005/development-vrp
1f78f2a10fd0cfdd8b470bb263aee8947763beda
[ "MIT" ]
null
null
null
resources/[fivem]/money/server.lua
raag2005/development-vrp
1f78f2a10fd0cfdd8b470bb263aee8947763beda
[ "MIT" ]
1
2022-01-25T23:01:13.000Z
2022-01-25T23:01:13.000Z
local playerData = exports['cfx.re/playerData.v1alpha1'] local validMoneyTypes = { bank = true, cash = true, } local function getMoneyForId(playerId, moneyType) return GetResourceKvpInt(('money:%s:%s'):format(playerId, moneyType)) / 100.0 end local function setMoneyForId(playerId, moneyType, money) local s = playerData:getPlayerById(playerId) TriggerEvent('money:updated', { dbId = playerId, source = s, moneyType = moneyType, money = money }) return SetResourceKvpInt(('money:%s:%s'):format(playerId, moneyType), math.tointeger(money * 100.0)) end local function addMoneyForId(playerId, moneyType, amount) local curMoney = getMoneyForId(playerId, moneyType) curMoney += amount if curMoney >= 0 then setMoneyForId(playerId, moneyType, curMoney) return true, curMoney end return false, 0 end exports('addMoney', function(playerIdx, moneyType, amount) amount = tonumber(amount) if amount <= 0 or amount > (1 << 30) then return false end if not validMoneyTypes[moneyType] then return false end local playerId = playerData:getPlayerId(playerIdx) local success, money = addMoneyForId(playerId, moneyType, amount) if success then Player(playerIdx).state['money_' .. moneyType] = money end return true end) exports('removeMoney', function(playerIdx, moneyType, amount) amount = tonumber(amount) if amount <= 0 or amount > (1 << 30) then return false end if not validMoneyTypes[moneyType] then return false end local playerId = playerData:getPlayerId(playerIdx) local success, money = addMoneyForId(playerId, moneyType, -amount) if success then Player(playerIdx).state['money_' .. moneyType] = money end return success end) exports('getMoney', function(playerIdx, moneyType) local playerId = playerData:getPlayerId(playerIdx) return getMoneyForId(playerId, moneyType) end) -- player display bits AddEventHandler('money:updated', function(data) if data.source then TriggerClientEvent('money:displayUpdate', data.source, data.moneyType, data.money) end end) RegisterNetEvent('money:requestDisplay') AddEventHandler('money:requestDisplay', function() local source = source local playerId = playerData:getPlayerId(source) for type, _ in pairs(validMoneyTypes) do local amount = getMoneyForId(playerId, type) TriggerClientEvent('money:displayUpdate', source, type, amount) Player(source).state['money_' .. type] = amount end end) RegisterCommand('earn', function(source, args) local type = args[1] local amount = tonumber(args[2]) exports['money']:addMoney(source, type, amount) end, true) RegisterCommand('spend', function(source, args) local type = args[1] local amount = tonumber(args[2]) if not exports['money']:removeMoney(source, type, amount) then print('you are broke??') end end, true)
26.512605
105
0.660222
3.078125
eae3a15d2bf31791efb64463530f9ef6fafed5ab
1,315
lua
Lua
scripts/endpoints/event.lua
ICESat2-SlideRule/sliderule
90776d7e174e151c5806077001f5f9c21ef81f48
[ "BSD-3-Clause" ]
2
2021-05-06T19:56:26.000Z
2021-05-27T16:41:56.000Z
scripts/endpoints/event.lua
ICESat2-SlideRule/sliderule
90776d7e174e151c5806077001f5f9c21ef81f48
[ "BSD-3-Clause" ]
54
2021-03-30T18:45:12.000Z
2022-03-17T20:13:04.000Z
scripts/endpoints/event.lua
ICESat2-SlideRule/sliderule
90776d7e174e151c5806077001f5f9c21ef81f48
[ "BSD-3-Clause" ]
1
2021-05-14T16:34:08.000Z
2021-05-14T16:34:08.000Z
-- -- ENDPOINT: /source/event -- -- INPUT: arg[1] - -- { -- "type": <core.LOG | core.TRACE | core.METRIC> -- "level": "<event level string>" -OR- <event level number> -- "format": <core.FMT_TEXT | core.FMT_JSON> -- "duration": <seconds to hold connection open | 0 for indefinite> -- } -- -- rspq - output queue to stream log messages -- -- OUTPUT: application event messages -- local global = require("global") local json = require("json") local parm = json.decode(arg[1]) local type = global.eval(parm["type"]) or core.LOG local level = global.eval(parm["level"]) or core.INFO local format = global.eval(parm["format"]) or nil local duration = parm["duration"] or 0 -- Attach monitor to post event to response queue -- local userevents = core.dispatcher(core.EVENTQ) userevents:attach(core.monitor(type, level, format, rspq), "eventrec") userevents:run() -- Bounds check duration if duration > 300 then duration = 300 end -- Watch response queue local watchq = msg.publish(rspq) -- Pend for duration (in 1 second intervals to allow hooks to execute) -- local seconds = 0 while (watchq:numsubs() > 0) and (seconds < duration) do seconds = seconds + 1 sys.wait(1) end
29.222222
84
0.620532
3.3125